0
0
PyTesttesting~5 mins

First PyTest test

Choose your learning style9 modes available
Introduction

We write tests to check if our code works correctly. PyTest helps us run these checks easily.

You want to check if a function returns the right answer.
You want to make sure a bug is fixed and stays fixed.
You want to test small parts of your program one by one.
You want to run tests automatically when you save your code.
Syntax
PyTest
def test_function_name():
    assert expression

Test functions start with test_ so PyTest can find them.

assert checks if something is true. If not, the test fails.

Examples
This test checks if 2 plus 2 equals 4.
PyTest
def test_addition():
    assert 2 + 2 == 4
This test checks if converting 'hello' to uppercase works.
PyTest
def test_string():
    assert 'hello'.upper() == 'HELLO'
Sample Program

This script has a simple add function and a test that checks it with different numbers.

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

Save your test file starting with test_ or ending with _test.py so PyTest finds it.

Run tests by typing pytest in your terminal inside the folder with your tests.

Summary

PyTest runs functions starting with test_ to check code.

Use assert to compare expected and actual results.

Passing tests mean your code works for those cases.