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 (
46
TestCaseWithMemoryTransport,
47
TestCaseWithTransport,
53
from bzrlib.tests.test_sftp_transport import TestCaseWithSFTPServer
54
from bzrlib.tests.TestUtil import _load_module_by_name
55
from bzrlib.trace import note
56
from bzrlib.transport.memory import MemoryServer, MemoryTransport
57
from bzrlib.version import _get_bzr_source_tree
60
class SelftestTests(TestCase):
62
def test_import_tests(self):
63
mod = _load_module_by_name('bzrlib.tests.test_selftest')
64
self.assertEqual(mod.SelftestTests, SelftestTests)
66
def test_import_test_failure(self):
67
self.assertRaises(ImportError,
71
class MetaTestLog(TestCase):
73
def test_logging(self):
74
"""Test logs are captured when a test fails."""
75
self.log('a test message')
76
self._log_file.flush()
77
self.assertContainsRe(self._get_log(keep_log_file=True),
81
class TestTreeShape(TestCaseInTempDir):
83
def test_unicode_paths(self):
84
filename = u'hell\u00d8'
86
self.build_tree_contents([(filename, 'contents of hello')])
87
except UnicodeEncodeError:
88
raise TestSkipped("can't build unicode working tree in "
89
"filesystem encoding %s" % sys.getfilesystemencoding())
90
self.failUnlessExists(filename)
93
class TestTransportProviderAdapter(TestCase):
94
"""A group of tests that test the transport implementation adaption core.
96
This is a meta test that the tests are applied to all available
99
This will be generalised in the future which is why it is in this
100
test file even though it is specific to transport tests at the moment.
103
def test_get_transport_permutations(self):
104
# this checks that we the module get_test_permutations call
105
# is made by the adapter get_transport_test_permitations method.
106
class MockModule(object):
107
def get_test_permutations(self):
108
return sample_permutation
109
sample_permutation = [(1,2), (3,4)]
110
from bzrlib.transport import TransportTestProviderAdapter
111
adapter = TransportTestProviderAdapter()
112
self.assertEqual(sample_permutation,
113
adapter.get_transport_test_permutations(MockModule()))
115
def test_adapter_checks_all_modules(self):
116
# this checks that the adapter returns as many permurtations as
117
# there are in all the registered# transport modules for there
118
# - we assume if this matches its probably doing the right thing
119
# especially in combination with the tests for setting the right
121
from bzrlib.transport import (TransportTestProviderAdapter,
122
_get_transport_modules
124
modules = _get_transport_modules()
125
permutation_count = 0
126
for module in modules:
128
permutation_count += len(reduce(getattr,
129
(module + ".get_test_permutations").split('.')[1:],
130
__import__(module))())
131
except errors.DependencyNotPresent:
133
input_test = TestTransportProviderAdapter(
134
"test_adapter_sets_transport_class")
135
adapter = TransportTestProviderAdapter()
136
self.assertEqual(permutation_count,
137
len(list(iter(adapter.adapt(input_test)))))
139
def test_adapter_sets_transport_class(self):
140
# Check that the test adapter inserts a transport and server into the
143
# This test used to know about all the possible transports and the
144
# order they were returned but that seems overly brittle (mbp
146
input_test = TestTransportProviderAdapter(
147
"test_adapter_sets_transport_class")
148
from bzrlib.transport import TransportTestProviderAdapter
149
suite = TransportTestProviderAdapter().adapt(input_test)
150
tests = list(iter(suite))
151
self.assertTrue(len(tests) > 6)
152
# there are at least that many builtin transports
154
self.assertTrue(issubclass(one_test.transport_class,
155
bzrlib.transport.Transport))
156
self.assertTrue(issubclass(one_test.transport_server,
157
bzrlib.transport.Server))
160
class TestBranchProviderAdapter(TestCase):
161
"""A group of tests that test the branch implementation test adapter."""
163
def test_adapted_tests(self):
164
# check that constructor parameters are passed through to the adapted
166
from bzrlib.branch import BranchTestProviderAdapter
167
input_test = TestBranchProviderAdapter(
168
"test_adapted_tests")
171
formats = [("c", "C"), ("d", "D")]
172
adapter = BranchTestProviderAdapter(server1, server2, formats)
173
suite = adapter.adapt(input_test)
174
tests = list(iter(suite))
175
self.assertEqual(2, len(tests))
176
self.assertEqual(tests[0].branch_format, formats[0][0])
177
self.assertEqual(tests[0].bzrdir_format, formats[0][1])
178
self.assertEqual(tests[0].transport_server, server1)
179
self.assertEqual(tests[0].transport_readonly_server, server2)
180
self.assertEqual(tests[1].branch_format, formats[1][0])
181
self.assertEqual(tests[1].bzrdir_format, formats[1][1])
182
self.assertEqual(tests[1].transport_server, server1)
183
self.assertEqual(tests[1].transport_readonly_server, server2)
186
class TestBzrDirProviderAdapter(TestCase):
187
"""A group of tests that test the bzr dir implementation test adapter."""
189
def test_adapted_tests(self):
190
# check that constructor parameters are passed through to the adapted
192
from bzrlib.bzrdir import BzrDirTestProviderAdapter
193
input_test = TestBzrDirProviderAdapter(
194
"test_adapted_tests")
199
adapter = BzrDirTestProviderAdapter(vfs_factory,
200
server1, server2, formats)
201
suite = adapter.adapt(input_test)
202
tests = list(iter(suite))
203
self.assertEqual(2, len(tests))
204
self.assertEqual(tests[0].bzrdir_format, formats[0])
205
self.assertEqual(tests[0].vfs_transport_factory, vfs_factory)
206
self.assertEqual(tests[0].transport_server, server1)
207
self.assertEqual(tests[0].transport_readonly_server, server2)
208
self.assertEqual(tests[1].bzrdir_format, formats[1])
209
self.assertEqual(tests[1].vfs_transport_factory, vfs_factory)
210
self.assertEqual(tests[1].transport_server, server1)
211
self.assertEqual(tests[1].transport_readonly_server, server2)
214
class TestRepositoryProviderAdapter(TestCase):
215
"""A group of tests that test the repository implementation test adapter."""
217
def test_adapted_tests(self):
218
# check that constructor parameters are passed through to the adapted
220
from bzrlib.repository import RepositoryTestProviderAdapter
221
input_test = TestRepositoryProviderAdapter(
222
"test_adapted_tests")
225
formats = [("c", "C"), ("d", "D")]
226
adapter = RepositoryTestProviderAdapter(server1, server2, formats)
227
suite = adapter.adapt(input_test)
228
tests = list(iter(suite))
229
self.assertEqual(2, len(tests))
230
self.assertEqual(tests[0].bzrdir_format, formats[0][1])
231
self.assertEqual(tests[0].repository_format, formats[0][0])
232
self.assertEqual(tests[0].transport_server, server1)
233
self.assertEqual(tests[0].transport_readonly_server, server2)
234
self.assertEqual(tests[1].bzrdir_format, formats[1][1])
235
self.assertEqual(tests[1].repository_format, formats[1][0])
236
self.assertEqual(tests[1].transport_server, server1)
237
self.assertEqual(tests[1].transport_readonly_server, server2)
239
def test_setting_vfs_transport(self):
240
"""The vfs_transport_factory can be set optionally."""
241
from bzrlib.repository import RepositoryTestProviderAdapter
242
input_test = TestRepositoryProviderAdapter(
243
"test_adapted_tests")
244
formats = [("c", "C")]
245
adapter = RepositoryTestProviderAdapter(None, None, formats,
246
vfs_transport_factory="vfs")
247
suite = adapter.adapt(input_test)
248
tests = list(iter(suite))
249
self.assertEqual(1, len(tests))
250
self.assertEqual(tests[0].vfs_transport_factory, "vfs")
253
class TestInterRepositoryProviderAdapter(TestCase):
254
"""A group of tests that test the InterRepository test adapter."""
256
def test_adapted_tests(self):
257
# check that constructor parameters are passed through to the adapted
259
from bzrlib.repository import InterRepositoryTestProviderAdapter
260
input_test = TestInterRepositoryProviderAdapter(
261
"test_adapted_tests")
264
formats = [(str, "C1", "C2"), (int, "D1", "D2")]
265
adapter = InterRepositoryTestProviderAdapter(server1, server2, formats)
266
suite = adapter.adapt(input_test)
267
tests = list(iter(suite))
268
self.assertEqual(2, len(tests))
269
self.assertEqual(tests[0].interrepo_class, formats[0][0])
270
self.assertEqual(tests[0].repository_format, formats[0][1])
271
self.assertEqual(tests[0].repository_format_to, formats[0][2])
272
self.assertEqual(tests[0].transport_server, server1)
273
self.assertEqual(tests[0].transport_readonly_server, server2)
274
self.assertEqual(tests[1].interrepo_class, formats[1][0])
275
self.assertEqual(tests[1].repository_format, formats[1][1])
276
self.assertEqual(tests[1].repository_format_to, formats[1][2])
277
self.assertEqual(tests[1].transport_server, server1)
278
self.assertEqual(tests[1].transport_readonly_server, server2)
281
class TestInterVersionedFileProviderAdapter(TestCase):
282
"""A group of tests that test the InterVersionedFile test adapter."""
284
def test_adapted_tests(self):
285
# check that constructor parameters are passed through to the adapted
287
from bzrlib.versionedfile import InterVersionedFileTestProviderAdapter
288
input_test = TestInterRepositoryProviderAdapter(
289
"test_adapted_tests")
292
formats = [(str, "C1", "C2"), (int, "D1", "D2")]
293
adapter = InterVersionedFileTestProviderAdapter(server1, server2, formats)
294
suite = adapter.adapt(input_test)
295
tests = list(iter(suite))
296
self.assertEqual(2, len(tests))
297
self.assertEqual(tests[0].interversionedfile_class, formats[0][0])
298
self.assertEqual(tests[0].versionedfile_factory, formats[0][1])
299
self.assertEqual(tests[0].versionedfile_factory_to, formats[0][2])
300
self.assertEqual(tests[0].transport_server, server1)
301
self.assertEqual(tests[0].transport_readonly_server, server2)
302
self.assertEqual(tests[1].interversionedfile_class, formats[1][0])
303
self.assertEqual(tests[1].versionedfile_factory, formats[1][1])
304
self.assertEqual(tests[1].versionedfile_factory_to, formats[1][2])
305
self.assertEqual(tests[1].transport_server, server1)
306
self.assertEqual(tests[1].transport_readonly_server, server2)
309
class TestRevisionStoreProviderAdapter(TestCase):
310
"""A group of tests that test the RevisionStore test adapter."""
312
def test_adapted_tests(self):
313
# check that constructor parameters are passed through to the adapted
315
from bzrlib.store.revision import RevisionStoreTestProviderAdapter
316
input_test = TestRevisionStoreProviderAdapter(
317
"test_adapted_tests")
318
# revision stores need a store factory - i.e. RevisionKnit
319
#, a readonly and rw transport
323
store_factories = ["c", "d"]
324
adapter = RevisionStoreTestProviderAdapter(server1, server2, store_factories)
325
suite = adapter.adapt(input_test)
326
tests = list(iter(suite))
327
self.assertEqual(2, len(tests))
328
self.assertEqual(tests[0].store_factory, store_factories[0][0])
329
self.assertEqual(tests[0].transport_server, server1)
330
self.assertEqual(tests[0].transport_readonly_server, server2)
331
self.assertEqual(tests[1].store_factory, store_factories[1][0])
332
self.assertEqual(tests[1].transport_server, server1)
333
self.assertEqual(tests[1].transport_readonly_server, server2)
336
class TestWorkingTreeProviderAdapter(TestCase):
337
"""A group of tests that test the workingtree implementation test adapter."""
339
def test_adapted_tests(self):
340
# check that constructor parameters are passed through to the adapted
342
from bzrlib.workingtree import WorkingTreeTestProviderAdapter
343
input_test = TestWorkingTreeProviderAdapter(
344
"test_adapted_tests")
347
formats = [("c", "C"), ("d", "D")]
348
adapter = WorkingTreeTestProviderAdapter(server1, server2, formats)
349
suite = adapter.adapt(input_test)
350
tests = list(iter(suite))
351
self.assertEqual(2, len(tests))
352
self.assertEqual(tests[0].workingtree_format, formats[0][0])
353
self.assertEqual(tests[0].bzrdir_format, formats[0][1])
354
self.assertEqual(tests[0].transport_server, server1)
355
self.assertEqual(tests[0].transport_readonly_server, server2)
356
self.assertEqual(tests[1].workingtree_format, formats[1][0])
357
self.assertEqual(tests[1].bzrdir_format, formats[1][1])
358
self.assertEqual(tests[1].transport_server, server1)
359
self.assertEqual(tests[1].transport_readonly_server, server2)
362
class TestTreeProviderAdapter(TestCase):
363
"""Test the setup of tree_implementation tests."""
365
def test_adapted_tests(self):
366
# the tree implementation adapter is meant to setup one instance for
367
# each working tree format, and one additional instance that will
368
# use the default wt format, but create a revision tree for the tests.
369
# this means that the wt ones should have the workingtree_to_test_tree
370
# attribute set to 'return_parameter' and the revision one set to
371
# revision_tree_from_workingtree.
373
from bzrlib.tests.tree_implementations import (
374
TreeTestProviderAdapter,
376
revision_tree_from_workingtree
378
from bzrlib.workingtree import WorkingTreeFormat, WorkingTreeFormat3
379
input_test = TestTreeProviderAdapter(
380
"test_adapted_tests")
383
formats = [("c", "C"), ("d", "D")]
384
adapter = TreeTestProviderAdapter(server1, server2, formats)
385
suite = adapter.adapt(input_test)
386
tests = list(iter(suite))
387
self.assertEqual(4, len(tests))
388
# this must match the default format setp up in
389
# TreeTestProviderAdapter.adapt
390
default_format = WorkingTreeFormat3
391
self.assertEqual(tests[0].workingtree_format, formats[0][0])
392
self.assertEqual(tests[0].bzrdir_format, formats[0][1])
393
self.assertEqual(tests[0].transport_server, server1)
394
self.assertEqual(tests[0].transport_readonly_server, server2)
395
self.assertEqual(tests[0].workingtree_to_test_tree, return_parameter)
396
self.assertEqual(tests[1].workingtree_format, formats[1][0])
397
self.assertEqual(tests[1].bzrdir_format, formats[1][1])
398
self.assertEqual(tests[1].transport_server, server1)
399
self.assertEqual(tests[1].transport_readonly_server, server2)
400
self.assertEqual(tests[1].workingtree_to_test_tree, return_parameter)
401
self.assertIsInstance(tests[2].workingtree_format, default_format)
402
#self.assertEqual(tests[2].bzrdir_format,
403
# default_format._matchingbzrdir)
404
self.assertEqual(tests[2].transport_server, server1)
405
self.assertEqual(tests[2].transport_readonly_server, server2)
406
self.assertEqual(tests[2].workingtree_to_test_tree,
407
revision_tree_from_workingtree)
410
class TestInterTreeProviderAdapter(TestCase):
411
"""A group of tests that test the InterTreeTestAdapter."""
413
def test_adapted_tests(self):
414
# check that constructor parameters are passed through to the adapted
416
# for InterTree tests we want the machinery to bring up two trees in
417
# each instance: the base one, and the one we are interacting with.
418
# because each optimiser can be direction specific, we need to test
419
# each optimiser in its chosen direction.
420
# unlike the TestProviderAdapter we dont want to automatically add a
421
# parameterised one for WorkingTree - the optimisers will tell us what
423
from bzrlib.tests.tree_implementations import (
425
revision_tree_from_workingtree
427
from bzrlib.tests.intertree_implementations import (
428
InterTreeTestProviderAdapter,
430
from bzrlib.workingtree import WorkingTreeFormat2, WorkingTreeFormat3
431
input_test = TestInterTreeProviderAdapter(
432
"test_adapted_tests")
435
format1 = WorkingTreeFormat2()
436
format2 = WorkingTreeFormat3()
437
formats = [(str, format1, format2, "converter1"),
438
(int, format2, format1, "converter2")]
439
adapter = InterTreeTestProviderAdapter(server1, server2, formats)
440
suite = adapter.adapt(input_test)
441
tests = list(iter(suite))
442
self.assertEqual(2, len(tests))
443
self.assertEqual(tests[0].intertree_class, formats[0][0])
444
self.assertEqual(tests[0].workingtree_format, formats[0][1])
445
self.assertEqual(tests[0].workingtree_format_to, formats[0][2])
446
self.assertEqual(tests[0].mutable_trees_to_test_trees, formats[0][3])
447
self.assertEqual(tests[0].workingtree_to_test_tree, return_parameter)
448
self.assertEqual(tests[0].transport_server, server1)
449
self.assertEqual(tests[0].transport_readonly_server, server2)
450
self.assertEqual(tests[1].intertree_class, formats[1][0])
451
self.assertEqual(tests[1].workingtree_format, formats[1][1])
452
self.assertEqual(tests[1].workingtree_format_to, formats[1][2])
453
self.assertEqual(tests[1].mutable_trees_to_test_trees, formats[1][3])
454
self.assertEqual(tests[1].workingtree_to_test_tree, return_parameter)
455
self.assertEqual(tests[1].transport_server, server1)
456
self.assertEqual(tests[1].transport_readonly_server, server2)
459
class TestTestCaseInTempDir(TestCaseInTempDir):
461
def test_home_is_not_working(self):
462
self.assertNotEqual(self.test_dir, self.test_home_dir)
463
cwd = osutils.getcwd()
464
self.assertEqual(self.test_dir, cwd)
465
self.assertEqual(self.test_home_dir, os.environ['HOME'])
468
class TestTestCaseWithMemoryTransport(TestCaseWithMemoryTransport):
470
def test_home_is_non_existant_dir_under_root(self):
471
"""The test_home_dir for TestCaseWithMemoryTransport is missing.
473
This is because TestCaseWithMemoryTransport is for tests that do not
474
need any disk resources: they should be hooked into bzrlib in such a
475
way that no global settings are being changed by the test (only a
476
few tests should need to do that), and having a missing dir as home is
477
an effective way to ensure that this is the case.
479
self.assertEqual(self.TEST_ROOT + "/MemoryTransportMissingHomeDir",
481
self.assertEqual(self.test_home_dir, os.environ['HOME'])
483
def test_cwd_is_TEST_ROOT(self):
484
self.assertEqual(self.test_dir, self.TEST_ROOT)
485
cwd = osutils.getcwd()
486
self.assertEqual(self.test_dir, cwd)
488
def test_make_branch_and_memory_tree(self):
489
"""In TestCaseWithMemoryTransport we should not make the branch on disk.
491
This is hard to comprehensively robustly test, so we settle for making
492
a branch and checking no directory was created at its relpath.
494
tree = self.make_branch_and_memory_tree('dir')
495
# Guard against regression into MemoryTransport leaking
496
# files to disk instead of keeping them in memory.
497
self.failIf(osutils.lexists('dir'))
498
self.assertIsInstance(tree, memorytree.MemoryTree)
500
def test_make_branch_and_memory_tree_with_format(self):
501
"""make_branch_and_memory_tree should accept a format option."""
502
format = bzrdir.BzrDirMetaFormat1()
503
format.repository_format = weaverepo.RepositoryFormat7()
504
tree = self.make_branch_and_memory_tree('dir', format=format)
505
# Guard against regression into MemoryTransport leaking
506
# files to disk instead of keeping them in memory.
507
self.failIf(osutils.lexists('dir'))
508
self.assertIsInstance(tree, memorytree.MemoryTree)
509
self.assertEqual(format.repository_format.__class__,
510
tree.branch.repository._format.__class__)
513
class TestTestCaseWithTransport(TestCaseWithTransport):
514
"""Tests for the convenience functions TestCaseWithTransport introduces."""
516
def test_get_readonly_url_none(self):
517
from bzrlib.transport import get_transport
518
from bzrlib.transport.memory import MemoryServer
519
from bzrlib.transport.readonly import ReadonlyTransportDecorator
520
self.vfs_transport_factory = MemoryServer
521
self.transport_readonly_server = None
522
# calling get_readonly_transport() constructs a decorator on the url
524
url = self.get_readonly_url()
525
url2 = self.get_readonly_url('foo/bar')
526
t = get_transport(url)
527
t2 = get_transport(url2)
528
self.failUnless(isinstance(t, ReadonlyTransportDecorator))
529
self.failUnless(isinstance(t2, ReadonlyTransportDecorator))
530
self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
532
def test_get_readonly_url_http(self):
533
from bzrlib.tests.HttpServer import HttpServer
534
from bzrlib.transport import get_transport
535
from bzrlib.transport.local import LocalURLServer
536
from bzrlib.transport.http import HttpTransportBase
537
self.transport_server = LocalURLServer
538
self.transport_readonly_server = HttpServer
539
# calling get_readonly_transport() gives us a HTTP server instance.
540
url = self.get_readonly_url()
541
url2 = self.get_readonly_url('foo/bar')
542
# the transport returned may be any HttpTransportBase subclass
543
t = get_transport(url)
544
t2 = get_transport(url2)
545
self.failUnless(isinstance(t, HttpTransportBase))
546
self.failUnless(isinstance(t2, HttpTransportBase))
547
self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
549
def test_is_directory(self):
550
"""Test assertIsDirectory assertion"""
551
t = self.get_transport()
552
self.build_tree(['a_dir/', 'a_file'], transport=t)
553
self.assertIsDirectory('a_dir', t)
554
self.assertRaises(AssertionError, self.assertIsDirectory, 'a_file', t)
555
self.assertRaises(AssertionError, self.assertIsDirectory, 'not_here', t)
558
class TestTestCaseTransports(TestCaseWithTransport):
561
super(TestTestCaseTransports, self).setUp()
562
self.vfs_transport_factory = MemoryServer
564
def test_make_bzrdir_preserves_transport(self):
565
t = self.get_transport()
566
result_bzrdir = self.make_bzrdir('subdir')
567
self.assertIsInstance(result_bzrdir.transport,
569
# should not be on disk, should only be in memory
570
self.failIfExists('subdir')
573
class TestChrootedTest(ChrootedTestCase):
575
def test_root_is_root(self):
576
from bzrlib.transport import get_transport
577
t = get_transport(self.get_readonly_url())
579
self.assertEqual(url, t.clone('..').base)
582
class MockProgress(_BaseProgressBar):
583
"""Progress-bar standin that records calls.
585
Useful for testing pb using code.
589
_BaseProgressBar.__init__(self)
593
self.calls.append(('tick',))
595
def update(self, msg=None, current=None, total=None):
596
self.calls.append(('update', msg, current, total))
599
self.calls.append(('clear',))
601
def note(self, msg, *args):
602
self.calls.append(('note', msg, args))
605
class TestTestResult(TestCase):
607
def test_elapsed_time_with_benchmarking(self):
608
result = bzrlib.tests.TextTestResult(self._log_file,
612
result._recordTestStartTime()
614
result.extractBenchmarkTime(self)
615
timed_string = result._testTimeString()
616
# without explicit benchmarking, we should get a simple time.
617
self.assertContainsRe(timed_string, "^ *[ 1-9][0-9]ms$")
618
# if a benchmark time is given, we want a x of y style result.
619
self.time(time.sleep, 0.001)
620
result.extractBenchmarkTime(self)
621
timed_string = result._testTimeString()
622
self.assertContainsRe(timed_string, "^ *[ 1-9][0-9]ms/ *[ 1-9][0-9]ms$")
623
# extracting the time from a non-bzrlib testcase sets to None
624
result._recordTestStartTime()
625
result.extractBenchmarkTime(
626
unittest.FunctionTestCase(self.test_elapsed_time_with_benchmarking))
627
timed_string = result._testTimeString()
628
self.assertContainsRe(timed_string, "^ *[ 1-9][0-9]ms$")
629
# cheat. Yes, wash thy mouth out with soap.
630
self._benchtime = None
632
def test_assigned_benchmark_file_stores_date(self):
634
result = bzrlib.tests.TextTestResult(self._log_file,
639
output_string = output.getvalue()
641
# if you are wondering about the regexp please read the comment in
642
# test_bench_history (bzrlib.tests.test_selftest.TestRunner)
643
# XXX: what comment? -- Andrew Bennetts
644
self.assertContainsRe(output_string, "--date [0-9.]+")
646
def test_benchhistory_records_test_times(self):
647
result_stream = StringIO()
648
result = bzrlib.tests.TextTestResult(
652
bench_history=result_stream
655
# we want profile a call and check that its test duration is recorded
656
# make a new test instance that when run will generate a benchmark
657
example_test_case = TestTestResult("_time_hello_world_encoding")
658
# execute the test, which should succeed and record times
659
example_test_case.run(result)
660
lines = result_stream.getvalue().splitlines()
661
self.assertEqual(2, len(lines))
662
self.assertContainsRe(lines[1],
663
" *[0-9]+ms bzrlib.tests.test_selftest.TestTestResult"
664
"._time_hello_world_encoding")
666
def _time_hello_world_encoding(self):
667
"""Profile two sleep calls
669
This is used to exercise the test framework.
671
self.time(unicode, 'hello', errors='replace')
672
self.time(unicode, 'world', errors='replace')
674
def test_lsprofiling(self):
675
"""Verbose test result prints lsprof statistics from test cases."""
679
raise TestSkipped("lsprof not installed.")
680
result_stream = StringIO()
681
result = bzrlib.tests.VerboseTestResult(
682
unittest._WritelnDecorator(result_stream),
686
# we want profile a call of some sort and check it is output by
687
# addSuccess. We dont care about addError or addFailure as they
688
# are not that interesting for performance tuning.
689
# make a new test instance that when run will generate a profile
690
example_test_case = TestTestResult("_time_hello_world_encoding")
691
example_test_case._gather_lsprof_in_benchmarks = True
692
# execute the test, which should succeed and record profiles
693
example_test_case.run(result)
694
# lsprofile_something()
695
# if this worked we want
696
# LSProf output for <built in function unicode> (['hello'], {'errors': 'replace'})
697
# CallCount Recursive Total(ms) Inline(ms) module:lineno(function)
698
# (the lsprof header)
699
# ... an arbitrary number of lines
700
# and the function call which is time.sleep.
701
# 1 0 ??? ??? ???(sleep)
702
# and then repeated but with 'world', rather than 'hello'.
703
# this should appear in the output stream of our test result.
704
output = result_stream.getvalue()
705
self.assertContainsRe(output,
706
r"LSProf output for <type 'unicode'>\(\('hello',\), {'errors': 'replace'}\)")
707
self.assertContainsRe(output,
708
r" *CallCount *Recursive *Total\(ms\) *Inline\(ms\) *module:lineno\(function\)\n")
709
self.assertContainsRe(output,
710
r"( +1 +0 +0\.\d+ +0\.\d+ +<method 'disable' of '_lsprof\.Profiler' objects>\n)?")
711
self.assertContainsRe(output,
712
r"LSProf output for <type 'unicode'>\(\('world',\), {'errors': 'replace'}\)\n")
714
def test_known_failure(self):
715
"""A KnownFailure being raised should trigger several result actions."""
716
class InstrumentedTestResult(ExtendedTestResult):
718
def report_test_start(self, test): pass
719
def report_known_failure(self, test, err):
720
self._call = test, err
721
result = InstrumentedTestResult(None, None, None, None)
723
raise KnownFailure('failed!')
724
test = unittest.FunctionTestCase(test_function)
726
# it should invoke 'report_known_failure'.
727
self.assertEqual(2, len(result._call))
728
self.assertEqual(test, result._call[0])
729
self.assertEqual(KnownFailure, result._call[1][0])
730
self.assertIsInstance(result._call[1][1], KnownFailure)
731
# we dont introspec the traceback, if the rest is ok, it would be
732
# exceptional for it not to be.
733
# it should update the known_failure_count on the object.
734
self.assertEqual(1, result.known_failure_count)
735
# the result should be successful.
736
self.assertTrue(result.wasSuccessful())
738
def test_verbose_report_known_failure(self):
739
# verbose test output formatting
740
result_stream = StringIO()
741
result = bzrlib.tests.VerboseTestResult(
742
unittest._WritelnDecorator(result_stream),
746
test = self.get_passing_test()
747
result.startTest(test)
748
result.extractBenchmarkTime(test)
749
prefix = len(result_stream.getvalue())
750
# the err parameter has the shape:
751
# (class, exception object, traceback)
752
# KnownFailures dont get their tracebacks shown though, so we
754
err = (KnownFailure, KnownFailure('foo'), None)
755
result.report_known_failure(test, err)
756
output = result_stream.getvalue()[prefix:]
757
lines = output.splitlines()
758
self.assertEqual(lines, ['XFAIL 0ms', ' foo'])
760
def test_text_report_known_failure(self):
761
# text test output formatting
763
result = bzrlib.tests.TextTestResult(
769
test = self.get_passing_test()
770
# this seeds the state to handle reporting the test.
771
result.startTest(test)
772
result.extractBenchmarkTime(test)
773
# the err parameter has the shape:
774
# (class, exception object, traceback)
775
# KnownFailures dont get their tracebacks shown though, so we
777
err = (KnownFailure, KnownFailure('foo'), None)
778
result.report_known_failure(test, err)
781
('update', '[1 in 0s] passing_test', None, None),
782
('note', 'XFAIL: %s\n%s\n', ('passing_test', err[1]))
785
# known_failures should be printed in the summary, so if we run a test
786
# after there are some known failures, the update prefix should match
788
result.known_failure_count = 3
792
('update', '[2 in 0s, 3 known failures] passing_test', None, None),
796
def get_passing_test(self):
797
"""Return a test object that can't be run usefully."""
800
return unittest.FunctionTestCase(passing_test)
802
def test_add_not_supported(self):
803
"""Test the behaviour of invoking addNotSupported."""
804
class InstrumentedTestResult(ExtendedTestResult):
805
def report_test_start(self, test): pass
806
def report_unsupported(self, test, feature):
807
self._call = test, feature
808
result = InstrumentedTestResult(None, None, None, None)
809
test = SampleTestCase('_test_pass')
811
result.startTest(test)
812
result.addNotSupported(test, feature)
813
# it should invoke 'report_unsupported'.
814
self.assertEqual(2, len(result._call))
815
self.assertEqual(test, result._call[0])
816
self.assertEqual(feature, result._call[1])
817
# the result should be successful.
818
self.assertTrue(result.wasSuccessful())
819
# it should record the test against a count of tests not run due to
821
self.assertEqual(1, result.unsupported['Feature'])
822
# and invoking it again should increment that counter
823
result.addNotSupported(test, feature)
824
self.assertEqual(2, result.unsupported['Feature'])
826
def test_verbose_report_unsupported(self):
827
# verbose test output formatting
828
result_stream = StringIO()
829
result = bzrlib.tests.VerboseTestResult(
830
unittest._WritelnDecorator(result_stream),
834
test = self.get_passing_test()
836
result.startTest(test)
837
result.extractBenchmarkTime(test)
838
prefix = len(result_stream.getvalue())
839
result.report_unsupported(test, feature)
840
output = result_stream.getvalue()[prefix:]
841
lines = output.splitlines()
842
self.assertEqual(lines, ['NODEP 0ms', " The feature 'Feature' is not available."])
844
def test_text_report_unsupported(self):
845
# text test output formatting
847
result = bzrlib.tests.TextTestResult(
853
test = self.get_passing_test()
855
# this seeds the state to handle reporting the test.
856
result.startTest(test)
857
result.extractBenchmarkTime(test)
858
result.report_unsupported(test, feature)
859
# no output on unsupported features
861
[('update', '[1 in 0s] passing_test', None, None)
864
# the number of missing features should be printed in the progress
865
# summary, so check for that.
866
result.unsupported = {'foo':0, 'bar':0}
870
('update', '[2 in 0s, 2 missing features] passing_test', None, None),
874
def test_unavailable_exception(self):
875
"""An UnavailableFeature being raised should invoke addNotSupported."""
876
class InstrumentedTestResult(ExtendedTestResult):
878
def report_test_start(self, test): pass
879
def addNotSupported(self, test, feature):
880
self._call = test, feature
881
result = InstrumentedTestResult(None, None, None, None)
884
raise UnavailableFeature(feature)
885
test = unittest.FunctionTestCase(test_function)
887
# it should invoke 'addNotSupported'.
888
self.assertEqual(2, len(result._call))
889
self.assertEqual(test, result._call[0])
890
self.assertEqual(feature, result._call[1])
891
# and not count as an error
892
self.assertEqual(0, result.error_count)
895
class TestRunner(TestCase):
897
def dummy_test(self):
900
def run_test_runner(self, testrunner, test):
901
"""Run suite in testrunner, saving global state and restoring it.
903
This current saves and restores:
904
TestCaseInTempDir.TEST_ROOT
906
There should be no tests in this file that use bzrlib.tests.TextTestRunner
907
without using this convenience method, because of our use of global state.
909
old_root = TestCaseInTempDir.TEST_ROOT
911
TestCaseInTempDir.TEST_ROOT = None
912
return testrunner.run(test)
914
TestCaseInTempDir.TEST_ROOT = old_root
916
def test_known_failure_failed_run(self):
917
# run a test that generates a known failure which should be printed in
918
# the final output when real failures occur.
919
def known_failure_test():
920
raise KnownFailure('failed')
921
test = unittest.TestSuite()
922
test.addTest(unittest.FunctionTestCase(known_failure_test))
924
raise AssertionError('foo')
925
test.addTest(unittest.FunctionTestCase(failing_test))
927
runner = TextTestRunner(stream=stream)
928
result = self.run_test_runner(runner, test)
929
lines = stream.getvalue().splitlines()
932
'======================================================================',
933
'FAIL: unittest.FunctionTestCase (failing_test)',
934
'----------------------------------------------------------------------',
935
'Traceback (most recent call last):',
936
' raise AssertionError(\'foo\')',
937
'AssertionError: foo',
939
'----------------------------------------------------------------------',
941
'FAILED (failures=1, known_failure_count=1)'],
942
lines[0:5] + lines[6:10] + lines[11:])
944
def test_known_failure_ok_run(self):
945
# run a test that generates a known failure which should be printed in the final output.
946
def known_failure_test():
947
raise KnownFailure('failed')
948
test = unittest.FunctionTestCase(known_failure_test)
950
runner = TextTestRunner(stream=stream)
951
result = self.run_test_runner(runner, test)
954
'----------------------------------------------------------------------\n'
955
'Ran 1 test in 0.000s\n'
957
'OK (known_failures=1)\n',
960
def test_skipped_test(self):
961
# run a test that is skipped, and check the suite as a whole still
963
# skipping_test must be hidden in here so it's not run as a real test
965
raise TestSkipped('test intentionally skipped')
967
runner = TextTestRunner(stream=self._log_file, keep_output=True)
968
test = unittest.FunctionTestCase(skipping_test)
969
result = self.run_test_runner(runner, test)
970
self.assertTrue(result.wasSuccessful())
972
def test_skipped_from_setup(self):
973
class SkippedSetupTest(TestCase):
977
self.addCleanup(self.cleanup)
978
raise TestSkipped('skipped setup')
981
self.fail('test reached')
986
runner = TextTestRunner(stream=self._log_file, keep_output=True)
987
test = SkippedSetupTest('test_skip')
988
result = self.run_test_runner(runner, test)
989
self.assertTrue(result.wasSuccessful())
990
# Check if cleanup was called the right number of times.
991
self.assertEqual(0, test.counter)
993
def test_skipped_from_test(self):
994
class SkippedTest(TestCase):
998
self.addCleanup(self.cleanup)
1000
def test_skip(self):
1001
raise TestSkipped('skipped test')
1006
runner = TextTestRunner(stream=self._log_file, keep_output=True)
1007
test = SkippedTest('test_skip')
1008
result = self.run_test_runner(runner, test)
1009
self.assertTrue(result.wasSuccessful())
1010
# Check if cleanup was called the right number of times.
1011
self.assertEqual(0, test.counter)
1013
def test_unsupported_features_listed(self):
1014
"""When unsupported features are encountered they are detailed."""
1015
class Feature1(Feature):
1016
def _probe(self): return False
1017
class Feature2(Feature):
1018
def _probe(self): return False
1019
# create sample tests
1020
test1 = SampleTestCase('_test_pass')
1021
test1._test_needs_features = [Feature1()]
1022
test2 = SampleTestCase('_test_pass')
1023
test2._test_needs_features = [Feature2()]
1024
test = unittest.TestSuite()
1028
runner = TextTestRunner(stream=stream)
1029
result = self.run_test_runner(runner, test)
1030
lines = stream.getvalue().splitlines()
1033
"Missing feature 'Feature1' skipped 1 tests.",
1034
"Missing feature 'Feature2' skipped 1 tests.",
1038
def test_bench_history(self):
1039
# tests that the running the benchmark produces a history file
1040
# containing a timestamp and the revision id of the bzrlib source which
1042
workingtree = _get_bzr_source_tree()
1043
test = TestRunner('dummy_test')
1045
runner = TextTestRunner(stream=self._log_file, bench_history=output)
1046
result = self.run_test_runner(runner, test)
1047
output_string = output.getvalue()
1048
self.assertContainsRe(output_string, "--date [0-9.]+")
1049
if workingtree is not None:
1050
revision_id = workingtree.get_parent_ids()[0]
1051
self.assertEndsWith(output_string.rstrip(), revision_id)
1053
def test_success_log_deleted(self):
1054
"""Successful tests have their log deleted"""
1056
class LogTester(TestCase):
1058
def test_success(self):
1059
self.log('this will be removed\n')
1061
sio = cStringIO.StringIO()
1062
runner = TextTestRunner(stream=sio)
1063
test = LogTester('test_success')
1064
result = self.run_test_runner(runner, test)
1066
log = test._get_log()
1067
self.assertEqual("DELETED log file to reduce memory footprint", log)
1068
self.assertEqual('', test._log_contents)
1069
self.assertIs(None, test._log_file_name)
1071
def test_fail_log_kept(self):
1072
"""Failed tests have their log kept"""
1074
class LogTester(TestCase):
1076
def test_fail(self):
1077
self.log('this will be kept\n')
1078
self.fail('this test fails')
1080
sio = cStringIO.StringIO()
1081
runner = TextTestRunner(stream=sio)
1082
test = LogTester('test_fail')
1083
result = self.run_test_runner(runner, test)
1085
text = sio.getvalue()
1086
self.assertContainsRe(text, 'this will be kept')
1087
self.assertContainsRe(text, 'this test fails')
1089
log = test._get_log()
1090
self.assertContainsRe(log, 'this will be kept')
1091
self.assertEqual(log, test._log_contents)
1093
def test_error_log_kept(self):
1094
"""Tests with errors have their log kept"""
1096
class LogTester(TestCase):
1098
def test_error(self):
1099
self.log('this will be kept\n')
1100
raise ValueError('random exception raised')
1102
sio = cStringIO.StringIO()
1103
runner = TextTestRunner(stream=sio)
1104
test = LogTester('test_error')
1105
result = self.run_test_runner(runner, test)
1107
text = sio.getvalue()
1108
self.assertContainsRe(text, 'this will be kept')
1109
self.assertContainsRe(text, 'random exception raised')
1111
log = test._get_log()
1112
self.assertContainsRe(log, 'this will be kept')
1113
self.assertEqual(log, test._log_contents)
1116
class SampleTestCase(TestCase):
1118
def _test_pass(self):
1122
class TestTestCase(TestCase):
1123
"""Tests that test the core bzrlib TestCase."""
1125
def inner_test(self):
1126
# the inner child test
1129
def outer_child(self):
1130
# the outer child test
1132
self.inner_test = TestTestCase("inner_child")
1133
result = bzrlib.tests.TextTestResult(self._log_file,
1136
self.inner_test.run(result)
1137
note("outer finish")
1139
def test_trace_nesting(self):
1140
# this tests that each test case nests its trace facility correctly.
1141
# we do this by running a test case manually. That test case (A)
1142
# should setup a new log, log content to it, setup a child case (B),
1143
# which should log independently, then case (A) should log a trailer
1145
# we do two nested children so that we can verify the state of the
1146
# logs after the outer child finishes is correct, which a bad clean
1147
# up routine in tearDown might trigger a fault in our test with only
1148
# one child, we should instead see the bad result inside our test with
1150
# the outer child test
1151
original_trace = bzrlib.trace._trace_file
1152
outer_test = TestTestCase("outer_child")
1153
result = bzrlib.tests.TextTestResult(self._log_file,
1156
outer_test.run(result)
1157
self.assertEqual(original_trace, bzrlib.trace._trace_file)
1159
def method_that_times_a_bit_twice(self):
1160
# call self.time twice to ensure it aggregates
1161
self.time(time.sleep, 0.007)
1162
self.time(time.sleep, 0.007)
1164
def test_time_creates_benchmark_in_result(self):
1165
"""Test that the TestCase.time() method accumulates a benchmark time."""
1166
sample_test = TestTestCase("method_that_times_a_bit_twice")
1167
output_stream = StringIO()
1168
result = bzrlib.tests.VerboseTestResult(
1169
unittest._WritelnDecorator(output_stream),
1172
num_tests=sample_test.countTestCases())
1173
sample_test.run(result)
1174
self.assertContainsRe(
1175
output_stream.getvalue(),
1176
r"\d+ms/ +\d+ms\n$")
1178
def test_hooks_sanitised(self):
1179
"""The bzrlib hooks should be sanitised by setUp."""
1180
self.assertEqual(bzrlib.branch.BranchHooks(),
1181
bzrlib.branch.Branch.hooks)
1182
self.assertEqual(bzrlib.smart.server.SmartServerHooks(),
1183
bzrlib.smart.server.SmartTCPServer.hooks)
1185
def test__gather_lsprof_in_benchmarks(self):
1186
"""When _gather_lsprof_in_benchmarks is on, accumulate profile data.
1188
Each self.time() call is individually and separately profiled.
1191
import bzrlib.lsprof
1193
raise TestSkipped("lsprof not installed.")
1194
# overrides the class member with an instance member so no cleanup
1196
self._gather_lsprof_in_benchmarks = True
1197
self.time(time.sleep, 0.000)
1198
self.time(time.sleep, 0.003)
1199
self.assertEqual(2, len(self._benchcalls))
1200
self.assertEqual((time.sleep, (0.000,), {}), self._benchcalls[0][0])
1201
self.assertEqual((time.sleep, (0.003,), {}), self._benchcalls[1][0])
1202
self.assertIsInstance(self._benchcalls[0][1], bzrlib.lsprof.Stats)
1203
self.assertIsInstance(self._benchcalls[1][1], bzrlib.lsprof.Stats)
1205
def test_knownFailure(self):
1206
"""Self.knownFailure() should raise a KnownFailure exception."""
1207
self.assertRaises(KnownFailure, self.knownFailure, "A Failure")
1209
def test_requireFeature_available(self):
1210
"""self.requireFeature(available) is a no-op."""
1211
class Available(Feature):
1212
def _probe(self):return True
1213
feature = Available()
1214
self.requireFeature(feature)
1216
def test_requireFeature_unavailable(self):
1217
"""self.requireFeature(unavailable) raises UnavailableFeature."""
1218
class Unavailable(Feature):
1219
def _probe(self):return False
1220
feature = Unavailable()
1221
self.assertRaises(UnavailableFeature, self.requireFeature, feature)
1223
def test_run_no_parameters(self):
1224
test = SampleTestCase('_test_pass')
1227
def test_run_enabled_unittest_result(self):
1228
"""Test we revert to regular behaviour when the test is enabled."""
1229
test = SampleTestCase('_test_pass')
1230
class EnabledFeature(object):
1231
def available(self):
1233
test._test_needs_features = [EnabledFeature()]
1234
result = unittest.TestResult()
1236
self.assertEqual(1, result.testsRun)
1237
self.assertEqual([], result.errors)
1238
self.assertEqual([], result.failures)
1240
def test_run_disabled_unittest_result(self):
1241
"""Test our compatability for disabled tests with unittest results."""
1242
test = SampleTestCase('_test_pass')
1243
class DisabledFeature(object):
1244
def available(self):
1246
test._test_needs_features = [DisabledFeature()]
1247
result = unittest.TestResult()
1249
self.assertEqual(1, result.testsRun)
1250
self.assertEqual([], result.errors)
1251
self.assertEqual([], result.failures)
1253
def test_run_disabled_supporting_result(self):
1254
"""Test disabled tests behaviour with support aware results."""
1255
test = SampleTestCase('_test_pass')
1256
class DisabledFeature(object):
1257
def available(self):
1259
the_feature = DisabledFeature()
1260
test._test_needs_features = [the_feature]
1261
class InstrumentedTestResult(unittest.TestResult):
1263
unittest.TestResult.__init__(self)
1265
def startTest(self, test):
1266
self.calls.append(('startTest', test))
1267
def stopTest(self, test):
1268
self.calls.append(('stopTest', test))
1269
def addNotSupported(self, test, feature):
1270
self.calls.append(('addNotSupported', test, feature))
1271
result = InstrumentedTestResult()
1274
('startTest', test),
1275
('addNotSupported', test, the_feature),
1281
@symbol_versioning.deprecated_function(zero_eleven)
1282
def sample_deprecated_function():
1283
"""A deprecated function to test applyDeprecated with."""
1287
def sample_undeprecated_function(a_param):
1288
"""A undeprecated function to test applyDeprecated with."""
1291
class ApplyDeprecatedHelper(object):
1292
"""A helper class for ApplyDeprecated tests."""
1294
@symbol_versioning.deprecated_method(zero_eleven)
1295
def sample_deprecated_method(self, param_one):
1296
"""A deprecated method for testing with."""
1299
def sample_normal_method(self):
1300
"""A undeprecated method."""
1302
@symbol_versioning.deprecated_method(zero_ten)
1303
def sample_nested_deprecation(self):
1304
return sample_deprecated_function()
1307
class TestExtraAssertions(TestCase):
1308
"""Tests for new test assertions in bzrlib test suite"""
1310
def test_assert_isinstance(self):
1311
self.assertIsInstance(2, int)
1312
self.assertIsInstance(u'', basestring)
1313
self.assertRaises(AssertionError, self.assertIsInstance, None, int)
1314
self.assertRaises(AssertionError, self.assertIsInstance, 23.3, int)
1316
def test_assertEndsWith(self):
1317
self.assertEndsWith('foo', 'oo')
1318
self.assertRaises(AssertionError, self.assertEndsWith, 'o', 'oo')
1320
def test_applyDeprecated_not_deprecated(self):
1321
sample_object = ApplyDeprecatedHelper()
1322
# calling an undeprecated callable raises an assertion
1323
self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
1324
sample_object.sample_normal_method)
1325
self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
1326
sample_undeprecated_function, "a param value")
1327
# calling a deprecated callable (function or method) with the wrong
1328
# expected deprecation fails.
1329
self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
1330
sample_object.sample_deprecated_method, "a param value")
1331
self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
1332
sample_deprecated_function)
1333
# calling a deprecated callable (function or method) with the right
1334
# expected deprecation returns the functions result.
1335
self.assertEqual("a param value", self.applyDeprecated(zero_eleven,
1336
sample_object.sample_deprecated_method, "a param value"))
1337
self.assertEqual(2, self.applyDeprecated(zero_eleven,
1338
sample_deprecated_function))
1339
# calling a nested deprecation with the wrong deprecation version
1340
# fails even if a deeper nested function was deprecated with the
1342
self.assertRaises(AssertionError, self.applyDeprecated,
1343
zero_eleven, sample_object.sample_nested_deprecation)
1344
# calling a nested deprecation with the right deprecation value
1345
# returns the calls result.
1346
self.assertEqual(2, self.applyDeprecated(zero_ten,
1347
sample_object.sample_nested_deprecation))
1349
def test_callDeprecated(self):
1350
def testfunc(be_deprecated, result=None):
1351
if be_deprecated is True:
1352
symbol_versioning.warn('i am deprecated', DeprecationWarning,
1355
result = self.callDeprecated(['i am deprecated'], testfunc, True)
1356
self.assertIs(None, result)
1357
result = self.callDeprecated([], testfunc, False, 'result')
1358
self.assertEqual('result', result)
1359
self.callDeprecated(['i am deprecated'], testfunc, be_deprecated=True)
1360
self.callDeprecated([], testfunc, be_deprecated=False)
1363
class TestConvenienceMakers(TestCaseWithTransport):
1364
"""Test for the make_* convenience functions."""
1366
def test_make_branch_and_tree_with_format(self):
1367
# we should be able to supply a format to make_branch_and_tree
1368
self.make_branch_and_tree('a', format=bzrlib.bzrdir.BzrDirMetaFormat1())
1369
self.make_branch_and_tree('b', format=bzrlib.bzrdir.BzrDirFormat6())
1370
self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('a')._format,
1371
bzrlib.bzrdir.BzrDirMetaFormat1)
1372
self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('b')._format,
1373
bzrlib.bzrdir.BzrDirFormat6)
1375
def test_make_branch_and_memory_tree(self):
1376
# we should be able to get a new branch and a mutable tree from
1377
# TestCaseWithTransport
1378
tree = self.make_branch_and_memory_tree('a')
1379
self.assertIsInstance(tree, bzrlib.memorytree.MemoryTree)
1382
class TestSFTPMakeBranchAndTree(TestCaseWithSFTPServer):
1384
def test_make_tree_for_sftp_branch(self):
1385
"""Transports backed by local directories create local trees."""
1387
tree = self.make_branch_and_tree('t1')
1388
base = tree.bzrdir.root_transport.base
1389
self.failIf(base.startswith('sftp'),
1390
'base %r is on sftp but should be local' % base)
1391
self.assertEquals(tree.bzrdir.root_transport,
1392
tree.branch.bzrdir.root_transport)
1393
self.assertEquals(tree.bzrdir.root_transport,
1394
tree.branch.repository.bzrdir.root_transport)
1397
class TestSelftest(TestCase):
1398
"""Tests of bzrlib.tests.selftest."""
1400
def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
1403
factory_called.append(True)
1407
self.apply_redirected(out, err, None, bzrlib.tests.selftest,
1408
test_suite_factory=factory)
1409
self.assertEqual([True], factory_called)
1412
class TestSelftestCleanOutput(TestCaseInTempDir):
1414
def test_clean_output(self):
1415
# test functionality of clean_selftest_output()
1416
from bzrlib.tests import clean_selftest_output
1418
dirs = ('test0000.tmp', 'test0001.tmp', 'bzrlib', 'tests')
1419
files = ('bzr', 'setup.py', 'test9999.tmp')
1424
f.write('content of ')
1429
before = os.listdir(root)
1431
self.assertEquals(['bzr','bzrlib','setup.py',
1432
'test0000.tmp','test0001.tmp',
1433
'test9999.tmp','tests'],
1435
clean_selftest_output(root, quiet=True)
1436
after = os.listdir(root)
1438
self.assertEquals(['bzr','bzrlib','setup.py',
1439
'test9999.tmp','tests'],
1443
class TestKnownFailure(TestCase):
1445
def test_known_failure(self):
1446
"""Check that KnownFailure is defined appropriately."""
1447
# a KnownFailure is an assertion error for compatability with unaware
1449
self.assertIsInstance(KnownFailure(""), AssertionError)
1451
def test_expect_failure(self):
1453
self.expectFailure("Doomed to failure", self.assertTrue, False)
1454
except KnownFailure, e:
1455
self.assertEqual('Doomed to failure', e.args[0])
1457
self.expectFailure("Doomed to failure", self.assertTrue, True)
1458
except AssertionError, e:
1459
self.assertEqual('Unexpected success. Should have failed:'
1460
' Doomed to failure', e.args[0])
1462
self.fail('Assertion not raised')
1465
class TestFeature(TestCase):
1467
def test_caching(self):
1468
"""Feature._probe is called by the feature at most once."""
1469
class InstrumentedFeature(Feature):
1471
Feature.__init__(self)
1474
self.calls.append('_probe')
1476
feature = InstrumentedFeature()
1478
self.assertEqual(['_probe'], feature.calls)
1480
self.assertEqual(['_probe'], feature.calls)
1482
def test_named_str(self):
1483
"""Feature.__str__ should thunk to feature_name()."""
1484
class NamedFeature(Feature):
1485
def feature_name(self):
1487
feature = NamedFeature()
1488
self.assertEqual('symlinks', str(feature))
1490
def test_default_str(self):
1491
"""Feature.__str__ should default to __class__.__name__."""
1492
class NamedFeature(Feature):
1494
feature = NamedFeature()
1495
self.assertEqual('NamedFeature', str(feature))
1498
class TestUnavailableFeature(TestCase):
1500
def test_access_feature(self):
1502
exception = UnavailableFeature(feature)
1503
self.assertIs(feature, exception.args[0])