How to Use Assert in Python Test: Simple Guide
Use the
assert statement in Python tests to check if a condition is true. If the condition is false, assert raises an AssertionError, which helps identify test failures quickly.Syntax
The assert statement checks a condition and raises an error if the condition is false. It has two parts:
- Condition: The expression you expect to be true.
- Optional message: A message shown if the assertion fails.
python
assert condition, "optional error message"
Example
This example shows how to use assert in a simple test function to check if a number is positive.
python
def test_positive_number(): number = 5 assert number > 0, "Number should be positive" # Running the test try: test_positive_number() print("Test passed") except AssertionError as e: print(f"Test failed: {e}")
Output
Test passed
Common Pitfalls
Common mistakes when using assert in tests include:
- Not providing a clear error message, making failures hard to understand.
- Using
assertfor code that should always run, sinceassertcan be disabled with optimization flags. - Writing complex expressions inside
assertthat are hard to debug.
python
def test_wrong(): value = 0 # This assert has no message and might be unclear if it fails assert value > 0 def test_right(): value = 0 # Clear message helps understand failure assert value > 0, "Value must be greater than zero"
Quick Reference
Remember these tips when using assert in Python tests:
- Use clear, simple conditions.
- Always add a helpful message.
- Use
assertonly for testing, not for regular program checks.
Key Takeaways
Use
assert to check if a condition is true in tests.Add clear messages to
assert for easier debugging.assert raises an error if the condition is false, signaling test failure.Avoid using
assert for normal program logic since it can be disabled.Keep
assert conditions simple and readable.