2017-09-16 91 views
1

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

我一直在阅读这些文档http://pytest-bdd.readthedocs.io/en/latest/#step-arguments及其说法使用解析器?也许我误解了这些文档,但是我不清楚如何执行下面的操作。也许用户需要在字典中? {'user1':'John','user2':'Peter'}。我明白,在功能文件中使用示例表或步骤表会很好,但在这种情况下,我需要知道如何在后台执行此操作(仅在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 

回答

0

如果你的意思是要与USER1运行一次所有的测试,并再次与USER2,那么你要寻找的是parametrized tests

本质上,你定义你的测试一次。然后,您可以使用一组可选的ID来定义一组元组中的变量,然后pytest将针对每组参数运行一次该测试。

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

addition(a, b): 
    return a + b 

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

,而不是不同的参数遍地定义测试,如:

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

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

可以使用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 

我认为这是一种更容易管理的做事方式。你也可以参数化你的灯具,所以魔术真的很深。

相关问题