0
0
PytestHow-ToBeginner ยท 3 min read

How to Write Tests in pytest: Simple Guide for Beginners

To write a test in pytest, create a Python function whose name starts with test_. Inside the function, use assert statements to check expected outcomes. Run tests by executing pytest in your terminal.
๐Ÿ“

Syntax

A pytest test is a simple Python function starting with test_. Inside, use assert to verify conditions. No need for classes or special setup for basic tests.

  • def test_function_name(): - defines a test function
  • assert condition - checks if condition is true
python
def test_example():
    assert 1 + 1 == 2
๐Ÿ’ป

Example

This example shows a test function that checks if adding two numbers works correctly. If the assertion is true, pytest reports a pass; if false, it reports a failure.

python
def test_addition():
    result = 2 + 3
    assert result == 5

# To run this test, save it in a file named test_sample.py and run `pytest` in the terminal.
Output
============================= test session starts ============================== collected 1 item test_sample.py . [100%] ============================== 1 passed in 0.03s ===============================
โš ๏ธ

Common Pitfalls

Common mistakes include naming test functions without the test_ prefix, which pytest will ignore, and forgetting to use assert statements, so tests do not actually check anything.

Also, avoid putting test code inside if __name__ == '__main__' blocks because pytest discovers tests by function names.

python
def addition():  # Wrong: missing 'test_' prefix
    assert 1 + 1 == 2

def test_addition():  # Right
    assert 1 + 1 == 2
๐Ÿ“Š

Quick Reference

ConceptDescription
Test function nameMust start with 'test_' for pytest to find it
AssertionsUse 'assert' to check expected results
Test file nameUsually starts with 'test_' or ends with '_test.py'
Run testsRun 'pytest' command in terminal
Test discoveryPytest automatically finds tests by naming conventions
โœ…

Key Takeaways

Name test functions starting with 'test_' so pytest can find them.
Use assert statements inside test functions to check conditions.
Run tests by typing 'pytest' in your terminal in the test file directory.
Avoid missing 'test_' prefix or skipping assert statements to ensure tests run.
Keep tests simple and focused on one behavior per function.