Log In

Don't have an account? Sign up now

Lost Password?

Sign Up

Prev

MODULE 17: Python Testing

In Module 17, we focus on reliability. In a professional environment, you don’t just write code; you write code that proves your other code works. This ensures that when you add new features, you don’t accidentally break old ones.

1. Unit Testing

A Unit Test is a script that tests a small, specific “unit” of code—usually a single function or class method—in isolation. The goal is to ensure that for a given input, the function produces the expected output.

Example (using built-in unittest):

Python

import unittest

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

class TestMath(unittest.TestCase):
    def test_add(self):
        self.assertEqual(add(2, 3), 5)

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

2. PyTest

pytest is the most popular testing framework in the Python ecosystem. It is preferred over the built-in unittest because it is less “boilerplate-heavy” and more powerful.

  • Simple Syntax: No need for classes; just write functions starting with test_.
  • Detailed Failures: It provides clear info on why a test failed without extra configuration.

Example:

Python

# Save as test_logic.py
def test_addition():
    assert 1 + 1 == 2

Run it by simply typing pytest in your terminal.


3. Test-Driven Development (TDD)

TDD is a software development process where you write the test first, before writing the actual code. It follows the Red-Green-Refactor cycle:

  1. Red: Write a test for a feature and watch it fail.
  2. Green: Write just enough code to make the test pass.
  3. Refactor: Clean up the code while ensuring the test still passes.

4. Mocking

Sometimes, your code interacts with external systems like a database, an API, or the file system. You don’t want your tests to actually send a real email or delete a real database record.

Mocking allows you to replace those external dependencies with “fake” objects that simulate their behavior.

Example:

Python

from unittest.mock import Mock

# Create a mock object
database = Mock()
database.get_user_email.return_value = "fake@example.com"

# Now you can test logic without a real database
print(database.get_user_email(id=1)) # Returns 'fake@example.com'

5. Code Coverage

Code Coverage is a metric that tells you what percentage of your source code is actually executed during your tests. It helps identify “dark corners” of your app that haven’t been tested yet.

  • Tool: pytest-cov is commonly used.
  • Goal: While 100% is ideal, most professional projects aim for 80-90% coverage.

6. Real-world Testing Flow

In a modern 2026 workflow, testing is automated using CI/CD (Continuous Integration). Every time you push code to GitHub, a server automatically runs your pytest suite. If any test fails, the code is blocked from being deployed to production.

Leave a Comment

    🚀 Join Common Jobs Pro — Referrals & Profile Visibility Join Now ×
    🔥