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?