我有几个用 pytest 编写的测试文件:
test_foo.py :
class TestFoo:
def test_foo_one(self, current_locale):
# some actions with locale
# assert
def test_foo_two(self, current_locale):
# some actions with locale
# assert
test_bar.py :
class TestBar:
def test_bar_one(self, current_locale):
# some actions with locale
# assert
def test_bar_two(self, current_locale):
# some actions with locale
# assert
和 conftest.py :
locales = ["da-DK", "de-DE", "en-GB", "en-US", "es-AR", "es-CO", "es-ES", "es-MX", "fi-FI"]
def pytest_generate_tests(metafunc):
metafunc.parametrize('current_locale', locales, scope='session')
它允许为每个语言环境运行测试。
现在,我想创建一个我不需要语言环境的测试,它必须只运行一次。 的 test_without_locales.py :
class TestNoLocales:
def test_no_locales(self):
# some actions with locale
# assert
它引发了一个错误: ValueError:不使用参数' current_locale'
如何在不使用current_locales的情况下编写测试?
答案 0 :(得分:6)
You're just missing a check for the fixtures included in each test case.
locales = ["da-DK", "de-DE", "en-GB", "en-US", "es-AR", "es-CO", "es-ES", "es-MX", "fi-FI"]
def pytest_generate_tests(metafunc):
if 'current_locale' in metafunc.fixturenames:
metafunc.parametrize('current_locale', locales, scope='session')
或者你可以通过这样做使它更加光滑:
params = {"current_locale": ["da-DK", "de-DE", "en-GB", "en-US", "es-AR", "es-CO", "es-ES", "es-MX", "fi-FI"]}
def pytest_generate_tests(metafunc):
for k,v in params:
if k in metafunc.fixturenames:
metafunc.parametrize(k, v, scope='session')
这是有效的,因为pytest按顺序加载每个夹具,所以你可以逐个注入它们(如果你有多个param,那就是)
至于排除测试的运行,@ pytest.mark.skip()装饰器适合你。