简体   繁体   中英

How to pass command line option value within conftest.py file in pytest

I am trying to create a structure where a user gives command line option value while running pytest and internally I use that value inside conftest.py file to decide with which data the tests should run.

My conftest.py file is inside the test root folder.I am trying to extract the command line value given by user and pass it on to the fixtures which in turn is used by the tests.

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")

Issue is I am not seeing the value that the user passes via command line being used in conftest.py file as the testType variable still has the empty string value. Any help is much appreciated.

I think this is your case: How to read/process command line arguments?

Example:

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()

I used simple-settings plugin to pass the values in fixtures via command line. As pytest_generate_tests was not able to pass the values if the fixtures are written inside conftest.py file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM