我正在尝试创建一种结构,在该结构中,用户在运行pytest时会提供命令行选项值,并且在内部使用conftest.py文件中的该值来确定测试应使用哪些数据。
我的conftest.py文件位于测试根文件夹中。我试图提取用户提供的命令行值,并将其传递给测试使用的固定装置。
conftest.py:
import json
import pytest
from src.Utils.TestUtils import TestUtils
post_body = TestUtils.get_json_data_from_file('PositiveSets.json')
post_body = json.loads(post_body)
testType = ''
def pytest_addoption(parser):
parser.addoption(
"--cmdopt", action="store", default="regression", help="my option: smoke or regression"
)
@pytest.fixture
def cmdopt(request):
return request.config.getoption("--cmdopt")
# @pytest.mark.usefixtures('cmdopt')
def test_answer(cmdopt):
if cmdopt == "smoke":
return testType == "smoke"
elif cmdopt == "regression":
return testType == "regression"
# testType still has empty string as its value
@pytest.fixture(scope='class', params=post_body['sets_data'][testType])
def TCM_data(request):
return request.param
test.py:
@pytest.mark.usefixtures('TCM_data')
@pytest.fixture(params=response_body["status_code"])
def TCM_response(request):
return request.param
def test_tcm_1(TCM_data):
global post_body
global setId
post_data = json.dumps(TCM_data)
response = tcm.post_TCM_enrollment(post_data)
assert_valid_schema(response.text, "ValidationSchema.json")
问题是我没有在conftest.py文件中看到用户通过命令行传递的值,因为testType变量仍然具有空字符串值。非常感谢您的帮助。
答案 0 :(得分:0)
我认为这是您的情况:How to read/process command line arguments?
示例:
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument("-f", "--file", dest="filename", help="write report to FILE", metavar="FILE")
parser.add_argument("-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print status messages to stdout")
args = parser.parse_args()
答案 1 :(得分:0)
我使用simple-settings插件通过命令行传递了夹具中的值。因为如果将夹具写入conftest.py文件中,则pytest_generate_tests无法传递值。