What Is Pytest Addoption?
When you’re dealing with intricate code that operates in multiple modes or necessitates user input, it’s helpful to provide users with options, often referred to as CLI arguments or flags.
Believe it or not, it’s simpler than you might imagine, thanks to the pytest.addoption
feature.
def pytest_addoption(parser):
parser.addoption("--custom-option", action="store", default="default_value", help="Description of the custom option.")
The pytest addoption feature is a powerful tool that allows you to dynamically tailor your test behavior, giving you the flexibility to build a more efficient, adaptable, and easily maintainable test suite.
How To Use Pytest Addoption?
Now let’s use the pytest addoption
feature to write some tests.
Step 1: Create a file named conftest.py
in the same directory as your tests. This file will hold all the options for your test.
Step 2: Now inside your conftest.py
file, create options for the command line like the below,
Step 3: Now, access the custom option value in your test functions by using the request
fixture:
In the above function request.config.getoption
is used to retrieve the value of the --custom-option
command line option.
Step 4: After you have done all the previous steps correctly and successfully, you can now run your test like the below,
pytest --custom-option=new_value