我正在使用Pytest和Pytest-variables与parametrized test functions一起尝试减少测试用例中的代码重复。我在测试模块中使用硬编码字符串:类似于this;但是,我不知道如何从函数范围之外的变量文件中导入变量。非常感谢任何帮助,我理解使用pytest-variables可能无法做到这一点,但我想在这里发帖以确保我没有错过任何东西。
工作代码
import pytest
account_email_field = [
['test@google.com', 'Site Title', True],
['', '', False ],
['test@google.com', '', False ],
['', 'Default Title', False]
]
@pytest.fixture(params=account_email_field)
def email_field(request):
return [request.param[0], request.param[1], request.param[2]]
def test_sample_spage(email_field):
return [email_field[0], email_field[1], email_field[2]]
没有正常工作的代码,而是我想要的一个例子。
import pytest
account_email_field = [
[variables['sample_email'], variables['site_title'], True],
[variables['empty'], variables['empty'], False ],
[variables['sample_email'], variables['empty'], False ],
[variables['empty'], variables['site_title'], False]
]
@pytest.fixture(params=account_email_field)
def email_field(request):
return [request.param[0], request.param[1], request.param[2]]
def test_sample_spage(email_field):
return [email_field[0], email_field[1], email_field[2]]
答案 0 :(得分:0)
我会使用静态类进行查找而不是字典,因为它更适合IDE。在文件constants.py
(或其他名称)
class variables:
sample_email = 'test@google.com'
site_title = 'Site Title'
empty = ''
然后在测试文件中
from constants import variables as var
account_email_field = [
[var.sample_email, var.site_title, True ],
[var.empty, var.empty, False ],
[var.sample_email, var.empty, False ],
[var.empty, var.site_title, False ],
]
希望这有帮助!
答案 1 :(得分:0)
pytest-variables插件将变量存储在config对象中,因此您可以从pytest_generate_tests
钩子中访问它。
给出以下variables.json文件:
{
"data": [
["test@google.com", "Site Title", true],
["", "Default Title", false]
]
}
使用以下test_param_vars.py文件:
def pytest_generate_tests(metafunc):
if 'data' in metafunc.fixturenames:
metafunc.parametrize('data', metafunc.config._variables['data'])
def test_variables(data):
assert data[0]
您的输出应该类似于:
$ pytest test_param_variables.py --variables=variables.json -ra -s
======================= test session starts ========================
platform darwin -- Python 3.6.4, pytest-3.4.2, py-1.5.2, pluggy-0.6.0
rootdir: /Users/dhunt/workspace/pytest-scratchpad, inifile:
plugins: variables-1.7.1
collected 2 items
test_param_variables.py .F
===================== short test summary info ======================
FAIL test_param_variables.py::test_variables[data1]
============================= FAILURES =============================
______________________ test_variables[data1] _______________________
data = ['', 'Default Title', False]
def test_variables(data):
> assert data[0]
E AssertionError: assert ''
test_param_variables.py:6: AssertionError
================ 1 failed, 1 passed in 0.04 seconds ================