Nel ciclo di prova di unittest.TestSuite
, c'è una condizione break
alla partenza:
class TestSuite(BaseTestSuite):
def run(self, result, debug=False):
topLevel = False
if getattr(result, '_testRunEntered', False) is False:
result._testRunEntered = topLevel = True
for test in self:
if result.shouldStop:
break
Così sto usando una suite di test personalizzato come questo:
class CustomTestSuite(unittest.TestSuite):
""" This variant registers the test result object with all ScriptedTests,
so that a failed Loign test can abort the test suite by setting result.shouldStop
to True
"""
def run(self, result, debug=False):
for test in self._tests:
test.result = result
return super(CustomTestSuite, self).run(result, debug)
con un risultato del test personalizzato classe come questa:
class CustomTestResult(TextTestResult):
def __init__(self, stream, descriptions, verbosity):
super(CustomTestResult, self).__init__(stream, descriptions, verbosity)
self.verbosity = verbosity
self.shouldStop = False
e le mie classi di test sono come:
class ScriptedTest(unittest.TestCase):
def __init__(self, environment, test_cfg, module, test):
super(ScriptedTest, self).__init__()
self.result = None
In determinate condizioni, interrompere quindi la suite di test; per esempio, la suite di test inizia con un account di accesso, e se non funziona, non c'è bisogno di provare il resto:
try:
test_case.execute_script(test_command_list)
except AssertionError as e:
if test_case.module == 'session' and test_case.test == 'Login':
test_case.result.shouldStop = True
raise TestFatal('Login failed, aborting test.')
else:
raise sys.exc_info()
allora io uso la suite di test nel modo seguente:
suite = CustomTestSuite()
self.add_tests(suite)
result = unittest.TextTestRunner(verbosity=self.environment.verbosity, stream=UnitTestLoggerStream(self.logger),
resultclass=CustomTestResult).run(suite)
Non sono sicuro se c'è un modo migliore per farlo, ma si comporta correttamente per i miei test.
Lo uso per interrompere l'esecuzione di test prima di eseguire qualsiasi test se l'applicazione in prova è configurata con le impostazioni di prod. (in realtà, con qualsiasi impostazione non di prova.) –