Tests passed. The empty box won.


    Tests passed. The empty box won. CuratorsMemes testing checklist illustration.

    A small username example shows how to move from one reassuring input to a test table that checks the contract.

    The example worked. What did it prove?

    You tried one normal username. The function accepted it. The test turned green. Then someone submitted an empty field, and the behaviour was not what you intended.

    A passing test establishes something about the case and assertion you wrote. It does not automatically establish the behaviour for inputs you never tried. Before adding another happy-path example, write down what the function is supposed to accept, reject or raise.

    Start with a rule, not a guess

    For this invented example, a username must be a Python string containing 3 to 12 characters, inclusive. Allowed characters are lowercase ASCII a-z, digits 0-9 and underscore. We do not trim spaces or convert other types. A string outside the rule returns False; an input that is not a string raises TypeError.

    These are teaching choices, not a recommendation for every real signup system. A real product might allow other scripts, normalize input or return a structured error. Settle that contract first. Otherwise a test may faithfully preserve the wrong requirement.

    Try both sides of each boundary

    Under our rule, try strings made entirely of allowed characters at lengths 2, 3, 12 and 13. The expected results are False, True, True and False. Those cases distinguish an inclusive boundary from an off-by-one error.

    Then separate cases that are easy to confuse: an empty string, a string of spaces and None. In this example the first two return False, while None raises TypeError. Also try a disallowed character, such as the space in "a b", and the wrong type, such as the number 123. The string "123" is valid here; the number 123 is not a string.

    Put the cases in a small table

    pytest.mark.parametrize lets one test function run against several input and expected-result pairs. Keep the expectation visible beside the input. The point is not to make a long list; it is to make each distinct behaviour easy to review.

    The runnable example below contains the function and its tests. It uses re.fullmatch to require the whole string to match the stated rule. Read it with the requirements, rather than treating the test table as a substitute for them.

    import re
    import pytest
    
    
    def valid_username(value):
        """Invented rule: ASCII a-z, 0-9 or _, length 3-12 inclusive."""
        if not isinstance(value, str):
            raise TypeError('username must be a string')
        return re.fullmatch(r'[a-z0-9_]{3,12}', value) is not None
    
    
    @pytest.mark.parametrize('value, expected', [
        ('user_7', True),
        ('ab', False),
        ('abc', True),
        ('a' * 12, True),
        ('a' * 13, False),
        ('', False),
        ('   ', False),
        ('a b', False),
        ('User', False),
        ('123', True),
        ('abc\n', False),
    ])
    def test_username(value, expected):
        assert valid_username(value) is expected
    
    
    @pytest.mark.parametrize('value', [None, 123, [], {}])
    def test_wrong_type(value):
        with pytest.raises(TypeError, match='must be a string'):
            valid_username(value)
    

    Check outcomes and expected failures

    Running a function without a crash is not the same as checking its result. For boolean output, the example asserts that the returned value is the expected boolean. For non-string inputs, a separate test uses pytest.raises(TypeError).

    Python unittest offers the same underlying ideas through methods such as assertEqual and assertRaises. Choose a tool your project already uses. Clear requirements and meaningful assertions matter more than changing frameworks.

    Use coverage as a question

    Branch coverage can point out a decision path your tests have not exercised. coverage.py documents how it tracks transitions between lines and identifies missing branches.

    That does not make a coverage percentage a correctness certificate. A line can run without its important result being checked. Google Testing Blog warns that high coverage can still miss edge cases and that coverage measures execution, not whether every covered behaviour was tested correctly. Read the gaps, the assertions and the risks together.

    After explicit examples, widen the search

    When you can state a useful property, generated inputs can add another layer. Hypothesis uses strategies to generate inputs for tests. It does not decide the correct requirement for you, and it is not a replacement for the small explicit cases that explain your contract.

    For a student project, start small: choose one important function, write its rule, add normal, boundary, empty or missing, and wrong-type or wrong-format cases, then check the expected result or error. Keep any bug-reproducing case as a regression test when you fix the bug.

    When an error appears, our earlier guide, Your error message is trying to help, walks through reading it before changing the code.

    Save this before the next push

    Normal input. Both boundaries. Empty or missing. Wrong type or format. Expected result or error.

    This checklist is a starting point, not complete test coverage. Real systems may also need state, permission, integration, concurrency and failure-recovery tests. Match the test plan to what can actually go wrong.

    Disclosure: The username rule and scenario are invented teaching examples. Mascot illustrations are AI-generated conceptual scenes, not product screenshots or measured test results.

    Sources


    Comments

    Popular posts from this blog

    The code works. Now explain it.

    How to verify AI answers: did anyone open the citations?

    It works on my laptop. That's the problem.