Add docstrings in unit
[functest.git] / functest / core / unit.py
1 #!/usr/bin/env python
2
3 # Copyright (c) 2016 Cable Television Laboratories, Inc. and others.
4 #
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
9
10 """Define the parent class to run unittest.TestSuite as TestCase."""
11
12 from __future__ import division
13
14 import logging
15 import time
16 import unittest
17
18 import six
19
20 from functest.core import testcase
21
22 __author__ = ("Steven Pisarski <s.pisarski@cablelabs.com>, "
23               "Cedric Ollivier <cedric.ollivier@orange.com>")
24
25
26 class Suite(testcase.TestCase):
27     """Base model for running unittest.TestSuite."""
28
29     def __init__(self, **kwargs):
30         super(Suite, self).__init__(**kwargs)
31         self.suite = None
32         self.logger = logging.getLogger(__name__)
33
34     def run(self, **kwargs):
35         """Run the test suite.
36
37         It allows running any unittest.TestSuite and getting its
38         execution status.
39
40         By default, it runs the suite defined as instance attribute.
41         It can be overriden by passing name as arg. It must
42         conform with TestLoader.loadTestsFromName().
43
44         It sets the following attributes required to push the results
45         to DB:
46
47             * result,
48             * start_time,
49             * stop_time,
50             * details.
51
52         Args:
53             kwargs: Arbitrary keyword arguments.
54
55         Returns:
56             TestCase.EX_OK if any TestSuite has been run,
57             TestCase.EX_RUN_ERROR otherwise.
58         """
59         try:
60             name = kwargs["name"]
61             try:
62                 self.suite = unittest.TestLoader().loadTestsFromName(name)
63             except ImportError:
64                 self.logger.error("Can not import %s", name)
65                 return testcase.TestCase.EX_RUN_ERROR
66         except KeyError:
67             pass
68         self.start_time = time.time()
69         stream = six.StringIO()
70         result = unittest.TextTestRunner(
71             stream=stream, verbosity=2).run(self.suite)
72         self.logger.debug("\n\n%s", stream.getvalue())
73         self.stop_time = time.time()
74         self.details = {"failures": result.failures,
75                         "errors": result.errors}
76         try:
77             self.result = 100 * (
78                 (result.testsRun - (len(result.failures) +
79                                     len(result.errors))) /
80                 result.testsRun)
81             return testcase.TestCase.EX_OK
82         except ZeroDivisionError:
83             self.logger.error("No test has been run")
84             return testcase.TestCase.EX_RUN_ERROR