Python - testing

From NoskeWiki
Jump to navigation Jump to search


NOTE: This page is a daughter page of: Python

Some of the most used python testing libraries, ordered by popularity, according to ChatGPT are:

  1. pytest: pytest has grown significantly in popularity over the years and is known for its simplicity and rich feature set. The number of downloads, the active community, and the variety of plugins make it a strong contender for the top spot.
  2. unittest: Being a part of the Python standard library gives unittest an advantage in terms of user count. While some developers prefer third-party libraries like pytest, many still use unittest because of its ubiquity and familiarity.
  3. nose2: Even though the original nose library is no longer maintained, nose2 (its successor) and nose together have had a fair share of users, especially from legacy projects.
  4. doctest: A lightweight testing option where you can embed tests in docstrings. Because of its simplicity and the fact it's part of the standard library, it's widely known and used, especially for smaller projects or for documentation purposes.
  5. Hypothesis: The unique property-based testing approach offered by Hypothesis has gained it a lot of traction and attention. While its user base might not be as vast as pytest or unittest, it's still significant and growing.
  6. tox: While tox isn't a testing library per se, it's a popular tool among developers for testing Python code under multiple Python environments, which indirectly impacts the testing ecosystem.
  7. Again, while not a testing framework itself, many Python developers use in conjunction with other testing tools to measure test coverage, making it popular in the testing landscape.

Python Testing With Different Libraries


A little example using unittest (no installations needed):


def square(n):
    if n == 0:
        return 1
    print(f'running square({n})')
    return n * n



import unittest
from main import square

class TestSquare(unittest.TestCase):

    def test_square_of_zero(self):
        self.assertEqual(square(0), 1)

    def test_square_of_one(self):
        self.assertEqual(square(1), 1)

    def test_square_of_five(self):
        self.assertEqual(square(5), 25)

    # def test_factorial_of_negative(self):
    #     with self.assertRaises(RecursionError):
    #         factorial(-1)

if __name__ == '__main__':


Install pytest with $ pip3 install pytest, then here's a basic example of use:

# This file contains the divide function

def divide(a, b):
  """Divide a by b."""
  if b == 0:
    raise ValueError("The divisor (b) cannot be zero!")
  return a / b

# This file contains the tests for the divide function in

import pytest
from math_funcs import divide

def test_divide_normal():
  assert divide(6, 2) == 3

def test_divide_by_zero():
  with pytest.raises(ValueError, match="The divisor \(b\) cannot be zero!"):
    divide(5, 0)

Now test it with:

$ pytest