0
0
PyTesttesting~5 mins

Test functions in PyTest

Choose your learning style9 modes available
Introduction

Test functions help check if parts of your code work correctly. They make sure your program does what you expect.

When you want to check if a function returns the right result.
When you fix a bug and want to confirm it is really fixed.
When you add new features and want to make sure old parts still work.
When you want to run quick checks automatically without manual testing.
Syntax
PyTest
def test_function_name():
    assert expression

Test functions start with test_ so pytest can find them.

Use assert to check if something is true.

Examples
This test checks if 2 plus 2 equals 4.
PyTest
def test_addition():
    assert 2 + 2 == 4
This test checks if the length of 'hello' is 5.
PyTest
def test_string_length():
    assert len('hello') == 5
This test checks if the number 3 is in the list.
PyTest
def test_list_contains():
    assert 3 in [1, 2, 3]
Sample Program

This program defines a simple add function and tests it with three cases. Each assert checks if the result is correct.

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

def test_add():
    assert add(3, 4) == 7
    assert add(-1, 1) == 0
    assert add(0, 0) == 0
OutputSuccess
Important Notes

Keep test functions small and focused on one thing.

Use clear names starting with test_ so pytest finds them easily.

Run tests often to catch problems early.

Summary

Test functions check if code works as expected.

They start with test_ and use assert statements.

Running tests helps keep your code reliable and bug-free.