Pytest如何在step参数中使用内联变量?

2024-04-25 01:17:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一些pytest测试文件,这些文件附加到没有示例或步骤表的功能文件中。我不明白的是如何使用内联变量(USER1和USER2),它们是给定的、When和Then步骤中的字符串(下面简单的When示例)以便第一次执行“When”步骤时使用John,第二次使用“When”步骤时使用Peter。在

我一直在读这些文档http://pytest-bdd.readthedocs.io/en/latest/#step-arguments以及它说的使用解析器?也许我误解了文件,但我不太清楚我该如何做下面的事情。也许用户需要在dict中?{'user1':'John','user2':'Peter'}。我知道在特性文件中使用examples表或steps表会很好,但是在这种情况下,我需要知道如何在后台(仅在pytest文件中)这样做。在

提前谢谢大家

USER1 = 'John'
USER2 = 'Peter'

@scenario('User logs in')
def test_user_logs_in():
    """User logs in to website."""
    pass

@given('I go to a website')
def I_go_to_a_website():
   Do something

@When('{user} logs in')
def user_logs_in(user):
   Do something with user1 the first time this step is used
   Do something with user2 the second time this step is used.

@then('I should see the account page')
def should_see_account_page():
   Do something

Tags: 文件toinpytestdefstep步骤website
1条回答
网友
1楼 · 发布于 2024-04-25 01:17:12

如果您想用USER1运行所有测试,然后用USER2运行一次,那么您需要的是parametrized tests。在

本质上,定义测试一次。然后用一组可选的id在元组中定义一组变量,pytest将对每组参数运行一次该测试。在

让我们举一个基本的例子。在

addition(a, b):
    return a + b

def test_addition(a, b, expected):
    assert addition(a, b) == expected

而不是用不同的参数反复定义测试,比如:

^{pr2}$

您可以使用pytest.mark.parametrize修饰符:

import pytest

@pytest.mark.parametrize('a, b, expected', ((2, 2, 4), (-2, -2, -4)))
def test_addition(a, b, expected):
    assert addition(a, b) == expected

运行此测试时,将看到以下输出。在

$ pytest -v test_addition.py
====================================== test session starts =======================================
platform linux   Python 3.6.2, pytest-3.2.2, py-1.4.34, pluggy-0.4.0   /home/stackoverflow
cachedir: .cache
rootdir: /home/stackoverflow, inifile:
collected 2 items                                                                                 

test_addition.py::test_addition[2-2-4] PASSED
test_addition.py::test_addition[-2 2 4] PASSED

==================================== 2 passed in 0.01 seconds ====================================

所以,回到你的问题上,你想做这样的事情:

import pytest

USER1 = 'John'
USER2 = 'Peter'

@pytest.mark.parametrize('user', ((USER1), (USER2)))
def test_something(user):
    # Do something with ``user``
    # Test runs twice - once with USER1, once with USER2
    pass

如果您的列表很长,最好使用fixture。在

users_to_test = {
    'params': ((USER1), (USER2)),
    'ids': ['test first user', 'test second user']
}

@pytest.fixture(**users_to_test, scope='function')
def params_for_test_something(request):
    return request.param

def test_something(params_for_test_something):
    user = params_for_test_something[0]
    pass

我认为这是一种更容易管理的做事方式。你也可以参数化你的固定装置,这样魔法就非常深入了。在

相关问题 更多 >