1

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.

hoefling
  • 59,418
  • 12
  • 147
  • 194
lfc1988
  • 67
  • 1
  • 8
  • The decorators are evaluated at module import, `pytest_addoption` is executed a lot later. With parametrized tests, the way to solve this is by implementing a custom `pytest_generate_tests` hook ([docs](https://docs.pytest.org/en/latest/parametrize.html#basic-pytest-generate-tests-example)); not sure if it can be solved with parametrized fixtures, though. – hoefling Jun 18 '19 at 19:06

2 Answers2

0

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

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.

lfc1988
  • 67
  • 1
  • 8