How to use pytest_addoption

On This Page What is Pytest Addoption?Syntax for pytest addoption

June 25, 2026 · 12 min read · Testing Guide

How to use pytest_addoption

In Python, command-line arguments can be used to add or change a program & # 8217; s runtime doings. Passing the command-line arguments at runtime gives users the flexibility to monitor their program & # 8217; s runtime behavior and desired yield. One can do this by using the argparse/ measure stimulus library in Python.

Now the head arises of how to continue this functionality to pytest?

pytest is a powerful, pliable, and widely habituate testing framework for Python. It is project to create testing bare and efficient, providing developers with tools to write, organize, and execute tests for their Python codification.

What is Pytest Addoption?

The pytest espousal characteristic lead the flexibility of command-line arguments in pytest by dynamically passing them to unit trial. This feature allows you to define custom command line arguments for test.

For example, a login page requires multiple logins with different usernames and parole to prove functionalities for different user levels. In this case, one can surpass the usernames and passwords as command-line arguments using pytest adoption.

This is a simple example, but this feature can be habituate to care many complex covering that control in multiple modes and command user input. These are concern to as CLI commands or flag.

Also Read:

Syntax for pytest addoption

Here is the code snippet for pytest addoption & # 8211;

def pytest_addoption (parser): parser.addoption (“ -- all ”, action= ” store_true ”, nonremittal = “ nonremittal value ” help= ” run all combination ”)

Here is an account of what each parameter means & # 8211;

  • action& # 8211; indicates what action need to be guide as a afford value. This argument takes any of the below values.
ParameterDescription
store(Default) Stores the selection argument as twine
store_true(Boolean option) Sets the options value to True.
store _false(Boolean option) Sets the options value to True.
store_constStores a constant value
countCounts the number of times the option is qualify in command line
appendAppends argument to list
append_constAppends constant values to a inclination
  • default& # 8211; Default value that will be use if no value is provided.
  • help& # 8211; Helpful description of what the activeness does.

Why should you use Pytest Addoption?

Pytest addoption is a powerful tool that helps to tailor your test behavior dynamically.

Here are a few reward of using Pytest Addoption & # 8211;

1. Flexibility in Test Configuration:Pytest ’ s espousal can aid define custom command-line pick that can dynamically set to the behavior of your test cortege.

For example & # 8211;

  • Running tests across different test environments (e.g.Staging, Prod etc)
  • Passing credentials or API key for Integration test
# conftest.py def pytest_addoption (parser): parser.addoption (`` -- env '', action= '' store '', default= '' dev '', help= '' Environment to run trial against '') pytest -- env=staging

2. Dynamically Control Test Execution:Using custom options in Addoption, one can & # 8211;

  • Enable or disable specific tests
  • Pass runtime parameter that controls exam logic (e.g.Timeouts, Feature Flags)
def pytest_addoption (parser): parser.addoption (`` -- feature-flag '', action= '' store_true '', help= '' Enable feature iris '') def test_example (request): if request.config.getoption (`` -- feature-flag ''): assert True # Feature masthead enabled logic else: assert False # Feature flag incapacitate logic

3. Reusability Across Tests:The options that are bestow through pytest addoption are globally available making them reclaimable across all tests in the tryout suite. This simplifies the codification fundament and avoids duplication of code.

def pytest_addoption (parser): parser.addoption (`` -- db-uri '', action= '' store '', help= '' Database connection thread '') @ pytest.fixture def db_uri (request): return request.config.getoption (`` -- db-uri '') def test_database_connection (db_uri): assert db_uri == `` postgres: //user: word @ localhost/db '' # do pytest -- db-uri= '' postgres: //user: password @ localhost/db ''

4. Seamless Integration with:Command-line options can be defined that employment well with.

  • Pass configurations dynamically
  • Toggle feature or behaviours free-base on deployment stages.
pytest -- env=ci -- timeout=10

5. Improved Scalability:Addoption help to manage complexness by centralising configuration logic.This way it helps to reduce hardcoding in exam scripts by passing value at runtime and also use the same handwriting for different setups without modification.

6: Enhanced Debugging and Logging:With Addoption one can control debugging point or logging verbosity directly from the command line:

def pytest_addoption (parser): parser.addoption (`` -- debug '', action= '' store_true '', help= '' Enable debugging output '') def test_debugging (asking): if request.config.getoption (`` -- debug ''): print (`` Debugging mode enabled '')

Also Read:

What are the Similarities between Argparse and Pytest Adoption?

Argparse and Pytest Addoption aim to manage command-line arguments passed to handwriting or commands at runtime. Both of them accept user remark at runtime. They let you delimit options and retrieve their value at runtime.

With Argparse:

import argparse parser = argparse.ArgumentParser () parser.add_argument (`` -- option '', help= '' An example arguing '') args = parser.parse_args () print (args.option)

With Addoption:

# conftest.py def pytest_addoption (parser): parser.addoption (`` -- option '', help= '' An example argument '') # test_example.py def test_example (petition): option_value = request.config.getoption (`` -- option '') print (option_value)

Both allow you to define custom options with similar contour:

  • Option names (e.g., & # 8211; flag, & # 8211; env)
  • Default values
  • Help descriptions
  • Action types (e.g., store a value, store a boolean flag)

With Argparse:

parser.add_argument (`` -- debug '', action= '' store_true '', help= '' Enable debugging mode '')

With Addoption:

def pytest_addoption (parser): parser.addoption (`` -- debug '', action= '' store_true '', help= '' Enable debugging mode '')

Both support default values for options if no value is provide at runtime.

With Argparse:

parser.add_argument (`` -- env '', default= '' development '', help= '' Environment name '')

With Addoption:

def pytest_addoption (parser): parser.addoption (`` -- env '', default= '' development '', help= '' Environment name '')

Now, how do you decide which one to use when both proffer the like features? Here is the reply.

Also Read:

When to use Argparse?

Argparse is the right choice when you are working with a general-purpose Python script that accepts command-line arguments. It can be used for standalone scripts, command-line puppet, or when your playscript & # 8217; s primary purpose is not related to running tests and there is no dependency on a testing framework.

When to use Addoption?

pytest addoption is the right choice when you need to customize the behavior of a pytest test suite by adding command-line selection.

Prerequisites for expend pytest_addoption

To efficaciously usepytest_addoption, you need a canonical discernment of the pytest framework and some specific setup steps.

Here & # 8217; s a list of prerequisites for habituate pytest_addoption:

Step 1.Install Python: Python (Version: 3.11+)

Step 2.Install pytest: pip install pytest

For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users.

Verify after Installation

pytest & # 8211; version

Step 3.Creating a conftest.py File: pytest_addoption hooks need to be place in a conftest.py file, which acts as a contour file for pytest. This file must be:

  • In the radical directory of your test suite or a subdirectory containing tests.
  • Named conftest.py (it ’ s automatically recognized by pytest).

Example of stem directory & # 8211;
project/

├── tests/
│ ├── conftest.py
│ ├── test_example.py

Step 4.Familiarity with Pytest Hooks

Hooks in Pytest: pytest_addoption is a hook mapping in pytest.

One should understand what hook are (Functions that allow you to customise or extend pytest) and how to specify and use hooks in conftest.py.

Step 5.Basic Syntax of pytest_addoption

One should know how to:

  • Use the parser target to add options.
  • Define assign like activity, nonpayment, help, and type for options.
  • Access the added choice expend request.config.getoption.
def pytest_addoption (parser): parser.addoption ('' -- env '', action= '' store '', default= '' dev '', help= '' Specify the environment to run test '')

How to use Pytest Addoption?

Using pytest addoption involves defining and access custom command-line options in your tests. This allows you to dynamically modify test behaviour or pass extra argument to the test suite.

Below is a step-by-step guide:

1. Define a conftest.py file:The pytest adoption hook must be delimitate in the conftest.py file which serve as a configuration file for pytest.

project/

├── tests/
│ ├── conftest.py
│ ├── test_example.py

2. Implement pytest_addoption in conftest.py:The pytest_addoption hook specify custom command-line options. Create command line options like below-

# conftest.py def pytest_addoption (parser): parser.addoption (`` -- env '', # The tradition pick action= '' store '', # Stores the value provided default= '' dev '', # Default value if not supply help= '' Specify the surround: dev, represent, or prod '' # Help description)

3. Access the Custom Option in Tests using the request fixture:You can access the value of a impost option using request.config.getoption. Use the usance option in the test:

Example & # 8211; use the “ –env “ pick make in above step

def test_environment (asking): env = request.config.getoption (“ -- env ”) assert env in [“ dev ”, “ arrange ”, “ prod ”], f ” Invalid environment: {env} ” print (f ” Running tests in the {env} environment. ”)

4. Run the Tests with the Custom Option:Use the custom command-line option when running pytest:

pytest -- env=staging pytest -- env=prod pytest # Uses the nonpayment value (` dev ` in this case)

Example Use Case: Toggle a Feature Flag

You can define a boolean option (e.g., & # 8211; feature-flag) to toggle features.

# conftest.py def pytest_addoption (parser): parser.addoption (`` -- feature-flag '', action= '' store_true '', help= '' Enable the characteristic fleur-de-lis '') # test_example.py def test_feature_flag (request): feature_flag = request.config.getoption (`` -- feature-flag '') if feature_flag: print (`` Feature flag is enabled! '') asseverate True else: print (`` Feature iris is disabled! '') assert False

Run :

pytest & # 8211; feature-flag

pytest # Feature iris remains handicapped

Common number when using pytest_addoption

Using pytest_addoption can sometimes lead to subject, especially for those new to pytest or working with complex examination setups.

Below are common issues you might see along with their solutions:

1. pytest_addoption is Not Recognized:Pytest does not recognize the pytest_addoption function, so your custom options are ignored.

This might be caused due to:

  • pytest_addoption part is not placed in correct file (conftest.py)
  • The conftest.py file is not in a directory that pytest scan.

Solution:

  • Ensure pytest_addoption is defined in a conftest.py file.
  • Place the conftest.py file in your test suite & # 8217; s root directory or the directory where your tryout reside.

2. Option Value Not Set Correctly:This occurs when the value of a usance selection is not what you expect, yet though the command-line argument was supply.

This might be caused due to:

  • You pass an invalid value from the command line.
  • The action, case, or default for the pick is misconfigured.

Solution:

  • Ensure the value passed on the command line correspond the expected eccentric.
  • Verify the activity, case, and default values in the pytest_addoption definition.

3. Tests Fail When Option is Not Passed:A test fails because the custom option is required but wasn ’ t provided on the command line. This might be caused by the choice not hold a default value and the test logic not handling a missing value.

Solution:

  • Provide a reasonable default value in pytest_addoption.
  • Alternatively, use required=True in the option definition.

4. Errors When Using Fixtures with Options:Custom options in fixtures are not available or campaign runtime errors.

This might be make due to:

  • The option is accessed before pytest parses it.
  • The fixture is not delimitate properly.

Solution: Access options within the fixture expendrequest.

5. CI/CD Integration Issues:This issue occurs when custom options are not realize when run exam in a CI/CD pipeline. It might be cause by custom options not being legislate correctly in the CI configuration.

Solution:

  • Ensure you pass the selection correctly in your CI job configuration.
  • Example in a YAML-based CI pipeline:

steps:

run: pytest -- env=staging

Best Practices for Using pytest_addoption with BrowserStack

To use pytest_addoption effectively, you must postdate best practices to ensure that your custom options are robust, maintainable, and easy to use.

Integrate pytest with BrowserStack:One can also Integrate pytest with BrowserStack as using BrowserStack with pytest fling several benefits that heighten testing efficiency, coverage, and flexibility. BrowserStack offers seamless integration with pytest.

Learn More:

BrowserStack too eases debugging and reporting by cater network log, console logs, and screenshots for debugging failed exam.

Prerequisites

1. Sign up at BrowserStack.
2. Ensure pytest and seleniumare installed:

pip install pytest selenium pip install browserstack-sdk

3. Install the BrowserStack Python SDK: Run the following command

pip install browserstack-sdk

4. Configure BrowserStack SDK

The BrowserStack SDK uses a configuration file to delineate test capabilities, such as browser, OS, and settings.

5. Create the Configuration File

  • Create a file callbrowserstack.jsonin the origin directory of your project.

Example & # 8211;

{'' auth '': {'' username '': `` your_browserstack_username '', '' access_key '': `` your_browserstack_access_key ''}, '' browsers '': [{'' browser '': `` chrome '', '' os '': `` Windows '', '' os_version '': `` 10 '', '' browser_version '': `` latest ''}, {'' browser '': `` firefox '', '' os '': `` OS X '', '' os_version '': `` Monterey '', '' browser_version '': `` modish ''}], '' run_settings '': {'' cypress_config_file '': mistaken, '' project_name '': `` Pytest Integration '', '' build_name '': `` Build 1 '', '' exclude '': [], '' parallels '': 5}}
  • Replace your_browserstack_username and your_browserstack_access_key with your BrowserStack credentials, available on the Account Settings page.
  • Set Up a conftest.py: Configure a pytest fixture to initialize the BrowserStack WebDriver free-base on the SDK settings.
import pytest from selenium import webdriver from browserstack.local import Local import json import os @ pytest.fixture (scope= '' session '') def browserstack_local (): # Start BrowserStack Local for local testing if required local = Local () local_args = {`` key '': os.getenv (`` BROWSERSTACK_ACCESS_KEY '')} local.start (* * local_args) yield local.stop () @ pytest.fixture def browser (request, browserstack_local): # Load capabilities from browserstack.json with exposed (`` browserstack.json '') as f: config = json.load (f) capabilities = config [`` browser ''] [0] # Example: Use the inaugural browser potentiality [`` build ''] = config [`` run_settings ''] [`` build_name ''] capabilities [`` gens ''] = request.node.name # Initialize WebDriver driver = webdriver.Remote (command_executor=f '' https: // {config ['auth '] ['username ']}: {config ['auth '] ['access_key ']} @ hub-cloud.browserstack.com/wd/hub '', desired_capabilities=capabilities) yield driver driver.quit ()
  • Write Test Cases
def test_google_search (browser): browser.get (`` https: //www.google.com '') assert `` Google '' in browser.title
  • Run the Tests: Execute the tests using pytest. The BrowserStack SDK will automatically pick up configurations from browserstack.json
Command: pytest

  • Organise options in conftest.py: If you have many choice to be define, then organise them logically and define their purpose clearly in the file
  • Provide Default Values: Always ply default values so that the tests run smoothly even when the option is not cater.
  • Select the appropriate action character for the alternative:
  1. store: For options that direct value.
  2. store_true/store_false: For boolean flags.
  3. append: For options that can accept multiple values.
  • Document Custom Options: Use the assist argument to draw the intention of each option. Include usage examples in your project & # 8217; s documentation or README.
  • Ensure Compatibility with CI/CD Pipelines: Design tradition options with CI/CD in mind:
  1. Use default values for local test.
  2. Pass explicit options in the CI pipeline configuration.

Talk to an Expert

Conclusion

The pytest_addoption feature is a powerful tool in the pytest ecosystem that let developers to customize their test runs by adding command-line options. These alternative provide tractability to control trial behavior dynamically, integrate with external tools, and streamline testing workflows.

Key takeout for pytest_addoption:

  • Enhanced Flexibility: Custom options enable tailoring test tally to specific surround or configurations, making trial adaptable and reusable.
  • Seamless Integration: External puppet, APIs, or services can be well incorporated into the testing procedure by expend pytest_addoption.
  • Dynamic Configuration: You can dynamically pass parameter like environs variable, feature flags, or timeouts to your test suite, cut the need for hard cryptography.
  • Improved Collaboration: Documented custom pick improve collaboration among team member, especially in large or multi-environment labor.

pytest_addoption transforms quiz execution by offering a user-friendly and extremely configurable approach. Leveraging this feature ensures your test suite is more pliable and scalable, easier to maintain, and more adaptable to varying project motivation.

Tags
67,000+ Views

# Ask-and-Contributeabout this theme with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free