0
0
PyTesttesting~5 mins

Command-line options in PyTest

Choose your learning style9 modes available
Introduction

Command-line options let you control how tests run without changing the code. They make testing flexible and easy.

You want to run only tests with a specific name or keyword.
You want to see detailed information about test failures.
You want to stop running tests after the first failure.
You want to run tests in a specific folder or file.
You want to run tests quietly without extra output.
Syntax
PyTest
pytest [options] [file_or_dir] [additional_args]

Options start with one or two dashes, like -v or --maxfail=2.

You can combine options to customize test runs easily.

Examples
Runs tests with verbose output, showing each test name and result.
PyTest
pytest -v
Stops running tests after the first failure to save time.
PyTest
pytest --maxfail=1
Runs tests only in the specified file.
PyTest
pytest tests/test_example.py
Runs tests whose names contain 'login' but excludes those marked as 'slow'.
PyTest
pytest -k 'login and not slow'
Sample Program

This script has three tests. Running with -v shows detailed results. Using --maxfail=1 stops after the first failure.

PyTest
import pytest

def test_add():
    assert 1 + 1 == 2

def test_subtract():
    assert 2 - 1 == 1

def test_fail():
    assert 1 == 0

# Run this in command line:
# pytest -v --maxfail=1
OutputSuccess
Important Notes

Use pytest --help to see all available command-line options.

Combine options to fit your testing needs, like pytest -v -k 'test_name'.

Options make running tests faster and more focused without changing test code.

Summary

Command-line options customize how pytest runs tests.

They help run specific tests, control output, and stop on failures.

Using options saves time and makes testing easier.