I have a fixture pretest() like the example below which is intended to be called before every test case. I understand that this fixture is run before running the test case code.
Is there any way to get a value from the test case function so that I can use it inside the fixture?
For example, I need to read json_name defined in the test case and print it inside the pretest fixture before running the test case.
@pytest.fixture(autouse=True)
def pretest(request):
tc_name = request.node.name
json_name = # ==> how can i get this parameter or value from testcase and use here ?
yield
def test_case_EVA_01():
json_name = file1.json
def test_case_EVA_02():
json_name = file2.json
You seem to be collecting info about each test case to make a test report.
You can use pytest's
record_propertyfixture to store arbitrary information from each test case, which then becomes available as part of the test'suser_properties:First, modify the fixture to make it a
yield fixture, so that control first starts with the fixture, then passes it to the test function, and then finally back to the fixture. Next, in each test function, call therecord_propertyfixture to store thejson_namevalue using"json_name"as its key. Finally, when control comes back to the fixture (i.e. afteryield), you can now access thejson_namevalue fromuser_properties, which is a list of tuples where each tuple is the same key-value you passed torecord_property.Running the tests and turning on
-rPto output andprint's:Now, I don't know your exact use case, but if you really are doing this to make a report, I think an
autousefixture isn't the most appropriate solution. Instead, it's much better to use one of pytest'spytest_runtest_protocolhooks, specifically thepytest_runtest_makereporthook when it's called onreport.when=="teardown".There are quite a number of pytest plugins that make use of this hook for generating reports of different formats, but to keep this answer simple, let's just override the hook so that it creates a simple text file listing the test IDs and the JSON names.
If you add this to conftest.py:
Then run the tests:
The report should contain: