🌐
Kfchou
kfchou.github.io › pytest-addopts
Specifying tests via command line arguments
November 16, 2024 - { "python.testing.pytestArgs": [ "--A=3", "--B=4", "--C=my_C_value", "--D=my_D_value" ] } In conclusion, I’ve demonstrated a few ways to specifify test parameters. We use parser.addoption(--myOption) to pass in myOption from the command line, and retrieve it with request.config.getoption(--myOption).
🌐
Visual Studio Code
code.visualstudio.com › docs › python › testing
Python testing in Visual Studio Code
November 3, 2021 - For finer grain control of your coverage run when using pytest, you can edit the python.testing.pytestArgs setting to include your specifications. When the pytest argument --cov exists in python.testing.pytestArgs, the Python extension will make no additional edits to coverage args, to allow your customizations to take effect.
🌐
pytest
docs.pytest.org › en › 6.2.x › usage.html
Usage and Invocations — pytest documentation
Any prior test output that has already been captured and will be processed as such. Output capture gets resumed when ending the debugger session (via the continue command). Python 3.7 introduces a builtin breakpoint() function.
🌐
pytest
docs.pytest.org › en › stable › how-to › usage.html
How to invoke pytest - pytest documentation
In general, pytest is invoked with the command pytest (see below for other ways to invoke pytest). This will execute all tests in all files whose names follow the form test_*.py or *_test.py in the current directory and its subdirectories.
🌐
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
🌐
GitHub
github.com › microsoft › vscode-python › issues › 21255
Add separate `python.testing.pytestArgs` settings for regular, debug and discovery runs · Issue #21255 · microsoft/vscode-python
May 16, 2023 - "python.testing.pytestArgs": { "run": [], // equal to the current "python.testing.pytestArgs": [] "debug": [], "discovery": [] } or · "python.testing.pytestRunArgs": [], "python.testing.pytestDebugArgs": [], "python.testing.pytestDiscoveryArgs": [] Reactions are currently unavailable ·
Author: microsoft
🌐
Donjayamanne
donjayamanne.github.io › pythonVSCodeDocs › docs › unittests_pytest-framework
py.test | Python in Visual Studio Code
Ensure all other test frameworks have been disabled (i.e. have the value false). Ensure pytest has been installed in the currently configured python environment. Command line options Command line options for the pytest can be passed by adding the necessary options into the following section in the user or workspace settings file settings.json: Add the options as individual items as shown below: "python.unitTest.pyTestArgs": [ "--exitfirst", "--verbose" ], Note: Details on command line options can be found here.
🌐
GitHub
github.com › microsoft › vscode-python › issues › 15148
Support different options for discovering and running tests with pytest · Issue #15148 · microsoft/vscode-python
January 14, 2021 - "python.testing.pytestArgs": [ "src/unittests", "--cov=.", "--cov-report=xml:coverage.xml", "-vvv" ], But I don't want to generate coverage when debugging a test, so I disable it in my launch.json: { "name": "Debug Tests", "type": "python", "request": "test", "console": "integratedTerminal", "env": {"PYTEST_ADDOPTS": "--no-cov"}, "justMyCode": false } I also don't want coverage data when tests are discovered because discovery is way faster without these options.
Author: microsoft
Find elsewhere
🌐
GitHub
github.com › microsoft › vscode-python › issues › 21798
Python.testing.pytestArgs does not work with option -m · Issue #21798 · microsoft/vscode-python
August 10, 2023 - Python.testing.pytestArgs does not work with option -m#21798 · Copy link · Assignees · Labels · area-testing · Mond WAN (mondwan) opened · on Aug 10, 2023 · Issue body actions · Type: Bug · For settings.json · { "python.testing.pytestArgs": ["-m", "lazy"] } Expect to see vscode to run pytest with argument in TEST RESULT UI ·
Author: microsoft
Top answer
1 of 2
20

After much experimentation I finally found how to do it. What I needed was to pass user name and password to my script in order to allow the code to log into a test server. My test looked like this:
my_module_test.py

import pytest
import my_module

def login_test(username, password):
    instance = my_module.Login(username, password)
    # ...more...

conftest.py

import pytest

def pytest_addoption(parser):
    parser.addoption('--username', action='store', help='Repository user')
    parser.addoption('--password', action='store', help='Repository password')

def pytest_generate_tests(metafunc):
    username = metafunc.config.option.username
    if 'username' in metafunc.fixturenames and username is not None:
        metafunc.parametrize('username', [username])

    password = metafunc.config.option.password
    if 'password' in metafunc.fixturenames and password is not None:
        metafunc.parametrize('password', [password])

Then in my settings file I can use:
.vscode/settings.json

{
    // ...more...
    "python.testing.autoTestDiscoverOnSaveEnabled": true,
    "python.testing.unittestEnabled": false,
    "python.testing.nosetestsEnabled": false,
    "python.testing.pytestEnabled": true,
    "python.testing.pytestArgs": [
        "--exitfirst",
        "--verbose",
        "test/",
        "--username=myname",
        "--password=secret",
    // ...more...
    ],
}

An alternative way is to use pytest.ini file instead:
pytest.ini

[pytest]
junit_family=legacy
addopts = --username=myname --password=secret

2 of 2
2

If this is just for the debugger then you can specify things in "args" in your launch.json file. See https://code.visualstudio.com/docs/python/debugging#_args for more details.

🌐
pytest
docs.pytest.org › en › 6.2.x › example › parametrize.html
Parametrizing tests — pytest documentation
March 14, 2022 - 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
🌐
Pytest with Eric
pytest-with-eric.com › pytest-advanced › pytest-argparse-typer
How To Test CLI Applications With Pytest, Argparse And Typer | Pytest with Eric
March 23, 2026 - How do you do this without redefining all arguments in your tests? How do you abstract that layer? The good news is Pytest has you covered. Whether you’re using Python libraries like Argparse or Typer, Pytest provides a variety of methods to test command-line arguments.
🌐
pytest
docs.pytest.org › en › stable › reference › reference.html
API Reference - pytest documentation
When using pytest.mark.parametrize it is possible to parametrize tests such that some runs raise an exception and others do not. See Parametrizing conditional raising for an example. ... Assertions about expected exceptions for more examples and detailed discussion. ... Similar to caught exception objects in Python, explicitly clearing local references to returned ExceptionInfo objects can help the Python interpreter speed up its garbage collection.
🌐
Real Python
realpython.com › pytest-python-testing
pytest Tutorial: Effective Python Testing – Real Python
December 8, 2024 - A number of third-party testing frameworks attempt to address some of the issues with unittest, and pytest has proven to be one of the most popular. pytest is a feature-rich, plugin-based ecosystem for testing your Python code.
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
🌐
Medium
medium.com › programmers-journey › dead-simple-pytest-and-argparse-d1dbb6affbc3
Dead Simple: PyTest and ArgParse. You’re writing a Python script with an… | by Adam Hughes | Programmer’s Journey | Medium
August 4, 2023 - Invalid input is also important to test. Calling argparser with no args should produce a message like: python coolapp.py usage: start.py [-h] myfile start.py: error: the following arguments are required: myfile
🌐
pytest
docs.pytest.org › en › 7.1.x › how-to › usage.html
How to invoke pytest — pytest documentation
In general, pytest is invoked with the command pytest (see below for other ways to invoke pytest). This will execute all tests in all files whose names follow the form test_*.py or \*_test.py in the current directory and its subdirectories.
🌐
Simon Willison
til.simonwillison.net › pytest › pytest-argparse
Writing pytest tests against tools written with argparse | Simon Willison’s TILs
As you can see, main() takes an optional list of arguments. The default for that is None which will cause argparse to read sys.argv - but I can inject arguments to the function from my tests if I need to.
🌐
pytest
pytest.org
pytest documentation
$ pytest =========================== test session starts ============================ platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y rootdir: /home/sweet/project collected 1 item test_sample.py F [100%] ================================= FAILURES ================================= _______________________________ test_answer ________________________________ def test_answer(): > assert inc(3) == 5 E assert 4 == 5 E + where 4 = inc(3) test_sample.py:6: AssertionError ========================= short test summary info ========================== FAILED test_sample.py::test_answer - assert 4 == 5 ============================ 1 failed in 0.12s =============================