Python Testing Quicklist(GPT)

1. Create a Test File

  • Name convention: test_<module>.py

    Example:

    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

assertEqual(a, b)

a == b

assertNotEqual(a, b)

a != b

assertTrue(x)

bool(x) is True

assertFalse(x)

bool(x) is False

assertIsNone(x)

x is None

assertIn(a, b)

a in b

assertRaises(Error)

checks for exceptions

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

unittest

Built-in, solid for small/medium projects

pytest

Simpler syntax, plugins, better reporting

nose2

Successor to nose (older, less used now)

coverage

Measures code coverage

tox

Test across multiple environments