Context engineering
| Tipo di test | Come si fa | Quando usarlo | Esempio |
|---|---|---|---|
| Test manuale | Inserimento diretto di input e osservazione dell’output | In fase iniziale o esplorativa | Avviare una funzione e vedere se stampa ciò che ci si aspetta |
| Test automatico | Codice che verifica altre funzioni | In sviluppo e debugging professionale | Uso del modulo unittest |
Esempio – Funzione da testare:
def somma(a, b):
return a + b
✅ Test manuale:
print(somma(2, 3)) # Output atteso: 5
✅ Test automatico:
import unittest
class TestSomma(unittest.TestCase):
def test_somma_interi(self):
self.assertEqual(somma(2, 3), 5)
def test_somma_zero(self):
self.assertEqual(somma(0, 0), 0)
def test_somma_negativi(self):
self.assertEqual(somma(-1, -2), -3)
if __name__ == '__main__':
unittest.main()
Cosa succede se l’input non è previsto?
💥 Codice con errore:
print(somma("a", 2)) # Errore: TypeError
🎯 Possiamo gestire l’errore oppure testarlo:
def somma(a, b):
if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
raise TypeError("Devono essere numeri")
return a + b
✅ E relativo test:
def test_tipo_errato(self):
with self.assertRaises(TypeError):
somma("a", 2)
Funzione di esempio:
def dividi(a, b):
return a / b
Scrivi 3 test:
b = 1try/except o testare con assertRaises)unittestCrea un file test_calcoli.py e importa:
import unittest
from calcoli import somma, dividi
Usa setUp() per inizializzare valori, tearDown() per pulire.
👩💻 App: un calcolatore che fa somma, sottrazione, moltiplicazione, divisione.
📦 Struttura:
progetto_calcolatrice/
│
├── calcolatrice.py # Funzioni
├── app.py # Interfaccia utente
└── test_calcolatrice.py # Test con unittest
👨🔬 Esempi di test da includere:
test_somma_positivitest_divisione_zerotest_input_stringa (che solleva errore)1. Perché servono i test nei programmi?
A) Per scrivere meno codice
B) Per controllare che il programma funzioni
C) Per evitare i commenti
2. Cosa fa assertEqual() in unittest?
A) Confronta due numeri
B) Controlla che due valori siano uguali
C) Aggiunge due numeri
3. Come si scrive un test per un errore previsto?
A) assertErrore()
B) assertRaises()
C) tryAssert()
4. Qual è la differenza tra test manuale e test automatico?
A) Il manuale si scrive da soli, l’automatico no
B) Il manuale si osserva, l’automatico è codice
C) Nessuna
5. Dove si scrivono i test automatici?
A) In fogli di calcolo
B) In file .txt
C) In file .py con unittest
6. Il test self.assertEqual(somma(2, 2), 5) è…
A) Corretto
B) Fallito
C) Sintattico
Risposte
B B B B C B
Commenti
Posta un commento