【问题标题】:Passing parameter from WHEN to a THEN将参数从 WHEN 传递给 THEN
【发布时间】:2016-01-10 21:14:38
【问题描述】:

如何在 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 中通常不赞成将事物设为全局变量)。

【问题讨论】:

    标签: python bdd pytest-bdd


    【解决方案1】:

    你不能通过返回来传递从“when”到“then”的任何东西。通常你想避免这种情况。但如果必须,请在两个步骤中使用 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
    

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

    附带说明,测试您的测试不是最理想的 - 您在“何时”部分这样做,断言可分性。但这只是我猜的一些示例代码。

    【讨论】:

      【解决方案2】:

      pytest-bdd version 4.1.0 中,when 步骤现在支持target_fixture,就像given 步骤一样。

      这是来自pytest-bdd documentation的示例

      # test_blog.py
      
      from pytest_bdd import scenarios, given, when, then
      
      from my_app.models import Article
      
      scenarios("blog.feature")
      
      
      @given("there is an article", target_fixture="article")
      def there_is_an_article():
          return Article()
      
      
      @when("I request the "
      "deletion of the article", target_fixture="request_result") # <--- here
      def there_should_be_a_new_article(article, http_client):
          return http_client.delete(f"/articles/{article.uid}")
      
      
      @then("the request should be successful")
      def article_is_published(request_result):
          assert request_result.status_code == 200
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-01
        • 2014-07-13
        • 2015-12-30
        • 2015-10-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多