我如何多次重复 python PyTest,利用从以前的测试中结转的值
How do I repeat a python PyTest multiple times, utilizing values carried over from the previous test
我正在尝试创建一个测试,其中涉及将数据发送到外部硬件、重新启动该硬件以及断言硬件数据是否与之前发送的数据相匹配。这最终将重复 1000 次。
所以步骤是这样的:
- 查询硬件当前运行 ID(上述数据)
- 比较并断言它仍然与之前发送的 id 相同(或在第一次测试中“id = 1”)
- 创建一个新的 id (
id += 1
),将其保存在某个地方,然后将其发送到硬件。
- 重复。
我的问题是如何在测试之间携带保存的“id”进行比较?我本来打算从 json 中选择 read/write,因为我看到很多人说全局变量不好,但我不确定保存到 json 是最好的选择。
你可以做的一件事是在测试中运行一个for-loop。
def test_hardware():
previous_id = 1
set_hardware_id(1)
for i in range(2, 100):
current_id = get_hardware_id()
# this fill fail at the first mismatch
assert current_id == previous_id
previous_id = current_id
set_hardware_id(i)
如果您想 运行 整个测试 本身重复,请使用 @pytest.mark.parametrize
装饰器。
@pytest.mark.parametrize("test_input", range(100))
def test_hardware(test_input):
set_hardware_id(test_input)
result = get_hardware_id()
assert result == test_input
我正在尝试创建一个测试,其中涉及将数据发送到外部硬件、重新启动该硬件以及断言硬件数据是否与之前发送的数据相匹配。这最终将重复 1000 次。
所以步骤是这样的:
- 查询硬件当前运行 ID(上述数据)
- 比较并断言它仍然与之前发送的 id 相同(或在第一次测试中“id = 1”)
- 创建一个新的 id (
id += 1
),将其保存在某个地方,然后将其发送到硬件。 - 重复。
我的问题是如何在测试之间携带保存的“id”进行比较?我本来打算从 json 中选择 read/write,因为我看到很多人说全局变量不好,但我不确定保存到 json 是最好的选择。
你可以做的一件事是在测试中运行一个for-loop。
def test_hardware():
previous_id = 1
set_hardware_id(1)
for i in range(2, 100):
current_id = get_hardware_id()
# this fill fail at the first mismatch
assert current_id == previous_id
previous_id = current_id
set_hardware_id(i)
如果您想 运行 整个测试 本身重复,请使用 @pytest.mark.parametrize
装饰器。
@pytest.mark.parametrize("test_input", range(100))
def test_hardware(test_input):
set_hardware_id(test_input)
result = get_hardware_id()
assert result == test_input