When I run my pytest and mock patch a global variable in the python file that has a function call assigned to capture the output, I'm unable to mock it (I dont want to actually execute the function during tests). I find that the function is still getting called. How can I prevent it from being called?
file 1: /app/file1.py
def some_func():
return "the sky is like super blue"
file 2: /app/file2.py
from app.file1 import some_func
VAR1 = some_func()
file 3: /tests/app/test_file2.py
import mock
import pytest
from app.file2 import VAR1
@mock.patch('app.file2.VAR1', return_value=None)
def test_file_2_func(baba_fake_val):
print('made it to my test :)'
print(VAR1)
VAR = some_func()
will be executed when you import app.file2
, so you have to mock before importing it if you want to prevent som_func
call. some_func
, not VAR1
like this:import mock
import pytest
import app.file1
@mock.patch('app.file1.some_func', return_value=None)
def test_file_2_func(baba_fake_val):
from app.file2 import VAR1
print('made it to my test :)'
print(VAR1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.