CKTIS / Python
unittest.TestCase
Instancja TestCase uruchamia jedną metodę wskazaną nazwą.
Wersja: Python 3.14; repository image, production runtime not attested
Składnia
unittest.TestCase(methodName='runTest')Instancja TestCase uruchamia jedną metodę wskazaną nazwą.
Po błędzie setUp runner pomija ciało i tearDown, a cleanup wykonuje od ostatnio dodanej funkcji do pierwszej. Blok subTest identyfikuje nieudany wariant i przy zwykłym uruchomieniu pozwala kontynuować inne warianty metody. Po udanym setUp wykonuje tearDown także wtedy, gdy asercja zawiodła. Funkcje dodane przez addCleanup wykonują się po tearDown lub po nieudanym setUp. Błąd sprawdzenia równości 4 i 5 trafia do failures, a inny wyjątek, np. ValueError, do errors.
Przykład wypisuje 1 1 0.
import unittest
events=[]
class Check(unittest.TestCase):
def setUp(self):
events.append('up')
self.addCleanup(events.append,'clean')
def tearDown(self): events.append('down')
def test_bad(self): self.assertEqual(2,3)
def test_error(self): raise ValueError('bad')
r=unittest.TestResult()
Check('test_bad').run(r)
assert events==['up','down','clean'] and len(r.failures)==1
Check('test_error').run(r)
assert len(r.errors)==1 and r.testsRun==2
class Broken(unittest.TestCase):
def setUp(self):
self.addCleanup(events.append,'first')
self.addCleanup(events.append,'second')
raise ValueError('setup')
def tearDown(self): events.append('down')
def test_a(self): events.append('body')
events.clear()
Broken('test_a').run(r)
assert events==['second','first']
class Variants(unittest.TestCase):
def test_loop(self):
for n in (1,2):
with self.subTest(n=n):
events.append(n)
self.assertEqual(n,2)
r2=unittest.TestResult()
Variants('test_loop').run(r2)
assert events[-2:]==[1,2] and r2.testsRun==1 and len(r2.failures)==1
unittest.TestCase.setUp · unittest.TestCase.assertEqual · unittest.TestCase.assertRaises · unittest.TestCase.subTest
setUp przygotowuje świeży stan przed metodą testową. assertEqual porównuje wynik z oczekiwaniem. assertRaises(KeyError) wymaga tego wyjątku lub podklasy. subTest(key=...) wiąże niepowodzenie z wariantem w jednej metodzie, więc testsRun pozostaje 1.
import unittest
class PriceTests(unittest.TestCase):
def setUp(self):
self.values = {"small": 2}
def test_sizes(self):
for key, expected in [("small",2),("other",0)]:
with self.subTest(key=key):
self.assertEqual(self.values.get(key,0),expected)
with self.assertRaises(KeyError):
self.values["missing"]
r=unittest.TestResult()
PriceTests("test_sizes").run(r)
assert r.testsRun==1 and r.wasSuccessful()
Przykłady
import unittest
class Check(unittest.TestCase):
def test_total(self): self.assertEqual(4, 5)
r = unittest.TestResult()
Check("test_total").run(r)
print(r.testsRun, len(r.failures), len(r.errors))
Wynik
1 1 0
Przykład wypisuje 1 1 0.