CKTIS / Python
Testy i asercje
Test porównuje rzeczywiste zachowanie z oczekiwaniem, także po obu stronach wartości granicznej.
Wersja: Python 3.14; repository image, production runtime not attested
Składnia
self.assertEqual(actual, expected)
with self.assertRaises(ValueError):
operation()Test porównuje rzeczywiste zachowanie z oczekiwaniem, także po obu stronach wartości granicznej.
assertEqual sprawdza wynik, a assertRaises wymaga wskazanego wyjątku lub podklasy. Brak wyjątku powoduje niepowodzenie, inny wyjątek może stać się błędem testu. Instrukcje assert mogą zniknąć przy -O, metody TestCase nadal wykonują kontrolę.
Jedna metoda sprawdza 9, 10 oraz -1. Wynik 1 True oznacza jeden udany test, a nie jedną asercję.
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))
Przykłady
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())
Wynik
1 True
Jedna metoda sprawdza 9, 10 oraz -1. Wynik 1 True oznacza jeden udany test, a nie jedną asercję.