1

I am trying to mock the beginning of the file of the module dog.py. It seems that the patch method does not work at the import time but it works at later invocations.

test.py

import unittest
from unittest.mock import patch

class TestMethods(unittest.TestCase):
    @patch('dog.Cat')
    def test_1(self, cat_mock):
        from dog import Dog
        dog = Dog("a dog")

dog.py

from cat import Cat

cat = Cat('kitty')
class Dog:

    def __init__(self, name):
        self.name = name

cat.py

class Cat:

    def __init__(self, name):
         pass

When "from dog import Dog" is called, Cat is not the mock but the real class. However, when "dog = Dog("a dog")" is called, the Cat is the mock.

Why Cat is not the mock when the module is imported?

poiuytrez
  • 21,330
  • 35
  • 113
  • 172
  • 1
    Because patching is done after the entity-to-patch is imported? Patching will not effect the code executed on module import. If you want `Cat` to be mocked when the line `cat = Cat('kitty')` is executed, patching `cat.Cat` should help. – hoefling Aug 18 '18 at 10:26
  • It works! However, I don't understand why. – poiuytrez Aug 20 '18 at 12:22

0 Answers0