Sono nuovo di pytest e sto provando a convertire alcuni script di test funzionali in quelli che funzionano bene con pytest. Il mio modulo ha tipi di errore personalizzati e sto cercando di utilizzare il metodo "con pytest.raises() as excinfo". Questo è un pacchetto scientifico/numerico e ho bisogno di verificare che certi metodi siano coerenti quando vengono chiamati, quindi non posso semplicemente approfondire le cose di livello inferiore. Grazieutilizzando pytest.raises per rilevare l'errore personalizzato previsto
13
A
risposta
27
Che cosa si intende interrompere importando l'eccezione specifica e utilizzandola nell'istruzione with
pytest.raises? Perché non funziona? Sarebbe più utile se potessi fornire maggiori dettagli su quale problema stai affrontando.
# your code
class CustomError(Exception):
pass
def foo():
raise ValueError('everything is broken')
def bar():
raise CustomError('still broken')
#############
# your test
import pytest
# import your module, or functions from it, incl. exception class
def test_fooErrorHandling():
with pytest.raises(ValueError) as excinfo:
foo()
assert excinfo.value.message == 'everything is broken'
def test_barSimpleErrorHandling():
# don't care about the specific message
with pytest.raises(CustomError):
bar()
def test_barSpecificErrorHandling():
# check the specific error message
with pytest.raises(MyErr) as excinfo:
bar()
assert excinfo.value.message == 'oh no!'
def test_barWithoutImportingExceptionClass():
# if for some reason you can't import the specific exception class,
# catch it as generic and verify it's in the str(excinfo)
with pytest.raises(Exception) as excinfo:
bar()
assert 'MyErr:' in str(excinfo)
Sembra che il tuo ultimo 'con py.test.raises' dovrebbe essere' con pytest.raises' –
@IanHunter aggiornato ora, grazie (si può dire sto ancora utilizzando la versione 'py.test':)) – pfctdayelise
Per python3: 'assert str (excinfo.value) == 'tutto è rotto'' – incognick