gpt4 book ai didi

python - 将参数从 WHEN 传递给 THEN

转载 作者:太空宇宙 更新时间:2023-11-03 11:00:03 26 4
gpt4 key购买 nike

如何在 pytest bdd 中将参数从 WHEN 传递到 THEN?
例如,如果我有以下代码:

@when('<n1> is a number divisible by 10')
def n1_is_a_number_divisible_by_10(n1):
assert (n1 % 10) == 0
newN1 = n1/10
return newN1

@then('the result will also be divisible by 3')
def the_result_will_also_be_divisible_by_3(newN1):
assert newN1 % 3 == 0

如何将 newN1 从 when 传递到 then?

(我试过让 newN1 成为一个全局变量……这行得通,但是在 python 中,让事物成为全局变量通常是不受欢迎的)。

最佳答案

你不能通过返回来传递从“when”到“then”的任何东西。通常你想避免这种情况。但是,如果必须,请在这两个步骤中使用 pytest fixture 作为消息框:

@pytest.fixture(scope='function')
def context():
return {}

@when('<n1> is a number divisible by 10')
def n1_is_a_number_divisible_by_10(n1, context):
assert (n1 % 10) == 0
newN1 = n1 / 10
context['partial_result'] = newN1

@then('the result will also be divisible by 3')
def the_result_will_also_be_divisible_by_3(context):
assert context['partial_result'] % 3 == 0

“context”夹具的结果被传递到“when”步骤,填充,然后传递到“then”部分。它不是每次都重新创建。

作为旁注,测试您的测试不是最佳选择 - 您在“何时”部分这样做,断言可分性。但这只是我猜的一些示例代码。

关于python - 将参数从 WHEN 传递给 THEN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34710832/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com