1

I have a class that I try to mock in tests. The class is located in server/cache.py and looks like:

class Storage(object):
    def __init__(self, host, port):
        # set up connection to a storage engine

    def store_element(self, element, num_of_seconds):
        # store something

    def remove_element(self, element):
        # remove something

This class is used in server/app.py similar to this one:

import cache
STORAGE = cache.Storage('host', 'port')
STORAGE.store_element(1, 5)

Now the problem arise when I try to mock it in the tests:

import unittest, mock
import server.app as application
class SomeTest(unittest.TestCase):
    # part1
    def setUp(self):
        # part2
        self.app = application.app.test_client()

This clearly does not work during the test, if I can't connect to a storage. So I have to mock it somehow by writing things in 'part1, part2'.

I tried to achieve it with

@mock.patch('server.app.cache')  # part 1
mock.side_effect = ... # hoping to overwriting the init function to do nothing

But it still tries to connect to a real host. So how can I mock a full class here correctly? P.S. I reviewed many many questions which look similar to me, but in vain.

Community
  • 1
  • 1
Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
  • 1
    I believe you need to just `@mock.patch('application.cache')`. – Will Apr 05 '16 at 20:54
  • @Will thanks for your interest in my problem. I tried it, but it fails with an error `No module named application`. – Salvador Dali Apr 05 '16 at 21:00
  • 2
    I think you are looking to mock out something in the global space like [this](http://stackoverflow.com/questions/26668515/python-mocking-global-variable). Because what is happening is that when you import that module, your global will already have that instance. So your mocking is going to be too late. I remember solving this. I would have to dig through some of my code. Try out the link I attached. If it does not work, let me know. – idjaw Apr 05 '16 at 21:37

0 Answers0