其他分享
首页 > 其他分享> > 传递参数从WHEN到THEN

传递参数从WHEN到THEN

作者:互联网

如何在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中通常不赞成将其设置为全局).

解决方法:

您无法通过返回将任何内容从“何时”传递到“然后”.通常,您想避免这种情况.但是,如果需要,请在两个步骤中将pytest固定装置用作消息框:

@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

“上下文”固定装置的结果传递到“时间”步骤,进行填充,然后传递到“然后”部分.它不会每次都重新创建.

附带说明一下,测试您的测试不是最佳选择-您在“何时”部分中进行了可除性声明.但这只是一些示例代码.

标签:pytest,bdd,python
来源: https://codeday.me/bug/20191119/2034253.html