~ubuntu-branches/ubuntu/precise/glance/precise-security

« back to all changes in this revision

Viewing changes to .pc/disable_db_table_auto_create.patch/run_tests.py

  • Committer: Package Import Robot
  • Author(s): Adam Gandelman, Adam Gandelman, Chuck Short
  • Date: 2012-04-12 15:02:08 UTC
  • Revision ID: package-import@ubuntu.com-20120412150208-slfoy4vx2pqr4v6h
Tags: 2012.1-0ubuntu2
[ Adam Gandelman ]
* debian/patches/disable_db_table_auto_create.patch: Disable auto-creation
  of database schema at service start, inspect for consistenty and advise
  running manual migrations instead.
* debian/patches/fix_migration_012_foreign_keys.patch: Fix a migration issue
  around missing FKs. Cherry-picked from upstream.  Can be dropped with
  first stable update.
* debian/patches/convert_properties_to_uuid.patch: Fixes migration 012 to
  also convert kernel_id and ramdisk_ids to UUID. Cherry picked from upstream.
  Can be dropped with first stable update (LP: #975651)
* debian/glance-common.postinst: Clean up, fix purging issue due to poor
  us of conditionals
* debian/glance-registry.postinst:  Ensure new database is version_controlled
  before first call of db_sync. 

[ Chuck Short ]
* debian/control: Fix upgrades from oneiric to precise. (LP: #974592)

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/env python
 
2
# vim: tabstop=4 shiftwidth=4 softtabstop=4
 
3
 
 
4
# Copyright 2010 OpenStack, LLC
 
5
# All Rights Reserved.
 
6
#
 
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
 
10
#
 
11
#        http://www.apache.org/licenses/LICENSE-2.0
 
12
#
 
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.
 
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
"""
 
42
Unittest runner for glance
 
43
 
 
44
To run all test::
 
45
    python run_tests.py
 
46
 
 
47
To run a single test::
 
48
    python run_tests.py test_stores:TestSwiftBackend.test_get
 
49
 
 
50
To run a single test module::
 
51
    python run_tests.py test_stores
 
52
"""
 
53
 
 
54
import gettext
 
55
import logging
 
56
import os
 
57
import unittest
 
58
import sys
 
59
 
 
60
gettext.install('glance', unicode=1)
 
61
 
 
62
from glance.tests import logcapture
 
63
 
 
64
from nose import config
 
65
from nose import result
 
66
from nose import core
 
67
 
 
68
 
 
69
class _AnsiColorizer(object):
 
70
    """
 
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.
 
73
 
 
74
    Colorizer classes must implement C{supported()} and C{write(text, color)}.
 
75
    """
 
76
    _colors = dict(black=30, red=31, green=32, yellow=33,
 
77
                   blue=34, magenta=35, cyan=36, white=37)
 
78
 
 
79
    def __init__(self, stream):
 
80
        self.stream = stream
 
81
 
 
82
    def supported(cls, stream=sys.stdout):
 
83
        """
 
84
        A class method that returns True if the current platform supports
 
85
        coloring terminal output using this method. Returns False otherwise.
 
86
        """
 
87
        if not stream.isatty():
 
88
            return False  # auto color only on TTYs
 
89
        try:
 
90
            import curses
 
91
        except ImportError:
 
92
            return False
 
93
        else:
 
94
            try:
 
95
                try:
 
96
                    return curses.tigetnum("colors") > 2
 
97
                except curses.error:
 
98
                    curses.setupterm()
 
99
                    return curses.tigetnum("colors") > 2
 
100
            except:
 
101
                raise
 
102
                # guess false in case of error
 
103
                return False
 
104
    supported = classmethod(supported)
 
105
 
 
106
    def write(self, text, color):
 
107
        """
 
108
        Write the given text to the stream in the given color.
 
109
 
 
110
        @param text: Text to be written to the stream.
 
111
 
 
112
        @param color: A string label for a color. e.g. 'red', 'white'.
 
113
        """
 
114
        color = self._colors[color]
 
115
        self.stream.write('\x1b[%s;1m%s\x1b[0m' % (color, text))
 
116
 
 
117
 
 
118
class _Win32Colorizer(object):
 
119
    """
 
120
    See _AnsiColorizer docstring.
 
121
    """
 
122
    def __init__(self, stream):
 
123
        from win32console import GetStdHandle, STD_OUT_HANDLE, \
 
124
             FOREGROUND_RED, FOREGROUND_BLUE, FOREGROUND_GREEN, \
 
125
             FOREGROUND_INTENSITY
 
126
        red, green, blue, bold = (FOREGROUND_RED, FOREGROUND_GREEN,
 
127
                                  FOREGROUND_BLUE, FOREGROUND_INTENSITY)
 
128
        self.stream = stream
 
129
        self.screenBuffer = GetStdHandle(STD_OUT_HANDLE)
 
130
        self._colors = {
 
131
            'normal': red | green | blue,
 
132
            'red': red | bold,
 
133
            'green': green | bold,
 
134
            'blue': blue | bold,
 
135
            'yellow': red | green | bold,
 
136
            'magenta': red | blue | bold,
 
137
            'cyan': green | blue | bold,
 
138
            'white': red | green | blue | bold}
 
139
 
 
140
    def supported(cls, stream=sys.stdout):
 
141
        try:
 
142
            import win32console
 
143
            screenBuffer = win32console.GetStdHandle(
 
144
                win32console.STD_OUT_HANDLE)
 
145
        except ImportError:
 
146
            return False
 
147
        import pywintypes
 
148
        try:
 
149
            screenBuffer.SetConsoleTextAttribute(
 
150
                win32console.FOREGROUND_RED |
 
151
                win32console.FOREGROUND_GREEN |
 
152
                win32console.FOREGROUND_BLUE)
 
153
        except pywintypes.error:
 
154
            return False
 
155
        else:
 
156
            return True
 
157
    supported = classmethod(supported)
 
158
 
 
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'])
 
164
 
 
165
 
 
166
class _NullColorizer(object):
 
167
    """
 
168
    See _AnsiColorizer docstring.
 
169
    """
 
170
    def __init__(self, stream):
 
171
        self.stream = stream
 
172
 
 
173
    def supported(cls, stream=sys.stdout):
 
174
        return True
 
175
    supported = classmethod(supported)
 
176
 
 
177
    def write(self, text, color):
 
178
        self.stream.write(text)
 
179
 
 
180
 
 
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
 
187
        stdout = sys.stdout
 
188
        sys.stdout = sys.__stdout__
 
189
        for colorizer in [_Win32Colorizer, _AnsiColorizer, _NullColorizer]:
 
190
            if colorizer.supported():
 
191
                self.colorizer = colorizer(self.stream)
 
192
                break
 
193
        sys.stdout = stdout
 
194
 
 
195
    def getDescription(self, test):
 
196
        return str(test)
 
197
 
 
198
    # NOTE(vish, tfukushima): copied from unittest with edit to add color
 
199
    def addSuccess(self, test):
 
200
        unittest.TestResult.addSuccess(self, test)
 
201
        if self.showAll:
 
202
            self.colorizer.write("OK", 'green')
 
203
            self.stream.writeln()
 
204
        elif self.dots:
 
205
            self.stream.write('.')
 
206
            self.stream.flush()
 
207
 
 
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)
 
211
        if self.showAll:
 
212
            self.colorizer.write("FAIL", 'red')
 
213
            self.stream.writeln()
 
214
        elif self.dots:
 
215
            self.stream.write('F')
 
216
            self.stream.flush()
 
217
 
 
218
    # NOTE(vish, tfukushima): copied from unittest with edit to add color
 
219
    def addError(self, test, err):
 
220
        """
 
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.
 
224
        """
 
225
        stream = getattr(self, 'stream', None)
 
226
        ec, ev, tb = err
 
227
        try:
 
228
            exc_info = self._exc_info_to_string(err, test)
 
229
        except TypeError:
 
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):
 
234
                if isfail:
 
235
                    test.passwd = False
 
236
                storage.append((test, exc_info))
 
237
                # Might get patched into a streamless result
 
238
                if stream is not None:
 
239
                    if self.showAll:
 
240
                        message = [label]
 
241
                        detail = result._exception_detail(err[1])
 
242
                        if detail:
 
243
                            message.append(detail)
 
244
                        stream.writeln(": ".join(message))
 
245
                    elif self.dots:
 
246
                        stream.write(label[:1])
 
247
                return
 
248
        self.errors.append((test, exc_info))
 
249
        test.passed = False
 
250
        if stream is not None:
 
251
            if self.showAll:
 
252
                self.colorizer.write("ERROR", 'red')
 
253
                self.stream.writeln()
 
254
            elif self.dots:
 
255
                stream.write('E')
 
256
 
 
257
    def startTest(self, test):
 
258
        unittest.TestResult.startTest(self, test)
 
259
        current_case = test.test.__class__.__name__
 
260
 
 
261
        if self.showAll:
 
262
            if current_case != self._last_case:
 
263
                self.stream.writeln(current_case)
 
264
                self._last_case = current_case
 
265
 
 
266
            self.stream.write(
 
267
                '    %s' % str(test.test._testMethodName).ljust(60))
 
268
            self.stream.flush()
 
269
 
 
270
 
 
271
class GlanceTestRunner(core.TextTestRunner):
 
272
    def _makeResult(self):
 
273
        return GlanceTestResult(self.stream,
 
274
                              self.descriptions,
 
275
                              self.verbosity,
 
276
                              self.config)
 
277
 
 
278
 
 
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)
 
286
 
 
287
    c = config.Config(stream=sys.stdout,
 
288
                      env=os.environ,
 
289
                      verbosity=3,
 
290
                      plugins=core.DefaultPluginManager())
 
291
 
 
292
    runner = GlanceTestRunner(stream=c.stream,
 
293
                            verbosity=c.verbosity,
 
294
                            config=c)
 
295
    sys.exit(not core.run(config=c, testRunner=runner,
 
296
                          addplugins=[logcapture.GlanceLogCapture()]))