0

I want to access my custom command line options before any test processed in order to get the input and output path of the files that need to be tested.

# content of conftest.py
import pytest
from pathlib import Path

def pytest_addoption(parser):
    parser.addoption("--inpath", type=Path, action="store", help="Test case input")
    parser.addoption("--anticipated_outpath", type=Path, action="store", help="Anticipated output")
# content of test_unit.py
import pytest
from pytest import mark

@pytest.fixture(autouse=True)
def add_custom_config(request):
    config = request.config
    global inpath
    inpath = config.getoption('--inpath', default="testfolder/test1.txt")
    global anticipated_outpath
    anticipated_outpath = config.getoption('--anticipated_outpath', default="expected_test1_output.txt")

in_file = open(inpath,'r')
actual_output_total = in_file.read().split('\n')
expected_output_file = open(anticipated_outpath,'r')
expected_output_total = expected_output_file.read().split('\n')

def test_unit_test1():
    actual_output = actual_output_total[1:3]
    expected_output = expected_output_total[0:2]
    assert actual_output == expected_output

When I invoke test file test_unit.py with:

pytest -v --inpath=testfolder/test1.txt

Get the following error:

E   NameError: name 'inpath' is not defined

So how can I process my command line options outside of tests?

EDIT - please re-open the question: Suggested answer does not solve my problem, because that command line option is processed inside a test and the point of my question is how to process command line options outside of a test:

def test_print_name(name):
    print ("Displaying name: %s" % name)
macuko
  • 1
  • 1

1 Answers1

0

You're getting NameError because you're trying to access a global variable that does not exist.

Creating your two variables in the global scope before your function will solve that particular exception.

import pytest
from pytest import mark

inpath, anticipated_outpath = None, None 

@pytest.fixture(autouse=True)
def add_custom_config(request):
    # Rest of code
Teejay Bruno
  • 1,716
  • 1
  • 4
  • 11
  • Yes, that's true so thanks! But it does not solve my original problem. Variables `inpath` and `anticipated_outpath` will be None in this case, instead of getting the values from command line options. – macuko May 25 '22 at 16:11
  • @macuko The `default` arg should be part of `addoption`, not `getoption`. But regardless your block of code in between the fixture and function will not get executed in the order I think you expect. I recommend reading more about the concept of pytest hooks/fixtures. – Teejay Bruno May 25 '22 at 16:47
  • Thanks, I will check the suggested topics from the documentation. – macuko May 25 '22 at 21:36