Published on

Pytest

Authors
  • avatar
    Name
    Loc Truong
    Twitter

Installation

pip install pytest

Asesertions

pytest allows of using the standard Python assert for verifying expect­ations and values in Python tests

assert actual == expected
assert actual != expected
assert value in collection
assert value not in collection

Basic Test

def test_name():
  assert True

Exception

Test if the exception is raised

def test_zero_division():
  with pytest.raises(ZeroDivisionError):
    1 / 0

Fixtures

In testing, a fixture provides a defined, reliable and consistent context for the tests. This could include enviro­nment (for example a database configured with known parame­ters) or content (such as a dataset).

from pytest import fixture

@pytest.fixture
def user():
    return {
        'name': 'John Snow',
        'email': 'john@snow.wes'
    }
def test_do_something(user):
    assert user['name'] == 'John Snow'

@pytest.fixture(scope = 'function')
def Component1():
    continue

@fixture
def fixture():
    fixture = Component1()
    yield fixture
    fixture.cleanup()

Scopes:

function     	Recreated every test function.	(default)
class	Once per test class.
module	Once for the test module.
package	Once for the entire package.
session	Once for the entire test session.

Data parameterization

import pytest

def is_even(input):
    if input % 2 == 0:
        return True
    return False

@pytest.mark.parametrize("input,expected", [
    (2, True),
    (3, False),
    (11, False),
])
def test_is_even(input, expected):
    assert is_even(input) == expected