Introduction
We write tests to check if our code works correctly. PyTest helps us run these checks easily.
We write tests to check if our code works correctly. PyTest helps us run these checks easily.
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.
def test_addition(): assert 2 + 2 == 4
def test_string(): assert 'hello'.upper() == 'HELLO'
This script has a simple add function and a test that checks it with different numbers.
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
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.
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.
test_.test_ are recognized as tests by default.test_, so test_add is correct.1 + 1 == 2 is true, so the test will pass.def test_example():
x = 5
y = 2
assert x - y == 3x - y which is 5 - 2 = 3.3 == 3, which is true, so no error is raised.def test_sum():
total = 2 + 2
assert total = 4= which is assignment, not comparison. It should be ==.test_ and indentation is correct, so no error there.multiply(a, b) that returns the product of two numbers. Which PyTest test function correctly tests that multiply(3, 4) returns 12?test_, so test_multiply is correct.== and the expected result is 12, so assert multiply(3, 4) == 12 is correct.Pass the test and this pattern moves unknown