Testing


unit test

import unittest

class TestStringMethods(unittest.TestCase):
    def test_upper(self):
        self.assertEqual('foo'.upper(), 'FOO')

    def test_isupper(self):
        self.assertTrue('FOO'.isupper())
        self.assertFalse('Foo'.isupper())

    def test_split(self):
        s = 'hello world'
        self.assertEqual(s.split(), ['hello', 'world'])
        # s.split should throw when the separator is not a string
        with self.assertRaises(TypeError):
            s.split(2)

unittest.main(exit=False)

pytest

import pytest

def test_upper():
    assert 'foo'.upper() == 'FOO'

def test_isupper():
    assert 'FOO'.isupper()
    assert not 'Foo'.isupper()

def test_split():
    s = 'hello world'
    assert s.split() == ['hello', 'world']
    # s.split should throw when the separator is not a string
    with pytest.raises(TypeError):
        s.split(2)

pytest.main()

Mock

mock is also available if you need to stub out some behavior.

from mock import Mock

mock = Mock()
mock.method(1, 2, 3)
mock.method.assert_called_with('this should break')

Hypothesis

hypothesis is available for property-based testing in Python.

from hypothesis import given
from hypothesis.strategies import text

def encode(string):
    # return encoded string

def decode(string):
    # return decoded string

@given(text())
def test_decode_inverts_encode(s):
    assert decode(encode(s)) == s

test_decode_inverts_encode()
Last modified November 27, 2020