Is there a way to suppress `unrecognized argument` errors in pytest?

Viewed 26

I have a script that loops through a number of projects and executes pytest ${project} --foo 123. I need to change the option from foo to bar. I would like to change the script to pytest ${project} --foo 123 --bar 123, give teams time to switch from using foo to bar, and then remove --foo 123. Is there a way to accomplish that?

1 Answers

For that, you may want to use a pytest.ini file at the root folder where you run pytest. (More info: https://pytest.org/en/latest/reference/customize.html)

Inside the pytes.ini file, you may have something like this:

[pytest]                                                                                   
                                                                                           
# Display console output and disable cacheprovider:
addopts = --capture=no -p no:cacheprovider

The pytest.ini file lets you specify args for all tests run with pytest so that you don't have to directly specify those in your run commands.

For your case, it may look like this initially:

[pytest]                                                                                   

addopts = --foo 123 --bar 123

Then you can swap out things as needed. To modify your existing scripts that have foo_abc in them, (and replace with bar_abc), you could use the following script (example for Linux):

Replace all occurrences of "foo_abc" with "bar_xyz" on Linux, for Python files from the current directory:

sed -i 's/foo_abc/bar_xyz/g' *.py

(Other operating systems may have a slight variation on the optimal string replacement command.)


To avoid errors if you haven't yet declared --bar, you could create a temporary arg in a conftest.py file. (Reference: https://docs.pytest.org/en/latest/example/simple.html)

def pytest_addoption(parser):
    parser.addoption(
        "--bar", action="store", dest="bar_var", default=None
    )

And then remove that placeholder when you've actually defined the --bar arg.

Related