DevPath
Mid lesson · 12 min

Write tests for rejected and duplicate work

Prove that errors leave state unchanged.

Start from the business rule

For a unique registration, the rule is that one email maps to one account. Create the first account, attempt the duplicate, and assert both the reported error and the final count. Checking only that an exception was raised can miss a partial write performed before the exception.

Use a clear test shape

Arrange a minimal valid baseline, act once, then assert observable output and side effects. Parameterize malformed inputs that should behave the same way, but keep complex scenarios separate so failures remain readable. Use a temporary database or transaction isolation appropriate to the test suite.

with pytest.raises(DuplicateAccount):
    register(email='ada@example.test')
assert count_accounts('ada@example.test') == 1

Exercise dependency failure

Make a repository or network dependency fail after validation and verify the operation reports failure without leaving a half-created record. If the operation spans a database and an external service, specify the compensation or retry plan. Tests cannot replace a sound transaction boundary, but they can expose a missing one.

Check your understanding

What should a duplicate registration test assert besides the error?

Show explanation

That the persistent state still contains exactly one account and no partial duplicate work.

Put this lesson into practice

A practice activity at this level in the same module.

Try: Fix a SQL injection

Further reading

Primary references for this module. Check the current version when behavior or framework guidance may have changed.