Cas
Cas

Reputation: 2277

Destroy a mock in Python after the test

Let's say I have a couple of tests like these:

class TestMyTest(unittest.TestCase):

    def SetUpClass(cls):
        cls.my_lib = MyLib()

    def my_first_test(self):
        self.my_lib.my_function = Mock(return_value=True)
        self.assertTrue(self.my_lib.run_my_function(), 'my function failed')

    def my_second_test(self):
        # Some other test that calls self.my_lib.my_function...

And let's say I have something like this in MyLib:

class MyLib(Object):

    def my_function(self):
        # This function does a whole bunch of stuff using an external API
        # ...

    def run_my_function(self):
        result = self.my_function()
        # Does some more stuff
        # ...

In my_first_test I am mocking my_lib.my_function and returning a True when the function is executed. In this example, my assertion is calling run_my_function(), which is another function from the same library that among other things, it calls my_lib.my_function. But when my_second_test is executed I don't want the mocked function to be called but the real one. So I guess I would need to destroy the mock somehow after running my_first_test, maybe during tearDown(). How do I destroy that mock?

I edited my original question to add more details since looks like it was not that clear, sorry about that.

Upvotes: 2

Views: 3969

Answers (2)

Patrick Collins
Patrick Collins

Reputation: 10574

You can do this:

class TestYourLib(unittest.TestCase):

    def setUp(self):
        self.my_lib = MyLib()

    def test_my_first_test(self):
        self.my_lib.my_function = Mock(return_value=True)
        self.assertTrue(self.run_my_function(), 'my function failed')

    def test_my_second_test(self):
        # Some other test that calls self.my_lib.my_function...

Then the Mock is "destroyed" by passing out of scope when setUp is called for the next test case.

Upvotes: 2

Mast
Mast

Reputation: 1884

Destroying the mock won't do it. You'll either have to re-assign self.my_lib.my_function or call Mock(return_value=True) in a different manner.

The first is what Patrick seems to suggest.

Upvotes: 1

Related Questions