69
68
OVERRIDE_PYTHON = None # to run with alternative python 'python'
76
super(TestBase, self).setUp()
72
super(TestCase, self).setUp()
73
# setup a temporary log for the test
77
self.TEST_LOG = tempfile.NamedTemporaryFile(mode='wt', bufsize=0)
78
# save stdout & stderr so there's no leakage from code-under-test
79
self.real_stdout = sys.stdout
80
self.real_stderr = sys.stderr
81
sys.stdout = sys.stderr = self.TEST_LOG
77
82
self.log("%s setup" % self.id())
80
84
def tearDown(self):
81
super(TestBase, self).tearDown()
85
sys.stdout = self.real_stdout
86
sys.stderr = self.real_stderr
82
87
self.log("%s teardown" % self.id())
89
super(TestCase, self).tearDown()
92
"""Log a message to a progress file"""
93
print >>self.TEST_LOG, msg
95
def check_inventory_shape(self, inv, shape):
97
Compare an inventory to a list of expected names.
99
Fail if they are not precisely equal.
102
shape = list(shape) # copy
103
for path, ie in inv.entries():
104
name = path.replace('\\', '/')
112
self.fail("expected paths not found in inventory: %r" % shape)
114
self.fail("unexpected paths found in inventory: %r" % extras)
117
"""Get the log the test case used. This can only be called once,
118
after which an exception will be raised.
120
self.TEST_LOG.flush()
121
log = open(self.TEST_LOG.name, 'rt').read()
122
self.TEST_LOG.close()
126
class FunctionalTestCase(TestCase):
127
"""Base class for tests that perform function testing - running bzr,
128
using files on disk, and similar activities.
130
InTempDir is an old alias for FunctionalTestCase.
136
def check_file_contents(self, filename, expect):
137
self.log("check contents of file %s" % filename)
138
contents = file(filename, 'r').read()
139
if contents != expect:
140
self.log("expected: %r" % expect)
141
self.log("actually: %r" % contents)
142
self.fail("contents of %s not as expected")
144
def _make_test_root(self):
149
if FunctionalTestCase.TEST_ROOT is not None:
151
FunctionalTestCase.TEST_ROOT = os.path.abspath(
152
tempfile.mkdtemp(suffix='.tmp',
153
prefix=self._TEST_NAME + '-',
156
# make a fake bzr directory there to prevent any tests propagating
157
# up onto the source directory's real branch
158
os.mkdir(os.path.join(FunctionalTestCase.TEST_ROOT, '.bzr'))
161
super(FunctionalTestCase, self).setUp()
163
self._make_test_root()
164
self._currentdir = os.getcwdu()
165
self.test_dir = os.path.join(self.TEST_ROOT, self.id())
166
os.mkdir(self.test_dir)
167
os.chdir(self.test_dir)
171
os.chdir(self._currentdir)
172
super(FunctionalTestCase, self).tearDown()
86
174
def formcmd(self, cmd):
87
175
if isinstance(cmd, basestring):
90
177
if cmd[0] == 'bzr':
91
178
cmd[0] = self.BZRPATH
92
179
if self.OVERRIDE_PYTHON:
93
180
cmd.insert(0, self.OVERRIDE_PYTHON)
95
181
self.log('$ %r' % cmd)
100
184
def runcmd(self, cmd, retcode=0):
101
185
"""Run one command and check the return code.
166
245
f = file(name, 'wt')
167
246
print >>f, "contents of", name
172
"""Log a message to a progress file"""
173
# XXX: The problem with this is that code that writes straight
174
# to the log file won't be shown when we display the log
175
# buffer; would be better to not have the in-memory buffer and
176
# instead just a log file per test, which is read in and
177
# displayed if the test fails. That seems to imply one log
178
# per test case, not globally. OK?
179
self._log_buf = self._log_buf + str(msg) + '\n'
180
print >>self.TEST_LOG, msg
183
def check_inventory_shape(self, inv, shape):
185
Compare an inventory to a list of expected names.
187
Fail if they are not precisely equal.
190
shape = list(shape) # copy
191
for path, ie in inv.entries():
192
name = path.replace('\\', '/')
200
self.fail("expected paths not found in inventory: %r" % shape)
202
self.fail("unexpected paths found in inventory: %r" % extras)
205
def check_file_contents(self, filename, expect):
206
self.log("check contents of file %s" % filename)
207
contents = file(filename, 'r').read()
208
if contents != expect:
209
self.log("expected: %r" % expect)
210
self.log("actually: %r" % contents)
211
self.fail("contents of %s not as expected")
215
class InTempDir(TestBase):
216
"""Base class for tests run in a temporary branch."""
219
self.test_dir = os.path.join(self.TEST_ROOT, self.__class__.__name__)
220
os.mkdir(self.test_dir)
221
os.chdir(self.test_dir)
225
os.chdir(self.TEST_ROOT)
231
class _MyResult(TestResult):
249
InTempDir = FunctionalTestCase
252
class _MyResult(unittest._TextTestResult):
233
254
Custom TestResult.
235
256
No special behaviour for now.
237
def __init__(self, out, style):
239
TestResult.__init__(self)
240
assert style in ('none', 'progress', 'verbose')
244
259
def startTest(self, test):
260
unittest.TestResult.startTest(self, test)
245
261
# TODO: Maybe show test.shortDescription somewhere?
247
263
# python2.3 has the bad habit of just "runit" for doctests
248
264
if what == 'runit':
249
265
what = test.shortDescription()
251
if self.style == 'verbose':
252
print >>self.out, '%-60.60s' % what,
254
elif self.style == 'progress':
257
TestResult.startTest(self, test)
260
def stopTest(self, test):
262
TestResult.stopTest(self, test)
267
self.stream.write('%-60.60s' % what)
265
270
def addError(self, test, err):
266
if self.style == 'verbose':
267
print >>self.out, 'ERROR'
268
TestResult.addError(self, test, err)
269
_show_test_failure('error', test, err, self.out)
271
super(_MyResult, self).addError(test, err)
271
274
def addFailure(self, test, err):
272
if self.style == 'verbose':
273
print >>self.out, 'FAILURE'
274
TestResult.addFailure(self, test, err)
275
_show_test_failure('failure', test, err, self.out)
275
super(_MyResult, self).addFailure(test, err)
277
278
def addSuccess(self, test):
278
if self.style == 'verbose':
279
print >>self.out, 'OK'
280
TestResult.addSuccess(self, test)
280
self.stream.writeln('OK')
282
self.stream.write('~')
284
unittest.TestResult.addSuccess(self, test)
286
def printErrorList(self, flavour, errors):
287
for test, err in errors:
288
self.stream.writeln(self.separator1)
289
self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
290
self.stream.writeln(self.separator2)
291
self.stream.writeln("%s" % err)
292
if isinstance(test, TestCase):
293
self.stream.writeln()
294
self.stream.writeln('log from this test:')
295
print >>self.stream, test._get_log()
298
class TextTestRunner(unittest.TextTestRunner):
300
def _makeResult(self):
301
return _MyResult(self.stream, self.descriptions, self.verbosity)
284
304
def run_suite(suite, name='test', verbose=False):
290
_setup_test_log(name)
291
_setup_test_dir(name)
294
# save stdout & stderr so there's no leakage from code-under-test
295
real_stdout = sys.stdout
296
real_stderr = sys.stderr
297
sys.stdout = sys.stderr = TestBase.TEST_LOG
303
result = _MyResult(real_stdout, style)
306
sys.stdout = real_stdout
307
sys.stderr = real_stderr
309
_show_results(result)
306
FunctionalTestCase._TEST_NAME = name
311
runner = TextTestRunner(stream=sys.stdout,
314
result = runner.run(suite)
315
# This is still a little bogus,
316
# but only a little. Folk not using our testrunner will
317
# have to delete their temp directories themselves.
318
if result.wasSuccessful():
319
shutil.rmtree(FunctionalTestCase.TEST_ROOT)
321
print "Failed tests working directories are in '%s'\n" % FunctionalTestCase.TEST_ROOT
311
322
return result.wasSuccessful()
315
def _setup_test_log(name):
319
log_filename = os.path.abspath(name + '.log')
320
TestBase.TEST_LOG = open(log_filename, 'wt', buffering=1) # line buffered
322
print >>TestBase.TEST_LOG, "tests run at " + time.ctime()
323
print '%-30s %s' % ('test log', log_filename)
326
def _setup_test_dir(name):
330
TestBase.ORIG_DIR = os.getcwdu()
331
TestBase.TEST_ROOT = os.path.abspath(name + '.tmp')
333
print '%-30s %s' % ('running tests in', TestBase.TEST_ROOT)
335
if os.path.exists(TestBase.TEST_ROOT):
336
shutil.rmtree(TestBase.TEST_ROOT)
337
os.mkdir(TestBase.TEST_ROOT)
338
os.chdir(TestBase.TEST_ROOT)
340
# make a fake bzr directory there to prevent any tests propagating
341
# up onto the source directory's real branch
342
os.mkdir(os.path.join(TestBase.TEST_ROOT, '.bzr'))
346
def _show_results(result):
348
print '%4d tests run' % result.testsRun
349
print '%4d errors' % len(result.errors)
350
print '%4d failures' % len(result.failures)
354
def _show_test_failure(kind, case, exc_info, out):
355
from traceback import print_exception
358
print >>out, '-' * 60
361
desc = case.shortDescription()
363
print >>out, ' (%s)' % desc
365
print_exception(exc_info[0], exc_info[1], exc_info[2], None, out)
367
if isinstance(case, TestBase):
369
print >>out, 'log from this test:'
370
print >>out, case._log_buf
372
print >>out, '-' * 60