Examples of Unittest , Doctest and Pytest are listed bellow-respectively- if you aren't familiar with them.
# Testing Framework:
# Unittest supports test automation by writing classes.
import unittest
def fib(n):
"""Return the n-th number in the fibonacci series."""
if n <= 0:
return 0
elif n == 1:
return 1
return fib(n - 1) + fib(n - 2)
class TestFib(unittest.TestCase):
def test_fib_series(self):
self.assertEqual(fib(0), 0)
self.assertEqual(fib(1), 1)
self.assertEqual(fib(2), 1)
self.assertEqual(fib(3), 2)
self.assertEqual(fib(4), 3)
self.assertEqual(fib(5), 5)
if __name__ == "__main__":
# normally this is unittest.main()...this is for jupyter
unittest.main(argv=['first-arg-is-ignored'], exit=False, verbosity=2)
# Testing Framework:
# Doctest allows you to write tests in the docstrings
def fib(n):
"""Return the n-th number in the fibonacci series.
>>> fib(0)
0
>>> fib(1)
1
>>> fib(29)
514229
"""
if n <= 0:
return 0
elif n == 1:
return 1
return fib(n - 1) + fib(n - 2)
if __name__ == "__main__":
import doctest
# doctest.testmod()
doctest.testmod(verbose=True)
#Testing framework pytest
# Test discovery: for doctests, unittests and pytests.
import pytest
%%run_pytest[clean] -vvv
def fib(n):
"""Return the n-th number in the fibonacci series."""
if n <= 0:
return 0
elif n == 1:
return 1
return fib(n-1) + fib(n-2)
def test_fib_series():
assert fib(0) == 0
assert fib(1) == 1
assert fib(2) == 1
assert fib(3) == 2
assert fib(4) == 3
assert fib(5) == 5
Top comments (2)
My favorite is pytest with fixtures, they make it really easy to share code and data between tests, using dependency injection instead of encapsulating everything in unittest.TestCase: docs.pytest.org/en/latest/fixture....
I'm fine with unittest.
Putting my tests in different classes allows me to organize a bit more my code by correctly splitting what needs to (package > classes > methods) whether it is about the core or the tests.
I think documentation needs to... Well, document my methods/functions and that tests doesn't belong to it (single responsibility for my docstring?). By writting methods with unittest I can event document them in a more precise way without having 40 lines of text per method :)
And finally, for pytest, I just think unittest allow me more wrapping around the structure of my tests
Just my opinion tho, hope it helps!