1
# Copyright (C) 2005 by Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
"""Enhanced layer on unittest.
20
This does several things:
22
* nicer reporting as tests run
24
* test code can log messages into a buffer that is recorded to disk
25
and displayed if the test fails
27
* tests can be run in a separate directory, which is useful for code that
30
* utilities to run external commands and check their return code
33
Test cases should normally subclass TestBase. The test runner should
36
This is meant to become independent of bzr, though that's not quite
41
from unittest import TestResult, TestCase
43
def _need_subprocess():
44
sys.stderr.write("sorry, this test suite requires the subprocess module\n"
45
"this is shipped with python2.4 and available separately for 2.3\n")
48
class CommandFailed(Exception):
53
class TestSkipped(Exception):
54
"""Indicates that a test was intentionally skipped, rather than failing."""
58
class TestBase(TestCase):
59
"""Base class for bzr test cases.
61
Just defines some useful helper functions; doesn't actually test
65
# TODO: Special methods to invoke bzr, so that we can run it
66
# through a specified Python intepreter
68
OVERRIDE_PYTHON = None # to run with alternative python 'python'
75
super(TestBase, self).setUp()
76
self.log("%s setup" % self.id())
80
super(TestBase, self).tearDown()
81
self.log("%s teardown" % self.id())
85
def formcmd(self, cmd):
86
if isinstance(cmd, basestring):
91
if self.OVERRIDE_PYTHON:
92
cmd.insert(0, self.OVERRIDE_PYTHON)
94
self.log('$ %r' % cmd)
99
def runcmd(self, cmd, retcode=0):
100
"""Run one command and check the return code.
102
Returns a tuple of (stdout,stderr) strings.
104
If a single string is based, it is split into words.
105
For commands that are not simple space-separated words, please
106
pass a list instead."""
109
from subprocess import call
110
except ImportError, e:
115
cmd = self.formcmd(cmd)
117
self.log('$ ' + ' '.join(cmd))
118
actual_retcode = call(cmd, stdout=self.TEST_LOG, stderr=self.TEST_LOG)
120
if retcode != actual_retcode:
121
raise CommandFailed("test failed: %r returned %d, expected %d"
122
% (cmd, actual_retcode, retcode))
125
def backtick(self, cmd, retcode=0):
126
"""Run a command and return its output"""
129
from subprocess import Popen, PIPE
130
except ImportError, e:
134
cmd = self.formcmd(cmd)
135
child = Popen(cmd, stdout=PIPE, stderr=self.TEST_LOG)
136
outd, errd = child.communicate()
138
actual_retcode = child.wait()
140
outd = outd.replace('\r', '')
142
if retcode != actual_retcode:
143
raise CommandFailed("test failed: %r returned %d, expected %d"
144
% (cmd, actual_retcode, retcode))
150
def build_tree(self, shape):
151
"""Build a test tree according to a pattern.
153
shape is a sequence of file specifications. If the final
154
character is '/', a directory is created.
156
This doesn't add anything to a branch.
158
# XXX: It's OK to just create them using forward slashes on windows?
161
assert isinstance(name, basestring)
166
print >>f, "contents of", name
171
"""Log a message to a progress file"""
172
self._log_buf = self._log_buf + str(msg) + '\n'
173
print >>self.TEST_LOG, msg
176
def check_inventory_shape(self, inv, shape):
178
Compare an inventory to a list of expected names.
180
Fail if they are not precisely equal.
183
shape = list(shape) # copy
184
for path, ie in inv.entries():
185
name = path.replace('\\', '/')
193
self.fail("expected paths not found in inventory: %r" % shape)
195
self.fail("unexpected paths found in inventory: %r" % extras)
198
def check_file_contents(self, filename, expect):
199
self.log("check contents of file %s" % filename)
200
contents = file(filename, 'r').read()
201
if contents != expect:
202
self.log("expected: %r" % expect)
203
self.log("actually: %r" % contents)
204
self.fail("contents of %s not as expected")
208
class InTempDir(TestBase):
209
"""Base class for tests run in a temporary branch."""
212
self.test_dir = os.path.join(self.TEST_ROOT, self.__class__.__name__)
213
os.mkdir(self.test_dir)
214
os.chdir(self.test_dir)
218
os.chdir(self.TEST_ROOT)
224
class _MyResult(TestResult):
228
No special behaviour for now.
230
def __init__(self, out, style):
232
TestResult.__init__(self)
233
assert style in ('none', 'progress', 'verbose')
237
def startTest(self, test):
238
# TODO: Maybe show test.shortDescription somewhere?
240
# python2.3 has the bad habit of just "runit" for doctests
242
what = test.shortDescription()
244
if self.style == 'verbose':
245
print >>self.out, '%-60.60s' % what,
247
elif self.style == 'progress':
250
TestResult.startTest(self, test)
253
def stopTest(self, test):
255
TestResult.stopTest(self, test)
258
def addError(self, test, err):
259
if self.style == 'verbose':
260
print >>self.out, 'ERROR'
261
TestResult.addError(self, test, err)
262
_show_test_failure('error', test, err, self.out)
264
def addFailure(self, test, err):
265
if self.style == 'verbose':
266
print >>self.out, 'FAILURE'
267
TestResult.addFailure(self, test, err)
268
_show_test_failure('failure', test, err, self.out)
270
def addSuccess(self, test):
271
if self.style == 'verbose':
272
print >>self.out, 'OK'
273
TestResult.addSuccess(self, test)
277
def run_suite(suite, name='test', verbose=False):
283
_setup_test_log(name)
284
_setup_test_dir(name)
287
# save stdout & stderr so there's no leakage from code-under-test
288
real_stdout = sys.stdout
289
real_stderr = sys.stderr
290
sys.stdout = sys.stderr = TestBase.TEST_LOG
296
result = _MyResult(real_stdout, style)
299
sys.stdout = real_stdout
300
sys.stderr = real_stderr
302
_show_results(result)
304
return result.wasSuccessful()
308
def _setup_test_log(name):
312
log_filename = os.path.abspath(name + '.log')
313
TestBase.TEST_LOG = open(log_filename, 'wt', buffering=1) # line buffered
315
print >>TestBase.TEST_LOG, "tests run at " + time.ctime()
316
print '%-30s %s' % ('test log', log_filename)
319
def _setup_test_dir(name):
323
TestBase.ORIG_DIR = os.getcwdu()
324
TestBase.TEST_ROOT = os.path.abspath(name + '.tmp')
326
print '%-30s %s' % ('running tests in', TestBase.TEST_ROOT)
328
if os.path.exists(TestBase.TEST_ROOT):
329
shutil.rmtree(TestBase.TEST_ROOT)
330
os.mkdir(TestBase.TEST_ROOT)
331
os.chdir(TestBase.TEST_ROOT)
333
# make a fake bzr directory there to prevent any tests propagating
334
# up onto the source directory's real branch
335
os.mkdir(os.path.join(TestBase.TEST_ROOT, '.bzr'))
339
def _show_results(result):
341
print '%4d tests run' % result.testsRun
342
print '%4d errors' % len(result.errors)
343
print '%4d failures' % len(result.failures)
347
def _show_test_failure(kind, case, exc_info, out):
348
from traceback import print_exception
350
print >>out, '-' * 60
353
desc = case.shortDescription()
355
print >>out, ' (%s)' % desc
357
print_exception(exc_info[0], exc_info[1], exc_info[2], None, out)
359
if isinstance(case, TestBase):
361
print >>out, 'log from this test:'
362
print >>out, case._log_buf
364
print >>out, '-' * 60