关于python:为pytest bdd设置和拆除函数

Set up and tear down functions for pytest bdd

我正在尝试使用pytest-bdd进行设置和拆卸模块。我知道您可以使用before_all和after_all模块创建一个environment.py文件。我如何在pytest-bdd

中执行此操作,我研究了\\\\"经典的xunit-style setup \\\\"插件,但是在尝试时它没有起作用。 (我知道那与py-test更相关,而不是py-test bdd)。


对我来说,一种简单的方法是使用琐碎的夹具。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# This declaration can go in the project's confest.py:
@pytest.fixture
def context():
    class Context(object):
        pass

    return Context()

@given('some given step')
def some_when_step(context):
    context.uut = ...

@when('some when step')
def some_when_step(context):
    context.result = context.uut...

注意:confest.py允许您在代码之间共享夹具,并将所有内容放在一个文件中可以进行静态分析。反正警告。


您可以只用autouse=true和所需的任何范围声明一个pytest.fixture。然后,您可以使用request固定装置指定拆解。例如:

1
2
3
4
5
6
7
8
9
@pytest.fixture(autouse=True, scope='module')
def setup(request):

    # Setup code

    def fin():
        # Teardown code

    request.addfinalizer(fin)


\\\\" pytest支持在夹具超出范围时执行夹具特定的终结代码。通过使用yield语句而不是return,yield语句之后的所有代码均用作拆卸代码:\\\\"

请参阅:https://docs.pytest.org/en/latest/fixture.html

例如

1
2
3
4
5
6
    @pytest.fixture(scope="module")
def smtp_connection():
    smtp_connection = smtplib.SMTP("smtp.gmail.com", 587, timeout=5)
    yield smtp_connection  # provide the fixture value
    print("teardown smtp")
    smtp_connection.close()