0
0
PythonHow-ToBeginner · 3 min read

How to Run All Tests in Python Quickly and Easily

To run all tests in Python, use the unittest module with python -m unittest discover or use pytest by running pytest in your project directory. These commands automatically find and run all test files following standard naming conventions.
📐

Syntax

Here are the common commands to run all tests in Python:

  • python -m unittest discover: Runs all tests found in the current directory and subdirectories following the pattern test*.py.
  • pytest: Runs all tests in the current directory and subdirectories automatically detecting test files and functions.

Both commands should be run in your project root folder where your tests are located.

bash
python -m unittest discover

pytest
💻

Example

This example shows a simple test file and how to run all tests using unittest and pytest.

python
import unittest

class TestMath(unittest.TestCase):
    def test_add(self):
        self.assertEqual(1 + 1, 2)

if __name__ == '__main__':
    unittest.main()
Output
... ---------------------------------------------------------------------- Ran 1 test in 0.000s OK
⚠️

Common Pitfalls

Common mistakes when running all tests include:

  • Running the command from the wrong directory, so tests are not found.
  • Using incorrect test file or function names that do not match the discovery pattern (e.g., files not starting with test or functions not starting with test_).
  • Not installing pytest if you want to use it (pip install pytest).

Always check your test file names and run commands from your project root.

bash
## Wrong: running unittest from wrong folder
# $ cd some/other/folder
# $ python -m unittest discover

## Right: run from project root
# $ cd project_root
# $ python -m unittest discover
📊

Quick Reference

CommandDescription
python -m unittest discoverRun all unittest tests matching test*.py pattern
pytestRun all tests detected by pytest automatically
pip install pytestInstall pytest if not already installed

Key Takeaways

Use python -m unittest discover to run all unittest tests automatically.
Use pytest command to run all tests with pytest's powerful discovery.
Run test commands from your project root directory where test files are located.
Name test files and functions starting with test_ to ensure they are found.
Install pytest with pip install pytest before using it.