我已经在“sample.py”中编写了以下函数,在“test_sample.py”中编写了相应的测试脚本。主要函数roll_dice在名为“dice.py”的模块中。所有这些文件都在名为“myapp”的文件夹中。
场景1
dice.py
import random
def roll_dice():
print("rolling...")
return random.randint(1, 6)
sample.py
from myapp.dice import roll_dice
def guess_number(num):
result = roll_dice()
if result == num:
return "You won!"
else:
return "You lost!"
test_sample.py
@mock.patch("myapp.sample.roll_dice")
def test_guess_number(mock_roll_dice):
mock_roll_dice.return_value = 3
assert guess_number(3) == "You won!"
当我使用 Pytest 运行测试时,它可以正常运行。但是当我对下面的 sample.py 文件进行小改动后,测试失败了: 场景 2 sample.py
from myapp.dice import roll_dice
result = roll_dice() # Here is the change
def guess_number(num):
if result == num:
return "You won!"
else:
return "You lost!"
其余的都不变!
当我在 sample.py 模块的全局作用域中调用函数而不是在另一个函数内部调用它时,测试会失败。 有人能告诉我如何在方案二中模拟 roll_dice 函数吗?
我猜想我们无法在模块的全局作用域中模拟函数调用。这正确吗?