0

I'm trying to get my head around why I can't access the method when mocking. I have simplified the code examples to only show the content that is relevant.

Here's the class with the method that I want to test / mock:

import sqlite3
from customer import Customer

class DataChecker:
    def find_customer(self, customerID):
        query = "SELECT * FROM Customers WHERE ID == ?;"
        customers = self.execute_db(query, customerID, True)
        
        if len(customers) == 0:
            print("Customer with given ID not found in DB")
            return False
        else:
            print("Customer found")
            return True

    def execute_db(self, query, params=None, fetch_one=False):
        if params:
            self.cursor.execute(query, [params])
            self.conn.commit()
        else:
            self.cursor.execute(query)
            self.conn.commit()
        if fetch_one:
            return self.cursor.fetchone()
        else:
            return self.cursor.fetchall()

Mock:

from datachecker import DataChecker
from unittest import mock

@mock.patch('datachecker.find_customer')
def test_find_customer_true(mocker):
    datachecker.execute_db.return_value = {'customers': 10}
    assert datachecker.find_customer() == True
octavemirbeau
  • 481
  • 6
  • 19
  • 1
    You're patching the `find_customer` function in the `datachecker` module, which doesn't exist. You could patch `datachecker.DataChecker`, but that eliminates any ability to actually test the `DataChecker` class. I'd suggest just patching its db. – Samwise Apr 07 '21 at 01:20
  • 2
    You might want to take a look at [Mocking only a single method on an object](https://stackoverflow.com/questions/19737124/mocking-only-a-single-method-on-an-object), as you appear to be trying to patch methods of an object. – metatoaster Apr 07 '21 at 01:22
  • Where does your `DataChecker` get its `self.cursor` and `self.conn` attributes from? More importantly: how does your test get its `datachecker` object? The test as written looks like it'd fail on `datachecker` being undefined. – Samwise Apr 07 '21 at 02:03
  • I found my way around it, using object.patch but now the return value is not set as intended. But I believe that's for a new topic as it doesn't relate any longer to this question. Cheers! – octavemirbeau Apr 07 '21 at 02:24

0 Answers0