Reputation: 209
I have a package A using a function in a package B.
A is running a function c imported from B:
#B code
def c():
# code that can't be executed during tests
#A code
from B import c
c()
#c is executed every time A is imported
Now, i need to monkeypatch c during the unites tests. The problem I am facing with monkey patch is that package A is imported when I run the following code:
def test(monkeypatch):
monkeypatch.setattr("A.c", lambda x: "dummy")
How can I do that without modifying package A's code. I thought about adding an environment variable in code A to detect test mode. The idea is to not call function c during test mode. Unfortunately, this is not a clean solution at all.
Upvotes: 0
Views: 720
Reputation: 2159
A module is only loaded during the first import at runtime.
To mitigate your issue, you can first import module B
and monkeypatch c()
before importing A
.
import B
B.c = lambda: print("monkeypatched")
import A
Upvotes: 1