0

I'm trying to unit test a class connection to a database. To avoid hardcoding a database, I'd like to assert that the mysql.connector.connect method is called with adequate values.

from mysql.connector import connect
from mysql.connector import Error

from discovery.database import Database


class MariaDatabase(Database):

    def connect(self, username, password):
        """
        Don't forget to close the connection !

        :return: connection to the database
        """
        try:
            return connect(host=str(self.target),
                           database=self.db_name,
                           user=username,
                           password=password)

I've read documentation around mocks and similar problems (notably this one Python Unit Test : How to unit test the module which contains database operations?, which I thought would solve my problem, but mysql.connector.connect keeps being called instead of the mock).

I don't know what could I do to UTest this class

Cholesterol
  • 177
  • 2
  • 10
  • Why not create a test db in the start of the test and drop it when you are done? Also 'Don't forget to close the connection !' ==> read about the [`with`](https://stackoverflow.com/a/1984346/1918287) keyword, it could help – Maor Refaeli Aug 30 '18 at 12:39
  • 1
    Do you have insights on how could I mock a database ? That would solve efficiently my problem indeed ! I only want the object to give the connection to the caller. The class won't allow to perform queries/other stuff, just return the connection. I'm not sure I can use with in that case ? – Cholesterol Aug 30 '18 at 12:48
  • You can set a db in the `setUp` method in [`testcase`](https://docs.python.org/2/library/unittest.html#module-unittest) each test case. Also, see [this](https://stackoverflow.com/a/47160503/1918287) and [this](https://stackoverflow.com/a/15922422/1918287) answers for patching methods – Maor Refaeli Aug 30 '18 at 12:52
  • start with `@mock.patch.object(MariaDatabase, 'connect') ` or `@mock.patch('ur_pkg.maria_database.mysql.connector' )` where `maria_database` is the module name where `MariaDatabase` is in. and update your post. – Gang Aug 30 '18 at 23:34

0 Answers0