Znalostná bázaCentrum skúšok
SKSlovenčina
Vybrať jazyk13

CKTIS / Python

unittest.TestCase

Inštancia TestCase spúšťa jednu metódu určenú menom.

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

Syntax

unittest.TestCase(methodName='runTest')

Inštancia TestCase spúšťa jednu metódu určenú menom.

Pri chybe setUp sa vynechá telo aj tearDown, upratovacie funkcie sa vykonajú v opačnom poradí registrácie. subTest označí neúspešný variant a pri bežnom spustení umožní pokračovať ďalšími. Po úspešnom setUp sa tearDown vykoná aj pri zlyhaní kontroly. Funkcie pridané pomocou addCleanup sa vykonajú po tearDown alebo po neúspešnom setUp. Porovnanie hodnôt 4 a 5 skončí vo failures, iná výnimka ako ValueError v errors.

Príklad vypíše 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 pripraví stav pred testovacou metódou. assertEqual porovná výsledok s očakávaním. assertRaises(KeyError) vyžaduje túto výnimku alebo podtriedu. subTest(key=...) označí varianty v jednej metóde, takže testsRun zostane 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()

Príklady

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))

Výsledok

1 1 0

Príklad vypíše 1 1 0.

Zdroje