Practical Python Programming: Understanding unittest and pytest Testing Frameworks

As software development grows, you will find:

  • • Requirements keep changing
  • • Bugs reappear after being fixed
  • • You hesitate to modify functions as they increase

At this point, automated testing becomes your “safety net”. Python provides two mainstream unit testing frameworks:

  • unittest (official library, built-in)
  • pytest (third-party library, more modern)

This article will help you understand:

  • • How to use unittest
  • • Core advantages of pytest
  • • Comparison between the two
  • • How to choose in a project
  • • Example code demonstration

1. unittest: Python’s Built-in xUnit Style Framework

Its features are very “enterprise-level”:

  • • You need to write test classes
  • • You must inherit from <span>unittest.TestCase</span>
  • • You need to follow a fixed naming convention
  • • There are many assertion methods

It resembles the standard unit testing systems of Java and C#.

Basic Example of unittest

Assuming we have a function to test:

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

Writing with unittest:

import unittest
from main import add

class TestMath(unittest.TestCase):

    def test_add(self):
        self.assertEqual(add(2, 3), 5)
        self.assertNotEqual(add(2, 3), 6)

if __name__ == "__main__":
    unittest.main()

How to run:

python test_math.py

Common Assertion Methods in unittest

Method Description
assertEqual(a, b) a == b
assertNotEqual(a, b) a != b
assertTrue(x) x is True
assertFalse(x) x is False
assertIn(x, y) x in y
assertRaises(err, func, args) Check if an exception is raised

unittest emphasizes norms and structure, making it suitable for large projects.

2. pytest: More Pythonic, More Modern, More Attractive

pytest is currently the most popular Python testing framework, aiming for simplicity and power.

Its features include:

  • • No need to write test classes
  • • No need to inherit from any parent class
  • • Test files and function names can be automatically discovered
  • • Assertions use Python’s <span>assert</span> (natural syntax)
  • • A rich plugin ecosystem (about 1800+)

pytest Example

Using the same add function:

def test_add():
    assert add(2, 3) == 5
    assert add(2, 3) != 6

How to run:

pytest

Isn’t it much cleaner?

3. Powerful Features of pytest

① Super Intelligent Assertions

pytest automatically parses detailed assertion comparison information:

assert add(2, 3) == 10

Output:

E   assert 5 == 10
E   + where 5 = add(2, 3)

Debugging experience is greatly enhanced.

② Parameterized Testing (Extremely Useful)

import pytest

@pytest.mark.parametrize("a,b,res", [
    (2, 3, 5),
    (1, 1, 2),
    (-1, 1, 0)
])
def test_add(a, b, res):
    assert add(a, b) == res

A single function runs multiple sets of test data, suitable for API testing and algorithm validation.

③ Fixtures (Dependency Injection)

When writing tests, you don’t need to repeatedly initialize the environment:

import pytest

@pytest.fixture
def user():
    return {"name": "Tom", "age": 18}

def test_user(user):
    assert user["age"] == 18

Similar to Django’s test client and Flask’s app fixture, they can be provided automatically.

④ Coverage Statistics

pytest --cov=myproject

Directly generates a coverage report for the project.

4. Comparison Summary of unittest vs pytest

Comparison Item unittest pytest
Built-in ✔ Built-in ❌ Needs pip install
Usage Style Object-oriented More Pythonic
Extensibility Average Very strong (rich plugins)
Difficulty of Writing More complex Easier
Automatic Discovery Average Very strong
Assertions Special assertion methods Directly use assert

In summary:

  • • For small projects → pytest
  • • For elegant testing → pytest
  • • Company project standards require unittest → unittest
  • • Need compatibility with Java/CI processes → unittest is also fine
  • • You have complete choice → pytest is the best

5. Example Project Test Directory Structure (pytest)

Recommended structure:

project/
    app/
    utils/
    tests/
        test_utils.py
        test_api.py
        conftest.py

pytest will automatically recognize:

  • • Files starting with <span>test_</span>
  • • Functions starting with <span>test_</span>
  • • Global fixtures in conftest.py

6. Can unittest & pytest be Mixed?

Absolutely. pytest can automatically recognize unittest test classes and execute them.

For example, if your company’s legacy code uses unittest, you can gradually migrate to pytest without conflicts.

7. Conclusion

This article has helped you clarify the two major testing frameworks in Python:

  • • unittest: Standardized, traditional, structured
  • • pytest: Modern, easy, strong ecosystem

If you ask me which one to use in a project?

99% of the time use pytest because it is truly user-friendly and more suitable for modern Python engineering.

Leave a Comment