【发布时间】:2021-06-26 15:37:39
【问题描述】:
我在“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 模块的全局范围内调用它时,测试失败,而不是在另一个函数内部调用函数。谁能告诉我如何模拟场景 2 中的 roll_dice 函数?
我的猜测是我们不能在模块的全局范围内模拟函数调用。对吗?
【问题讨论】:
标签: python unit-testing testing pytest