Il modulo doctest effettua una ricerca nelle docstring di un modulo cercando del testo che somigli ad una sessione interattiva del Python, quindi esegue tutte le sessioni per verificare che funzionino come mostrato. Ecco un esempio piccolo ma completo:
"""
Questo è un modulo d'esempio.
L'esempio rappresenta una funzione, factorial. Per esempio,
>>> factorial(5)
120
"""
def factorial(n):
"""Restituisce il fattoriale di n , un intero esatto >= 0.
Se il risultato è abbastanza piccolo per adattarsi ad un int,
restituisce un int. Altrimenti un long.
>>> [factorial(n) for n in range(6)]
[1, 1, 2, 6, 24, 120]
>>> [factorial(long(n)) for n in range(6)]
[1, 1, 2, 6, 24, 120]
>>> factorial(30)
265252859812191058636308480000000L
>>> factorial(30L)
265252859812191058636308480000000L
>>> factorial(-1)
Traceback (most recent call last):
...
ValueError: n must be >= 0
Fattoriali di un numero in virgola mobile sono OK, ma la frazione
deve essere un intero esattamente :
>>> factorial(30.1)
Traceback (most recent call last):
...
ValueError: n must be exact integer
>>> factorial(30.0)
265252859812191058636308480000000L
Deve anche non essere ridicolmente grande:
>>> factorial(1e100)
Traceback (most recent call last):
...
OverflowError: n too large
"""
import math
if not n >= 0:
raise ValueError("n must be >= 0")
if math.floor(n) != n:
raise ValueError("n must be exact integer")
if n+1 == n: # catch a value like 1e300
raise OverflowError("n too large")
result = 1
factor = 2
while factor <= n:
try:
result *= factor
except OverflowError:
result *= long(factor)
factor += 1
return result
def _test():
import doctest, example
return doctest.testmod(example)
if __name__ == "__main__":
_test()
Se lanciate il programma example.py direttamente da riga di comando, doctest mostra la sua magia:
$ python example.py $
Non c'è nessun messaggio! È normale e significa che tutti gli esempi funzionano. Aggiungendo -v allo script, doctest stampa un resoconto dettagliato di ciò che sta testando ed un riassunto alla fine:
$ python example.py -v Running example.__doc__ Trying: factorial(5) Expecting: 120 ok 0 of 1 examples failed in example.__doc__ Running example.factorial.__doc__ Trying: [factorial(n) for n in range(6)] Expecting: [1, 1, 2, 6, 24, 120] ok Trying: [factorial(long(n)) for n in range(6)] Expecting: [1, 1, 2, 6, 24, 120] ok Trying: factorial(30) Expecting: 265252859812191058636308480000000L ok
E così di seguito, eventualmente finendo con:
Trying: factorial(1e100)
Expecting:
Traceback (most recent call last):
...
OverflowError: n too large
ok
0 of 8 examples failed in example.factorial.__doc__
2 items passed all tests:
1 tests in example
8 tests in example.factorial
9 tests in 2 items.
9 passed and 0 failed.
Test passed.
$
É tutto quello di cui avete bisogno per per cominciare ad essere produttivi con doctest! Le stringhe in doctest.py contengono informazioni dettagliate riguardo tutti gli aspetti di doctest. In questa sede abbiamo toccato solo gli argomenti principali.