1
# Copyright (C) 2005, 2006, 2007 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
17
"""Tests for the test framework."""
21
from StringIO import StringIO
36
from bzrlib.progress import _BaseProgressBar
37
from bzrlib.repofmt import weaverepo
38
from bzrlib.symbol_versioning import zero_ten, zero_eleven
39
from bzrlib.tests import (
43
TestCaseWithMemoryTransport,
44
TestCaseWithTransport,
49
from bzrlib.tests.test_sftp_transport import TestCaseWithSFTPServer
50
from bzrlib.tests.TestUtil import _load_module_by_name
51
from bzrlib.trace import note
52
from bzrlib.transport.memory import MemoryServer, MemoryTransport
53
from bzrlib.version import _get_bzr_source_tree
56
class SelftestTests(TestCase):
58
def test_import_tests(self):
59
mod = _load_module_by_name('bzrlib.tests.test_selftest')
60
self.assertEqual(mod.SelftestTests, SelftestTests)
62
def test_import_test_failure(self):
63
self.assertRaises(ImportError,
67
class MetaTestLog(TestCase):
69
def test_logging(self):
70
"""Test logs are captured when a test fails."""
71
self.log('a test message')
72
self._log_file.flush()
73
self.assertContainsRe(self._get_log(keep_log_file=True),
77
class TestTreeShape(TestCaseInTempDir):
79
def test_unicode_paths(self):
80
filename = u'hell\u00d8'
82
self.build_tree_contents([(filename, 'contents of hello')])
83
except UnicodeEncodeError:
84
raise TestSkipped("can't build unicode working tree in "
85
"filesystem encoding %s" % sys.getfilesystemencoding())
86
self.failUnlessExists(filename)
89
class TestTransportProviderAdapter(TestCase):
90
"""A group of tests that test the transport implementation adaption core.
92
This is a meta test that the tests are applied to all available
95
This will be generalised in the future which is why it is in this
96
test file even though it is specific to transport tests at the moment.
99
def test_get_transport_permutations(self):
100
# this checks that we the module get_test_permutations call
101
# is made by the adapter get_transport_test_permitations method.
102
class MockModule(object):
103
def get_test_permutations(self):
104
return sample_permutation
105
sample_permutation = [(1,2), (3,4)]
106
from bzrlib.transport import TransportTestProviderAdapter
107
adapter = TransportTestProviderAdapter()
108
self.assertEqual(sample_permutation,
109
adapter.get_transport_test_permutations(MockModule()))
111
def test_adapter_checks_all_modules(self):
112
# this checks that the adapter returns as many permurtations as
113
# there are in all the registered# transport modules for there
114
# - we assume if this matches its probably doing the right thing
115
# especially in combination with the tests for setting the right
117
from bzrlib.transport import (TransportTestProviderAdapter,
118
_get_transport_modules
120
modules = _get_transport_modules()
121
permutation_count = 0
122
for module in modules:
124
permutation_count += len(reduce(getattr,
125
(module + ".get_test_permutations").split('.')[1:],
126
__import__(module))())
127
except errors.DependencyNotPresent:
129
input_test = TestTransportProviderAdapter(
130
"test_adapter_sets_transport_class")
131
adapter = TransportTestProviderAdapter()
132
self.assertEqual(permutation_count,
133
len(list(iter(adapter.adapt(input_test)))))
135
def test_adapter_sets_transport_class(self):
136
# Check that the test adapter inserts a transport and server into the
139
# This test used to know about all the possible transports and the
140
# order they were returned but that seems overly brittle (mbp
142
input_test = TestTransportProviderAdapter(
143
"test_adapter_sets_transport_class")
144
from bzrlib.transport import TransportTestProviderAdapter
145
suite = TransportTestProviderAdapter().adapt(input_test)
146
tests = list(iter(suite))
147
self.assertTrue(len(tests) > 6)
148
# there are at least that many builtin transports
150
self.assertTrue(issubclass(one_test.transport_class,
151
bzrlib.transport.Transport))
152
self.assertTrue(issubclass(one_test.transport_server,
153
bzrlib.transport.Server))
156
class TestBranchProviderAdapter(TestCase):
157
"""A group of tests that test the branch implementation test adapter."""
159
def test_adapted_tests(self):
160
# check that constructor parameters are passed through to the adapted
162
from bzrlib.branch import BranchTestProviderAdapter
163
input_test = TestBranchProviderAdapter(
164
"test_adapted_tests")
167
formats = [("c", "C"), ("d", "D")]
168
adapter = BranchTestProviderAdapter(server1, server2, formats)
169
suite = adapter.adapt(input_test)
170
tests = list(iter(suite))
171
self.assertEqual(2, len(tests))
172
self.assertEqual(tests[0].branch_format, formats[0][0])
173
self.assertEqual(tests[0].bzrdir_format, formats[0][1])
174
self.assertEqual(tests[0].transport_server, server1)
175
self.assertEqual(tests[0].transport_readonly_server, server2)
176
self.assertEqual(tests[1].branch_format, formats[1][0])
177
self.assertEqual(tests[1].bzrdir_format, formats[1][1])
178
self.assertEqual(tests[1].transport_server, server1)
179
self.assertEqual(tests[1].transport_readonly_server, server2)
182
class TestBzrDirProviderAdapter(TestCase):
183
"""A group of tests that test the bzr dir implementation test adapter."""
185
def test_adapted_tests(self):
186
# check that constructor parameters are passed through to the adapted
188
from bzrlib.bzrdir import BzrDirTestProviderAdapter
189
input_test = TestBzrDirProviderAdapter(
190
"test_adapted_tests")
194
adapter = BzrDirTestProviderAdapter(server1, server2, formats)
195
suite = adapter.adapt(input_test)
196
tests = list(iter(suite))
197
self.assertEqual(2, len(tests))
198
self.assertEqual(tests[0].bzrdir_format, formats[0])
199
self.assertEqual(tests[0].transport_server, server1)
200
self.assertEqual(tests[0].transport_readonly_server, server2)
201
self.assertEqual(tests[1].bzrdir_format, formats[1])
202
self.assertEqual(tests[1].transport_server, server1)
203
self.assertEqual(tests[1].transport_readonly_server, server2)
206
class TestRepositoryProviderAdapter(TestCase):
207
"""A group of tests that test the repository implementation test adapter."""
209
def test_adapted_tests(self):
210
# check that constructor parameters are passed through to the adapted
212
from bzrlib.repository import RepositoryTestProviderAdapter
213
input_test = TestRepositoryProviderAdapter(
214
"test_adapted_tests")
217
formats = [("c", "C"), ("d", "D")]
218
adapter = RepositoryTestProviderAdapter(server1, server2, formats)
219
suite = adapter.adapt(input_test)
220
tests = list(iter(suite))
221
self.assertEqual(2, len(tests))
222
self.assertEqual(tests[0].bzrdir_format, formats[0][1])
223
self.assertEqual(tests[0].repository_format, formats[0][0])
224
self.assertEqual(tests[0].transport_server, server1)
225
self.assertEqual(tests[0].transport_readonly_server, server2)
226
self.assertEqual(tests[1].bzrdir_format, formats[1][1])
227
self.assertEqual(tests[1].repository_format, formats[1][0])
228
self.assertEqual(tests[1].transport_server, server1)
229
self.assertEqual(tests[1].transport_readonly_server, server2)
232
class TestInterRepositoryProviderAdapter(TestCase):
233
"""A group of tests that test the InterRepository test adapter."""
235
def test_adapted_tests(self):
236
# check that constructor parameters are passed through to the adapted
238
from bzrlib.repository import InterRepositoryTestProviderAdapter
239
input_test = TestInterRepositoryProviderAdapter(
240
"test_adapted_tests")
243
formats = [(str, "C1", "C2"), (int, "D1", "D2")]
244
adapter = InterRepositoryTestProviderAdapter(server1, server2, formats)
245
suite = adapter.adapt(input_test)
246
tests = list(iter(suite))
247
self.assertEqual(2, len(tests))
248
self.assertEqual(tests[0].interrepo_class, formats[0][0])
249
self.assertEqual(tests[0].repository_format, formats[0][1])
250
self.assertEqual(tests[0].repository_format_to, formats[0][2])
251
self.assertEqual(tests[0].transport_server, server1)
252
self.assertEqual(tests[0].transport_readonly_server, server2)
253
self.assertEqual(tests[1].interrepo_class, formats[1][0])
254
self.assertEqual(tests[1].repository_format, formats[1][1])
255
self.assertEqual(tests[1].repository_format_to, formats[1][2])
256
self.assertEqual(tests[1].transport_server, server1)
257
self.assertEqual(tests[1].transport_readonly_server, server2)
260
class TestInterVersionedFileProviderAdapter(TestCase):
261
"""A group of tests that test the InterVersionedFile test adapter."""
263
def test_adapted_tests(self):
264
# check that constructor parameters are passed through to the adapted
266
from bzrlib.versionedfile import InterVersionedFileTestProviderAdapter
267
input_test = TestInterRepositoryProviderAdapter(
268
"test_adapted_tests")
271
formats = [(str, "C1", "C2"), (int, "D1", "D2")]
272
adapter = InterVersionedFileTestProviderAdapter(server1, server2, formats)
273
suite = adapter.adapt(input_test)
274
tests = list(iter(suite))
275
self.assertEqual(2, len(tests))
276
self.assertEqual(tests[0].interversionedfile_class, formats[0][0])
277
self.assertEqual(tests[0].versionedfile_factory, formats[0][1])
278
self.assertEqual(tests[0].versionedfile_factory_to, formats[0][2])
279
self.assertEqual(tests[0].transport_server, server1)
280
self.assertEqual(tests[0].transport_readonly_server, server2)
281
self.assertEqual(tests[1].interversionedfile_class, formats[1][0])
282
self.assertEqual(tests[1].versionedfile_factory, formats[1][1])
283
self.assertEqual(tests[1].versionedfile_factory_to, formats[1][2])
284
self.assertEqual(tests[1].transport_server, server1)
285
self.assertEqual(tests[1].transport_readonly_server, server2)
288
class TestRevisionStoreProviderAdapter(TestCase):
289
"""A group of tests that test the RevisionStore test adapter."""
291
def test_adapted_tests(self):
292
# check that constructor parameters are passed through to the adapted
294
from bzrlib.store.revision import RevisionStoreTestProviderAdapter
295
input_test = TestRevisionStoreProviderAdapter(
296
"test_adapted_tests")
297
# revision stores need a store factory - i.e. RevisionKnit
298
#, a readonly and rw transport
302
store_factories = ["c", "d"]
303
adapter = RevisionStoreTestProviderAdapter(server1, server2, store_factories)
304
suite = adapter.adapt(input_test)
305
tests = list(iter(suite))
306
self.assertEqual(2, len(tests))
307
self.assertEqual(tests[0].store_factory, store_factories[0][0])
308
self.assertEqual(tests[0].transport_server, server1)
309
self.assertEqual(tests[0].transport_readonly_server, server2)
310
self.assertEqual(tests[1].store_factory, store_factories[1][0])
311
self.assertEqual(tests[1].transport_server, server1)
312
self.assertEqual(tests[1].transport_readonly_server, server2)
315
class TestWorkingTreeProviderAdapter(TestCase):
316
"""A group of tests that test the workingtree implementation test adapter."""
318
def test_adapted_tests(self):
319
# check that constructor parameters are passed through to the adapted
321
from bzrlib.workingtree import WorkingTreeTestProviderAdapter
322
input_test = TestWorkingTreeProviderAdapter(
323
"test_adapted_tests")
326
formats = [("c", "C"), ("d", "D")]
327
adapter = WorkingTreeTestProviderAdapter(server1, server2, formats)
328
suite = adapter.adapt(input_test)
329
tests = list(iter(suite))
330
self.assertEqual(2, len(tests))
331
self.assertEqual(tests[0].workingtree_format, formats[0][0])
332
self.assertEqual(tests[0].bzrdir_format, formats[0][1])
333
self.assertEqual(tests[0].transport_server, server1)
334
self.assertEqual(tests[0].transport_readonly_server, server2)
335
self.assertEqual(tests[1].workingtree_format, formats[1][0])
336
self.assertEqual(tests[1].bzrdir_format, formats[1][1])
337
self.assertEqual(tests[1].transport_server, server1)
338
self.assertEqual(tests[1].transport_readonly_server, server2)
341
class TestTreeProviderAdapter(TestCase):
342
"""Test the setup of tree_implementation tests."""
344
def test_adapted_tests(self):
345
# the tree implementation adapter is meant to setup one instance for
346
# each working tree format, and one additional instance that will
347
# use the default wt format, but create a revision tree for the tests.
348
# this means that the wt ones should have the workingtree_to_test_tree
349
# attribute set to 'return_parameter' and the revision one set to
350
# revision_tree_from_workingtree.
352
from bzrlib.tests.tree_implementations import (
353
TreeTestProviderAdapter,
355
revision_tree_from_workingtree
357
from bzrlib.workingtree import WorkingTreeFormat
358
input_test = TestTreeProviderAdapter(
359
"test_adapted_tests")
362
formats = [("c", "C"), ("d", "D")]
363
adapter = TreeTestProviderAdapter(server1, server2, formats)
364
suite = adapter.adapt(input_test)
365
tests = list(iter(suite))
366
self.assertEqual(4, len(tests))
367
default_format = WorkingTreeFormat.get_default_format()
368
self.assertEqual(tests[0].workingtree_format, formats[0][0])
369
self.assertEqual(tests[0].bzrdir_format, formats[0][1])
370
self.assertEqual(tests[0].transport_server, server1)
371
self.assertEqual(tests[0].transport_readonly_server, server2)
372
self.assertEqual(tests[0].workingtree_to_test_tree, return_parameter)
373
self.assertEqual(tests[1].workingtree_format, formats[1][0])
374
self.assertEqual(tests[1].bzrdir_format, formats[1][1])
375
self.assertEqual(tests[1].transport_server, server1)
376
self.assertEqual(tests[1].transport_readonly_server, server2)
377
self.assertEqual(tests[1].workingtree_to_test_tree, return_parameter)
378
self.assertEqual(tests[2].workingtree_format, default_format)
379
self.assertEqual(tests[2].bzrdir_format, default_format._matchingbzrdir)
380
self.assertEqual(tests[2].transport_server, server1)
381
self.assertEqual(tests[2].transport_readonly_server, server2)
382
self.assertEqual(tests[2].workingtree_to_test_tree,
383
revision_tree_from_workingtree)
386
class TestInterTreeProviderAdapter(TestCase):
387
"""A group of tests that test the InterTreeTestAdapter."""
389
def test_adapted_tests(self):
390
# check that constructor parameters are passed through to the adapted
392
# for InterTree tests we want the machinery to bring up two trees in
393
# each instance: the base one, and the one we are interacting with.
394
# because each optimiser can be direction specific, we need to test
395
# each optimiser in its chosen direction.
396
# unlike the TestProviderAdapter we dont want to automatically add a
397
# parameterised one for WorkingTree - the optimisers will tell us what
399
from bzrlib.tests.tree_implementations import (
401
revision_tree_from_workingtree
403
from bzrlib.tests.intertree_implementations import (
404
InterTreeTestProviderAdapter,
406
from bzrlib.workingtree import WorkingTreeFormat2, WorkingTreeFormat3
407
input_test = TestInterTreeProviderAdapter(
408
"test_adapted_tests")
411
format1 = WorkingTreeFormat2()
412
format2 = WorkingTreeFormat3()
413
formats = [(str, format1, format2, "converter1"),
414
(int, format2, format1, "converter2")]
415
adapter = InterTreeTestProviderAdapter(server1, server2, formats)
416
suite = adapter.adapt(input_test)
417
tests = list(iter(suite))
418
self.assertEqual(2, len(tests))
419
self.assertEqual(tests[0].intertree_class, formats[0][0])
420
self.assertEqual(tests[0].workingtree_format, formats[0][1])
421
self.assertEqual(tests[0].workingtree_format_to, formats[0][2])
422
self.assertEqual(tests[0].mutable_trees_to_test_trees, formats[0][3])
423
self.assertEqual(tests[0].workingtree_to_test_tree, return_parameter)
424
self.assertEqual(tests[0].transport_server, server1)
425
self.assertEqual(tests[0].transport_readonly_server, server2)
426
self.assertEqual(tests[1].intertree_class, formats[1][0])
427
self.assertEqual(tests[1].workingtree_format, formats[1][1])
428
self.assertEqual(tests[1].workingtree_format_to, formats[1][2])
429
self.assertEqual(tests[1].mutable_trees_to_test_trees, formats[1][3])
430
self.assertEqual(tests[1].workingtree_to_test_tree, return_parameter)
431
self.assertEqual(tests[1].transport_server, server1)
432
self.assertEqual(tests[1].transport_readonly_server, server2)
435
class TestTestCaseInTempDir(TestCaseInTempDir):
437
def test_home_is_not_working(self):
438
self.assertNotEqual(self.test_dir, self.test_home_dir)
439
cwd = osutils.getcwd()
440
self.assertEqual(self.test_dir, cwd)
441
self.assertEqual(self.test_home_dir, os.environ['HOME'])
444
class TestTestCaseWithMemoryTransport(TestCaseWithMemoryTransport):
446
def test_home_is_non_existant_dir_under_root(self):
447
"""The test_home_dir for TestCaseWithMemoryTransport is missing.
449
This is because TestCaseWithMemoryTransport is for tests that do not
450
need any disk resources: they should be hooked into bzrlib in such a
451
way that no global settings are being changed by the test (only a
452
few tests should need to do that), and having a missing dir as home is
453
an effective way to ensure that this is the case.
455
self.assertEqual(self.TEST_ROOT + "/MemoryTransportMissingHomeDir",
457
self.assertEqual(self.test_home_dir, os.environ['HOME'])
459
def test_cwd_is_TEST_ROOT(self):
460
self.assertEqual(self.test_dir, self.TEST_ROOT)
461
cwd = osutils.getcwd()
462
self.assertEqual(self.test_dir, cwd)
464
def test_make_branch_and_memory_tree(self):
465
"""In TestCaseWithMemoryTransport we should not make the branch on disk.
467
This is hard to comprehensively robustly test, so we settle for making
468
a branch and checking no directory was created at its relpath.
470
tree = self.make_branch_and_memory_tree('dir')
471
# Guard against regression into MemoryTransport leaking
472
# files to disk instead of keeping them in memory.
473
self.failIf(osutils.lexists('dir'))
474
self.assertIsInstance(tree, memorytree.MemoryTree)
476
def test_make_branch_and_memory_tree_with_format(self):
477
"""make_branch_and_memory_tree should accept a format option."""
478
format = bzrdir.BzrDirMetaFormat1()
479
format.repository_format = weaverepo.RepositoryFormat7()
480
tree = self.make_branch_and_memory_tree('dir', format=format)
481
# Guard against regression into MemoryTransport leaking
482
# files to disk instead of keeping them in memory.
483
self.failIf(osutils.lexists('dir'))
484
self.assertIsInstance(tree, memorytree.MemoryTree)
485
self.assertEqual(format.repository_format.__class__,
486
tree.branch.repository._format.__class__)
489
class TestTestCaseWithTransport(TestCaseWithTransport):
490
"""Tests for the convenience functions TestCaseWithTransport introduces."""
492
def test_get_readonly_url_none(self):
493
from bzrlib.transport import get_transport
494
from bzrlib.transport.memory import MemoryServer
495
from bzrlib.transport.readonly import ReadonlyTransportDecorator
496
self.transport_server = MemoryServer
497
self.transport_readonly_server = None
498
# calling get_readonly_transport() constructs a decorator on the url
500
url = self.get_readonly_url()
501
url2 = self.get_readonly_url('foo/bar')
502
t = get_transport(url)
503
t2 = get_transport(url2)
504
self.failUnless(isinstance(t, ReadonlyTransportDecorator))
505
self.failUnless(isinstance(t2, ReadonlyTransportDecorator))
506
self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
508
def test_get_readonly_url_http(self):
509
from bzrlib.tests.HttpServer import HttpServer
510
from bzrlib.transport import get_transport
511
from bzrlib.transport.local import LocalURLServer
512
from bzrlib.transport.http import HttpTransportBase
513
self.transport_server = LocalURLServer
514
self.transport_readonly_server = HttpServer
515
# calling get_readonly_transport() gives us a HTTP server instance.
516
url = self.get_readonly_url()
517
url2 = self.get_readonly_url('foo/bar')
518
# the transport returned may be any HttpTransportBase subclass
519
t = get_transport(url)
520
t2 = get_transport(url2)
521
self.failUnless(isinstance(t, HttpTransportBase))
522
self.failUnless(isinstance(t2, HttpTransportBase))
523
self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
525
def test_is_directory(self):
526
"""Test assertIsDirectory assertion"""
527
t = self.get_transport()
528
self.build_tree(['a_dir/', 'a_file'], transport=t)
529
self.assertIsDirectory('a_dir', t)
530
self.assertRaises(AssertionError, self.assertIsDirectory, 'a_file', t)
531
self.assertRaises(AssertionError, self.assertIsDirectory, 'not_here', t)
534
class TestTestCaseTransports(TestCaseWithTransport):
537
super(TestTestCaseTransports, self).setUp()
538
self.transport_server = MemoryServer
540
def test_make_bzrdir_preserves_transport(self):
541
t = self.get_transport()
542
result_bzrdir = self.make_bzrdir('subdir')
543
self.assertIsInstance(result_bzrdir.transport,
545
# should not be on disk, should only be in memory
546
self.failIfExists('subdir')
549
class TestChrootedTest(ChrootedTestCase):
551
def test_root_is_root(self):
552
from bzrlib.transport import get_transport
553
t = get_transport(self.get_readonly_url())
555
self.assertEqual(url, t.clone('..').base)
558
class MockProgress(_BaseProgressBar):
559
"""Progress-bar standin that records calls.
561
Useful for testing pb using code.
565
_BaseProgressBar.__init__(self)
569
self.calls.append(('tick',))
571
def update(self, msg=None, current=None, total=None):
572
self.calls.append(('update', msg, current, total))
575
self.calls.append(('clear',))
577
def note(self, msg, *args):
578
self.calls.append(('note', msg, args))
581
class TestTestResult(TestCase):
583
def test_elapsed_time_with_benchmarking(self):
584
result = bzrlib.tests.TextTestResult(self._log_file,
588
result._recordTestStartTime()
590
result.extractBenchmarkTime(self)
591
timed_string = result._testTimeString()
592
# without explicit benchmarking, we should get a simple time.
593
self.assertContainsRe(timed_string, "^ *[ 1-9][0-9]ms$")
594
# if a benchmark time is given, we want a x of y style result.
595
self.time(time.sleep, 0.001)
596
result.extractBenchmarkTime(self)
597
timed_string = result._testTimeString()
598
self.assertContainsRe(timed_string, "^ *[ 1-9][0-9]ms/ *[ 1-9][0-9]ms$")
599
# extracting the time from a non-bzrlib testcase sets to None
600
result._recordTestStartTime()
601
result.extractBenchmarkTime(
602
unittest.FunctionTestCase(self.test_elapsed_time_with_benchmarking))
603
timed_string = result._testTimeString()
604
self.assertContainsRe(timed_string, "^ *[ 1-9][0-9]ms$")
605
# cheat. Yes, wash thy mouth out with soap.
606
self._benchtime = None
608
def test_assigned_benchmark_file_stores_date(self):
610
result = bzrlib.tests.TextTestResult(self._log_file,
615
output_string = output.getvalue()
617
# if you are wondering about the regexp please read the comment in
618
# test_bench_history (bzrlib.tests.test_selftest.TestRunner)
619
# XXX: what comment? -- Andrew Bennetts
620
self.assertContainsRe(output_string, "--date [0-9.]+")
622
def test_benchhistory_records_test_times(self):
623
result_stream = StringIO()
624
result = bzrlib.tests.TextTestResult(
628
bench_history=result_stream
631
# we want profile a call and check that its test duration is recorded
632
# make a new test instance that when run will generate a benchmark
633
example_test_case = TestTestResult("_time_hello_world_encoding")
634
# execute the test, which should succeed and record times
635
example_test_case.run(result)
636
lines = result_stream.getvalue().splitlines()
637
self.assertEqual(2, len(lines))
638
self.assertContainsRe(lines[1],
639
" *[0-9]+ms bzrlib.tests.test_selftest.TestTestResult"
640
"._time_hello_world_encoding")
642
def _time_hello_world_encoding(self):
643
"""Profile two sleep calls
645
This is used to exercise the test framework.
647
self.time(unicode, 'hello', errors='replace')
648
self.time(unicode, 'world', errors='replace')
650
def test_lsprofiling(self):
651
"""Verbose test result prints lsprof statistics from test cases."""
655
raise TestSkipped("lsprof not installed.")
656
result_stream = StringIO()
657
result = bzrlib.tests.VerboseTestResult(
658
unittest._WritelnDecorator(result_stream),
662
# we want profile a call of some sort and check it is output by
663
# addSuccess. We dont care about addError or addFailure as they
664
# are not that interesting for performance tuning.
665
# make a new test instance that when run will generate a profile
666
example_test_case = TestTestResult("_time_hello_world_encoding")
667
example_test_case._gather_lsprof_in_benchmarks = True
668
# execute the test, which should succeed and record profiles
669
example_test_case.run(result)
670
# lsprofile_something()
671
# if this worked we want
672
# LSProf output for <built in function unicode> (['hello'], {'errors': 'replace'})
673
# CallCount Recursive Total(ms) Inline(ms) module:lineno(function)
674
# (the lsprof header)
675
# ... an arbitrary number of lines
676
# and the function call which is time.sleep.
677
# 1 0 ??? ??? ???(sleep)
678
# and then repeated but with 'world', rather than 'hello'.
679
# this should appear in the output stream of our test result.
680
output = result_stream.getvalue()
681
self.assertContainsRe(output,
682
r"LSProf output for <type 'unicode'>\(\('hello',\), {'errors': 'replace'}\)")
683
self.assertContainsRe(output,
684
r" *CallCount *Recursive *Total\(ms\) *Inline\(ms\) *module:lineno\(function\)\n")
685
self.assertContainsRe(output,
686
r"( +1 +0 +0\.\d+ +0\.\d+ +<method 'disable' of '_lsprof\.Profiler' objects>\n)?")
687
self.assertContainsRe(output,
688
r"LSProf output for <type 'unicode'>\(\('world',\), {'errors': 'replace'}\)\n")
691
class TestRunner(TestCase):
693
def dummy_test(self):
696
def run_test_runner(self, testrunner, test):
697
"""Run suite in testrunner, saving global state and restoring it.
699
This current saves and restores:
700
TestCaseInTempDir.TEST_ROOT
702
There should be no tests in this file that use bzrlib.tests.TextTestRunner
703
without using this convenience method, because of our use of global state.
705
old_root = TestCaseInTempDir.TEST_ROOT
707
TestCaseInTempDir.TEST_ROOT = None
708
return testrunner.run(test)
710
TestCaseInTempDir.TEST_ROOT = old_root
712
def test_skipped_test(self):
713
# run a test that is skipped, and check the suite as a whole still
715
# skipping_test must be hidden in here so it's not run as a real test
717
raise TestSkipped('test intentionally skipped')
718
runner = TextTestRunner(stream=self._log_file, keep_output=True)
719
test = unittest.FunctionTestCase(skipping_test)
720
result = self.run_test_runner(runner, test)
721
self.assertTrue(result.wasSuccessful())
723
def test_bench_history(self):
724
# tests that the running the benchmark produces a history file
725
# containing a timestamp and the revision id of the bzrlib source which
727
workingtree = _get_bzr_source_tree()
728
test = TestRunner('dummy_test')
730
runner = TextTestRunner(stream=self._log_file, bench_history=output)
731
result = self.run_test_runner(runner, test)
732
output_string = output.getvalue()
733
self.assertContainsRe(output_string, "--date [0-9.]+")
734
if workingtree is not None:
735
revision_id = workingtree.get_parent_ids()[0]
736
self.assertEndsWith(output_string.rstrip(), revision_id)
738
def test_success_log_deleted(self):
739
"""Successful tests have their log deleted"""
741
class LogTester(TestCase):
743
def test_success(self):
744
self.log('this will be removed\n')
746
sio = cStringIO.StringIO()
747
runner = TextTestRunner(stream=sio)
748
test = LogTester('test_success')
749
result = self.run_test_runner(runner, test)
751
log = test._get_log()
752
self.assertEqual("DELETED log file to reduce memory footprint", log)
753
self.assertEqual('', test._log_contents)
754
self.assertIs(None, test._log_file_name)
756
def test_fail_log_kept(self):
757
"""Failed tests have their log kept"""
759
class LogTester(TestCase):
762
self.log('this will be kept\n')
763
self.fail('this test fails')
765
sio = cStringIO.StringIO()
766
runner = TextTestRunner(stream=sio)
767
test = LogTester('test_fail')
768
result = self.run_test_runner(runner, test)
770
text = sio.getvalue()
771
self.assertContainsRe(text, 'this will be kept')
772
self.assertContainsRe(text, 'this test fails')
774
log = test._get_log()
775
self.assertContainsRe(log, 'this will be kept')
776
self.assertEqual(log, test._log_contents)
778
def test_error_log_kept(self):
779
"""Tests with errors have their log kept"""
781
class LogTester(TestCase):
783
def test_error(self):
784
self.log('this will be kept\n')
785
raise ValueError('random exception raised')
787
sio = cStringIO.StringIO()
788
runner = TextTestRunner(stream=sio)
789
test = LogTester('test_error')
790
result = self.run_test_runner(runner, test)
792
text = sio.getvalue()
793
self.assertContainsRe(text, 'this will be kept')
794
self.assertContainsRe(text, 'random exception raised')
796
log = test._get_log()
797
self.assertContainsRe(log, 'this will be kept')
798
self.assertEqual(log, test._log_contents)
801
class TestTestCase(TestCase):
802
"""Tests that test the core bzrlib TestCase."""
804
def inner_test(self):
805
# the inner child test
808
def outer_child(self):
809
# the outer child test
811
self.inner_test = TestTestCase("inner_child")
812
result = bzrlib.tests.TextTestResult(self._log_file,
815
self.inner_test.run(result)
818
def test_trace_nesting(self):
819
# this tests that each test case nests its trace facility correctly.
820
# we do this by running a test case manually. That test case (A)
821
# should setup a new log, log content to it, setup a child case (B),
822
# which should log independently, then case (A) should log a trailer
824
# we do two nested children so that we can verify the state of the
825
# logs after the outer child finishes is correct, which a bad clean
826
# up routine in tearDown might trigger a fault in our test with only
827
# one child, we should instead see the bad result inside our test with
829
# the outer child test
830
original_trace = bzrlib.trace._trace_file
831
outer_test = TestTestCase("outer_child")
832
result = bzrlib.tests.TextTestResult(self._log_file,
835
outer_test.run(result)
836
self.assertEqual(original_trace, bzrlib.trace._trace_file)
838
def method_that_times_a_bit_twice(self):
839
# call self.time twice to ensure it aggregates
840
self.time(time.sleep, 0.007)
841
self.time(time.sleep, 0.007)
843
def test_time_creates_benchmark_in_result(self):
844
"""Test that the TestCase.time() method accumulates a benchmark time."""
845
sample_test = TestTestCase("method_that_times_a_bit_twice")
846
output_stream = StringIO()
847
result = bzrlib.tests.VerboseTestResult(
848
unittest._WritelnDecorator(output_stream),
851
num_tests=sample_test.countTestCases())
852
sample_test.run(result)
853
self.assertContainsRe(
854
output_stream.getvalue(),
857
def test_hooks_sanitised(self):
858
"""The bzrlib hooks should be sanitised by setUp."""
859
self.assertEqual(bzrlib.branch.BranchHooks(),
860
bzrlib.branch.Branch.hooks)
862
def test__gather_lsprof_in_benchmarks(self):
863
"""When _gather_lsprof_in_benchmarks is on, accumulate profile data.
865
Each self.time() call is individually and separately profiled.
870
raise TestSkipped("lsprof not installed.")
871
# overrides the class member with an instance member so no cleanup
873
self._gather_lsprof_in_benchmarks = True
874
self.time(time.sleep, 0.000)
875
self.time(time.sleep, 0.003)
876
self.assertEqual(2, len(self._benchcalls))
877
self.assertEqual((time.sleep, (0.000,), {}), self._benchcalls[0][0])
878
self.assertEqual((time.sleep, (0.003,), {}), self._benchcalls[1][0])
879
self.assertIsInstance(self._benchcalls[0][1], bzrlib.lsprof.Stats)
880
self.assertIsInstance(self._benchcalls[1][1], bzrlib.lsprof.Stats)
883
@symbol_versioning.deprecated_function(zero_eleven)
884
def sample_deprecated_function():
885
"""A deprecated function to test applyDeprecated with."""
889
def sample_undeprecated_function(a_param):
890
"""A undeprecated function to test applyDeprecated with."""
893
class ApplyDeprecatedHelper(object):
894
"""A helper class for ApplyDeprecated tests."""
896
@symbol_versioning.deprecated_method(zero_eleven)
897
def sample_deprecated_method(self, param_one):
898
"""A deprecated method for testing with."""
901
def sample_normal_method(self):
902
"""A undeprecated method."""
904
@symbol_versioning.deprecated_method(zero_ten)
905
def sample_nested_deprecation(self):
906
return sample_deprecated_function()
909
class TestExtraAssertions(TestCase):
910
"""Tests for new test assertions in bzrlib test suite"""
912
def test_assert_isinstance(self):
913
self.assertIsInstance(2, int)
914
self.assertIsInstance(u'', basestring)
915
self.assertRaises(AssertionError, self.assertIsInstance, None, int)
916
self.assertRaises(AssertionError, self.assertIsInstance, 23.3, int)
918
def test_assertEndsWith(self):
919
self.assertEndsWith('foo', 'oo')
920
self.assertRaises(AssertionError, self.assertEndsWith, 'o', 'oo')
922
def test_applyDeprecated_not_deprecated(self):
923
sample_object = ApplyDeprecatedHelper()
924
# calling an undeprecated callable raises an assertion
925
self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
926
sample_object.sample_normal_method)
927
self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
928
sample_undeprecated_function, "a param value")
929
# calling a deprecated callable (function or method) with the wrong
930
# expected deprecation fails.
931
self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
932
sample_object.sample_deprecated_method, "a param value")
933
self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
934
sample_deprecated_function)
935
# calling a deprecated callable (function or method) with the right
936
# expected deprecation returns the functions result.
937
self.assertEqual("a param value", self.applyDeprecated(zero_eleven,
938
sample_object.sample_deprecated_method, "a param value"))
939
self.assertEqual(2, self.applyDeprecated(zero_eleven,
940
sample_deprecated_function))
941
# calling a nested deprecation with the wrong deprecation version
942
# fails even if a deeper nested function was deprecated with the
944
self.assertRaises(AssertionError, self.applyDeprecated,
945
zero_eleven, sample_object.sample_nested_deprecation)
946
# calling a nested deprecation with the right deprecation value
947
# returns the calls result.
948
self.assertEqual(2, self.applyDeprecated(zero_ten,
949
sample_object.sample_nested_deprecation))
951
def test_callDeprecated(self):
952
def testfunc(be_deprecated, result=None):
953
if be_deprecated is True:
954
symbol_versioning.warn('i am deprecated', DeprecationWarning,
957
result = self.callDeprecated(['i am deprecated'], testfunc, True)
958
self.assertIs(None, result)
959
result = self.callDeprecated([], testfunc, False, 'result')
960
self.assertEqual('result', result)
961
self.callDeprecated(['i am deprecated'], testfunc, be_deprecated=True)
962
self.callDeprecated([], testfunc, be_deprecated=False)
965
class TestConvenienceMakers(TestCaseWithTransport):
966
"""Test for the make_* convenience functions."""
968
def test_make_branch_and_tree_with_format(self):
969
# we should be able to supply a format to make_branch_and_tree
970
self.make_branch_and_tree('a', format=bzrlib.bzrdir.BzrDirMetaFormat1())
971
self.make_branch_and_tree('b', format=bzrlib.bzrdir.BzrDirFormat6())
972
self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('a')._format,
973
bzrlib.bzrdir.BzrDirMetaFormat1)
974
self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('b')._format,
975
bzrlib.bzrdir.BzrDirFormat6)
977
def test_make_branch_and_memory_tree(self):
978
# we should be able to get a new branch and a mutable tree from
979
# TestCaseWithTransport
980
tree = self.make_branch_and_memory_tree('a')
981
self.assertIsInstance(tree, bzrlib.memorytree.MemoryTree)
984
class TestSFTPMakeBranchAndTree(TestCaseWithSFTPServer):
986
def test_make_tree_for_sftp_branch(self):
987
"""Transports backed by local directories create local trees."""
989
tree = self.make_branch_and_tree('t1')
990
base = tree.bzrdir.root_transport.base
991
self.failIf(base.startswith('sftp'),
992
'base %r is on sftp but should be local' % base)
993
self.assertEquals(tree.bzrdir.root_transport,
994
tree.branch.bzrdir.root_transport)
995
self.assertEquals(tree.bzrdir.root_transport,
996
tree.branch.repository.bzrdir.root_transport)
999
class TestSelftest(TestCase):
1000
"""Tests of bzrlib.tests.selftest."""
1002
def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
1005
factory_called.append(True)
1009
self.apply_redirected(out, err, None, bzrlib.tests.selftest,
1010
test_suite_factory=factory)
1011
self.assertEqual([True], factory_called)
1014
class TestSelftestCleanOutput(TestCaseInTempDir):
1016
def test_clean_output(self):
1017
# test functionality of clean_selftest_output()
1018
from bzrlib.tests import clean_selftest_output
1020
dirs = ('test0000.tmp', 'test0001.tmp', 'bzrlib', 'tests')
1021
files = ('bzr', 'setup.py', 'test9999.tmp')
1026
f.write('content of ')
1031
before = os.listdir(root)
1033
self.assertEquals(['bzr','bzrlib','setup.py',
1034
'test0000.tmp','test0001.tmp',
1035
'test9999.tmp','tests'],
1037
clean_selftest_output(root, quiet=True)
1038
after = os.listdir(root)
1040
self.assertEquals(['bzr','bzrlib','setup.py',
1041
'test9999.tmp','tests'],