mardi 5 avril 2016

Can't mock the class method in python

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.

Aucun commentaire:

Enregistrer un commentaire