CodingNic

Testing and Best Practices

pytest Basics

Testing and Best Practices 36 min read

pytest Basics

pytest Basics

Python has another popular testing tool called pytest.

Many developers use it because it is simple, powerful, and easy to read.

What Is pytest?

pytest is a testing framework for Python.

It helps you:

  • write tests faster
  • use simple assert
  • run many tests
  • read failures clearly
  • use advanced features later

Why Learn pytest?

Compared with unittest, pytest often needs less code.

That makes tests easier to write and maintain.

Install pytest

In terminal:

bash
pip install pytest

Basic Test File

Create:

text
test_math.py

Add:

python
def add(a, b):
    return a + b

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

Run Tests

In terminal:

bash
pytest

Example Output

text
1 passed

How It Works

Test File Name

Use names like:

text
test_math.py

Test Function Name

Functions should start with:

text
test_

Example:

python
def test_add():

Use Plain assert

python
assert add(2, 3) == 5

If false, the test fails.

Multiple Tests

python
def add(a, b):
    return a + b

def test_add_one():
    assert add(1, 1) == 2

def test_add_two():
    assert add(0, 5) == 5

def test_add_three():
    assert add(-2, 3) == 1

Example Output

text
3 passed

Example Failure

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

Output shows expected vs actual values clearly.

pytest vs unittest

unittest

  • class-based style
  • methods like assertEqual()

pytest

  • simpler functions
  • plain assert

Both are useful.

Code Along

Create function:

python
def square(n):
    return n * n

Write two pytest tests.

Mini Challenge

Create function:

python
def is_even(n):
    return n % 2 == 0

Write tests for:

  • 2 → True
  • 3 → False
  • 0 → True

Expected output:

text
3 passed

Real World Use Case

Many teams use pytest for APIs, web apps, automation tools, data projects, and backend systems.

Quiz

  1. What is pytest?
  2. How do you install it?
  3. What should test function names start with?
  4. Why do many developers like pytest?

Assignment

Create a double(n) function and test it with three pytest test functions.

Summary

You learned how to use pytest to write simple and readable automated tests in Python.