2
# vim: tabstop=4 shiftwidth=4 softtabstop=4
4
# Copyright 2010 OpenStack, LLC
7
# Licensed under the Apache License, Version 2.0 (the "License");
8
# you may not use this file except in compliance with the License.
9
# You may obtain a copy of the License at
11
# http://www.apache.org/licenses/LICENSE-2.0
13
# Unless required by applicable law or agreed to in writing, software
14
# distributed under the License is distributed on an "AS IS" BASIS,
15
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
# See the License for the specific language governing permissions and
17
# limitations under the License.
19
# Colorizer Code is borrowed from Twisted:
20
# Copyright (c) 2001-2010 Twisted Matrix Laboratories.
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:
30
# The above copyright notice and this permission notice shall be
31
# included in all copies or substantial portions of the Software.
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.
42
Unittest runner for glance
47
To run a single test::
48
python run_tests.py test_stores:TestSwiftBackend.test_get
50
To run a single test module::
51
python run_tests.py test_stores
60
gettext.install('glance', unicode=1)
62
from glance.tests import logcapture
64
from nose import config
65
from nose import result
69
class _AnsiColorizer(object):
71
A colorizer is an object that loosely wraps around a stream, allowing
72
callers to write text to the stream in a particular color.
74
Colorizer classes must implement C{supported()} and C{write(text, color)}.
76
_colors = dict(black=30, red=31, green=32, yellow=33,
77
blue=34, magenta=35, cyan=36, white=37)
79
def __init__(self, stream):
82
def supported(cls, stream=sys.stdout):
84
A class method that returns True if the current platform supports
85
coloring terminal output using this method. Returns False otherwise.
87
if not stream.isatty():
88
return False # auto color only on TTYs
96
return curses.tigetnum("colors") > 2
99
return curses.tigetnum("colors") > 2
102
# guess false in case of error
104
supported = classmethod(supported)
106
def write(self, text, color):
108
Write the given text to the stream in the given color.
110
@param text: Text to be written to the stream.
112
@param color: A string label for a color. e.g. 'red', 'white'.
114
color = self._colors[color]
115
self.stream.write('\x1b[%s;1m%s\x1b[0m' % (color, text))
118
class _Win32Colorizer(object):
120
See _AnsiColorizer docstring.
122
def __init__(self, stream):
123
from win32console import GetStdHandle, STD_OUT_HANDLE, \
124
FOREGROUND_RED, FOREGROUND_BLUE, FOREGROUND_GREEN, \
126
red, green, blue, bold = (FOREGROUND_RED, FOREGROUND_GREEN,
127
FOREGROUND_BLUE, FOREGROUND_INTENSITY)
129
self.screenBuffer = GetStdHandle(STD_OUT_HANDLE)
131
'normal': red | green | blue,
133
'green': green | bold,
135
'yellow': red | green | bold,
136
'magenta': red | blue | bold,
137
'cyan': green | blue | bold,
138
'white': red | green | blue | bold}
140
def supported(cls, stream=sys.stdout):
143
screenBuffer = win32console.GetStdHandle(
144
win32console.STD_OUT_HANDLE)
149
screenBuffer.SetConsoleTextAttribute(
150
win32console.FOREGROUND_RED |
151
win32console.FOREGROUND_GREEN |
152
win32console.FOREGROUND_BLUE)
153
except pywintypes.error:
157
supported = classmethod(supported)
159
def write(self, text, color):
160
color = self._colors[color]
161
self.screenBuffer.SetConsoleTextAttribute(color)
162
self.stream.write(text)
163
self.screenBuffer.SetConsoleTextAttribute(self._colors['normal'])
166
class _NullColorizer(object):
168
See _AnsiColorizer docstring.
170
def __init__(self, stream):
173
def supported(cls, stream=sys.stdout):
175
supported = classmethod(supported)
177
def write(self, text, color):
178
self.stream.write(text)
181
class GlanceTestResult(result.TextTestResult):
182
def __init__(self, *args, **kw):
183
result.TextTestResult.__init__(self, *args, **kw)
184
self._last_case = None
185
self.colorizer = None
186
# NOTE(vish, tfukushima): reset stdout for the terminal check
188
sys.stdout = sys.__stdout__
189
for colorizer in [_Win32Colorizer, _AnsiColorizer, _NullColorizer]:
190
if colorizer.supported():
191
self.colorizer = colorizer(self.stream)
195
def getDescription(self, test):
198
# NOTE(vish, tfukushima): copied from unittest with edit to add color
199
def addSuccess(self, test):
200
unittest.TestResult.addSuccess(self, test)
202
self.colorizer.write("OK", 'green')
203
self.stream.writeln()
205
self.stream.write('.')
208
# NOTE(vish, tfukushima): copied from unittest with edit to add color
209
def addFailure(self, test, err):
210
unittest.TestResult.addFailure(self, test, err)
212
self.colorizer.write("FAIL", 'red')
213
self.stream.writeln()
215
self.stream.write('F')
218
# NOTE(vish, tfukushima): copied from unittest with edit to add color
219
def addError(self, test, err):
221
Overrides normal addError to add support for errorClasses.
222
If the exception is a registered class, the error will be added
223
to the list for that class, not errors.
225
stream = getattr(self, 'stream', None)
228
exc_info = self._exc_info_to_string(err, test)
230
# This is for compatibility with Python 2.3.
231
exc_info = self._exc_info_to_string(err)
232
for cls, (storage, label, isfail) in self.errorClasses.items():
233
if result.isclass(ec) and issubclass(ec, cls):
236
storage.append((test, exc_info))
237
# Might get patched into a streamless result
238
if stream is not None:
241
detail = result._exception_detail(err[1])
243
message.append(detail)
244
stream.writeln(": ".join(message))
246
stream.write(label[:1])
248
self.errors.append((test, exc_info))
250
if stream is not None:
252
self.colorizer.write("ERROR", 'red')
253
self.stream.writeln()
257
def startTest(self, test):
258
unittest.TestResult.startTest(self, test)
259
current_case = test.test.__class__.__name__
262
if current_case != self._last_case:
263
self.stream.writeln(current_case)
264
self._last_case = current_case
267
' %s' % str(test.test._testMethodName).ljust(60))
271
class GlanceTestRunner(core.TextTestRunner):
272
def _makeResult(self):
273
return GlanceTestResult(self.stream,
279
if __name__ == '__main__':
280
logger = logging.getLogger()
281
hdlr = logging.StreamHandler()
282
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
283
hdlr.setFormatter(formatter)
284
logger.addHandler(hdlr)
285
logger.setLevel(logging.DEBUG)
287
c = config.Config(stream=sys.stdout,
290
plugins=core.DefaultPluginManager())
292
runner = GlanceTestRunner(stream=c.stream,
293
verbosity=c.verbosity,
295
sys.exit(not core.run(config=c, testRunner=runner,
296
addplugins=[logcapture.GlanceLogCapture()]))