CKTIS / Python
Sottotest in unittest: uguaglianza ed eccezioni attese
Verifica più input in un solo metodo di test, identifica i sottotest non riusciti e distingui un’asserzione di uguaglianza da una verifica delle eccezioni.
Versione: Python 3.12
Sintassi
with self.subTest("case label", value=value):
self.assertEqual(actual, expected)
with self.subTest(value=value):
self.assertRaises(ExpectedError, func, *args, **kwargs)
with self.assertRaises(ExpectedError):
func(*args, **kwargs)In Python 3.12, unittest.TestCase.subTest restituisce un gestore di contesto. Usa with self.subTest("etichetta", value=value): per delimitare un sottotest, ad esempio un’iterazione di un ciclo. Il messaggio facoltativo msg e gli argomenti con nome **params identificano il sottotest nel resoconto degli insuccessi; non vengono passati alla funzione sotto test.
Senza failfast, un’asserzione fallita interrompe il blocco with corrente, ma il metodo di test riprende dopo il blocco e può eseguire i sottotest successivi. I sottotest non sono metodi di test separati e non eseguono setUp() o tearDown() singolarmente. Con failfast, non dare per scontato che i sottotest successivi vengano eseguiti.
self.assertEqual(actual, expected) verifica l’uguaglianza dei valori (==), non l’identità degli oggetti (is). Se i valori sono diversi, l’asserzione fallisce. Inseriscila nel sottotest affinché il resoconto identifichi l’input che ha prodotto il risultato inatteso.
Nella forma con un oggetto invocabile, self.assertRaises(ExpectedError, func, *args, **kwargs) chiama func con gli argomenti forniti. Passa func, non func(...). L’asserzione riesce se viene sollevata l’eccezione attesa o una sua sottoclasse, fallisce se non viene sollevata alcuna eccezione e lascia propagare un’eccezione non corrispondente. In alternativa, usa with self.assertRaises(ExpectedError): e chiama la funzione dentro il blocco.
Esempi
import unittest
class ParseTests(unittest.TestCase):
def test_parse(self):
for text, expected in [("12", 13), ("-3", -3)]:
with self.subTest("valid integer", text=text):
self.assertEqual(int(text), expected)
with self.subTest("invalid integer", text="bad"):
self.assertRaises(ValueError, int, "bad")
print("Invalid input rejected")
if __name__ == "__main__":
result = ParseTests("test_parse").run()
tests, failures, errors = result.testsRun, len(result.failures), len(result.errors)
print(f"tests={tests}, failures={failures}, errors={errors}")
# The demonstration succeeds only if it records the deliberate failure.
if (tests, failures, errors) != (1, 1, 0):
raise SystemExit(1)
Risultato
Invalid input rejected tests=1, failures=1, errors=0
Il valore atteso `13` per `"12"` è volutamente errato. Il sottotest per `"-3"` riesce, mentre il caso `"bad"` stampa il messaggio solo dopo che il `ValueError` atteso è stato intercettato. Il riepilogo conta un metodo di test, un’asserzione fallita e zero errori. Lo script termina con il codice di uscita `0` se i conteggi corrispondono a questi valori.
Lezioni correlate
- Python · Lezione 37 · Avanzato · Versione: 5
Fonti
- Python 3.12 unittest — TestCase.subTest
- Python 3.12 unittest — Distinguishing test iterations using subtests
- Python 3.12 unittest — TestCase.assertEqual
- Python 3.12 unittest — TestCase.assertRaises
- Python 3.12 unittest — TestCase.run
- Python 3.12 unittest — TestResult.addSubTest
- Python 3.12 unittest — failfast command-line option