Use the pytest_addoption hook function in conftest.py to define a new option.
Then use pytestconfig fixture in a fixture of your own to grab the name.
You can also use pytestconfig from a test to avoid having to write your own fixture, but I think having the option have it's own name is a bit cleaner.
# conftest.py
def pytest_addoption(parser):
parser.addoption("--name", action="store", default="default name")
# test_param.py
import pytest
@pytest.fixture(scope="session")
def name(pytestconfig):
return pytestconfig.getoption("name")
def test_print_name(name):
print(f"\ncommand line param (name): {name}")
def test_print_name_2(pytestconfig):
print(f"test_print_name_2(name): {pytestconfig.getoption('name')}")
# in action
$ pytest -q -s --name Brian test_param.py
test_print_name(name): Brian
.test_print_name_2(name): Brian
.
Answer from Okken on Stack OverflowValentino G.
valentinog.com › blog › pytest
Pytest cheat sheet
October 22, 2020 - If we make instead BASE_DIR an argument for initialization, we can pass it from the outside, and use Pytest tmp_path in our test.
PyPI
pypi.org › project › pytest-params
pytest-params · PyPI
The example below shows the rectangle fixture using get_request_param() and the test cases using that fixture passing the w and h arguments in the form of a dictionary. Also shows different ways to implement test cases, including not using get_request_param(). Note that this example is rather simple and may not illustrate the usefulness of the get_request_param, but as the test cases grow in number and complexity, this comes in handy. from dataclasses import dataclass import pytest from src.pytest_params import params, get_request_param @dataclass class Rectangle: width: float height: float de
» pip install pytest-params
Published Mar 14, 2026
Version 0.4.0
Videos
18:25
Mastering PyTest Fixtures: The Complete Guide - YouTube
40:53
03. Pytest Markers & Test Parameterization - YouTube
00:54
How to use pytest fixture to run test against multiple parameters ...
Handle large number CLI arguments using pytest variables file
02:35
Passing command line arguments in python by pytest - YouTube
05:30
pytest Basics: Forwarding Parameters to Fixtures - YouTube
pytest
docs.pytest.org › en › 6.2.x › usage.html
Usage and Invocations — pytest documentation
pytest --version # shows where pytest was imported from pytest --fixtures # show available builtin function arguments pytest -h | --help # show help on command line and config file options
Top answer 1 of 10
115
Use the pytest_addoption hook function in conftest.py to define a new option.
Then use pytestconfig fixture in a fixture of your own to grab the name.
You can also use pytestconfig from a test to avoid having to write your own fixture, but I think having the option have it's own name is a bit cleaner.
# conftest.py
def pytest_addoption(parser):
parser.addoption("--name", action="store", default="default name")
# test_param.py
import pytest
@pytest.fixture(scope="session")
def name(pytestconfig):
return pytestconfig.getoption("name")
def test_print_name(name):
print(f"\ncommand line param (name): {name}")
def test_print_name_2(pytestconfig):
print(f"test_print_name_2(name): {pytestconfig.getoption('name')}")
# in action
$ pytest -q -s --name Brian test_param.py
test_print_name(name): Brian
.test_print_name_2(name): Brian
.
2 of 10
113
In your pytest test, don't use @pytest.mark.parametrize:
def test_print_name(name):
print ("Displaying name: %s" % name)
In conftest.py:
def pytest_addoption(parser):
parser.addoption("--name", action="store", default="default name")
def pytest_generate_tests(metafunc):
# This is called for every test. Only get/set command line arguments
# if the argument is specified in the list of test "fixturenames".
option_value = metafunc.config.option.name
if 'name' in metafunc.fixturenames and option_value is not None:
metafunc.parametrize("name", [option_value])
Then you can run from the command line with a command line argument:
pytest -s tests/my_test_module.py --name abc
pytest
docs.pytest.org › en › stable › reference › customize.html
Configuration - pytest documentation
Custom pytest plugin commandline arguments may include a path, as in pytest --log-output ../../test.log args. Then args is mandatory, otherwise pytest uses the folder of test.log for rootdir determination (see also #1435).
O'Reilly
oreilly.com › library › view › python-testing-with › 9781680509427 › f_0131.xhtml
Passing pytest Parameters Through tox - Python Testing with pytest [Book]
February 18, 2022 - The changes are as simple as adding {posargs} to our pytest command: ... Then to pass arguments to pytest, add a -- between the tox arguments and the pytest arguments. In this case, we’ll select test_version tests using keyword flag -k.
Author Brian Okken
Published 2022
Pages 274
pytest
docs.pytest.org › en › stable › how-to › usage.html
How to invoke pytest - pytest documentation
You can pass in options and arguments explicitly: ... # content of myinvoke.py import sys import pytest class MyPlugin: def pytest_sessionfinish(self): print("*** test run reporting finishing") if __name__ == "__main__": sys.exit(pytest.main(["-qq"], plugins=[MyPlugin()]))
pytest
docs.pytest.org › en › stable › example › parametrize.html
Parametrizing tests - pytest documentation
We define a test_basic_objects function which is to be run with different sets of arguments for its three arguments: python1: first python interpreter, run to pickle-dump an object to a file · python2: second interpreter, run to pickle-load an object from a file ... """Module containing a parametrized tests testing cross-python serialization via the pickle module.""" from __future__ import annotations import shutil import subprocess import textwrap import pytest pythonlist = ["python3.11", "python3.12", "python3.13"] @pytest.fixture(params=pythonlist) def python1(request, tmp_path): picklefil
Medium
aignishant.medium.com › introduction-to-parametrized-testing-in-pytest-ba3667b48891
Introduction to Parametrized Testing in Pytest | by Nishant Gupta | Medium
March 25, 2023 - Parametrized testing in pytest allows you to define a test function with multiple sets of input values. You can use the @pytest.mark.parametrize decorator to define the input values for your test function. The decorator takes the name of the parameter as the first argument, followed by a list of values or tuples of values for each parameter.
Readthedocs
happytest.readthedocs.io › en › latest › contents
Full pytest documentation — pytest documentation
@pytest.mark.parametrize argument names as a tuple · setup: is now an “autouse fixture” · Conditions as strings instead of booleans · pytest.set_trace() “compat” properties · Talks and Tutorials · Books · Talks and blog postings · Project examples ·
pytest
docs.pytest.org › en › stable › example › simple.html
Basic patterns and examples - pytest documentation
You can also dynamically modify the command line arguments before they get processed: # installable external plugin import sys def pytest_load_initial_conftests(args): if "xdist" in sys.modules: # pytest-xdist plugin import multiprocessing num = max(multiprocessing.cpu_count() / 2, 1) args[:] = ["-n", str(num)] + args
On Test Automation
ontestautomation.com › pytest-and-custom-command-line-arguments
pytest and custom command line arguments | On Test Automation
August 20, 2022 - This test method uses the base_url fixture to retrieve the base URL passed through the command line when pytest was invoked (or the default value when none was specified) to send an HTTP request to the endpoint using that base URL. ... as the endpoint that was used for the HTTP call, since we did not specify any value for the base-url command line argument.
pytest
docs.pytest.org › en › stable › contents.html
Full pytest documentation - pytest documentation
@pytest.mark.parametrize argument names as a tuple · setup: is now an “autouse fixture” · Conditions as strings instead of booleans · pytest.set_trace() “compat” properties · Talks and Tutorials · Books · Talks and blog postings · Release announcements ·
Alysivji
alysivji.com › pytest-fixures-with-function-arguments.html
Adding Function Arguments to pytest Fixtures - Siv Scripts
January 3, 2018 - A good use case for having fixtures that take arguments is loading test data from a JSON file. This testing pattern comes in handy when we have to write tests around an API. We can load predefined data from text files and write assertions based on expected output as shown in the following example: import json import pytest @pytest.fixture def json_loader(): """Loads data from JSON file""" def _loader(filename): with open(filename, 'r') as f: print(filename) data = json.load(f) return data return _loader def test_wrong_stop(client, mocker, json_loader): # Arrange get_mock = mocker.MagicMock() g
Pytest with Eric
pytest-with-eric.com › fixtures › pytest-fixture-with-arguments
A Step-by-Step Guide To Using Pytest Fixtures With Arguments | Pytest with Eric
September 15, 2023 - Factories, in the context of Pytest fixtures, are functions that are used to create and return instances of objects that are needed for testing. Factories are a way to generate test data or objects with specific configurations in a reusable manner. They can be thought of as a type of fixture that specializes in creating instances of classes or generating data. We can pass arguments to factory functions very easily.