import subprocess
import sys
from pathlib import Path
import pytest
def test_pytest_command_line_options(tmp_path):
# Create a sample test file with two tests, one fails
test_file = tmp_path / "test_sample.py"
test_file.write_text(
"""
import pytest
def test_pass():
assert True
def test_fail():
assert False
"""
)
# Run pytest with --maxfail=1 --disable-warnings -q
result = subprocess.run(
[sys.executable, "-m", "pytest", str(test_file), "--maxfail=1", "--disable-warnings", "-q"],
capture_output=True,
text=True
)
# Check that return code is 1 (because of failure)
assert result.returncode == 1, f"Expected return code 1 but got {result.returncode}"
# Check output contains only one failure reported
# The output should mention '1 failed' and not '2 failed'
assert "1 failed" in result.stdout or "1 failed" in result.stderr, "Expected exactly one failure"
assert "2 failed" not in result.stdout and "2 failed" not in result.stderr, "More than one failure reported"
# Check warnings are not shown
assert "WARNING" not in result.stdout and "WARNING" not in result.stderr, "Warnings should be suppressed"
# Check output is quiet (no verbose info)
# The -q option reduces output, so no 'collected' line
assert "collected" not in result.stdout, "Output should be quiet without 'collected' line"
This test creates a temporary test file with two tests: one passes and one fails.
It runs pytest as a subprocess with the command-line options --maxfail=1 to stop after the first failure, --disable-warnings to suppress warnings, and -q for quiet output.
The test then asserts the return code is 1, indicating a failure occurred.
It checks the output to confirm only one failure is reported, no warnings appear, and the output is quiet without extra lines like 'collected'.
This approach uses subprocess to simulate real command-line usage and captures output for assertions, following best practices.