英文:
unable to mock global variable assigned to function call python pytest
问题
以下是翻译好的部分:
当我运行我的 pytest 并且使用 mock 来替换一个 python 文件中的全局变量,该变量被赋予了一个函数调用来捕获输出,我无法对其进行模拟(我不希望在测试期间实际执行该函数)。我发现该函数仍然被调用。如何防止它被调用?
文件 1: /app/file1.py
def some_func():
return "天空好像超级蓝"
文件 2: /app/file2.py
from app.file1 import some_func
VAR1 = some_func()
文件 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('测试通过 :)'
print(VAR1)
英文:
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)
答案1
得分: 2
VAR = some_func()
在导入app.file2
时会被执行,所以如果要阻止som_func
的调用,你必须在导入之前进行模拟。- 为了阻止这个函数调用,你必须模拟
some_func
,而不是VAR1
,如下所示:
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('到达我的测试 :)'
print(VAR1)
英文:
VAR = some_func()
will be executed when you importapp.file2
, so you have to mock before importing it if you want to preventsom_func
call.- In order to prevent this function call you have to mock
some_func
, notVAR1
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论