Supponiamo che abbiamo dovrebbe occupare del genere:Come utilizzare pytest per controllare che l'errore non viene generato
import py, pytest
ERROR1 = ' --- Error : value < 5! ---'
ERROR2 = ' --- Error : value > 10! ---'
class MyError(Exception):
def __init__(self, m):
self.m = m
def __str__(self):
return self.m
def foo(i):
if i < 5:
raise MyError(ERROR1)
elif i > 10:
raise MyError(ERROR2)
return i
# ---------------------- TESTS -------------------------
def test_foo1():
with pytest.raises(MyError) as e:
foo(3)
assert ERROR1 in str(e)
def test_foo2():
with pytest.raises(MyError) as e:
foo(11)
assert ERROR2 in str(e)
def test_foo3():
....
foo(7)
....
D: Come posso fare test_foo3() per testare, che nessuna MyError è sollevata? E 'ovvio, che ho potuto solo prova:
def test_foo3():
assert foo(7) == 7
ma voglio provare che via pytest.raises(). È possibile in qualche modo? Ad esempio: in un caso, tale funzione "foo" non ha alcun ritorno valore,
def foo(i):
if i < 5:
raise MyError(ERROR1)
elif i > 10:
raise MyError(ERROR2)
potrebbe avere senso per testare questo modo, imho.
Sembra cercare un problema, il test del codice 'foo (7)' va bene. Otterrai il messaggio giusto e sarà più facile eseguire il debug con tutti gli output pytest. Il suggerimento che hai forzato da @Faruk (''Errore inaspettato ...'') non dice nulla sull'errore e rimarrai bloccato. L'unica cosa che puoi fare per renderlo migliore è dichiarare la tua intenzione come 'test_foo3_works_on_integers_within_range()'. – dhill