0
0
PyTesttesting~5 mins

Running tests (pytest command)

Choose your learning style9 modes available
Introduction

We run tests to check if our code works correctly. The pytest command helps us run all tests easily.

After writing new test functions to check your code
To quickly check if recent changes broke anything
Before sharing your code with others to ensure quality
When you want a summary of which tests passed or failed
Syntax
PyTest
pytest [options] [file_or_dir]

You can run pytest without arguments to run all tests in the current folder.

Use options like -v for more details or -k to run specific tests.

Examples
Runs all tests in the current directory and subdirectories.
PyTest
pytest
Runs all tests with detailed output showing each test name and result.
PyTest
pytest -v
Runs tests only in the file test_example.py.
PyTest
pytest test_example.py
Runs tests that match the name test_function_name.
PyTest
pytest -k test_function_name
Sample Program

This simple test checks if the add function returns correct sums. Running pytest -v will show each test and if it passed.

PyTest
def add(a, b):
    return a + b

def test_add():
    assert add(2, 3) == 5
    assert add(-1, 1) == 0

# Run this in terminal:
# pytest -v
OutputSuccess
Important Notes

Make sure your test files and functions start with test_ so pytest finds them.

You can stop tests early with Ctrl+C if needed.

Summary

The pytest command runs your tests automatically.

Use options like -v for detailed results or specify files to run specific tests.

Running tests often helps catch mistakes early and keeps your code working well.