← All lessons

Testing

Sign in · Sign up

Lesson 13.1

A test is a check of an expectation: "for this data the function must give that".

import unittest

def double(x):
    return x * 2

class TestDouble(unittest.TestCase):
    def test_positive(self):
        self.assertEqual(double(4), 8)

    def test_zero(self):
        self.assertEqual(double(0), 0)
  • a test class inherits from unittest.TestCase;
  • only a method whose name starts with test_ counts as a test;
  • assertEqual(expected, actual) is the main assertion;
  • with many tests you run them with unittest.main() or a test suite.

The check gives two pairs of numbers first and second. Write add(a, b) and the class TestAdd with two tests — one per pair, and at the end run the tests and print Tests: <how many>, Failed: <how many>.

Hint

The name of a test method must start with test_, otherwise unittest will not find it.

Inside — self.assertEqual(expected, result). The tests are run by the class name (loadTestsFromTestCase) and the number of tests run is taken from the result.