4

Not sure why but here is my code snippet :

stats_collector.py

class StatsCollector( object ) :
def __init__( self, user_id, app_id ) :
    logging.info( "Stats: APP_ID = {0}, ID = {1}".format( app_id, user_id ) )

mydb.py

from namespacename.mylibname.stats_collector import StatsCollector
class Db( object ) :
    # constructor/destructor
    def __init__( self, dbname ) :
        ....

    def beginTransaction( self, user_id, app_id ) :
        logging.info( "Begin" )
        self._stats = StatsCollector( user_id, app_id ) 

test_mylibname_mydb

from namespacename.mylibname.mydb import Db
from namespacename.mylibname.stats_collector import StatsCollector
@pytest.mark.mydb_temp
@mock.patch( 'namespacename.mylibname.stats_collector.StatsCollector')
def test_db_beginTransaction( mock_stats_collector ) :
    db = Db( TEST_DB_NAME )
    mock_stats_collector.return_value = mock.Mock()
    db.beginTransaction( TEST_ID, TEST_APP_ID )
    ......
    ......

I can see my log in my stats_collector.__init__ - why do I enter that? Shouldn't when inside my beginTransaction I call StatsCollector return value to be a MockObject and I shouldn't see any logs ?

Structure looks like :

tests/
├── mylibname
│   ├── test_mylibname_mydb.py
namespacename/mylibname
├── stats_collector
│   ├── mylibname_stats_collector.py
│   ├── __init__.py
├── mydb
│   ├── mylibname_mydb.py
│   ├── __init__.py

** Edit **

Followed advice on comment -

@mock.patch( 'namespacename.mylibname.mydb.StatsCollector')
def test_db_beginTransaction( mock_stats_init ) :
    db = Db( TEST_DB_NAME )
    db.beginTransaction( TEST_UUID, TEST_APP_ID )
    print db._transaction
    assert db._transaction is mock_stats_init

gets me :

E       AssertionError: assert <namespacename.mylibname.stats_collector.mylibname_stats_collector.StatsCollector object at 0x7f42d837b110> is <MagicMock name='StatsCollector' id='139925072008976'>
E        +  where <namespacename.mylibname.stats_collector.mylibname_stats_collector.StatsCollector object at 0x7f42d837b110> = <namespacename.mylibname.mydb.mylibname_mydb.Db object at 0x7f42d8365850>._transaction
ghostrider
  • 5,131
  • 14
  • 72
  • 120

3 Answers3

3

You need to patch The symbol 'A' in the module which is being tested i.e. 'B'.

When you do @mock.patch("full.path.A"), it should be:

@mock.patch("full.path.to.B.A")

Now the symbol A in module B is patched with your mock.

rdas
  • 20,604
  • 6
  • 33
  • 46
3

Aren't you missing the name of the file itself?

@mock.patch( 'namespacename.mylibname.stats_collector.mylibname_stats_collector.StatsCollector')
Higor Rossato
  • 1,996
  • 1
  • 10
  • 15
1

you might have figured out as i write this.

Rule of thumb: Don't patch classes or functions where they are defined, instead patch them where they are used.

a.py

class A:
    def exponent(self, a, b)
        return a ** b
    

b.py    


from a import A
class B:
   def add_constat(a, b, c)
      return A().exponent(a, b) + c
      
  
  
  

For testing add_constant method, you may be tempted to patch A as in

TestB:

@patch('a.A.exponent', mock_a)
    test_add_constant(self, mock_a) 

this is wrong, as you are patching a class in the file where its defintion is given at.

A is used in file b in class B. Hence, you should patch that class instead.

TestB:

    @patch('b.A')
    test_add_constant(self, mock_a):
    # mock_a is fake class of A, the return_value of mock_a gives us an instance (object) of the class(A)
    instance_a = mock_a.return_value # 
   
    # we now have instance of the class i.e A, hence it is possible to call the methods of class A
   
    instance_a.exponent.return_value = 16
   
    assert 26 = B().add_constant(2,4,10)

I have modified your code a bit so that it works in my python environment.

stats_collector.py

class StatsCollector:
    def __init__(self, user_id, app_id):
        self.user_id = user_id
        self.app_id = app_id

    def stat(self):
        return self.user_id + ':' + self.app_id


mydb.py

from stats_collector import StatsCollector
import logging

class Db:
    # constructor
    def __init__(self, db_name):
        self.db_name = db_name

    def begin_transaction(self, user_id, app_id):
        logging.info("Begin")
        stat = StatsCollector(user_id, app_id).stat()

        if stat:
            return user_id + ':' + app_id
        return "wrong User"

using similar anlogy: for testing "begin_transaction" in class Db of file mydb.py, you need to patch StatsCollector class used in mydb.py file

test_mydb.py

from unittest.mock import patch
from unittest import TestCase


class TestDb(TestCase):

    @patch('mydb.StatsCollector')
    def test_begin_transaction(self, db_class_mock):

        # db_class_mock is the mock of the class, it is not an instance of the DB class.
        # to create an instance of the class, you need to call return_value
       
        db_instance = db_class_mock.return_value
        db_instance.stat.return_value = 1
        # i prefere to do the above two lines in just one line as

        #db_class_mock.return_value.stat.return_value = 1
        

        db = Db('stat')
        expected = db.begin_transaction('Addis', 'Abeba')

        assert expected == 'Addis' + ':' + 'Abeba'

        # set the return value of stat method
        db_class_mock.return_value.stat.return_value = 0
        expected = db.begin_transaction('Addis', 'Abeba')

        assert expected == "wrong User"

I hope this helps someone in the net