Python Testing Framework with Example

In Python, more testing frameworks are there with its own use cases. Some example is like pytest, unittest, nose 2, doctest, etc. I will see pytest and unit test frameworks examples here.

unittest

unittest is built in Python testing framework. It offers test discovery and test cases in classes.

sample.py

import unittest

def add(x, y):
    return x + y

class TestMathFunctions(unittest.TestCase):
    def test_add(self):
        self.assertEqual(add(2, 3), 5)
        self.assertEqual(add(-1, 1), 0)

if __name__ == '__main__':
    unittest.main()

Output

[Running] python -u "/home/coder/project/sample.py"
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

pytest

pytest is a rich plugin ecosystem and it includes fixtures and parameterization features. Using pytest testing framework uses both complex functional testing and simple unit test cases. Open the command line terminal and run the below command.

pip install pytest (Windows)

spellcheck.py

def word_count(sentence):     
    words = len(sentence.split())
    print(words)
    return words

def char_count(sentence):
    chars = len(sentence)
    print(chars)
    return chars

def first_char(sentence):
    first = sentence[0]
    return first

def last_char(sentence):
    last = sentence[-1]
    return last

test_spellcheck.py

import pytest
import spellcheck

aaa = "Checking the test cases"
bbb = "This sentence should fail or pass the test"

@pytest.fixture
def input_value():
    input = aaa
    return input

def test_length(input_value):
    assert len(input_value.split()) < 10
    assert len(input_value) < 50

def test_struc(input_value):
    assert input_value[0].isupper()
    assert input_value.endswith('.')

Open the command line terminal and run the below command.

 python3 -m pytest test_spellcheck.py

Output

collected 2 items

test_spellcheck.py ..   [100%]

================= 2 passed in 0.05s ==============


Similar Articles