CodingNic

Testing and Best Practices

Final Testing Project

Testing and Best Practices 60 min read

Final Testing Project

Final Testing Project

Great job finishing this module.

Now it is time to build one complete project using everything you learned about testing and best practices.

You will use:

  • unittest
  • pytest
  • assertions
  • organized test files
  • debugging
  • code style
  • refactoring
  • documentation

Project: Tested Utility App

Build a small utility app with clean code and automated tests.


Step 1: Create Project Structure

text
utility_app/
    app/
        math_tools.py
        text_tools.py
    tests/
        test_math_tools.py
        test_text_tools.py

Step 2: Create math_tools.py

Add:

python
def add(a, b):
    """Return the sum of two numbers."""
    return a + b

def square(n):
    """Return square of a number."""
    return n * n

def is_even(n):
    """Return True if number is even."""
    return n % 2 == 0

Step 3: Create text_tools.py

Add:

python
def shout(text):
    """Return uppercase text."""
    return text.upper()

def count_letters(text):
    """Return number of letters."""
    return len(text)

Step 4: Create tests/test_math_tools.py

Write tests for:

  • add(2, 3) → 5
  • square(4) → 16
  • is_even(6) → True

Example with pytest:

python
from app.math_tools import add, square, is_even

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

Add more tests too.


Step 5: Create tests/test_text_tools.py

Write tests for:

  • shout("hello") → "HELLO"
  • count_letters("cat") → 3

Step 6: Run Tests

Use terminal:

bash
pytest

Expected result:

text
5 passed

Step 7: Add unittest File

Create:

text
tests/test_unittest_math.py

Write one unittest.TestCase class for square().

Run:

bash
python -m unittest

Step 8: Debug a Failure

Break one function on purpose.

Example:

python
return n * 2

Run tests.

Read the failure.

Fix the code.

Run tests again.


Step 9: Refactor

Improve one part of the project:

  • better names
  • cleaner structure
  • more docstrings
  • remove repeated code

Run tests again after refactoring.


Final Structure

text
utility_app/
    app/
        math_tools.py
        text_tools.py
    tests/
        test_math_tools.py
        test_text_tools.py
        test_unittest_math.py

Extra Challenges

After finishing, try adding:

  • subtract()
  • reverse_text()
  • cube()
  • more pytest cases
  • fixtures
  • parametrize
  • style cleanup using PEP 8

Real World Use Case

Professional teams build apps with tests so features stay reliable as code changes.


Assignment

Build the full project and add one new function with both pytest and unittest tests.


Summary

You built a clean Python project with organized files, automated tests, debugging, refactoring, documentation, pytest, and unittest.