-2

I have code like this:

a.py

from app.cache import Cache 
my_cache = Cache(cache_prefix='xxxxx') 

b.py

from a import my_cache
class MyApp:
     def run_app():
         my_cache.get(1,2)

test_b.py

from mock import Mock, patch
import b
mock_my_cache_get= Mock(b.my_cache.get)

class MyTests():
     @patch('b.my_cache.get', mock_my_cache_get)
     def test_cache(self):
          b.MyApp().run_app()
          mock_my_cache_get.assert_called_with(1,2)

As you can see above, I am trying to write a unit test where I mock the get method of the class instance of Cache. However, when I try to assert that this mocked method is called with the specified arguments, I get an error saying that call is not found. Which, as iis obvious that is is.

user2611836
  • 386
  • 4
  • 6
  • 17

1 Answers1

-1

You can leave unchanged files a.py and b.py, but you have to change your test_b.py as following:

import unittest
from unittest.mock import Mock, patch
import b         # <--------------- add the import

mock_my_cache_get = Mock(b.my_cache.get)

class MyTests(unittest.TestCase):

    @patch('b.my_cache.get', mock_my_cache_get)
    def test_cache(self):
        b.MyApp().run_app()    # <--- add the call to the method under test
        mock_my_cache_get.assert_called_with(1, 2)

if __name__ == '__main__':
    unittest.main()
  • In the test you have to call the run_app() method.
  • Furthermore you have to add the import b instruction.

EDIT I have replicated your code in my system and the structure of my folder is:

question_76708763
 |--app
 |   |-cache.py
 |--a.py
 |--b.py
 |--test_b.py 

Following I report how I have executed the test in my system and the output of the execution:

> cd /path/to/question_76708763

> python test_b.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

It is strange what happens in your system.

frankfalse
  • 1,553
  • 1
  • 4
  • 17