Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Testing and assertions

A test compares observed behavior to an expectation, including values on either side of a boundary.

Version: Python 3.14; repository image, production runtime not attested

Syntax

self.assertEqual(actual, expected)
with self.assertRaises(ValueError):
    operation()

A test compares observed behavior to an expectation, including values on either side of a boundary.

assertEqual checks a result and assertRaises requires the specified exception or a subclass. No exception causes a failure and a different one can become a test error. Optimization with -O can remove assert statements, while TestCase methods still perform their checks.

One method checks 9, 10 and -1. The output 1 True counts the successful test method, not individual assertions.

import unittest
for body,expected in [(lambda:None,'failure'),(lambda:(_ for _ in ()).throw(TypeError()),'error')]:
    class Check(unittest.TestCase):
        def test_exception(self):
            with self.assertRaises(ValueError): body()
    r=unittest.TestResult()
    Check('test_exception').run(r)
    assert (len(r.failures),len(r.errors))==((1,0) if expected=='failure' else (0,1))

Examples

import unittest

def discount(amount):
    if amount < 0:
        raise ValueError("negative")
    return amount // 10

class DiscountTests(unittest.TestCase):
    def test_boundaries(self):
        self.assertEqual(discount(9), 0)
        self.assertEqual(discount(10), 1)
        with self.assertRaises(ValueError):
            discount(-1)

result = unittest.TestResult()
DiscountTests("test_boundaries").run(result)
print(result.testsRun, result.wasSuccessful())

Result

1 True

One method checks 9, 10 and -1. The output 1 True counts the successful test method, not individual assertions.

Sources