无法模拟分配给函数调用的全局变量 Python pytest.

huangapple go评论67阅读模式
英文:

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

  1. VAR = some_func() 在导入 app.file2 时会被执行,所以如果要阻止 som_func 的调用,你必须在导入之前进行模拟。
  2. 为了阻止这个函数调用,你必须模拟 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)
英文:
  1. 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.
  2. In order to prevent this function call you have to mock 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)

huangapple
  • 本文由 发表于 2023年1月9日 00:03:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/75049265.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定