Python Testing Quicklist(GPT)¶
1. Create a Test File¶
Name convention:
test_<module>.pyExample:
calc.py test_calc.py
2. Import the Tools¶
import unittest # built-in testing framework
import pytest # external framework (optional, powerful)
Using unittest (Built-in)¶
Basic Structure
import unittest
import calc # the file you’re testing
class TestCalc(unittest.TestCase):
def test_add(self):
self.assertEqual(calc.add(2, 3), 5)
def test_subtract(self):
self.assertEqual(calc.subtract(5, 3), 2)
if __name__ == '__main__':
unittest.main()
Common Assertions
Method |
Description |
|---|---|
|
a == b |
|
a != b |
|
bool(x) is True |
|
bool(x) is False |
|
x is None |
|
a in b |
|
checks for exceptions |
Using pytest (Popular Alternative)¶
Simple Example
def add(a, b):
return a + b
def test_add():
assert add(2, 3) == 5
Run tests
pytest
Pytest Extras
pytest -v→ verbosepytest -q→ quietpytest <file>→ run specific filepytest -k "add"→ run tests with “add” in the namepytest --maxfail=1 --disable-warnings -q→ stop on first fail
Best Practices¶
One
test_file per module.Each test function name starts with
test_.Keep tests independent.
Use descriptive names (e.g.
test_add_positive_numbers).Automate with CI/CD (e.g., GitHub Actions).
Useful Tools¶
Tool |
Purpose |
|---|---|
|
Built-in, solid for small/medium projects |
|
Simpler syntax, plugins, better reporting |
|
Successor to nose (older, less used now) |
|
Measures code coverage |
|
Test across multiple environments |