3 # Copyright (c) 2016 Cable Television Laboratories, Inc. and others.
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
10 """Define the parent class to run unittest.TestSuite as TestCase."""
12 from __future__ import division
20 from xtesting.core import testcase
22 __author__ = ("Steven Pisarski <s.pisarski@cablelabs.com>, "
23 "Cedric Ollivier <cedric.ollivier@orange.com>")
26 class Suite(testcase.TestCase):
27 """Base model for running unittest.TestSuite."""
29 __logger = logging.getLogger(__name__)
31 def __init__(self, **kwargs):
32 super(Suite, self).__init__(**kwargs)
35 def run(self, **kwargs):
36 """Run the test suite.
38 It allows running any unittest.TestSuite and getting its
41 By default, it runs the suite defined as instance attribute.
42 It can be overriden by passing name as arg. It must
43 conform with TestLoader.loadTestsFromName().
45 It sets the following attributes required to push the results
54 kwargs: Arbitrary keyword arguments.
57 TestCase.EX_OK if any TestSuite has been run,
58 TestCase.EX_RUN_ERROR otherwise.
63 self.suite = unittest.TestLoader().loadTestsFromName(name)
65 self.__logger.error("Can not import %s", name)
66 return testcase.TestCase.EX_RUN_ERROR
71 self.start_time = time.time()
72 stream = six.StringIO()
73 result = unittest.TextTestRunner(
74 stream=stream, verbosity=2).run(self.suite)
75 self.__logger.debug("\n\n%s", stream.getvalue())
76 self.stop_time = time.time()
78 "testsRun": result.testsRun,
79 "failures": len(result.failures),
80 "errors": len(result.errors),
81 "stream": stream.getvalue()}
83 (result.testsRun - (len(result.failures) +
84 len(result.errors))) /
86 return testcase.TestCase.EX_OK
87 except AssertionError:
88 self.__logger.error("No suite is defined")
89 return testcase.TestCase.EX_RUN_ERROR
90 except ZeroDivisionError:
91 self.__logger.error("No test has been run")
92 return testcase.TestCase.EX_RUN_ERROR