Writing Unit Tests

  • unittest: Python’s built-in module for creating and running unit tests. It provides a framework for test case creation, test discovery, and test execution.

Example:

  import unittest

def add(a, b):
    return a + b

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

if __name__ == '__main__':
    unittest.main()
  
  • pytest: A popular third-party testing framework that offers a more flexible and powerful testing experience. It supports fixtures, parameterized testing, and more.

Example:

  # test_math_functions.py
import pytest

def add(a, b):
    return a + b

def test_add():
    assert add(1, 2) == 3
    assert add(-1, 1) == 0

# Run tests with the command: pytest
  

Code Quality Tools

  • Linting: Tools that analyze code for potential errors, stylistic issues, and deviations from coding standards. Common Python linters include pylint, flake8, and pyflakes.

Example with flake8:

  flake8 your_script.py
  
  • Formatting: Tools that automatically format your code to conform to coding standards. Common Python formatters include black and autopep8.

Example with black:

  black your_script.py
  

Summary of Commands:

  • Running unittest tests: python -m unittest discover
  • Running pytest tests: pytest
  • Linting with flake8: flake8 your_script.py
  • Formatting with black: black your_script.py