~cisco-openstack/neutron/l2network-plugin-multiblade

« back to all changes in this revision

Viewing changes to quantum/plugins/cisco/run_tests.py

Mergin Shweta's test changes, also README file.

Show diffs side-by-side

added added

removed removed

Lines of Context:
16
16
#    See the License for the specific language governing permissions and
17
17
#    limitations under the License.
18
18
 
19
 
# Colorizer Code is borrowed from Twisted:
20
 
# Copyright (c) 2001-2010 Twisted Matrix Laboratories.
21
 
#
22
 
#    Permission is hereby granted, free of charge, to any person obtaining
23
 
#    a copy of this software and associated documentation files (the
24
 
#    "Software"), to deal in the Software without restriction, including
25
 
#    without limitation the rights to use, copy, modify, merge, publish,
26
 
#    distribute, sublicense, and/or sell copies of the Software, and to
27
 
#    permit persons to whom the Software is furnished to do so, subject to
28
 
#    the following conditions:
29
 
#
30
 
#    The above copyright notice and this permission notice shall be
31
 
#    included in all copies or substantial portions of the Software.
32
 
#
33
 
#    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
34
 
#    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
35
 
#    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
36
 
#    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
37
 
#    LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
38
 
#    OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
39
 
#    WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
40
 
 
41
 
"""Unittest runner for quantum
 
19
 
 
20
"""Unittest runner for quantum OVS plugin
 
21
 
 
22
This file should be run from the top dir in the quantum directory
42
23
 
43
24
To run all test::
44
 
    python run_tests.py
 
25
    python quantum/plugins/cisco/run_tests.py
45
26
 
46
27
To run all unit tests::
47
 
    python run_tests.py unit
 
28
    python quantum/plugins/cisco/run_tests.py quantum.plugins.cisco.tests.unit
48
29
 
49
30
To run all functional tests::
50
 
    python run_tests.py functional
 
31
    python quantum/plugins/openvswitch/run_tests.py functional
51
32
 
52
33
To run a single unit test::
53
 
    python run_tests.py unit.test_stores:TestSwiftBackend.test_get
 
34
    python  quantum/plugins/openvswitch/run_tests.py \
 
35
        quantum.plugins.cisco.tests.unit.test_stores:TestSwiftBackend.test_get
54
36
 
55
37
To run a single functional test::
56
 
    python run_tests.py functional.test_service:TestController.test_create
 
38
    python  quantum/plugins/openvswitch/run_tests.py \
 
39
    quantum.plugins.cisco.tests.functional.test_service \
 
40
    :TestController.test_create
57
41
 
58
42
To run a single unit test module::
59
 
    python run_tests.py unit.test_stores
 
43
    python quantum/plugins/openvswitch/run_tests.py unit.test_stores
60
44
 
61
45
To run a single functional test module::
62
 
    python run_tests.py functional.test_stores
 
46
    python quantum/plugins/openvswitch/run_tests.py functional.test_stores
63
47
"""
64
48
 
65
49
import gettext
69
53
import sys
70
54
 
71
55
from nose import config
72
 
from nose import result
73
 
from nose import core
74
 
 
75
 
 
76
 
class _AnsiColorizer(object):
77
 
    """
78
 
    A colorizer is an object that loosely wraps around a stream, allowing
79
 
    callers to write text to the stream in a particular color.
80
 
 
81
 
    Colorizer classes must implement C{supported()} and C{write(text, color)}.
82
 
    """
83
 
    _colors = dict(black=30, red=31, green=32, yellow=33,
84
 
                   blue=34, magenta=35, cyan=36, white=37)
85
 
 
86
 
    def __init__(self, stream):
87
 
        self.stream = stream
88
 
 
89
 
    def supported(cls, stream=sys.stdout):
90
 
        """
91
 
        A class method that returns True if the current platform supports
92
 
        coloring terminal output using this method. Returns False otherwise.
93
 
        """
94
 
        if not stream.isatty():
95
 
            return False  # auto color only on TTYs
96
 
        try:
97
 
            import curses
98
 
        except ImportError:
99
 
            return False
100
 
        else:
101
 
            try:
102
 
                try:
103
 
                    return curses.tigetnum("colors") > 2
104
 
                except curses.error:
105
 
                    curses.setupterm()
106
 
                    return curses.tigetnum("colors") > 2
107
 
            except:
108
 
                raise
109
 
                # guess false in case of error
110
 
                return False
111
 
    supported = classmethod(supported)
112
 
 
113
 
    def write(self, text, color):
114
 
        """
115
 
        Write the given text to the stream in the given color.
116
 
 
117
 
        @param text: Text to be written to the stream.
118
 
 
119
 
        @param color: A string label for a color. e.g. 'red', 'white'.
120
 
        """
121
 
        color = self._colors[color]
122
 
        self.stream.write('\x1b[%s;1m%s\x1b[0m' % (color, text))
123
 
 
124
 
 
125
 
class _Win32Colorizer(object):
126
 
    """
127
 
    See _AnsiColorizer docstring.
128
 
    """
129
 
    def __init__(self, stream):
130
 
        from win32console import GetStdHandle, STD_OUT_HANDLE, \
131
 
             FOREGROUND_RED, FOREGROUND_BLUE, FOREGROUND_GREEN, \
132
 
             FOREGROUND_INTENSITY
133
 
        red, green, blue, bold = (FOREGROUND_RED, FOREGROUND_GREEN,
134
 
                                  FOREGROUND_BLUE, FOREGROUND_INTENSITY)
135
 
        self.stream = stream
136
 
        self.screenBuffer = GetStdHandle(STD_OUT_HANDLE)
137
 
        self._colors = {
138
 
            'normal': red | green | blue,
139
 
            'red': red | bold,
140
 
            'green': green | bold,
141
 
            'blue': blue | bold,
142
 
            'yellow': red | green | bold,
143
 
            'magenta': red | blue | bold,
144
 
            'cyan': green | blue | bold,
145
 
            'white': red | green | blue | bold}
146
 
 
147
 
    def supported(cls, stream=sys.stdout):
148
 
        try:
149
 
            import win32console
150
 
            screenBuffer = win32console.GetStdHandle(
151
 
                win32console.STD_OUT_HANDLE)
152
 
        except ImportError:
153
 
            return False
154
 
        import pywintypes
155
 
        try:
156
 
            screenBuffer.SetConsoleTextAttribute(
157
 
                win32console.FOREGROUND_RED |
158
 
                win32console.FOREGROUND_GREEN |
159
 
                win32console.FOREGROUND_BLUE)
160
 
        except pywintypes.error:
161
 
            return False
162
 
        else:
163
 
            return True
164
 
    supported = classmethod(supported)
165
 
 
166
 
    def write(self, text, color):
167
 
        color = self._colors[color]
168
 
        self.screenBuffer.SetConsoleTextAttribute(color)
169
 
        self.stream.write(text)
170
 
        self.screenBuffer.SetConsoleTextAttribute(self._colors['normal'])
171
 
 
172
 
 
173
 
class _NullColorizer(object):
174
 
    """
175
 
    See _AnsiColorizer docstring.
176
 
    """
177
 
    def __init__(self, stream):
178
 
        self.stream = stream
179
 
 
180
 
    def supported(cls, stream=sys.stdout):
181
 
        return True
182
 
    supported = classmethod(supported)
183
 
 
184
 
    def write(self, text, color):
185
 
        self.stream.write(text)
186
 
 
187
 
 
188
 
class QuantumTestResult(result.TextTestResult):
189
 
    def __init__(self, *args, **kw):
190
 
        result.TextTestResult.__init__(self, *args, **kw)
191
 
        self._last_case = None
192
 
        self.colorizer = None
193
 
        # NOTE(vish, tfukushima): reset stdout for the terminal check
194
 
        stdout = sys.__stdout__
195
 
        for colorizer in [_Win32Colorizer, _AnsiColorizer, _NullColorizer]:
196
 
            if colorizer.supported():
197
 
                self.colorizer = colorizer(self.stream)
198
 
                break
199
 
        sys.stdout = stdout
200
 
 
201
 
    def getDescription(self, test):
202
 
        return str(test)
203
 
 
204
 
    # NOTE(vish, tfukushima): copied from unittest with edit to add color
205
 
    def addSuccess(self, test):
206
 
        unittest.TestResult.addSuccess(self, test)
207
 
        if self.showAll:
208
 
            self.colorizer.write("OK", 'green')
209
 
            self.stream.writeln()
210
 
        elif self.dots:
211
 
            self.stream.write('.')
212
 
            self.stream.flush()
213
 
 
214
 
    # NOTE(vish, tfukushima): copied from unittest with edit to add color
215
 
    def addFailure(self, test, err):
216
 
        unittest.TestResult.addFailure(self, test, err)
217
 
        if self.showAll:
218
 
            self.colorizer.write("FAIL", 'red')
219
 
            self.stream.writeln()
220
 
        elif self.dots:
221
 
            self.stream.write('F')
222
 
            self.stream.flush()
223
 
 
224
 
    # NOTE(vish, tfukushima): copied from unittest with edit to add color
225
 
    def addError(self, test, err):
226
 
        """Overrides normal addError to add support for errorClasses.
227
 
        If the exception is a registered class, the error will be added
228
 
        to the list for that class, not errors.
229
 
        """
230
 
        stream = getattr(self, 'stream', None)
231
 
        ec, ev, tb = err
232
 
        try:
233
 
            exc_info = self._exc_info_to_string(err, test)
234
 
        except TypeError:
235
 
            # This is for compatibility with Python 2.3.
236
 
            exc_info = self._exc_info_to_string(err)
237
 
        for cls, (storage, label, isfail) in self.errorClasses.items():
238
 
            if result.isclass(ec) and issubclass(ec, cls):
239
 
                if isfail:
240
 
                    test.passwd = False
241
 
                storage.append((test, exc_info))
242
 
                # Might get patched into a streamless result
243
 
                if stream is not None:
244
 
                    if self.showAll:
245
 
                        message = [label]
246
 
                        detail = result._exception_details(err[1])
247
 
                        if detail:
248
 
                            message.append(detail)
249
 
                        stream.writeln(": ".join(message))
250
 
                    elif self.dots:
251
 
                        stream.write(label[:1])
252
 
                return
253
 
        self.errors.append((test, exc_info))
254
 
        test.passed = False
255
 
        if stream is not None:
256
 
            if self.showAll:
257
 
                self.colorizer.write("ERROR", 'red')
258
 
                self.stream.writeln()
259
 
            elif self.dots:
260
 
                stream.write('E')
261
 
 
262
 
    def startTest(self, test):
263
 
        unittest.TestResult.startTest(self, test)
264
 
        current_case = test.test.__class__.__name__
265
 
 
266
 
        if self.showAll:
267
 
            if current_case != self._last_case:
268
 
                self.stream.writeln(current_case)
269
 
                self._last_case = current_case
270
 
 
271
 
            self.stream.write(
272
 
                '    %s' % str(test.test._testMethodName).ljust(60))
273
 
            self.stream.flush()
274
 
 
275
 
 
276
 
class QuantumTestRunner(core.TextTestRunner):
277
 
    def _makeResult(self):
278
 
        return QuantumTestResult(self.stream,
279
 
                              self.descriptions,
280
 
                              self.verbosity,
281
 
                              self.config)
282
 
 
 
56
 
 
57
sys.path.append(os.getcwd())
 
58
 
 
59
from quantum.common.test_lib import run_tests, test_config
 
60
#from quantum.plugins.openvswitch.tests.test_vlan_map import VlanMapTest
283
61
 
284
62
if __name__ == '__main__':
285
 
    # Set up test logger.
286
 
    logger = logging.getLogger()
287
 
    hdlr = logging.StreamHandler()
288
 
    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
289
 
    hdlr.setFormatter(formatter)
290
 
    logger.addHandler(hdlr)
291
 
    logger.setLevel(logging.DEBUG)
 
63
    exit_status = False
 
64
 
 
65
    # if a single test case was specified,
 
66
    # we should only invoked the tests once
 
67
    invoke_once = len(sys.argv) > 1
 
68
 
 
69
    cwd = os.getcwd()
292
70
 
293
71
    working_dir = os.path.abspath("tests")
294
72
    c = config.Config(stream=sys.stdout,
295
73
                      env=os.environ,
296
74
                      verbosity=3,
297
75
                      workingDir=working_dir)
298
 
    runner = QuantumTestRunner(stream=c.stream,
299
 
                            verbosity=c.verbosity,
300
 
                            config=c)
301
 
    sys.exit(not core.run(config=c, testRunner=runner))
 
76
    exit_status = run_tests(c)
 
77
 
 
78
    if invoke_once:
 
79
        sys.exit(0)
 
80
 
 
81
    os.chdir(cwd)
 
82
 
 
83
    working_dir = os.path.abspath("quantum/plugins/cisco/tests")
 
84
    c = config.Config(stream=sys.stdout,
 
85
                      env=os.environ,
 
86
                      verbosity=3,
 
87
                      workingDir=working_dir)
 
88
    exit_status = exit_status or run_tests(c)
 
89
 
 
90
    sys.exit(exit_status)