为 pytest bdd 设置和拆除函数
Set up and tear down functions for pytest bdd
我正在尝试使用 pytest-bdd 进行设置和拆卸模块。
我知道使用 behave 你可以用 before_all 和 after_all 模块做一个 environment.py 文件。我如何在 pytest-bdd
中执行此操作
我查看了 "classic xunit-style setup" 插件,但在我尝试时没有用。 (我知道这与 py-test 而不是 py-test bdd 更相关)。
您可以只声明一个 pytest.fixture
和 autouse=true
以及您想要的任何范围。然后,您可以使用 request
fixture 来指定拆解。例如:
@pytest.fixture(autouse=True, scope='module')
def setup(request):
# Setup code
def fin():
# Teardown code
request.addfinalizer(fin)
对我来说 simple-ish 方法是使用一个普通的固定装置。
# 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 允许您在代码之间共享固定装置,将所有内容放在一个文件中无论如何都会给我静态分析警告。
"pytest supports execution of fixture specific finalization code when the fixture goes out of scope. By using a yield statement instead of return, all the code after the yield statement serves as the teardown code:"
参见:https://docs.pytest.org/en/latest/fixture.html
例如
@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()
我正在尝试使用 pytest-bdd 进行设置和拆卸模块。 我知道使用 behave 你可以用 before_all 和 after_all 模块做一个 environment.py 文件。我如何在 pytest-bdd
中执行此操作我查看了 "classic xunit-style setup" 插件,但在我尝试时没有用。 (我知道这与 py-test 而不是 py-test bdd 更相关)。
您可以只声明一个 pytest.fixture
和 autouse=true
以及您想要的任何范围。然后,您可以使用 request
fixture 来指定拆解。例如:
@pytest.fixture(autouse=True, scope='module')
def setup(request):
# Setup code
def fin():
# Teardown code
request.addfinalizer(fin)
对我来说 simple-ish 方法是使用一个普通的固定装置。
# 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 允许您在代码之间共享固定装置,将所有内容放在一个文件中无论如何都会给我静态分析警告。
"pytest supports execution of fixture specific finalization code when the fixture goes out of scope. By using a yield statement instead of return, all the code after the yield statement serves as the teardown code:"
参见:https://docs.pytest.org/en/latest/fixture.html
例如
@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()