Skip to content

Unit tests

ChristianGerloff edited this page Apr 22, 2020 · 2 revisions

Unit tests are a way to make sure your code is correct. Python has a built-in unittest framwork. Some commonly used API include pytest, hypothesis, mock, etc.

Greate resource for pytest: Tutorial pytest

Execution tests

Source: https://ericmjl.github.io/essays-on-data-science/software-skills/testing

from custom_lib import my_function

def test_my_function():

    """Execution test for my_function.

    my_function()

Example-based test

from custom_lib import another_function

def test_another_function():
    arg1 = ...
    arg2 = ...
    result = another_function(arg1, arg2)
    expected_result = ...
    assert result == expected_result

Pytest

Source: https://docs.pytest.org/en/latest/\ Pytest is a library as an alternative to Python's standard unittest module. Installation:
pip install pytest

Example Structure:

pytest-demo
    │  README.md
    │
    ├─libs
    │      module.py
    │      __init__.py
    │
    └─tests
           test_module.py

Step:

  1. Define a class with name as "Module" in module.py, and then import class into test_module.py
  2. Deine test functions with name starting with "test_"
  3. Add the path of test_*.py file into the test folder

Note: pytest will run all files of the form test_*.py or *_test.py in the current directory\

Example

# content of test_sample.py
def func(x):
    return x + 1


def test_answer():
    assert func(3) == 5

Assert certain exception by "raise"

# content of test_sysexit.py
import pytest


def f():
    raise SystemExit(1)


def test_mytest():
    with pytest.raises(SystemExit):
        f()

Group multiple tests in a class

# content of test_class.py
class TestClass:
    def test_one(self):
        x = "this"
        assert "h" in x

    def test_two(self):
        x = "hello"
        assert hasattr(x, "check")

Hypothesis

source: https://hypothesis.readthedocs.io/en/latest/
Hypothesis is a library which lets you write tests that are parameterized by a source of examples. It then generates simple and comprehensible examples that makes your tests fail, letting you find more bugs with less work.
installation:
$ pip install hypothesis

Example:

@given(lists(floats(allow_nan=False, allow_infinity=False), min_size=1))
def test_mean(xs):
    mean = sum(xs) / len(xs)
    assert min(xs) <= mean(xs) <= max(xs)
Falsifying example: test_mean(
    xs=[1.7976321109618856e+308, 6.102390043022755e+303]
)

mock

source: https://docs.python.org/3/library/unittest.mock.html
unittest.mock is a library for testing in Python. It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used.

Example:

from mock import MagicMock
thing = ProductionClass()
thing.method = MagicMock(return_value=3)
thing.method(3, 4, 5, key='value')

thing.method.assert_called_with(3, 4, 5, key='value')

To mock classess or objects in a module under test, use patch decorator.

def mock_search(self):
    class MockSearchQuerySet(SearchQuerySet):
        def __iter__(self):
            return iter(["foo", "bar", "baz"])
    return MockSearchQuerySet()

# SearchForm here refers to the imported class reference in myapp,
# not where the SearchForm class itself is imported from
@mock.patch('myapp.SearchForm.search', mock_search)
def test_new_watchlist_activities(self):
    # get_search_results runs a search and iterates over the result
    self.assertEqual(len(myapp.get_search_results(q="fish")), 3)
Clone this wiki locally