Meeting the Unittest

Introduction to Testing in Python

Alexander Levin

Data Scientist

Recap of OOP

  • OOP - programming paradigm based on objects and classes.
  • Class - a template of an object that can contain methods and attributes.
  • Method - a function or procedure that belongs to a class.
  • Attribute - a variable that belongs to a class.
  • Object - an instance of a class.
  • Example of a Python class:
    class Rectangle:
      # Constructor of Rectangle
      def __init__(self, a, b):
          self.a = a
          self.b = b
      # Area method
      def get_area(self):
          return self.a * self.b
    # Usage example
    r = Rectangle(4, 5)
    print(r.get_area())
    
>> 20
Introduction to Testing in Python

OOP Inheritance

  • Classes can inherit properties from other classes.
  • Put the parent class in the brackets after the name of the new class.
    class RedRectangle(Rectangle):
      self.color = 'red'
    
Introduction to Testing in Python

What is unittest

  • unittest - built-in Python framework for test automation (it is installed with Python).
  • unittest - not only for unit tests alone.
  • Based on OOP: each test case is a class, and each test is a method.
  • Test case - is an instance of testing.
  • Test suite - is a collection of test cases.
Introduction to Testing in Python

unittest vs. pytest

unittest

  • OOP-based - requires to create test classes)
  • Built-in (is installed with the Python distribution)
  • More assertion methods

pytest

  • Functon-based - searches for scripts and functions starting with test_
  • Third-party package (has to be installed separately from the Python distribution)

  • Less assertion methods

Introduction to Testing in Python

How to create a test with unittest

Test of the exponentiation operator:

import unittest

# Declaring the TestCase class
class TestSquared(unittest.TestCase):
    # Defining the test
    def test_negative(self):
        self.assertEqual((-3) ** 2, 9)
Introduction to Testing in Python

Assertion methods

  • .assertEqual(), .assertNotEqual()
  • .assertTrue(), .assertFalse()
  • .assertIs(), .assertIsNone()
  • .assertIsInstance(), .assertIn()
  • .assertRaises()
  • Many others
Introduction to Testing in Python

Summary

  • unittest - OOP-based built-in Python framework for test automation
  • Test case - is a testing instance in unittest
  • To create a test:
    1. Declare a class inheriting from unittest.TestCase
    2. Define test functions
  • Assertion methods
Introduction to Testing in Python

Let's practice!

Introduction to Testing in Python

Preparing Video For Download...