Blog on Pytest

 

Testing Python Applications with Pytest

 

 Pytest is a testing framework and test runner for Python. In this guide, we will look at the most useful configuration and usage, including several pytest plugins and external libraries.
 

Pytest basics 

Pytest will automatically scan our codebase for test modules, files following the file name convention test_*.py or *_test.py, and scan them for functions named test_*(). If we want to run tests defined as methods inside classes, we need to prefix the class names with Test. Pytest will also automatically pick up any tests written using unittest module.

 

Standard test functions and test runs

from python_pytest.basics import add


def test_add_can_add_numbers():
# given
num = 3
num2 = 45

# when
result = add(num, num2)

# then
assert result == 48

By default, fixtures are function-scoped, meaning that a fixture's lifetime is tied to the execution of the test function. However, this behavior can be changed to one of the other supported scopes (function, class, module, package, or session).

Pytest fixtures can also be parametrized (taking arguments). See Parametrizing fixtures in the documentation.

 

example code :

 

Parametrized tests

Pytest marker @pytest.mark.parametrize can be used to feed different data into one test function and turn it into multiple tests. The first parameter is a string listing all arguments that will be set for the test and the second one is a list of tuples with the matching data.

 

 

Fixtures 

The biggest power in using fixtures is being able to define our own. A fixture can provide some reusable test data for our tests, contain some before/after logic, or return a useful object, e.g., a configured HTTP client or a database session.

All we have to do is define a function in conftest.py file with @pytest.fixture decorator. Let's see a simple example of a fixture that provides a reusable database of allowed names:

@pytest.fixture
def allowed_names():
return ["Peter", "Mark", "Mary"]
 

import assignfunc


#@pytest.mark.skip(reason = "something")
@pytest.mark.parametrize("a,b", [(370, "yes"), (400, "no"), (153, "yes")])
def test_arm(a, b):
r1 = assignfunc.arm(a)
assert r1 == b


#@pytest.mark.xfail
@pytest.mark.parametrize("a,b", [(343, "yes"), (1220, "no"), (5005, "yes")])
def test_palin(a, b):
r2 = assignfunc.palin(a)
assert r2 == b


@pytest.mark.parametrize("a,b", [(64, "yes"), (60, "no"), (56, "yes")])
def test_divby8(a, b):
r2 = assignfunc.divby8(a)
assert r2 == b


@pytest.mark.parametrize("a,b", [(64, "even"), (69, "odd"), (56, "even")])
def test_evod(a, b):
r2 = assignfunc.evod(a)
assert r2 == b


@pytest.mark.parametrize("a,b,c,d", [(64, 60, 65, 60), (1, 2, 3, 1), (10, 50, 60, 10)])
def test_small(a, b, c, d):
r2 = assignfunc.smallest(a, b, c)
assert r2 == d 
import pytest      
 

Comments

Popular posts from this blog

Queue in Java

Using lists , tuples, sets, dictionaries