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
from unittest import TestResult, TestCase
22
from subprocess import call, Popen, PIPE
23
except ImportError, e:
24
sys.stderr.write("sorry, this test suite requires the subprocess module\n"
25
"this is shipped with python2.4 and available separately for 2.3\n")
29
class CommandFailed(Exception):
34
class TestSkipped(Exception):
35
"""Indicates that a test was intentionally skipped, rather than failing."""
39
class TestBase(TestCase):
40
"""Base class for bzr test cases.
42
Just defines some useful helper functions; doesn't actually test
46
# TODO: Special methods to invoke bzr, so that we can run it
47
# through a specified Python intepreter
49
OVERRIDE_PYTHON = None # to run with alternative python 'python'
56
super(TestBase, self).setUp()
57
self.log("%s setup" % self.id())
61
super(TestBase, self).tearDown()
62
self.log("%s teardown" % self.id())
66
def formcmd(self, cmd):
67
if isinstance(cmd, basestring):
72
if self.OVERRIDE_PYTHON:
73
cmd.insert(0, self.OVERRIDE_PYTHON)
75
self.log('$ %r' % cmd)
80
def runcmd(self, cmd, retcode=0):
81
"""Run one command and check the return code.
83
Returns a tuple of (stdout,stderr) strings.
85
If a single string is based, it is split into words.
86
For commands that are not simple space-separated words, please
87
pass a list instead."""
88
cmd = self.formcmd(cmd)
90
self.log('$ ' + ' '.join(cmd))
91
actual_retcode = call(cmd, stdout=self.TEST_LOG, stderr=self.TEST_LOG)
93
if retcode != actual_retcode:
94
raise CommandFailed("test failed: %r returned %d, expected %d"
95
% (cmd, actual_retcode, retcode))
98
def backtick(self, cmd, retcode=0):
99
"""Run a command and return its output"""
100
cmd = self.formcmd(cmd)
101
child = Popen(cmd, stdout=PIPE, stderr=self.TEST_LOG)
102
outd, errd = child.communicate()
104
actual_retcode = child.wait()
106
outd = outd.replace('\r', '')
108
if retcode != actual_retcode:
109
raise CommandFailed("test failed: %r returned %d, expected %d"
110
% (cmd, actual_retcode, retcode))
116
def build_tree(self, shape):
117
"""Build a test tree according to a pattern.
119
shape is a sequence of file specifications. If the final
120
character is '/', a directory is created.
122
This doesn't add anything to a branch.
124
# XXX: It's OK to just create them using forward slashes on windows?
127
assert isinstance(name, basestring)
132
print >>f, "contents of", name
137
"""Log a message to a progress file"""
138
self._log_buf = self._log_buf + str(msg) + '\n'
139
print >>self.TEST_LOG, msg
142
def check_inventory_shape(self, inv, shape):
144
Compare an inventory to a list of expected names.
146
Fail if they are not precisely equal.
149
shape = list(shape) # copy
150
for path, ie in inv.entries():
151
name = path.replace('\\', '/')
159
self.fail("expected paths not found in inventory: %r" % shape)
161
self.fail("unexpected paths found in inventory: %r" % extras)
164
def check_file_contents(self, filename, expect):
165
self.log("check contents of file %s" % filename)
166
contents = file(filename, 'r').read()
167
if contents != expect:
168
self.log("expected: %r" % expected)
169
self.log("actually: %r" % contents)
170
self.fail("contents of %s not as expected")
174
class InTempDir(TestBase):
175
"""Base class for tests run in a temporary branch."""
178
self.test_dir = os.path.join(self.TEST_ROOT, self.__class__.__name__)
179
os.mkdir(self.test_dir)
180
os.chdir(self.test_dir)
184
os.chdir(self.TEST_ROOT)
190
class _MyResult(TestResult):
194
No special behaviour for now.
196
def __init__(self, out):
198
TestResult.__init__(self)
200
def startTest(self, test):
201
# TODO: Maybe show test.shortDescription somewhere?
202
print >>self.out, '%-60.60s' % test.id(),
204
TestResult.startTest(self, test)
206
def stopTest(self, test):
208
TestResult.stopTest(self, test)
211
def addError(self, test, err):
212
print >>self.out, 'ERROR'
213
TestResult.addError(self, test, err)
214
_show_test_failure('error', test, err, self.out)
216
def addFailure(self, test, err):
217
print >>self.out, 'FAILURE'
218
TestResult.addFailure(self, test, err)
219
_show_test_failure('failure', test, err, self.out)
221
def addSuccess(self, test):
222
print >>self.out, 'OK'
223
TestResult.addSuccess(self, test)
228
from unittest import TestLoader, TestSuite
230
import bzrlib.selftest.whitebox
231
import bzrlib.selftest.blackbox
232
import bzrlib.selftest.versioning
233
from doctest import DocTestSuite
242
for m in bzrlib.selftest.whitebox, \
243
bzrlib.selftest.versioning:
244
suite.addTest(tl.loadTestsFromModule(m))
246
for m in bzrlib.store, bzrlib.inventory, bzrlib.branch, bzrlib.osutils, \
248
suite.addTest(DocTestSuite(m))
250
suite.addTest(bzrlib.selftest.blackbox.suite())
252
return run_suite(suite)
255
def run_suite(suite):
265
# save stdout & stderr so there's no leakage from code-under-test
266
real_stdout = sys.stdout
267
real_stderr = sys.stderr
268
sys.stdout = sys.stderr = TestBase.TEST_LOG
270
result = _MyResult(real_stdout)
273
sys.stdout = real_stdout
274
sys.stderr = real_stderr
276
_show_results(result)
278
return result.wasSuccessful()
282
def _setup_test_log():
286
log_filename = os.path.abspath('test.log')
287
TestBase.TEST_LOG = open(log_filename, 'wt', buffering=1) # line buffered
289
print >>TestBase.TEST_LOG, "tests run at " + time.ctime()
290
print '%-30s %s' % ('test log', log_filename)
293
def _setup_test_dir():
297
TestBase.ORIG_DIR = os.getcwdu()
298
TestBase.TEST_ROOT = os.path.abspath("test.tmp")
300
print '%-30s %s' % ('running tests in', TestBase.TEST_ROOT)
302
if os.path.exists(TestBase.TEST_ROOT):
303
shutil.rmtree(TestBase.TEST_ROOT)
304
os.mkdir(TestBase.TEST_ROOT)
305
os.chdir(TestBase.TEST_ROOT)
307
# make a fake bzr directory there to prevent any tests propagating
308
# up onto the source directory's real branch
309
os.mkdir(os.path.join(TestBase.TEST_ROOT, '.bzr'))
313
def _show_results(result):
315
print '%4d tests run' % result.testsRun
316
print '%4d errors' % len(result.errors)
317
print '%4d failures' % len(result.failures)
321
def _show_test_failure(kind, case, exc_info, out):
322
from traceback import print_exception
324
print >>out, '-' * 60
327
desc = case.shortDescription()
329
print >>out, ' (%s)' % desc
331
print_exception(exc_info[0], exc_info[1], exc_info[2], None, out)
333
if isinstance(case, TestBase):
335
print >>out, 'log from this test:'
336
print >>out, case._log_buf
338
print >>out, '-' * 60