'How to mock imported variable for file that is imported in __init__.py
I have the following files:
module/MyClass.py
from X import Y
class MyClass:
def do_things():
#does things with Y
module/__init__.py
from .MyClass import MyClass
test.py
def test_myclass():
with patch('module.MyClass.Y', 'mocked value'):
MyClass.do_things()
I find that it is impossible to mock the value of Y in this situation. When I try to mock Y, I get the error:
AttributeError: <class 'module.MyClass.MyClass'> does not have the attribute 'Y'
Which makes somewhat sense
As a workaround I have created a method in MyClass:
from X import Y
class MyClass:
def get_Y():
return Y
def do_things():
#does things with get_Y()
I can mock this method. But it feels clunky to have to create a method just for mocking in production code. Is there a better solution that I am not seeing?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
