Per assicurarsi che i messaggi di errore dal mio modulo siano informativi, vorrei vedere tutti i messaggi di errore rilevati da assertRaises(). Oggi lo faccio per ogni assertRaises(), ma poiché ce ne sono molti nel codice di test diventa molto noioso.Come mostrare i messaggi di errore rilevati da assertRaises() in unittest in Python2.7?
Come posso stampare i messaggi di errore per tutte le assertRaises()? Ho studiato la documentazione su http://docs.python.org/library/unittest.html senza capire come risolverlo. Posso in qualche modo monkeypatch il metodo assertRaises()? Preferisco non modificare tutte le righe assertRaises() nel codice di test, poiché il più delle volte utilizzo il codice di prova nel modo standard.
Credo che questa domanda è legata alla Python unittest: how do I test the argument in an Exceptions?
Questo è come lo faccio oggi. Per esempio:
#!/usr/bin/env python
def fail():
raise ValueError('Misspellled errrorr messageee')
E il codice di prova:
#!/usr/bin/env python
import unittest
import failure
class TestFailureModule(unittest.TestCase):
def testFail(self):
self.assertRaises(ValueError, failure.fail)
if __name__ == '__main__':
unittest.main()
Per controllare il messaggio di errore, ho semplicemente cambiare il tipo di errore nelle assertRaises() per, ad esempio IOError. Quindi posso vedere il messaggio di errore:
E
======================================================================
ERROR: testFail (__main__.TestFailureModule)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test_failure.py", line 8, in testFail
self.assertRaises(IOError, failure.fail)
File "/usr/lib/python2.7/unittest/case.py", line 471, in assertRaises
callableObj(*args, **kwargs)
File "/home/jonas/Skrivbord/failure.py", line 4, in fail
raise ValueError('Misspellled errrorr messageee')
ValueError: Misspellled errrorr messageee
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
Qualche suggerimento? /Jonas
EDIT:
Con i suggerimenti di Robert Rossney sono riuscito a risolvere il problema. Non è principalmente inteso per errori di ortografia, ma per assicurarsi che i messaggi di errore siano veramente significativi per l'utente del modulo. La normale funzionalità di unittest (questo è il modo in cui la utilizzo la maggior parte delle volte) si ottiene impostando SHOW_ERROR_MESSAGES = False.
Semplicemente sovrascrivo il metodo assertRaises(), come illustrato di seguito. Funziona come un incantesimo!
SHOW_ERROR_MESSAGES = True
class NonexistantError(Exception):
pass
class ExtendedTestCase(unittest.TestCase):
def assertRaises(self, excClass, callableObj, *args, **kwargs):
if SHOW_ERROR_MESSAGES:
excClass = NonexistantError
try:
unittest.TestCase.assertRaises(self, excClass, callableObj, *args, **kwargs)
except:
print '\n ' + repr(sys.exc_info()[1])
Una frazione del output risultante:
testNotIntegerInput (__main__.TestCheckRegisteraddress) ...
TypeError('The registeraddress must be an integer. Given: 1.0',)
TypeError("The registeraddress must be an integer. Given: '1'",)
TypeError('The registeraddress must be an integer. Given: [1]',)
TypeError('The registeraddress must be an integer. Given: None',)
ok
testCorrectNumberOfBytes (__main__.TestCheckResponseNumberOfBytes) ... ok
testInconsistentLimits (__main__.TestCheckNumerical) ...
ValueError('The maxvalue must not be smaller than minvalue. Given: 45 and 47, respectively.',)
ValueError('The maxvalue must not be smaller than minvalue. Given: 45.0 and 47.0, respectively.',)
ok
testWrongValues (__main__.TestCheckRegisteraddress) ...
ValueError('The registeraddress is too small: -1, but minimum value is 0.',)
ValueError('The registeraddress is too large: 65536, but maximum value is 65535.',)
ok
testTooShortString (__main__.TestCheckResponseWriteData) ...
ValueError("The payload is too short: 2, but minimum value is 4. Given: '\\x00X'",)
ValueError("The payload is too short: 0, but minimum value is 4. Given: ''",)
ValueError("The writedata is too short: 1, but minimum value is 2. Given: 'X'",)
ValueError("The writedata is too short: 0, but minimum value is 2. Given: ''",)
ok
testKnownValues (__main__.TestCreateBitPattern) ... ok
testNotIntegerInput (__main__.TestCheckSlaveaddress) ...
TypeError('The slaveaddress must be an integer. Given: 1.0',)
TypeError("The slaveaddress must be an integer. Given: '1'",)
TypeError('The slaveaddress must be an integer. Given: [1]',)
TypeError('The slaveaddress must be an integer. Given: None',)
ok
Perché continuare a utilizzare assertRaises se è necessario controllare gli argomenti? Perché non catturare semplicemente l'eccezione ed esaminarla usando 'try' e' except'? –