1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
"""Tests for the test framework."""
19
from cStringIO import StringIO
43
from bzrlib.repofmt import (
48
from bzrlib.symbol_versioning import (
53
from bzrlib.tests import (
59
from bzrlib.trace import note
60
from bzrlib.transport.memory import MemoryServer, MemoryTransport
61
from bzrlib.version import _get_bzr_source_tree
64
def _test_ids(test_suite):
65
"""Get the ids for the tests in a test suite."""
66
return [t.id() for t in tests.iter_suite_tests(test_suite)]
69
class SelftestTests(tests.TestCase):
71
def test_import_tests(self):
72
mod = TestUtil._load_module_by_name('bzrlib.tests.test_selftest')
73
self.assertEqual(mod.SelftestTests, SelftestTests)
75
def test_import_test_failure(self):
76
self.assertRaises(ImportError,
77
TestUtil._load_module_by_name,
80
class MetaTestLog(tests.TestCase):
82
def test_logging(self):
83
"""Test logs are captured when a test fails."""
84
self.log('a test message')
85
self._log_file.flush()
86
self.assertContainsRe(self._get_log(keep_log_file=True),
90
class TestUnicodeFilename(tests.TestCase):
92
def test_probe_passes(self):
93
"""UnicodeFilename._probe passes."""
94
# We can't test much more than that because the behaviour depends
96
tests.UnicodeFilename._probe()
99
class TestTreeShape(tests.TestCaseInTempDir):
101
def test_unicode_paths(self):
102
self.requireFeature(tests.UnicodeFilename)
104
filename = u'hell\u00d8'
105
self.build_tree_contents([(filename, 'contents of hello')])
106
self.failUnlessExists(filename)
109
class TestTransportScenarios(tests.TestCase):
110
"""A group of tests that test the transport implementation adaption core.
112
This is a meta test that the tests are applied to all available
115
This will be generalised in the future which is why it is in this
116
test file even though it is specific to transport tests at the moment.
119
def test_get_transport_permutations(self):
120
# this checks that get_test_permutations defined by the module is
121
# called by the get_transport_test_permutations function.
122
class MockModule(object):
123
def get_test_permutations(self):
124
return sample_permutation
125
sample_permutation = [(1,2), (3,4)]
126
from bzrlib.tests.per_transport import get_transport_test_permutations
127
self.assertEqual(sample_permutation,
128
get_transport_test_permutations(MockModule()))
130
def test_scenarios_include_all_modules(self):
131
# this checks that the scenario generator returns as many permutations
132
# as there are in all the registered transport modules - we assume if
133
# this matches its probably doing the right thing especially in
134
# combination with the tests for setting the right classes below.
135
from bzrlib.tests.per_transport import transport_test_permutations
136
from bzrlib.transport import _get_transport_modules
137
modules = _get_transport_modules()
138
permutation_count = 0
139
for module in modules:
141
permutation_count += len(reduce(getattr,
142
(module + ".get_test_permutations").split('.')[1:],
143
__import__(module))())
144
except errors.DependencyNotPresent:
146
scenarios = transport_test_permutations()
147
self.assertEqual(permutation_count, len(scenarios))
149
def test_scenarios_include_transport_class(self):
150
# This test used to know about all the possible transports and the
151
# order they were returned but that seems overly brittle (mbp
153
from bzrlib.tests.per_transport import transport_test_permutations
154
scenarios = transport_test_permutations()
155
# there are at least that many builtin transports
156
self.assertTrue(len(scenarios) > 6)
157
one_scenario = scenarios[0]
158
self.assertIsInstance(one_scenario[0], str)
159
self.assertTrue(issubclass(one_scenario[1]["transport_class"],
160
bzrlib.transport.Transport))
161
self.assertTrue(issubclass(one_scenario[1]["transport_server"],
162
bzrlib.transport.Server))
165
class TestBranchScenarios(tests.TestCase):
167
def test_scenarios(self):
168
# check that constructor parameters are passed through to the adapted
170
from bzrlib.tests.per_branch import make_scenarios
173
formats = [("c", "C"), ("d", "D")]
174
scenarios = make_scenarios(server1, server2, formats)
175
self.assertEqual(2, len(scenarios))
178
{'branch_format': 'c',
179
'bzrdir_format': 'C',
180
'transport_readonly_server': 'b',
181
'transport_server': 'a'}),
183
{'branch_format': 'd',
184
'bzrdir_format': 'D',
185
'transport_readonly_server': 'b',
186
'transport_server': 'a'})],
190
class TestBzrDirScenarios(tests.TestCase):
192
def test_scenarios(self):
193
# check that constructor parameters are passed through to the adapted
195
from bzrlib.tests.per_bzrdir import make_scenarios
200
scenarios = make_scenarios(vfs_factory, server1, server2, formats)
203
{'bzrdir_format': 'c',
204
'transport_readonly_server': 'b',
205
'transport_server': 'a',
206
'vfs_transport_factory': 'v'}),
208
{'bzrdir_format': 'd',
209
'transport_readonly_server': 'b',
210
'transport_server': 'a',
211
'vfs_transport_factory': 'v'})],
215
class TestRepositoryScenarios(tests.TestCase):
217
def test_formats_to_scenarios(self):
218
from bzrlib.tests.per_repository import formats_to_scenarios
219
formats = [("(c)", remote.RemoteRepositoryFormat()),
220
("(d)", repository.format_registry.get(
221
'Bazaar repository format 2a (needs bzr 1.16 or later)\n'))]
222
no_vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
224
vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
225
vfs_transport_factory="vfs")
226
# no_vfs generate scenarios without vfs_transport_factory
228
('RemoteRepositoryFormat(c)',
229
{'bzrdir_format': remote.RemoteBzrDirFormat(),
230
'repository_format': remote.RemoteRepositoryFormat(),
231
'transport_readonly_server': 'readonly',
232
'transport_server': 'server'}),
233
('RepositoryFormat2a(d)',
234
{'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
235
'repository_format': groupcompress_repo.RepositoryFormat2a(),
236
'transport_readonly_server': 'readonly',
237
'transport_server': 'server'})]
238
self.assertEqual(expected, no_vfs_scenarios)
240
('RemoteRepositoryFormat(c)',
241
{'bzrdir_format': remote.RemoteBzrDirFormat(),
242
'repository_format': remote.RemoteRepositoryFormat(),
243
'transport_readonly_server': 'readonly',
244
'transport_server': 'server',
245
'vfs_transport_factory': 'vfs'}),
246
('RepositoryFormat2a(d)',
247
{'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
248
'repository_format': groupcompress_repo.RepositoryFormat2a(),
249
'transport_readonly_server': 'readonly',
250
'transport_server': 'server',
251
'vfs_transport_factory': 'vfs'})],
255
class TestTestScenarioApplication(tests.TestCase):
256
"""Tests for the test adaption facilities."""
258
def test_apply_scenario(self):
259
from bzrlib.tests import apply_scenario
260
input_test = TestTestScenarioApplication("test_apply_scenario")
261
# setup two adapted tests
262
adapted_test1 = apply_scenario(input_test,
264
{"bzrdir_format":"bzr_format",
265
"repository_format":"repo_fmt",
266
"transport_server":"transport_server",
267
"transport_readonly_server":"readonly-server"}))
268
adapted_test2 = apply_scenario(input_test,
269
("new id 2", {"bzrdir_format":None}))
270
# input_test should have been altered.
271
self.assertRaises(AttributeError, getattr, input_test, "bzrdir_format")
272
# the new tests are mutually incompatible, ensuring it has
273
# made new ones, and unspecified elements in the scenario
274
# should not have been altered.
275
self.assertEqual("bzr_format", adapted_test1.bzrdir_format)
276
self.assertEqual("repo_fmt", adapted_test1.repository_format)
277
self.assertEqual("transport_server", adapted_test1.transport_server)
278
self.assertEqual("readonly-server",
279
adapted_test1.transport_readonly_server)
281
"bzrlib.tests.test_selftest.TestTestScenarioApplication."
282
"test_apply_scenario(new id)",
284
self.assertEqual(None, adapted_test2.bzrdir_format)
286
"bzrlib.tests.test_selftest.TestTestScenarioApplication."
287
"test_apply_scenario(new id 2)",
291
class TestInterRepositoryScenarios(tests.TestCase):
293
def test_scenarios(self):
294
# check that constructor parameters are passed through to the adapted
296
from bzrlib.tests.per_interrepository import make_scenarios
299
formats = [("C0", "C1", "C2"), ("D0", "D1", "D2")]
300
scenarios = make_scenarios(server1, server2, formats)
303
{'repository_format': 'C1',
304
'repository_format_to': 'C2',
305
'transport_readonly_server': 'b',
306
'transport_server': 'a'}),
308
{'repository_format': 'D1',
309
'repository_format_to': 'D2',
310
'transport_readonly_server': 'b',
311
'transport_server': 'a'})],
315
class TestWorkingTreeScenarios(tests.TestCase):
317
def test_scenarios(self):
318
# check that constructor parameters are passed through to the adapted
320
from bzrlib.tests.per_workingtree import make_scenarios
323
formats = [workingtree.WorkingTreeFormat2(),
324
workingtree.WorkingTreeFormat3(),]
325
scenarios = make_scenarios(server1, server2, formats)
327
('WorkingTreeFormat2',
328
{'bzrdir_format': formats[0]._matchingbzrdir,
329
'transport_readonly_server': 'b',
330
'transport_server': 'a',
331
'workingtree_format': formats[0]}),
332
('WorkingTreeFormat3',
333
{'bzrdir_format': formats[1]._matchingbzrdir,
334
'transport_readonly_server': 'b',
335
'transport_server': 'a',
336
'workingtree_format': formats[1]})],
340
class TestTreeScenarios(tests.TestCase):
342
def test_scenarios(self):
343
# the tree implementation scenario generator is meant to setup one
344
# instance for each working tree format, and one additional instance
345
# that will use the default wt format, but create a revision tree for
346
# the tests. this means that the wt ones should have the
347
# workingtree_to_test_tree attribute set to 'return_parameter' and the
348
# revision one set to revision_tree_from_workingtree.
350
from bzrlib.tests.per_tree import (
351
_dirstate_tree_from_workingtree,
356
revision_tree_from_workingtree
360
formats = [workingtree.WorkingTreeFormat2(),
361
workingtree.WorkingTreeFormat3(),]
362
scenarios = make_scenarios(server1, server2, formats)
363
self.assertEqual(7, len(scenarios))
364
default_wt_format = workingtree.WorkingTreeFormat4._default_format
365
wt4_format = workingtree.WorkingTreeFormat4()
366
wt5_format = workingtree.WorkingTreeFormat5()
367
expected_scenarios = [
368
('WorkingTreeFormat2',
369
{'bzrdir_format': formats[0]._matchingbzrdir,
370
'transport_readonly_server': 'b',
371
'transport_server': 'a',
372
'workingtree_format': formats[0],
373
'_workingtree_to_test_tree': return_parameter,
375
('WorkingTreeFormat3',
376
{'bzrdir_format': formats[1]._matchingbzrdir,
377
'transport_readonly_server': 'b',
378
'transport_server': 'a',
379
'workingtree_format': formats[1],
380
'_workingtree_to_test_tree': return_parameter,
383
{'_workingtree_to_test_tree': revision_tree_from_workingtree,
384
'bzrdir_format': default_wt_format._matchingbzrdir,
385
'transport_readonly_server': 'b',
386
'transport_server': 'a',
387
'workingtree_format': default_wt_format,
389
('DirStateRevisionTree,WT4',
390
{'_workingtree_to_test_tree': _dirstate_tree_from_workingtree,
391
'bzrdir_format': wt4_format._matchingbzrdir,
392
'transport_readonly_server': 'b',
393
'transport_server': 'a',
394
'workingtree_format': wt4_format,
396
('DirStateRevisionTree,WT5',
397
{'_workingtree_to_test_tree': _dirstate_tree_from_workingtree,
398
'bzrdir_format': wt5_format._matchingbzrdir,
399
'transport_readonly_server': 'b',
400
'transport_server': 'a',
401
'workingtree_format': wt5_format,
404
{'_workingtree_to_test_tree': preview_tree_pre,
405
'bzrdir_format': default_wt_format._matchingbzrdir,
406
'transport_readonly_server': 'b',
407
'transport_server': 'a',
408
'workingtree_format': default_wt_format}),
410
{'_workingtree_to_test_tree': preview_tree_post,
411
'bzrdir_format': default_wt_format._matchingbzrdir,
412
'transport_readonly_server': 'b',
413
'transport_server': 'a',
414
'workingtree_format': default_wt_format}),
416
self.assertEqual(expected_scenarios, scenarios)
419
class TestInterTreeScenarios(tests.TestCase):
420
"""A group of tests that test the InterTreeTestAdapter."""
422
def test_scenarios(self):
423
# check that constructor parameters are passed through to the adapted
425
# for InterTree tests we want the machinery to bring up two trees in
426
# each instance: the base one, and the one we are interacting with.
427
# because each optimiser can be direction specific, we need to test
428
# each optimiser in its chosen direction.
429
# unlike the TestProviderAdapter we dont want to automatically add a
430
# parameterized one for WorkingTree - the optimisers will tell us what
432
from bzrlib.tests.per_tree import (
434
revision_tree_from_workingtree
436
from bzrlib.tests.per_intertree import (
439
from bzrlib.workingtree import WorkingTreeFormat2, WorkingTreeFormat3
440
input_test = TestInterTreeScenarios(
444
format1 = WorkingTreeFormat2()
445
format2 = WorkingTreeFormat3()
446
formats = [("1", str, format1, format2, "converter1"),
447
("2", int, format2, format1, "converter2")]
448
scenarios = make_scenarios(server1, server2, formats)
449
self.assertEqual(2, len(scenarios))
450
expected_scenarios = [
452
"bzrdir_format": format1._matchingbzrdir,
453
"intertree_class": formats[0][1],
454
"workingtree_format": formats[0][2],
455
"workingtree_format_to": formats[0][3],
456
"mutable_trees_to_test_trees": formats[0][4],
457
"_workingtree_to_test_tree": return_parameter,
458
"transport_server": server1,
459
"transport_readonly_server": server2,
462
"bzrdir_format": format2._matchingbzrdir,
463
"intertree_class": formats[1][1],
464
"workingtree_format": formats[1][2],
465
"workingtree_format_to": formats[1][3],
466
"mutable_trees_to_test_trees": formats[1][4],
467
"_workingtree_to_test_tree": return_parameter,
468
"transport_server": server1,
469
"transport_readonly_server": server2,
472
self.assertEqual(scenarios, expected_scenarios)
475
class TestTestCaseInTempDir(tests.TestCaseInTempDir):
477
def test_home_is_not_working(self):
478
self.assertNotEqual(self.test_dir, self.test_home_dir)
479
cwd = osutils.getcwd()
480
self.assertIsSameRealPath(self.test_dir, cwd)
481
self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
483
def test_assertEqualStat_equal(self):
484
from bzrlib.tests.test_dirstate import _FakeStat
485
self.build_tree(["foo"])
486
real = os.lstat("foo")
487
fake = _FakeStat(real.st_size, real.st_mtime, real.st_ctime,
488
real.st_dev, real.st_ino, real.st_mode)
489
self.assertEqualStat(real, fake)
491
def test_assertEqualStat_notequal(self):
492
self.build_tree(["foo", "bar"])
493
self.assertRaises(AssertionError, self.assertEqualStat,
494
os.lstat("foo"), os.lstat("bar"))
497
class TestTestCaseWithMemoryTransport(tests.TestCaseWithMemoryTransport):
499
def test_home_is_non_existant_dir_under_root(self):
500
"""The test_home_dir for TestCaseWithMemoryTransport is missing.
502
This is because TestCaseWithMemoryTransport is for tests that do not
503
need any disk resources: they should be hooked into bzrlib in such a
504
way that no global settings are being changed by the test (only a
505
few tests should need to do that), and having a missing dir as home is
506
an effective way to ensure that this is the case.
508
self.assertIsSameRealPath(
509
self.TEST_ROOT + "/MemoryTransportMissingHomeDir",
511
self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
513
def test_cwd_is_TEST_ROOT(self):
514
self.assertIsSameRealPath(self.test_dir, self.TEST_ROOT)
515
cwd = osutils.getcwd()
516
self.assertIsSameRealPath(self.test_dir, cwd)
518
def test_make_branch_and_memory_tree(self):
519
"""In TestCaseWithMemoryTransport we should not make the branch on disk.
521
This is hard to comprehensively robustly test, so we settle for making
522
a branch and checking no directory was created at its relpath.
524
tree = self.make_branch_and_memory_tree('dir')
525
# Guard against regression into MemoryTransport leaking
526
# files to disk instead of keeping them in memory.
527
self.failIf(osutils.lexists('dir'))
528
self.assertIsInstance(tree, memorytree.MemoryTree)
530
def test_make_branch_and_memory_tree_with_format(self):
531
"""make_branch_and_memory_tree should accept a format option."""
532
format = bzrdir.BzrDirMetaFormat1()
533
format.repository_format = weaverepo.RepositoryFormat7()
534
tree = self.make_branch_and_memory_tree('dir', format=format)
535
# Guard against regression into MemoryTransport leaking
536
# files to disk instead of keeping them in memory.
537
self.failIf(osutils.lexists('dir'))
538
self.assertIsInstance(tree, memorytree.MemoryTree)
539
self.assertEqual(format.repository_format.__class__,
540
tree.branch.repository._format.__class__)
542
def test_make_branch_builder(self):
543
builder = self.make_branch_builder('dir')
544
self.assertIsInstance(builder, branchbuilder.BranchBuilder)
545
# Guard against regression into MemoryTransport leaking
546
# files to disk instead of keeping them in memory.
547
self.failIf(osutils.lexists('dir'))
549
def test_make_branch_builder_with_format(self):
550
# Use a repo layout that doesn't conform to a 'named' layout, to ensure
551
# that the format objects are used.
552
format = bzrdir.BzrDirMetaFormat1()
553
repo_format = weaverepo.RepositoryFormat7()
554
format.repository_format = repo_format
555
builder = self.make_branch_builder('dir', format=format)
556
the_branch = builder.get_branch()
557
# Guard against regression into MemoryTransport leaking
558
# files to disk instead of keeping them in memory.
559
self.failIf(osutils.lexists('dir'))
560
self.assertEqual(format.repository_format.__class__,
561
the_branch.repository._format.__class__)
562
self.assertEqual(repo_format.get_format_string(),
563
self.get_transport().get_bytes(
564
'dir/.bzr/repository/format'))
566
def test_make_branch_builder_with_format_name(self):
567
builder = self.make_branch_builder('dir', format='knit')
568
the_branch = builder.get_branch()
569
# Guard against regression into MemoryTransport leaking
570
# files to disk instead of keeping them in memory.
571
self.failIf(osutils.lexists('dir'))
572
dir_format = bzrdir.format_registry.make_bzrdir('knit')
573
self.assertEqual(dir_format.repository_format.__class__,
574
the_branch.repository._format.__class__)
575
self.assertEqual('Bazaar-NG Knit Repository Format 1',
576
self.get_transport().get_bytes(
577
'dir/.bzr/repository/format'))
579
def test_safety_net(self):
580
"""No test should modify the safety .bzr directory.
582
We just test that the _check_safety_net private method raises
583
AssertionError, it's easier than building a test suite with the same
586
# Oops, a commit in the current directory (i.e. without local .bzr
587
# directory) will crawl up the hierarchy to find a .bzr directory.
588
self.run_bzr(['commit', '-mfoo', '--unchanged'])
589
# But we have a safety net in place.
590
self.assertRaises(AssertionError, self._check_safety_net)
592
def test_dangling_locks_cause_failures(self):
593
class TestDanglingLock(tests.TestCaseWithMemoryTransport):
594
def test_function(self):
595
t = self.get_transport('.')
596
l = lockdir.LockDir(t, 'lock')
599
test = TestDanglingLock('test_function')
601
if self._lock_check_thorough:
602
self.assertEqual(1, len(result.errors))
604
# When _lock_check_thorough is disabled, then we don't trigger a
606
self.assertEqual(0, len(result.errors))
609
class TestTestCaseWithTransport(tests.TestCaseWithTransport):
610
"""Tests for the convenience functions TestCaseWithTransport introduces."""
612
def test_get_readonly_url_none(self):
613
from bzrlib.transport import get_transport
614
from bzrlib.transport.memory import MemoryServer
615
from bzrlib.transport.readonly import ReadonlyTransportDecorator
616
self.vfs_transport_factory = MemoryServer
617
self.transport_readonly_server = None
618
# calling get_readonly_transport() constructs a decorator on the url
620
url = self.get_readonly_url()
621
url2 = self.get_readonly_url('foo/bar')
622
t = get_transport(url)
623
t2 = get_transport(url2)
624
self.failUnless(isinstance(t, ReadonlyTransportDecorator))
625
self.failUnless(isinstance(t2, ReadonlyTransportDecorator))
626
self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
628
def test_get_readonly_url_http(self):
629
from bzrlib.tests.http_server import HttpServer
630
from bzrlib.transport import get_transport
631
from bzrlib.transport.local import LocalURLServer
632
from bzrlib.transport.http import HttpTransportBase
633
self.transport_server = LocalURLServer
634
self.transport_readonly_server = HttpServer
635
# calling get_readonly_transport() gives us a HTTP server instance.
636
url = self.get_readonly_url()
637
url2 = self.get_readonly_url('foo/bar')
638
# the transport returned may be any HttpTransportBase subclass
639
t = get_transport(url)
640
t2 = get_transport(url2)
641
self.failUnless(isinstance(t, HttpTransportBase))
642
self.failUnless(isinstance(t2, HttpTransportBase))
643
self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
645
def test_is_directory(self):
646
"""Test assertIsDirectory assertion"""
647
t = self.get_transport()
648
self.build_tree(['a_dir/', 'a_file'], transport=t)
649
self.assertIsDirectory('a_dir', t)
650
self.assertRaises(AssertionError, self.assertIsDirectory, 'a_file', t)
651
self.assertRaises(AssertionError, self.assertIsDirectory, 'not_here', t)
653
def test_make_branch_builder(self):
654
builder = self.make_branch_builder('dir')
655
rev_id = builder.build_commit()
656
self.failUnlessExists('dir')
657
a_dir = bzrdir.BzrDir.open('dir')
658
self.assertRaises(errors.NoWorkingTree, a_dir.open_workingtree)
659
a_branch = a_dir.open_branch()
660
builder_branch = builder.get_branch()
661
self.assertEqual(a_branch.base, builder_branch.base)
662
self.assertEqual((1, rev_id), builder_branch.last_revision_info())
663
self.assertEqual((1, rev_id), a_branch.last_revision_info())
666
class TestTestCaseTransports(tests.TestCaseWithTransport):
669
super(TestTestCaseTransports, self).setUp()
670
self.vfs_transport_factory = MemoryServer
672
def test_make_bzrdir_preserves_transport(self):
673
t = self.get_transport()
674
result_bzrdir = self.make_bzrdir('subdir')
675
self.assertIsInstance(result_bzrdir.transport,
677
# should not be on disk, should only be in memory
678
self.failIfExists('subdir')
681
class TestChrootedTest(tests.ChrootedTestCase):
683
def test_root_is_root(self):
684
from bzrlib.transport import get_transport
685
t = get_transport(self.get_readonly_url())
687
self.assertEqual(url, t.clone('..').base)
690
class TestProfileResult(tests.TestCase):
692
def test_profiles_tests(self):
693
self.requireFeature(test_lsprof.LSProfFeature)
694
terminal = unittest.TestResult()
695
result = tests.ProfileResult(terminal)
696
class Sample(tests.TestCase):
698
self.sample_function()
699
def sample_function(self):
702
test.attrs_to_keep = test.attrs_to_keep + ('_benchcalls',)
704
self.assertLength(1, test._benchcalls)
705
# We must be able to unpack it as the test reporting code wants
706
(_, _, _), stats = test._benchcalls[0]
707
self.assertTrue(callable(stats.pprint))
710
class TestTestResult(tests.TestCase):
712
def check_timing(self, test_case, expected_re):
713
result = bzrlib.tests.TextTestResult(self._log_file,
717
test_case.run(result)
718
timed_string = result._testTimeString(test_case)
719
self.assertContainsRe(timed_string, expected_re)
721
def test_test_reporting(self):
722
class ShortDelayTestCase(tests.TestCase):
723
def test_short_delay(self):
725
def test_short_benchmark(self):
726
self.time(time.sleep, 0.003)
727
self.check_timing(ShortDelayTestCase('test_short_delay'),
729
# if a benchmark time is given, we now show just that time followed by
731
self.check_timing(ShortDelayTestCase('test_short_benchmark'),
734
def test_unittest_reporting_unittest_class(self):
735
# getting the time from a non-bzrlib test works ok
736
class ShortDelayTestCase(unittest.TestCase):
737
def test_short_delay(self):
739
self.check_timing(ShortDelayTestCase('test_short_delay'),
742
def test_assigned_benchmark_file_stores_date(self):
744
result = bzrlib.tests.TextTestResult(self._log_file,
749
output_string = output.getvalue()
750
# if you are wondering about the regexp please read the comment in
751
# test_bench_history (bzrlib.tests.test_selftest.TestRunner)
752
# XXX: what comment? -- Andrew Bennetts
753
self.assertContainsRe(output_string, "--date [0-9.]+")
755
def test_benchhistory_records_test_times(self):
756
result_stream = StringIO()
757
result = bzrlib.tests.TextTestResult(
761
bench_history=result_stream
764
# we want profile a call and check that its test duration is recorded
765
# make a new test instance that when run will generate a benchmark
766
example_test_case = TestTestResult("_time_hello_world_encoding")
767
# execute the test, which should succeed and record times
768
example_test_case.run(result)
769
lines = result_stream.getvalue().splitlines()
770
self.assertEqual(2, len(lines))
771
self.assertContainsRe(lines[1],
772
" *[0-9]+ms bzrlib.tests.test_selftest.TestTestResult"
773
"._time_hello_world_encoding")
775
def _time_hello_world_encoding(self):
776
"""Profile two sleep calls
778
This is used to exercise the test framework.
780
self.time(unicode, 'hello', errors='replace')
781
self.time(unicode, 'world', errors='replace')
783
def test_lsprofiling(self):
784
"""Verbose test result prints lsprof statistics from test cases."""
785
self.requireFeature(test_lsprof.LSProfFeature)
786
result_stream = StringIO()
787
result = bzrlib.tests.VerboseTestResult(
788
unittest._WritelnDecorator(result_stream),
792
# we want profile a call of some sort and check it is output by
793
# addSuccess. We dont care about addError or addFailure as they
794
# are not that interesting for performance tuning.
795
# make a new test instance that when run will generate a profile
796
example_test_case = TestTestResult("_time_hello_world_encoding")
797
example_test_case._gather_lsprof_in_benchmarks = True
798
# execute the test, which should succeed and record profiles
799
example_test_case.run(result)
800
# lsprofile_something()
801
# if this worked we want
802
# LSProf output for <built in function unicode> (['hello'], {'errors': 'replace'})
803
# CallCount Recursive Total(ms) Inline(ms) module:lineno(function)
804
# (the lsprof header)
805
# ... an arbitrary number of lines
806
# and the function call which is time.sleep.
807
# 1 0 ??? ??? ???(sleep)
808
# and then repeated but with 'world', rather than 'hello'.
809
# this should appear in the output stream of our test result.
810
output = result_stream.getvalue()
811
self.assertContainsRe(output,
812
r"LSProf output for <type 'unicode'>\(\('hello',\), {'errors': 'replace'}\)")
813
self.assertContainsRe(output,
814
r" *CallCount *Recursive *Total\(ms\) *Inline\(ms\) *module:lineno\(function\)\n")
815
self.assertContainsRe(output,
816
r"( +1 +0 +0\.\d+ +0\.\d+ +<method 'disable' of '_lsprof\.Profiler' objects>\n)?")
817
self.assertContainsRe(output,
818
r"LSProf output for <type 'unicode'>\(\('world',\), {'errors': 'replace'}\)\n")
820
def test_known_failure(self):
821
"""A KnownFailure being raised should trigger several result actions."""
822
class InstrumentedTestResult(tests.ExtendedTestResult):
823
def stopTestRun(self): pass
824
def startTests(self): pass
825
def report_test_start(self, test): pass
826
def report_known_failure(self, test, err):
827
self._call = test, err
828
result = InstrumentedTestResult(None, None, None, None)
830
raise tests.KnownFailure('failed!')
831
test = unittest.FunctionTestCase(test_function)
833
# it should invoke 'report_known_failure'.
834
self.assertEqual(2, len(result._call))
835
self.assertEqual(test, result._call[0])
836
self.assertEqual(tests.KnownFailure, result._call[1][0])
837
self.assertIsInstance(result._call[1][1], tests.KnownFailure)
838
# we dont introspec the traceback, if the rest is ok, it would be
839
# exceptional for it not to be.
840
# it should update the known_failure_count on the object.
841
self.assertEqual(1, result.known_failure_count)
842
# the result should be successful.
843
self.assertTrue(result.wasSuccessful())
845
def test_verbose_report_known_failure(self):
846
# verbose test output formatting
847
result_stream = StringIO()
848
result = bzrlib.tests.VerboseTestResult(
849
unittest._WritelnDecorator(result_stream),
853
test = self.get_passing_test()
854
result.startTest(test)
855
prefix = len(result_stream.getvalue())
856
# the err parameter has the shape:
857
# (class, exception object, traceback)
858
# KnownFailures dont get their tracebacks shown though, so we
860
err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
861
result.report_known_failure(test, err)
862
output = result_stream.getvalue()[prefix:]
863
lines = output.splitlines()
864
self.assertContainsRe(lines[0], r'XFAIL *\d+ms$')
865
self.assertEqual(lines[1], ' foo')
866
self.assertEqual(2, len(lines))
868
def get_passing_test(self):
869
"""Return a test object that can't be run usefully."""
872
return unittest.FunctionTestCase(passing_test)
874
def test_add_not_supported(self):
875
"""Test the behaviour of invoking addNotSupported."""
876
class InstrumentedTestResult(tests.ExtendedTestResult):
877
def stopTestRun(self): pass
878
def startTests(self): pass
879
def report_test_start(self, test): pass
880
def report_unsupported(self, test, feature):
881
self._call = test, feature
882
result = InstrumentedTestResult(None, None, None, None)
883
test = SampleTestCase('_test_pass')
884
feature = tests.Feature()
885
result.startTest(test)
886
result.addNotSupported(test, feature)
887
# it should invoke 'report_unsupported'.
888
self.assertEqual(2, len(result._call))
889
self.assertEqual(test, result._call[0])
890
self.assertEqual(feature, result._call[1])
891
# the result should be successful.
892
self.assertTrue(result.wasSuccessful())
893
# it should record the test against a count of tests not run due to
895
self.assertEqual(1, result.unsupported['Feature'])
896
# and invoking it again should increment that counter
897
result.addNotSupported(test, feature)
898
self.assertEqual(2, result.unsupported['Feature'])
900
def test_verbose_report_unsupported(self):
901
# verbose test output formatting
902
result_stream = StringIO()
903
result = bzrlib.tests.VerboseTestResult(
904
unittest._WritelnDecorator(result_stream),
908
test = self.get_passing_test()
909
feature = tests.Feature()
910
result.startTest(test)
911
prefix = len(result_stream.getvalue())
912
result.report_unsupported(test, feature)
913
output = result_stream.getvalue()[prefix:]
914
lines = output.splitlines()
915
self.assertEqual(lines, ['NODEP 0ms',
916
" The feature 'Feature' is not available."])
918
def test_unavailable_exception(self):
919
"""An UnavailableFeature being raised should invoke addNotSupported."""
920
class InstrumentedTestResult(tests.ExtendedTestResult):
921
def stopTestRun(self): pass
922
def startTests(self): pass
923
def report_test_start(self, test): pass
924
def addNotSupported(self, test, feature):
925
self._call = test, feature
926
result = InstrumentedTestResult(None, None, None, None)
927
feature = tests.Feature()
929
raise tests.UnavailableFeature(feature)
930
test = unittest.FunctionTestCase(test_function)
932
# it should invoke 'addNotSupported'.
933
self.assertEqual(2, len(result._call))
934
self.assertEqual(test, result._call[0])
935
self.assertEqual(feature, result._call[1])
936
# and not count as an error
937
self.assertEqual(0, result.error_count)
939
def test_strict_with_unsupported_feature(self):
940
result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
942
test = self.get_passing_test()
943
feature = "Unsupported Feature"
944
result.addNotSupported(test, feature)
945
self.assertFalse(result.wasStrictlySuccessful())
946
self.assertEqual(None, result._extractBenchmarkTime(test))
948
def test_strict_with_known_failure(self):
949
result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
951
test = self.get_passing_test()
952
err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
953
result._addKnownFailure(test, err)
954
self.assertFalse(result.wasStrictlySuccessful())
955
self.assertEqual(None, result._extractBenchmarkTime(test))
957
def test_strict_with_success(self):
958
result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
960
test = self.get_passing_test()
961
result.addSuccess(test)
962
self.assertTrue(result.wasStrictlySuccessful())
963
self.assertEqual(None, result._extractBenchmarkTime(test))
965
def test_startTests(self):
966
"""Starting the first test should trigger startTests."""
967
class InstrumentedTestResult(tests.ExtendedTestResult):
969
def startTests(self): self.calls += 1
970
def report_test_start(self, test): pass
971
result = InstrumentedTestResult(None, None, None, None)
974
test = unittest.FunctionTestCase(test_function)
976
self.assertEquals(1, result.calls)
979
class TestUnicodeFilenameFeature(tests.TestCase):
981
def test_probe_passes(self):
982
"""UnicodeFilenameFeature._probe passes."""
983
# We can't test much more than that because the behaviour depends
985
tests.UnicodeFilenameFeature._probe()
988
class TestRunner(tests.TestCase):
990
def dummy_test(self):
993
def run_test_runner(self, testrunner, test):
994
"""Run suite in testrunner, saving global state and restoring it.
996
This current saves and restores:
997
TestCaseInTempDir.TEST_ROOT
999
There should be no tests in this file that use
1000
bzrlib.tests.TextTestRunner without using this convenience method,
1001
because of our use of global state.
1003
old_root = tests.TestCaseInTempDir.TEST_ROOT
1004
old_leak = tests.TestCase._first_thread_leaker_id
1006
tests.TestCaseInTempDir.TEST_ROOT = None
1007
tests.TestCase._first_thread_leaker_id = None
1008
return testrunner.run(test)
1010
tests.TestCaseInTempDir.TEST_ROOT = old_root
1011
tests.TestCase._first_thread_leaker_id = old_leak
1013
def test_known_failure_failed_run(self):
1014
# run a test that generates a known failure which should be printed in
1015
# the final output when real failures occur.
1016
def known_failure_test():
1017
raise tests.KnownFailure('failed')
1018
test = unittest.TestSuite()
1019
test.addTest(unittest.FunctionTestCase(known_failure_test))
1021
raise AssertionError('foo')
1022
test.addTest(unittest.FunctionTestCase(failing_test))
1024
runner = tests.TextTestRunner(stream=stream)
1025
result = self.run_test_runner(runner, test)
1026
lines = stream.getvalue().splitlines()
1027
self.assertContainsRe(stream.getvalue(),
1030
'^======================================================================\n'
1031
'^FAIL: unittest.FunctionTestCase \\(failing_test\\)\n'
1032
'^----------------------------------------------------------------------\n'
1033
'Traceback \\(most recent call last\\):\n'
1034
' .*' # File .*, line .*, in failing_test' - but maybe not from .pyc
1035
' raise AssertionError\\(\'foo\'\\)\n'
1037
'^----------------------------------------------------------------------\n'
1039
'FAILED \\(failures=1, known_failure_count=1\\)'
1042
def test_known_failure_ok_run(self):
1043
# run a test that generates a known failure which should be printed in the final output.
1044
def known_failure_test():
1045
raise tests.KnownFailure('failed')
1046
test = unittest.FunctionTestCase(known_failure_test)
1048
runner = tests.TextTestRunner(stream=stream)
1049
result = self.run_test_runner(runner, test)
1050
self.assertContainsRe(stream.getvalue(),
1053
'Ran 1 test in .*\n'
1055
'OK \\(known_failures=1\\)\n')
1057
def test_result_decorator(self):
1060
class LoggingDecorator(tests.ForwardingResult):
1061
def startTest(self, test):
1062
tests.ForwardingResult.startTest(self, test)
1063
calls.append('start')
1064
test = unittest.FunctionTestCase(lambda:None)
1066
runner = tests.TextTestRunner(stream=stream,
1067
result_decorators=[LoggingDecorator])
1068
result = self.run_test_runner(runner, test)
1069
self.assertLength(1, calls)
1071
def test_skipped_test(self):
1072
# run a test that is skipped, and check the suite as a whole still
1074
# skipping_test must be hidden in here so it's not run as a real test
1075
class SkippingTest(tests.TestCase):
1076
def skipping_test(self):
1077
raise tests.TestSkipped('test intentionally skipped')
1078
runner = tests.TextTestRunner(stream=self._log_file)
1079
test = SkippingTest("skipping_test")
1080
result = self.run_test_runner(runner, test)
1081
self.assertTrue(result.wasSuccessful())
1083
def test_skipped_from_setup(self):
1085
class SkippedSetupTest(tests.TestCase):
1088
calls.append('setUp')
1089
self.addCleanup(self.cleanup)
1090
raise tests.TestSkipped('skipped setup')
1092
def test_skip(self):
1093
self.fail('test reached')
1096
calls.append('cleanup')
1098
runner = tests.TextTestRunner(stream=self._log_file)
1099
test = SkippedSetupTest('test_skip')
1100
result = self.run_test_runner(runner, test)
1101
self.assertTrue(result.wasSuccessful())
1102
# Check if cleanup was called the right number of times.
1103
self.assertEqual(['setUp', 'cleanup'], calls)
1105
def test_skipped_from_test(self):
1107
class SkippedTest(tests.TestCase):
1110
tests.TestCase.setUp(self)
1111
calls.append('setUp')
1112
self.addCleanup(self.cleanup)
1114
def test_skip(self):
1115
raise tests.TestSkipped('skipped test')
1118
calls.append('cleanup')
1120
runner = tests.TextTestRunner(stream=self._log_file)
1121
test = SkippedTest('test_skip')
1122
result = self.run_test_runner(runner, test)
1123
self.assertTrue(result.wasSuccessful())
1124
# Check if cleanup was called the right number of times.
1125
self.assertEqual(['setUp', 'cleanup'], calls)
1127
def test_not_applicable(self):
1128
# run a test that is skipped because it's not applicable
1129
def not_applicable_test():
1130
raise tests.TestNotApplicable('this test never runs')
1132
runner = tests.TextTestRunner(stream=out, verbosity=2)
1133
test = unittest.FunctionTestCase(not_applicable_test)
1134
result = self.run_test_runner(runner, test)
1135
self._log_file.write(out.getvalue())
1136
self.assertTrue(result.wasSuccessful())
1137
self.assertTrue(result.wasStrictlySuccessful())
1138
self.assertContainsRe(out.getvalue(),
1139
r'(?m)not_applicable_test * N/A')
1140
self.assertContainsRe(out.getvalue(),
1141
r'(?m)^ this test never runs')
1143
def test_unsupported_features_listed(self):
1144
"""When unsupported features are encountered they are detailed."""
1145
class Feature1(tests.Feature):
1146
def _probe(self): return False
1147
class Feature2(tests.Feature):
1148
def _probe(self): return False
1149
# create sample tests
1150
test1 = SampleTestCase('_test_pass')
1151
test1._test_needs_features = [Feature1()]
1152
test2 = SampleTestCase('_test_pass')
1153
test2._test_needs_features = [Feature2()]
1154
test = unittest.TestSuite()
1158
runner = tests.TextTestRunner(stream=stream)
1159
result = self.run_test_runner(runner, test)
1160
lines = stream.getvalue().splitlines()
1163
"Missing feature 'Feature1' skipped 1 tests.",
1164
"Missing feature 'Feature2' skipped 1 tests.",
1168
def test_bench_history(self):
1169
# tests that the running the benchmark produces a history file
1170
# containing a timestamp and the revision id of the bzrlib source which
1172
workingtree = _get_bzr_source_tree()
1173
test = TestRunner('dummy_test')
1175
runner = tests.TextTestRunner(stream=self._log_file,
1176
bench_history=output)
1177
result = self.run_test_runner(runner, test)
1178
output_string = output.getvalue()
1179
self.assertContainsRe(output_string, "--date [0-9.]+")
1180
if workingtree is not None:
1181
revision_id = workingtree.get_parent_ids()[0]
1182
self.assertEndsWith(output_string.rstrip(), revision_id)
1184
def assertLogDeleted(self, test):
1185
log = test._get_log()
1186
self.assertEqual("DELETED log file to reduce memory footprint", log)
1187
self.assertEqual('', test._log_contents)
1188
self.assertIs(None, test._log_file_name)
1190
def test_success_log_deleted(self):
1191
"""Successful tests have their log deleted"""
1193
class LogTester(tests.TestCase):
1195
def test_success(self):
1196
self.log('this will be removed\n')
1199
runner = tests.TextTestRunner(stream=sio)
1200
test = LogTester('test_success')
1201
result = self.run_test_runner(runner, test)
1203
self.assertLogDeleted(test)
1205
def test_skipped_log_deleted(self):
1206
"""Skipped tests have their log deleted"""
1208
class LogTester(tests.TestCase):
1210
def test_skipped(self):
1211
self.log('this will be removed\n')
1212
raise tests.TestSkipped()
1215
runner = tests.TextTestRunner(stream=sio)
1216
test = LogTester('test_skipped')
1217
result = self.run_test_runner(runner, test)
1219
self.assertLogDeleted(test)
1221
def test_not_aplicable_log_deleted(self):
1222
"""Not applicable tests have their log deleted"""
1224
class LogTester(tests.TestCase):
1226
def test_not_applicable(self):
1227
self.log('this will be removed\n')
1228
raise tests.TestNotApplicable()
1231
runner = tests.TextTestRunner(stream=sio)
1232
test = LogTester('test_not_applicable')
1233
result = self.run_test_runner(runner, test)
1235
self.assertLogDeleted(test)
1237
def test_known_failure_log_deleted(self):
1238
"""Know failure tests have their log deleted"""
1240
class LogTester(tests.TestCase):
1242
def test_known_failure(self):
1243
self.log('this will be removed\n')
1244
raise tests.KnownFailure()
1247
runner = tests.TextTestRunner(stream=sio)
1248
test = LogTester('test_known_failure')
1249
result = self.run_test_runner(runner, test)
1251
self.assertLogDeleted(test)
1253
def test_fail_log_kept(self):
1254
"""Failed tests have their log kept"""
1256
class LogTester(tests.TestCase):
1258
def test_fail(self):
1259
self.log('this will be kept\n')
1260
self.fail('this test fails')
1263
runner = tests.TextTestRunner(stream=sio)
1264
test = LogTester('test_fail')
1265
result = self.run_test_runner(runner, test)
1267
text = sio.getvalue()
1268
self.assertContainsRe(text, 'this will be kept')
1269
self.assertContainsRe(text, 'this test fails')
1271
log = test._get_log()
1272
self.assertContainsRe(log, 'this will be kept')
1273
self.assertEqual(log, test._log_contents)
1275
def test_error_log_kept(self):
1276
"""Tests with errors have their log kept"""
1278
class LogTester(tests.TestCase):
1280
def test_error(self):
1281
self.log('this will be kept\n')
1282
raise ValueError('random exception raised')
1285
runner = tests.TextTestRunner(stream=sio)
1286
test = LogTester('test_error')
1287
result = self.run_test_runner(runner, test)
1289
text = sio.getvalue()
1290
self.assertContainsRe(text, 'this will be kept')
1291
self.assertContainsRe(text, 'random exception raised')
1293
log = test._get_log()
1294
self.assertContainsRe(log, 'this will be kept')
1295
self.assertEqual(log, test._log_contents)
1297
def test_startTestRun(self):
1298
"""run should call result.startTestRun()"""
1300
class LoggingDecorator(tests.ForwardingResult):
1301
def startTestRun(self):
1302
tests.ForwardingResult.startTestRun(self)
1303
calls.append('startTestRun')
1304
test = unittest.FunctionTestCase(lambda:None)
1306
runner = tests.TextTestRunner(stream=stream,
1307
result_decorators=[LoggingDecorator])
1308
result = self.run_test_runner(runner, test)
1309
self.assertLength(1, calls)
1311
def test_stopTestRun(self):
1312
"""run should call result.stopTestRun()"""
1314
class LoggingDecorator(tests.ForwardingResult):
1315
def stopTestRun(self):
1316
tests.ForwardingResult.stopTestRun(self)
1317
calls.append('stopTestRun')
1318
test = unittest.FunctionTestCase(lambda:None)
1320
runner = tests.TextTestRunner(stream=stream,
1321
result_decorators=[LoggingDecorator])
1322
result = self.run_test_runner(runner, test)
1323
self.assertLength(1, calls)
1326
class SampleTestCase(tests.TestCase):
1328
def _test_pass(self):
1331
class _TestException(Exception):
1335
class TestTestCase(tests.TestCase):
1336
"""Tests that test the core bzrlib TestCase."""
1338
def test_assertLength_matches_empty(self):
1340
self.assertLength(0, a_list)
1342
def test_assertLength_matches_nonempty(self):
1344
self.assertLength(3, a_list)
1346
def test_assertLength_fails_different(self):
1348
self.assertRaises(AssertionError, self.assertLength, 1, a_list)
1350
def test_assertLength_shows_sequence_in_failure(self):
1352
exception = self.assertRaises(AssertionError, self.assertLength, 2,
1354
self.assertEqual('Incorrect length: wanted 2, got 3 for [1, 2, 3]',
1357
def test_base_setUp_not_called_causes_failure(self):
1358
class TestCaseWithBrokenSetUp(tests.TestCase):
1360
pass # does not call TestCase.setUp
1363
test = TestCaseWithBrokenSetUp('test_foo')
1364
result = unittest.TestResult()
1366
self.assertFalse(result.wasSuccessful())
1367
self.assertEqual(1, result.testsRun)
1369
def test_base_tearDown_not_called_causes_failure(self):
1370
class TestCaseWithBrokenTearDown(tests.TestCase):
1372
pass # does not call TestCase.tearDown
1375
test = TestCaseWithBrokenTearDown('test_foo')
1376
result = unittest.TestResult()
1378
self.assertFalse(result.wasSuccessful())
1379
self.assertEqual(1, result.testsRun)
1381
def test_debug_flags_sanitised(self):
1382
"""The bzrlib debug flags should be sanitised by setUp."""
1383
if 'allow_debug' in tests.selftest_debug_flags:
1384
raise tests.TestNotApplicable(
1385
'-Eallow_debug option prevents debug flag sanitisation')
1386
# we could set something and run a test that will check
1387
# it gets santised, but this is probably sufficient for now:
1388
# if someone runs the test with -Dsomething it will error.
1390
if self._lock_check_thorough:
1391
flags.add('strict_locks')
1392
self.assertEqual(flags, bzrlib.debug.debug_flags)
1394
def change_selftest_debug_flags(self, new_flags):
1395
orig_selftest_flags = tests.selftest_debug_flags
1396
self.addCleanup(self._restore_selftest_debug_flags, orig_selftest_flags)
1397
tests.selftest_debug_flags = set(new_flags)
1399
def _restore_selftest_debug_flags(self, flags):
1400
tests.selftest_debug_flags = flags
1402
def test_allow_debug_flag(self):
1403
"""The -Eallow_debug flag prevents bzrlib.debug.debug_flags from being
1404
sanitised (i.e. cleared) before running a test.
1406
self.change_selftest_debug_flags(set(['allow_debug']))
1407
bzrlib.debug.debug_flags = set(['a-flag'])
1408
class TestThatRecordsFlags(tests.TestCase):
1409
def test_foo(nested_self):
1410
self.flags = set(bzrlib.debug.debug_flags)
1411
test = TestThatRecordsFlags('test_foo')
1412
test.run(self.make_test_result())
1413
flags = set(['a-flag'])
1414
if 'disable_lock_checks' not in tests.selftest_debug_flags:
1415
flags.add('strict_locks')
1416
self.assertEqual(flags, self.flags)
1418
def test_disable_lock_checks(self):
1419
"""The -Edisable_lock_checks flag disables thorough checks."""
1420
class TestThatRecordsFlags(tests.TestCase):
1421
def test_foo(nested_self):
1422
self.flags = set(bzrlib.debug.debug_flags)
1423
self.test_lock_check_thorough = nested_self._lock_check_thorough
1424
self.change_selftest_debug_flags(set())
1425
test = TestThatRecordsFlags('test_foo')
1426
test.run(self.make_test_result())
1427
# By default we do strict lock checking and thorough lock/unlock
1429
self.assertTrue(self.test_lock_check_thorough)
1430
self.assertEqual(set(['strict_locks']), self.flags)
1431
# Now set the disable_lock_checks flag, and show that this changed.
1432
self.change_selftest_debug_flags(set(['disable_lock_checks']))
1433
test = TestThatRecordsFlags('test_foo')
1434
test.run(self.make_test_result())
1435
self.assertFalse(self.test_lock_check_thorough)
1436
self.assertEqual(set(), self.flags)
1438
def test_this_fails_strict_lock_check(self):
1439
class TestThatRecordsFlags(tests.TestCase):
1440
def test_foo(nested_self):
1441
self.flags1 = set(bzrlib.debug.debug_flags)
1442
self.thisFailsStrictLockCheck()
1443
self.flags2 = set(bzrlib.debug.debug_flags)
1444
# Make sure lock checking is active
1445
self.change_selftest_debug_flags(set())
1446
test = TestThatRecordsFlags('test_foo')
1447
test.run(self.make_test_result())
1448
self.assertEqual(set(['strict_locks']), self.flags1)
1449
self.assertEqual(set(), self.flags2)
1451
def test_debug_flags_restored(self):
1452
"""The bzrlib debug flags should be restored to their original state
1453
after the test was run, even if allow_debug is set.
1455
self.change_selftest_debug_flags(set(['allow_debug']))
1456
# Now run a test that modifies debug.debug_flags.
1457
bzrlib.debug.debug_flags = set(['original-state'])
1458
class TestThatModifiesFlags(tests.TestCase):
1460
bzrlib.debug.debug_flags = set(['modified'])
1461
test = TestThatModifiesFlags('test_foo')
1462
test.run(self.make_test_result())
1463
self.assertEqual(set(['original-state']), bzrlib.debug.debug_flags)
1465
def make_test_result(self):
1466
return tests.TextTestResult(self._log_file, descriptions=0, verbosity=1)
1468
def inner_test(self):
1469
# the inner child test
1472
def outer_child(self):
1473
# the outer child test
1475
self.inner_test = TestTestCase("inner_child")
1476
result = self.make_test_result()
1477
self.inner_test.run(result)
1478
note("outer finish")
1480
def test_trace_nesting(self):
1481
# this tests that each test case nests its trace facility correctly.
1482
# we do this by running a test case manually. That test case (A)
1483
# should setup a new log, log content to it, setup a child case (B),
1484
# which should log independently, then case (A) should log a trailer
1486
# we do two nested children so that we can verify the state of the
1487
# logs after the outer child finishes is correct, which a bad clean
1488
# up routine in tearDown might trigger a fault in our test with only
1489
# one child, we should instead see the bad result inside our test with
1491
# the outer child test
1492
original_trace = bzrlib.trace._trace_file
1493
outer_test = TestTestCase("outer_child")
1494
result = self.make_test_result()
1495
outer_test.run(result)
1496
self.addCleanup(osutils.delete_any, outer_test._log_file_name)
1497
self.assertEqual(original_trace, bzrlib.trace._trace_file)
1499
def method_that_times_a_bit_twice(self):
1500
# call self.time twice to ensure it aggregates
1501
self.time(time.sleep, 0.007)
1502
self.time(time.sleep, 0.007)
1504
def test_time_creates_benchmark_in_result(self):
1505
"""Test that the TestCase.time() method accumulates a benchmark time."""
1506
sample_test = TestTestCase("method_that_times_a_bit_twice")
1507
output_stream = StringIO()
1508
result = bzrlib.tests.VerboseTestResult(
1509
unittest._WritelnDecorator(output_stream),
1512
sample_test.run(result)
1513
self.assertContainsRe(
1514
output_stream.getvalue(),
1517
def test_hooks_sanitised(self):
1518
"""The bzrlib hooks should be sanitised by setUp."""
1519
# Note this test won't fail with hooks that the core library doesn't
1520
# use - but it trigger with a plugin that adds hooks, so its still a
1521
# useful warning in that case.
1522
self.assertEqual(bzrlib.branch.BranchHooks(),
1523
bzrlib.branch.Branch.hooks)
1524
self.assertEqual(bzrlib.smart.server.SmartServerHooks(),
1525
bzrlib.smart.server.SmartTCPServer.hooks)
1526
self.assertEqual(bzrlib.commands.CommandHooks(),
1527
bzrlib.commands.Command.hooks)
1529
def test__gather_lsprof_in_benchmarks(self):
1530
"""When _gather_lsprof_in_benchmarks is on, accumulate profile data.
1532
Each self.time() call is individually and separately profiled.
1534
self.requireFeature(test_lsprof.LSProfFeature)
1535
# overrides the class member with an instance member so no cleanup
1537
self._gather_lsprof_in_benchmarks = True
1538
self.time(time.sleep, 0.000)
1539
self.time(time.sleep, 0.003)
1540
self.assertEqual(2, len(self._benchcalls))
1541
self.assertEqual((time.sleep, (0.000,), {}), self._benchcalls[0][0])
1542
self.assertEqual((time.sleep, (0.003,), {}), self._benchcalls[1][0])
1543
self.assertIsInstance(self._benchcalls[0][1], bzrlib.lsprof.Stats)
1544
self.assertIsInstance(self._benchcalls[1][1], bzrlib.lsprof.Stats)
1545
del self._benchcalls[:]
1547
def test_knownFailure(self):
1548
"""Self.knownFailure() should raise a KnownFailure exception."""
1549
self.assertRaises(tests.KnownFailure, self.knownFailure, "A Failure")
1551
def test_requireFeature_available(self):
1552
"""self.requireFeature(available) is a no-op."""
1553
class Available(tests.Feature):
1554
def _probe(self):return True
1555
feature = Available()
1556
self.requireFeature(feature)
1558
def test_requireFeature_unavailable(self):
1559
"""self.requireFeature(unavailable) raises UnavailableFeature."""
1560
class Unavailable(tests.Feature):
1561
def _probe(self):return False
1562
feature = Unavailable()
1563
self.assertRaises(tests.UnavailableFeature,
1564
self.requireFeature, feature)
1566
def test_run_no_parameters(self):
1567
test = SampleTestCase('_test_pass')
1570
def test_run_enabled_unittest_result(self):
1571
"""Test we revert to regular behaviour when the test is enabled."""
1572
test = SampleTestCase('_test_pass')
1573
class EnabledFeature(object):
1574
def available(self):
1576
test._test_needs_features = [EnabledFeature()]
1577
result = unittest.TestResult()
1579
self.assertEqual(1, result.testsRun)
1580
self.assertEqual([], result.errors)
1581
self.assertEqual([], result.failures)
1583
def test_run_disabled_unittest_result(self):
1584
"""Test our compatability for disabled tests with unittest results."""
1585
test = SampleTestCase('_test_pass')
1586
class DisabledFeature(object):
1587
def available(self):
1589
test._test_needs_features = [DisabledFeature()]
1590
result = unittest.TestResult()
1592
self.assertEqual(1, result.testsRun)
1593
self.assertEqual([], result.errors)
1594
self.assertEqual([], result.failures)
1596
def test_run_disabled_supporting_result(self):
1597
"""Test disabled tests behaviour with support aware results."""
1598
test = SampleTestCase('_test_pass')
1599
class DisabledFeature(object):
1600
def available(self):
1602
the_feature = DisabledFeature()
1603
test._test_needs_features = [the_feature]
1604
class InstrumentedTestResult(unittest.TestResult):
1606
unittest.TestResult.__init__(self)
1608
def startTest(self, test):
1609
self.calls.append(('startTest', test))
1610
def stopTest(self, test):
1611
self.calls.append(('stopTest', test))
1612
def addNotSupported(self, test, feature):
1613
self.calls.append(('addNotSupported', test, feature))
1614
result = InstrumentedTestResult()
1617
('startTest', test),
1618
('addNotSupported', test, the_feature),
1623
def test_assert_list_raises_on_generator(self):
1624
def generator_which_will_raise():
1625
# This will not raise until after the first yield
1627
raise _TestException()
1629
e = self.assertListRaises(_TestException, generator_which_will_raise)
1630
self.assertIsInstance(e, _TestException)
1632
e = self.assertListRaises(Exception, generator_which_will_raise)
1633
self.assertIsInstance(e, _TestException)
1635
def test_assert_list_raises_on_plain(self):
1636
def plain_exception():
1637
raise _TestException()
1640
e = self.assertListRaises(_TestException, plain_exception)
1641
self.assertIsInstance(e, _TestException)
1643
e = self.assertListRaises(Exception, plain_exception)
1644
self.assertIsInstance(e, _TestException)
1646
def test_assert_list_raises_assert_wrong_exception(self):
1647
class _NotTestException(Exception):
1650
def wrong_exception():
1651
raise _NotTestException()
1653
def wrong_exception_generator():
1656
raise _NotTestException()
1658
# Wrong exceptions are not intercepted
1659
self.assertRaises(_NotTestException,
1660
self.assertListRaises, _TestException, wrong_exception)
1661
self.assertRaises(_NotTestException,
1662
self.assertListRaises, _TestException, wrong_exception_generator)
1664
def test_assert_list_raises_no_exception(self):
1668
def success_generator():
1672
self.assertRaises(AssertionError,
1673
self.assertListRaises, _TestException, success)
1675
self.assertRaises(AssertionError,
1676
self.assertListRaises, _TestException, success_generator)
1679
# NB: Don't delete this; it's not actually from 0.11!
1680
@deprecated_function(deprecated_in((0, 11, 0)))
1681
def sample_deprecated_function():
1682
"""A deprecated function to test applyDeprecated with."""
1686
def sample_undeprecated_function(a_param):
1687
"""A undeprecated function to test applyDeprecated with."""
1690
class ApplyDeprecatedHelper(object):
1691
"""A helper class for ApplyDeprecated tests."""
1693
@deprecated_method(deprecated_in((0, 11, 0)))
1694
def sample_deprecated_method(self, param_one):
1695
"""A deprecated method for testing with."""
1698
def sample_normal_method(self):
1699
"""A undeprecated method."""
1701
@deprecated_method(deprecated_in((0, 10, 0)))
1702
def sample_nested_deprecation(self):
1703
return sample_deprecated_function()
1706
class TestExtraAssertions(tests.TestCase):
1707
"""Tests for new test assertions in bzrlib test suite"""
1709
def test_assert_isinstance(self):
1710
self.assertIsInstance(2, int)
1711
self.assertIsInstance(u'', basestring)
1712
e = self.assertRaises(AssertionError, self.assertIsInstance, None, int)
1713
self.assertEquals(str(e),
1714
"None is an instance of <type 'NoneType'> rather than <type 'int'>")
1715
self.assertRaises(AssertionError, self.assertIsInstance, 23.3, int)
1716
e = self.assertRaises(AssertionError,
1717
self.assertIsInstance, None, int, "it's just not")
1718
self.assertEquals(str(e),
1719
"None is an instance of <type 'NoneType'> rather than <type 'int'>"
1722
def test_assertEndsWith(self):
1723
self.assertEndsWith('foo', 'oo')
1724
self.assertRaises(AssertionError, self.assertEndsWith, 'o', 'oo')
1726
def test_assertEqualDiff(self):
1727
e = self.assertRaises(AssertionError,
1728
self.assertEqualDiff, '', '\n')
1729
self.assertEquals(str(e),
1730
# Don't blink ! The '+' applies to the second string
1731
'first string is missing a final newline.\n+ \n')
1732
e = self.assertRaises(AssertionError,
1733
self.assertEqualDiff, '\n', '')
1734
self.assertEquals(str(e),
1735
# Don't blink ! The '-' applies to the second string
1736
'second string is missing a final newline.\n- \n')
1739
class TestDeprecations(tests.TestCase):
1741
def test_applyDeprecated_not_deprecated(self):
1742
sample_object = ApplyDeprecatedHelper()
1743
# calling an undeprecated callable raises an assertion
1744
self.assertRaises(AssertionError, self.applyDeprecated,
1745
deprecated_in((0, 11, 0)),
1746
sample_object.sample_normal_method)
1747
self.assertRaises(AssertionError, self.applyDeprecated,
1748
deprecated_in((0, 11, 0)),
1749
sample_undeprecated_function, "a param value")
1750
# calling a deprecated callable (function or method) with the wrong
1751
# expected deprecation fails.
1752
self.assertRaises(AssertionError, self.applyDeprecated,
1753
deprecated_in((0, 10, 0)),
1754
sample_object.sample_deprecated_method, "a param value")
1755
self.assertRaises(AssertionError, self.applyDeprecated,
1756
deprecated_in((0, 10, 0)),
1757
sample_deprecated_function)
1758
# calling a deprecated callable (function or method) with the right
1759
# expected deprecation returns the functions result.
1760
self.assertEqual("a param value",
1761
self.applyDeprecated(deprecated_in((0, 11, 0)),
1762
sample_object.sample_deprecated_method, "a param value"))
1763
self.assertEqual(2, self.applyDeprecated(deprecated_in((0, 11, 0)),
1764
sample_deprecated_function))
1765
# calling a nested deprecation with the wrong deprecation version
1766
# fails even if a deeper nested function was deprecated with the
1768
self.assertRaises(AssertionError, self.applyDeprecated,
1769
deprecated_in((0, 11, 0)), sample_object.sample_nested_deprecation)
1770
# calling a nested deprecation with the right deprecation value
1771
# returns the calls result.
1772
self.assertEqual(2, self.applyDeprecated(deprecated_in((0, 10, 0)),
1773
sample_object.sample_nested_deprecation))
1775
def test_callDeprecated(self):
1776
def testfunc(be_deprecated, result=None):
1777
if be_deprecated is True:
1778
symbol_versioning.warn('i am deprecated', DeprecationWarning,
1781
result = self.callDeprecated(['i am deprecated'], testfunc, True)
1782
self.assertIs(None, result)
1783
result = self.callDeprecated([], testfunc, False, 'result')
1784
self.assertEqual('result', result)
1785
self.callDeprecated(['i am deprecated'], testfunc, be_deprecated=True)
1786
self.callDeprecated([], testfunc, be_deprecated=False)
1789
class TestWarningTests(tests.TestCase):
1790
"""Tests for calling methods that raise warnings."""
1792
def test_callCatchWarnings(self):
1794
warnings.warn("this is your last warning")
1796
wlist, result = self.callCatchWarnings(meth, 1, 2)
1797
self.assertEquals(3, result)
1798
# would like just to compare them, but UserWarning doesn't implement
1801
self.assertIsInstance(w0, UserWarning)
1802
self.assertEquals("this is your last warning", str(w0))
1805
class TestConvenienceMakers(tests.TestCaseWithTransport):
1806
"""Test for the make_* convenience functions."""
1808
def test_make_branch_and_tree_with_format(self):
1809
# we should be able to supply a format to make_branch_and_tree
1810
self.make_branch_and_tree('a', format=bzrlib.bzrdir.BzrDirMetaFormat1())
1811
self.make_branch_and_tree('b', format=bzrlib.bzrdir.BzrDirFormat6())
1812
self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('a')._format,
1813
bzrlib.bzrdir.BzrDirMetaFormat1)
1814
self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('b')._format,
1815
bzrlib.bzrdir.BzrDirFormat6)
1817
def test_make_branch_and_memory_tree(self):
1818
# we should be able to get a new branch and a mutable tree from
1819
# TestCaseWithTransport
1820
tree = self.make_branch_and_memory_tree('a')
1821
self.assertIsInstance(tree, bzrlib.memorytree.MemoryTree)
1823
def test_make_tree_for_local_vfs_backed_transport(self):
1824
# make_branch_and_tree has to use local branch and repositories
1825
# when the vfs transport and local disk are colocated, even if
1826
# a different transport is in use for url generation.
1827
from bzrlib.transport.fakevfat import FakeVFATServer
1828
self.transport_server = FakeVFATServer
1829
self.assertFalse(self.get_url('t1').startswith('file://'))
1830
tree = self.make_branch_and_tree('t1')
1831
base = tree.bzrdir.root_transport.base
1832
self.assertStartsWith(base, 'file://')
1833
self.assertEquals(tree.bzrdir.root_transport,
1834
tree.branch.bzrdir.root_transport)
1835
self.assertEquals(tree.bzrdir.root_transport,
1836
tree.branch.repository.bzrdir.root_transport)
1839
class SelfTestHelper:
1841
def run_selftest(self, **kwargs):
1842
"""Run selftest returning its output."""
1844
old_transport = bzrlib.tests.default_transport
1845
old_root = tests.TestCaseWithMemoryTransport.TEST_ROOT
1846
tests.TestCaseWithMemoryTransport.TEST_ROOT = None
1848
self.assertEqual(True, tests.selftest(stream=output, **kwargs))
1850
bzrlib.tests.default_transport = old_transport
1851
tests.TestCaseWithMemoryTransport.TEST_ROOT = old_root
1856
class TestSelftest(tests.TestCase, SelfTestHelper):
1857
"""Tests of bzrlib.tests.selftest."""
1859
def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
1862
factory_called.append(True)
1863
return TestUtil.TestSuite()
1866
self.apply_redirected(out, err, None, bzrlib.tests.selftest,
1867
test_suite_factory=factory)
1868
self.assertEqual([True], factory_called)
1871
"""A test suite factory."""
1872
class Test(tests.TestCase):
1879
return TestUtil.TestSuite([Test("a"), Test("b"), Test("c")])
1881
def test_list_only(self):
1882
output = self.run_selftest(test_suite_factory=self.factory,
1884
self.assertEqual(3, len(output.readlines()))
1886
def test_list_only_filtered(self):
1887
output = self.run_selftest(test_suite_factory=self.factory,
1888
list_only=True, pattern="Test.b")
1889
self.assertEndsWith(output.getvalue(), "Test.b\n")
1890
self.assertLength(1, output.readlines())
1892
def test_list_only_excludes(self):
1893
output = self.run_selftest(test_suite_factory=self.factory,
1894
list_only=True, exclude_pattern="Test.b")
1895
self.assertNotContainsRe("Test.b", output.getvalue())
1896
self.assertLength(2, output.readlines())
1898
def test_lsprof_tests(self):
1899
self.requireFeature(test_lsprof.LSProfFeature)
1902
def __call__(test, result):
1904
def run(test, result):
1905
self.assertIsInstance(result, tests.ForwardingResult)
1906
calls.append("called")
1907
def countTestCases(self):
1909
self.run_selftest(test_suite_factory=Test, lsprof_tests=True)
1910
self.assertLength(1, calls)
1912
def test_random(self):
1913
# test randomising by listing a number of tests.
1914
output_123 = self.run_selftest(test_suite_factory=self.factory,
1915
list_only=True, random_seed="123")
1916
output_234 = self.run_selftest(test_suite_factory=self.factory,
1917
list_only=True, random_seed="234")
1918
self.assertNotEqual(output_123, output_234)
1919
# "Randominzing test order..\n\n
1920
self.assertLength(5, output_123.readlines())
1921
self.assertLength(5, output_234.readlines())
1923
def test_random_reuse_is_same_order(self):
1924
# test randomising by listing a number of tests.
1925
expected = self.run_selftest(test_suite_factory=self.factory,
1926
list_only=True, random_seed="123")
1927
repeated = self.run_selftest(test_suite_factory=self.factory,
1928
list_only=True, random_seed="123")
1929
self.assertEqual(expected.getvalue(), repeated.getvalue())
1931
def test_runner_class(self):
1932
self.requireFeature(SubUnitFeature)
1933
from subunit import ProtocolTestCase
1934
stream = self.run_selftest(runner_class=tests.SubUnitBzrRunner,
1935
test_suite_factory=self.factory)
1936
test = ProtocolTestCase(stream)
1937
result = unittest.TestResult()
1939
self.assertEqual(3, result.testsRun)
1941
def test_starting_with_single_argument(self):
1942
output = self.run_selftest(test_suite_factory=self.factory,
1943
starting_with=['bzrlib.tests.test_selftest.Test.a'],
1945
self.assertEqual('bzrlib.tests.test_selftest.Test.a\n',
1948
def test_starting_with_multiple_argument(self):
1949
output = self.run_selftest(test_suite_factory=self.factory,
1950
starting_with=['bzrlib.tests.test_selftest.Test.a',
1951
'bzrlib.tests.test_selftest.Test.b'],
1953
self.assertEqual('bzrlib.tests.test_selftest.Test.a\n'
1954
'bzrlib.tests.test_selftest.Test.b\n',
1957
def check_transport_set(self, transport_server):
1958
captured_transport = []
1959
def seen_transport(a_transport):
1960
captured_transport.append(a_transport)
1961
class Capture(tests.TestCase):
1963
seen_transport(bzrlib.tests.default_transport)
1965
return TestUtil.TestSuite([Capture("a")])
1966
self.run_selftest(transport=transport_server, test_suite_factory=factory)
1967
self.assertEqual(transport_server, captured_transport[0])
1969
def test_transport_sftp(self):
1971
import bzrlib.transport.sftp
1972
except errors.ParamikoNotPresent:
1973
raise tests.TestSkipped("Paramiko not present")
1974
self.check_transport_set(bzrlib.transport.sftp.SFTPAbsoluteServer)
1976
def test_transport_memory(self):
1977
self.check_transport_set(bzrlib.transport.memory.MemoryServer)
1980
class TestSelftestWithIdList(tests.TestCaseInTempDir, SelfTestHelper):
1981
# Does IO: reads test.list
1983
def test_load_list(self):
1984
# Provide a list with one test - this test.
1985
test_id_line = '%s\n' % self.id()
1986
self.build_tree_contents([('test.list', test_id_line)])
1987
# And generate a list of the tests in the suite.
1988
stream = self.run_selftest(load_list='test.list', list_only=True)
1989
self.assertEqual(test_id_line, stream.getvalue())
1991
def test_load_unknown(self):
1992
# Provide a list with one test - this test.
1993
# And generate a list of the tests in the suite.
1994
err = self.assertRaises(errors.NoSuchFile, self.run_selftest,
1995
load_list='missing file name', list_only=True)
1998
class TestRunBzr(tests.TestCase):
2003
def _run_bzr_core(self, argv, retcode=0, encoding=None, stdin=None,
2005
"""Override _run_bzr_core to test how it is invoked by run_bzr.
2007
Attempts to run bzr from inside this class don't actually run it.
2009
We test how run_bzr actually invokes bzr in another location.
2010
Here we only need to test that it is run_bzr passes the right
2011
parameters to run_bzr.
2013
self.argv = list(argv)
2014
self.retcode = retcode
2015
self.encoding = encoding
2017
self.working_dir = working_dir
2018
return self.out, self.err
2020
def test_run_bzr_error(self):
2021
self.out = "It sure does!\n"
2022
out, err = self.run_bzr_error(['^$'], ['rocks'], retcode=34)
2023
self.assertEqual(['rocks'], self.argv)
2024
self.assertEqual(34, self.retcode)
2025
self.assertEqual(out, 'It sure does!\n')
2027
def test_run_bzr_error_regexes(self):
2029
self.err = "bzr: ERROR: foobarbaz is not versioned"
2030
out, err = self.run_bzr_error(
2031
["bzr: ERROR: foobarbaz is not versioned"],
2032
['file-id', 'foobarbaz'])
2034
def test_encoding(self):
2035
"""Test that run_bzr passes encoding to _run_bzr_core"""
2036
self.run_bzr('foo bar')
2037
self.assertEqual(None, self.encoding)
2038
self.assertEqual(['foo', 'bar'], self.argv)
2040
self.run_bzr('foo bar', encoding='baz')
2041
self.assertEqual('baz', self.encoding)
2042
self.assertEqual(['foo', 'bar'], self.argv)
2044
def test_retcode(self):
2045
"""Test that run_bzr passes retcode to _run_bzr_core"""
2046
# Default is retcode == 0
2047
self.run_bzr('foo bar')
2048
self.assertEqual(0, self.retcode)
2049
self.assertEqual(['foo', 'bar'], self.argv)
2051
self.run_bzr('foo bar', retcode=1)
2052
self.assertEqual(1, self.retcode)
2053
self.assertEqual(['foo', 'bar'], self.argv)
2055
self.run_bzr('foo bar', retcode=None)
2056
self.assertEqual(None, self.retcode)
2057
self.assertEqual(['foo', 'bar'], self.argv)
2059
self.run_bzr(['foo', 'bar'], retcode=3)
2060
self.assertEqual(3, self.retcode)
2061
self.assertEqual(['foo', 'bar'], self.argv)
2063
def test_stdin(self):
2064
# test that the stdin keyword to run_bzr is passed through to
2065
# _run_bzr_core as-is. We do this by overriding
2066
# _run_bzr_core in this class, and then calling run_bzr,
2067
# which is a convenience function for _run_bzr_core, so
2069
self.run_bzr('foo bar', stdin='gam')
2070
self.assertEqual('gam', self.stdin)
2071
self.assertEqual(['foo', 'bar'], self.argv)
2073
self.run_bzr('foo bar', stdin='zippy')
2074
self.assertEqual('zippy', self.stdin)
2075
self.assertEqual(['foo', 'bar'], self.argv)
2077
def test_working_dir(self):
2078
"""Test that run_bzr passes working_dir to _run_bzr_core"""
2079
self.run_bzr('foo bar')
2080
self.assertEqual(None, self.working_dir)
2081
self.assertEqual(['foo', 'bar'], self.argv)
2083
self.run_bzr('foo bar', working_dir='baz')
2084
self.assertEqual('baz', self.working_dir)
2085
self.assertEqual(['foo', 'bar'], self.argv)
2087
def test_reject_extra_keyword_arguments(self):
2088
self.assertRaises(TypeError, self.run_bzr, "foo bar",
2089
error_regex=['error message'])
2092
class TestRunBzrCaptured(tests.TestCaseWithTransport):
2093
# Does IO when testing the working_dir parameter.
2095
def apply_redirected(self, stdin=None, stdout=None, stderr=None,
2096
a_callable=None, *args, **kwargs):
2098
self.factory_stdin = getattr(bzrlib.ui.ui_factory, "stdin", None)
2099
self.factory = bzrlib.ui.ui_factory
2100
self.working_dir = osutils.getcwd()
2101
stdout.write('foo\n')
2102
stderr.write('bar\n')
2105
def test_stdin(self):
2106
# test that the stdin keyword to _run_bzr_core is passed through to
2107
# apply_redirected as a StringIO. We do this by overriding
2108
# apply_redirected in this class, and then calling _run_bzr_core,
2109
# which calls apply_redirected.
2110
self.run_bzr(['foo', 'bar'], stdin='gam')
2111
self.assertEqual('gam', self.stdin.read())
2112
self.assertTrue(self.stdin is self.factory_stdin)
2113
self.run_bzr(['foo', 'bar'], stdin='zippy')
2114
self.assertEqual('zippy', self.stdin.read())
2115
self.assertTrue(self.stdin is self.factory_stdin)
2117
def test_ui_factory(self):
2118
# each invocation of self.run_bzr should get its
2119
# own UI factory, which is an instance of TestUIFactory,
2120
# with stdin, stdout and stderr attached to the stdin,
2121
# stdout and stderr of the invoked run_bzr
2122
current_factory = bzrlib.ui.ui_factory
2123
self.run_bzr(['foo'])
2124
self.failIf(current_factory is self.factory)
2125
self.assertNotEqual(sys.stdout, self.factory.stdout)
2126
self.assertNotEqual(sys.stderr, self.factory.stderr)
2127
self.assertEqual('foo\n', self.factory.stdout.getvalue())
2128
self.assertEqual('bar\n', self.factory.stderr.getvalue())
2129
self.assertIsInstance(self.factory, tests.TestUIFactory)
2131
def test_working_dir(self):
2132
self.build_tree(['one/', 'two/'])
2133
cwd = osutils.getcwd()
2135
# Default is to work in the current directory
2136
self.run_bzr(['foo', 'bar'])
2137
self.assertEqual(cwd, self.working_dir)
2139
self.run_bzr(['foo', 'bar'], working_dir=None)
2140
self.assertEqual(cwd, self.working_dir)
2142
# The function should be run in the alternative directory
2143
# but afterwards the current working dir shouldn't be changed
2144
self.run_bzr(['foo', 'bar'], working_dir='one')
2145
self.assertNotEqual(cwd, self.working_dir)
2146
self.assertEndsWith(self.working_dir, 'one')
2147
self.assertEqual(cwd, osutils.getcwd())
2149
self.run_bzr(['foo', 'bar'], working_dir='two')
2150
self.assertNotEqual(cwd, self.working_dir)
2151
self.assertEndsWith(self.working_dir, 'two')
2152
self.assertEqual(cwd, osutils.getcwd())
2155
class StubProcess(object):
2156
"""A stub process for testing run_bzr_subprocess."""
2158
def __init__(self, out="", err="", retcode=0):
2161
self.returncode = retcode
2163
def communicate(self):
2164
return self.out, self.err
2167
class TestWithFakedStartBzrSubprocess(tests.TestCaseWithTransport):
2168
"""Base class for tests testing how we might run bzr."""
2171
tests.TestCaseWithTransport.setUp(self)
2172
self.subprocess_calls = []
2174
def start_bzr_subprocess(self, process_args, env_changes=None,
2175
skip_if_plan_to_signal=False,
2177
allow_plugins=False):
2178
"""capture what run_bzr_subprocess tries to do."""
2179
self.subprocess_calls.append({'process_args':process_args,
2180
'env_changes':env_changes,
2181
'skip_if_plan_to_signal':skip_if_plan_to_signal,
2182
'working_dir':working_dir, 'allow_plugins':allow_plugins})
2183
return self.next_subprocess
2186
class TestRunBzrSubprocess(TestWithFakedStartBzrSubprocess):
2188
def assertRunBzrSubprocess(self, expected_args, process, *args, **kwargs):
2189
"""Run run_bzr_subprocess with args and kwargs using a stubbed process.
2191
Inside TestRunBzrSubprocessCommands we use a stub start_bzr_subprocess
2192
that will return static results. This assertion method populates those
2193
results and also checks the arguments run_bzr_subprocess generates.
2195
self.next_subprocess = process
2197
result = self.run_bzr_subprocess(*args, **kwargs)
2199
self.next_subprocess = None
2200
for key, expected in expected_args.iteritems():
2201
self.assertEqual(expected, self.subprocess_calls[-1][key])
2204
self.next_subprocess = None
2205
for key, expected in expected_args.iteritems():
2206
self.assertEqual(expected, self.subprocess_calls[-1][key])
2209
def test_run_bzr_subprocess(self):
2210
"""The run_bzr_helper_external command behaves nicely."""
2211
self.assertRunBzrSubprocess({'process_args':['--version']},
2212
StubProcess(), '--version')
2213
self.assertRunBzrSubprocess({'process_args':['--version']},
2214
StubProcess(), ['--version'])
2215
# retcode=None disables retcode checking
2216
result = self.assertRunBzrSubprocess({},
2217
StubProcess(retcode=3), '--version', retcode=None)
2218
result = self.assertRunBzrSubprocess({},
2219
StubProcess(out="is free software"), '--version')
2220
self.assertContainsRe(result[0], 'is free software')
2221
# Running a subcommand that is missing errors
2222
self.assertRaises(AssertionError, self.assertRunBzrSubprocess,
2223
{'process_args':['--versionn']}, StubProcess(retcode=3),
2225
# Unless it is told to expect the error from the subprocess
2226
result = self.assertRunBzrSubprocess({},
2227
StubProcess(retcode=3), '--versionn', retcode=3)
2228
# Or to ignore retcode checking
2229
result = self.assertRunBzrSubprocess({},
2230
StubProcess(err="unknown command", retcode=3), '--versionn',
2232
self.assertContainsRe(result[1], 'unknown command')
2234
def test_env_change_passes_through(self):
2235
self.assertRunBzrSubprocess(
2236
{'env_changes':{'new':'value', 'changed':'newvalue', 'deleted':None}},
2238
env_changes={'new':'value', 'changed':'newvalue', 'deleted':None})
2240
def test_no_working_dir_passed_as_None(self):
2241
self.assertRunBzrSubprocess({'working_dir': None}, StubProcess(), '')
2243
def test_no_working_dir_passed_through(self):
2244
self.assertRunBzrSubprocess({'working_dir': 'dir'}, StubProcess(), '',
2247
def test_run_bzr_subprocess_no_plugins(self):
2248
self.assertRunBzrSubprocess({'allow_plugins': False},
2251
def test_allow_plugins(self):
2252
self.assertRunBzrSubprocess({'allow_plugins': True},
2253
StubProcess(), '', allow_plugins=True)
2256
class TestFinishBzrSubprocess(TestWithFakedStartBzrSubprocess):
2258
def test_finish_bzr_subprocess_with_error(self):
2259
"""finish_bzr_subprocess allows specification of the desired exit code.
2261
process = StubProcess(err="unknown command", retcode=3)
2262
result = self.finish_bzr_subprocess(process, retcode=3)
2263
self.assertEqual('', result[0])
2264
self.assertContainsRe(result[1], 'unknown command')
2266
def test_finish_bzr_subprocess_ignoring_retcode(self):
2267
"""finish_bzr_subprocess allows the exit code to be ignored."""
2268
process = StubProcess(err="unknown command", retcode=3)
2269
result = self.finish_bzr_subprocess(process, retcode=None)
2270
self.assertEqual('', result[0])
2271
self.assertContainsRe(result[1], 'unknown command')
2273
def test_finish_subprocess_with_unexpected_retcode(self):
2274
"""finish_bzr_subprocess raises self.failureException if the retcode is
2275
not the expected one.
2277
process = StubProcess(err="unknown command", retcode=3)
2278
self.assertRaises(self.failureException, self.finish_bzr_subprocess,
2282
class _DontSpawnProcess(Exception):
2283
"""A simple exception which just allows us to skip unnecessary steps"""
2286
class TestStartBzrSubProcess(tests.TestCase):
2288
def check_popen_state(self):
2289
"""Replace to make assertions when popen is called."""
2291
def _popen(self, *args, **kwargs):
2292
"""Record the command that is run, so that we can ensure it is correct"""
2293
self.check_popen_state()
2294
self._popen_args = args
2295
self._popen_kwargs = kwargs
2296
raise _DontSpawnProcess()
2298
def test_run_bzr_subprocess_no_plugins(self):
2299
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [])
2300
command = self._popen_args[0]
2301
self.assertEqual(sys.executable, command[0])
2302
self.assertEqual(self.get_bzr_path(), command[1])
2303
self.assertEqual(['--no-plugins'], command[2:])
2305
def test_allow_plugins(self):
2306
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2308
command = self._popen_args[0]
2309
self.assertEqual([], command[2:])
2311
def test_set_env(self):
2312
self.failIf('EXISTANT_ENV_VAR' in os.environ)
2314
def check_environment():
2315
self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2316
self.check_popen_state = check_environment
2317
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2318
env_changes={'EXISTANT_ENV_VAR':'set variable'})
2319
# not set in theparent
2320
self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2322
def test_run_bzr_subprocess_env_del(self):
2323
"""run_bzr_subprocess can remove environment variables too."""
2324
self.failIf('EXISTANT_ENV_VAR' in os.environ)
2325
def check_environment():
2326
self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2327
os.environ['EXISTANT_ENV_VAR'] = 'set variable'
2328
self.check_popen_state = check_environment
2329
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2330
env_changes={'EXISTANT_ENV_VAR':None})
2331
# Still set in parent
2332
self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2333
del os.environ['EXISTANT_ENV_VAR']
2335
def test_env_del_missing(self):
2336
self.failIf('NON_EXISTANT_ENV_VAR' in os.environ)
2337
def check_environment():
2338
self.assertFalse('NON_EXISTANT_ENV_VAR' in os.environ)
2339
self.check_popen_state = check_environment
2340
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2341
env_changes={'NON_EXISTANT_ENV_VAR':None})
2343
def test_working_dir(self):
2344
"""Test that we can specify the working dir for the child"""
2345
orig_getcwd = osutils.getcwd
2346
orig_chdir = os.chdir
2354
osutils.getcwd = getcwd
2356
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2359
osutils.getcwd = orig_getcwd
2361
os.chdir = orig_chdir
2362
self.assertEqual(['foo', 'current'], chdirs)
2365
class TestActuallyStartBzrSubprocess(tests.TestCaseWithTransport):
2366
"""Tests that really need to do things with an external bzr."""
2368
def test_start_and_stop_bzr_subprocess_send_signal(self):
2369
"""finish_bzr_subprocess raises self.failureException if the retcode is
2370
not the expected one.
2372
process = self.start_bzr_subprocess(['wait-until-signalled'],
2373
skip_if_plan_to_signal=True)
2374
self.assertEqual('running\n', process.stdout.readline())
2375
result = self.finish_bzr_subprocess(process, send_signal=signal.SIGINT,
2377
self.assertEqual('', result[0])
2378
self.assertEqual('bzr: interrupted\n', result[1])
2381
class TestKnownFailure(tests.TestCase):
2383
def test_known_failure(self):
2384
"""Check that KnownFailure is defined appropriately."""
2385
# a KnownFailure is an assertion error for compatability with unaware
2387
self.assertIsInstance(tests.KnownFailure(""), AssertionError)
2389
def test_expect_failure(self):
2391
self.expectFailure("Doomed to failure", self.assertTrue, False)
2392
except tests.KnownFailure, e:
2393
self.assertEqual('Doomed to failure', e.args[0])
2395
self.expectFailure("Doomed to failure", self.assertTrue, True)
2396
except AssertionError, e:
2397
self.assertEqual('Unexpected success. Should have failed:'
2398
' Doomed to failure', e.args[0])
2400
self.fail('Assertion not raised')
2403
class TestFeature(tests.TestCase):
2405
def test_caching(self):
2406
"""Feature._probe is called by the feature at most once."""
2407
class InstrumentedFeature(tests.Feature):
2409
super(InstrumentedFeature, self).__init__()
2412
self.calls.append('_probe')
2414
feature = InstrumentedFeature()
2416
self.assertEqual(['_probe'], feature.calls)
2418
self.assertEqual(['_probe'], feature.calls)
2420
def test_named_str(self):
2421
"""Feature.__str__ should thunk to feature_name()."""
2422
class NamedFeature(tests.Feature):
2423
def feature_name(self):
2425
feature = NamedFeature()
2426
self.assertEqual('symlinks', str(feature))
2428
def test_default_str(self):
2429
"""Feature.__str__ should default to __class__.__name__."""
2430
class NamedFeature(tests.Feature):
2432
feature = NamedFeature()
2433
self.assertEqual('NamedFeature', str(feature))
2436
class TestUnavailableFeature(tests.TestCase):
2438
def test_access_feature(self):
2439
feature = tests.Feature()
2440
exception = tests.UnavailableFeature(feature)
2441
self.assertIs(feature, exception.args[0])
2444
class TestSelftestFiltering(tests.TestCase):
2447
tests.TestCase.setUp(self)
2448
self.suite = TestUtil.TestSuite()
2449
self.loader = TestUtil.TestLoader()
2450
self.suite.addTest(self.loader.loadTestsFromModule(
2451
sys.modules['bzrlib.tests.test_selftest']))
2452
self.all_names = _test_ids(self.suite)
2454
def test_condition_id_re(self):
2455
test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2456
'test_condition_id_re')
2457
filtered_suite = tests.filter_suite_by_condition(
2458
self.suite, tests.condition_id_re('test_condition_id_re'))
2459
self.assertEqual([test_name], _test_ids(filtered_suite))
2461
def test_condition_id_in_list(self):
2462
test_names = ['bzrlib.tests.test_selftest.TestSelftestFiltering.'
2463
'test_condition_id_in_list']
2464
id_list = tests.TestIdList(test_names)
2465
filtered_suite = tests.filter_suite_by_condition(
2466
self.suite, tests.condition_id_in_list(id_list))
2467
my_pattern = 'TestSelftestFiltering.*test_condition_id_in_list'
2468
re_filtered = tests.filter_suite_by_re(self.suite, my_pattern)
2469
self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
2471
def test_condition_id_startswith(self):
2472
klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
2473
start1 = klass + 'test_condition_id_starts'
2474
start2 = klass + 'test_condition_id_in'
2475
test_names = [ klass + 'test_condition_id_in_list',
2476
klass + 'test_condition_id_startswith',
2478
filtered_suite = tests.filter_suite_by_condition(
2479
self.suite, tests.condition_id_startswith([start1, start2]))
2480
self.assertEqual(test_names, _test_ids(filtered_suite))
2482
def test_condition_isinstance(self):
2483
filtered_suite = tests.filter_suite_by_condition(
2484
self.suite, tests.condition_isinstance(self.__class__))
2485
class_pattern = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
2486
re_filtered = tests.filter_suite_by_re(self.suite, class_pattern)
2487
self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
2489
def test_exclude_tests_by_condition(self):
2490
excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2491
'test_exclude_tests_by_condition')
2492
filtered_suite = tests.exclude_tests_by_condition(self.suite,
2493
lambda x:x.id() == excluded_name)
2494
self.assertEqual(len(self.all_names) - 1,
2495
filtered_suite.countTestCases())
2496
self.assertFalse(excluded_name in _test_ids(filtered_suite))
2497
remaining_names = list(self.all_names)
2498
remaining_names.remove(excluded_name)
2499
self.assertEqual(remaining_names, _test_ids(filtered_suite))
2501
def test_exclude_tests_by_re(self):
2502
self.all_names = _test_ids(self.suite)
2503
filtered_suite = tests.exclude_tests_by_re(self.suite,
2504
'exclude_tests_by_re')
2505
excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2506
'test_exclude_tests_by_re')
2507
self.assertEqual(len(self.all_names) - 1,
2508
filtered_suite.countTestCases())
2509
self.assertFalse(excluded_name in _test_ids(filtered_suite))
2510
remaining_names = list(self.all_names)
2511
remaining_names.remove(excluded_name)
2512
self.assertEqual(remaining_names, _test_ids(filtered_suite))
2514
def test_filter_suite_by_condition(self):
2515
test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2516
'test_filter_suite_by_condition')
2517
filtered_suite = tests.filter_suite_by_condition(self.suite,
2518
lambda x:x.id() == test_name)
2519
self.assertEqual([test_name], _test_ids(filtered_suite))
2521
def test_filter_suite_by_re(self):
2522
filtered_suite = tests.filter_suite_by_re(self.suite,
2523
'test_filter_suite_by_r')
2524
filtered_names = _test_ids(filtered_suite)
2525
self.assertEqual(filtered_names, ['bzrlib.tests.test_selftest.'
2526
'TestSelftestFiltering.test_filter_suite_by_re'])
2528
def test_filter_suite_by_id_list(self):
2529
test_list = ['bzrlib.tests.test_selftest.'
2530
'TestSelftestFiltering.test_filter_suite_by_id_list']
2531
filtered_suite = tests.filter_suite_by_id_list(
2532
self.suite, tests.TestIdList(test_list))
2533
filtered_names = _test_ids(filtered_suite)
2536
['bzrlib.tests.test_selftest.'
2537
'TestSelftestFiltering.test_filter_suite_by_id_list'])
2539
def test_filter_suite_by_id_startswith(self):
2540
# By design this test may fail if another test is added whose name also
2541
# begins with one of the start value used.
2542
klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
2543
start1 = klass + 'test_filter_suite_by_id_starts'
2544
start2 = klass + 'test_filter_suite_by_id_li'
2545
test_list = [klass + 'test_filter_suite_by_id_list',
2546
klass + 'test_filter_suite_by_id_startswith',
2548
filtered_suite = tests.filter_suite_by_id_startswith(
2549
self.suite, [start1, start2])
2552
_test_ids(filtered_suite),
2555
def test_preserve_input(self):
2556
# NB: Surely this is something in the stdlib to do this?
2557
self.assertTrue(self.suite is tests.preserve_input(self.suite))
2558
self.assertTrue("@#$" is tests.preserve_input("@#$"))
2560
def test_randomize_suite(self):
2561
randomized_suite = tests.randomize_suite(self.suite)
2562
# randomizing should not add or remove test names.
2563
self.assertEqual(set(_test_ids(self.suite)),
2564
set(_test_ids(randomized_suite)))
2565
# Technically, this *can* fail, because random.shuffle(list) can be
2566
# equal to list. Trying multiple times just pushes the frequency back.
2567
# As its len(self.all_names)!:1, the failure frequency should be low
2568
# enough to ignore. RBC 20071021.
2569
# It should change the order.
2570
self.assertNotEqual(self.all_names, _test_ids(randomized_suite))
2571
# But not the length. (Possibly redundant with the set test, but not
2573
self.assertEqual(len(self.all_names), len(_test_ids(randomized_suite)))
2575
def test_split_suit_by_condition(self):
2576
self.all_names = _test_ids(self.suite)
2577
condition = tests.condition_id_re('test_filter_suite_by_r')
2578
split_suite = tests.split_suite_by_condition(self.suite, condition)
2579
filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2580
'test_filter_suite_by_re')
2581
self.assertEqual([filtered_name], _test_ids(split_suite[0]))
2582
self.assertFalse(filtered_name in _test_ids(split_suite[1]))
2583
remaining_names = list(self.all_names)
2584
remaining_names.remove(filtered_name)
2585
self.assertEqual(remaining_names, _test_ids(split_suite[1]))
2587
def test_split_suit_by_re(self):
2588
self.all_names = _test_ids(self.suite)
2589
split_suite = tests.split_suite_by_re(self.suite,
2590
'test_filter_suite_by_r')
2591
filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2592
'test_filter_suite_by_re')
2593
self.assertEqual([filtered_name], _test_ids(split_suite[0]))
2594
self.assertFalse(filtered_name in _test_ids(split_suite[1]))
2595
remaining_names = list(self.all_names)
2596
remaining_names.remove(filtered_name)
2597
self.assertEqual(remaining_names, _test_ids(split_suite[1]))
2600
class TestCheckInventoryShape(tests.TestCaseWithTransport):
2602
def test_check_inventory_shape(self):
2603
files = ['a', 'b/', 'b/c']
2604
tree = self.make_branch_and_tree('.')
2605
self.build_tree(files)
2609
self.check_inventory_shape(tree.inventory, files)
2614
class TestBlackboxSupport(tests.TestCase):
2615
"""Tests for testsuite blackbox features."""
2617
def test_run_bzr_failure_not_caught(self):
2618
# When we run bzr in blackbox mode, we want any unexpected errors to
2619
# propagate up to the test suite so that it can show the error in the
2620
# usual way, and we won't get a double traceback.
2621
e = self.assertRaises(
2623
self.run_bzr, ['assert-fail'])
2624
# make sure we got the real thing, not an error from somewhere else in
2625
# the test framework
2626
self.assertEquals('always fails', str(e))
2627
# check that there's no traceback in the test log
2628
self.assertNotContainsRe(self._get_log(keep_log_file=True),
2631
def test_run_bzr_user_error_caught(self):
2632
# Running bzr in blackbox mode, normal/expected/user errors should be
2633
# caught in the regular way and turned into an error message plus exit
2635
out, err = self.run_bzr(["log", "/nonexistantpath"], retcode=3)
2636
self.assertEqual(out, '')
2637
self.assertContainsRe(err,
2638
'bzr: ERROR: Not a branch: ".*nonexistantpath/".\n')
2641
class TestTestLoader(tests.TestCase):
2642
"""Tests for the test loader."""
2644
def _get_loader_and_module(self):
2645
"""Gets a TestLoader and a module with one test in it."""
2646
loader = TestUtil.TestLoader()
2648
class Stub(tests.TestCase):
2651
class MyModule(object):
2653
MyModule.a_class = Stub
2655
return loader, module
2657
def test_module_no_load_tests_attribute_loads_classes(self):
2658
loader, module = self._get_loader_and_module()
2659
self.assertEqual(1, loader.loadTestsFromModule(module).countTestCases())
2661
def test_module_load_tests_attribute_gets_called(self):
2662
loader, module = self._get_loader_and_module()
2663
# 'self' is here because we're faking the module with a class. Regular
2664
# load_tests do not need that :)
2665
def load_tests(self, standard_tests, module, loader):
2666
result = loader.suiteClass()
2667
for test in tests.iter_suite_tests(standard_tests):
2668
result.addTests([test, test])
2670
# add a load_tests() method which multiplies the tests from the module.
2671
module.__class__.load_tests = load_tests
2672
self.assertEqual(2, loader.loadTestsFromModule(module).countTestCases())
2674
def test_load_tests_from_module_name_smoke_test(self):
2675
loader = TestUtil.TestLoader()
2676
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2677
self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
2680
def test_load_tests_from_module_name_with_bogus_module_name(self):
2681
loader = TestUtil.TestLoader()
2682
self.assertRaises(ImportError, loader.loadTestsFromModuleName, 'bogus')
2685
class TestTestIdList(tests.TestCase):
2687
def _create_id_list(self, test_list):
2688
return tests.TestIdList(test_list)
2690
def _create_suite(self, test_id_list):
2692
class Stub(tests.TestCase):
2696
def _create_test_id(id):
2699
suite = TestUtil.TestSuite()
2700
for id in test_id_list:
2701
t = Stub('test_foo')
2702
t.id = _create_test_id(id)
2706
def _test_ids(self, test_suite):
2707
"""Get the ids for the tests in a test suite."""
2708
return [t.id() for t in tests.iter_suite_tests(test_suite)]
2710
def test_empty_list(self):
2711
id_list = self._create_id_list([])
2712
self.assertEquals({}, id_list.tests)
2713
self.assertEquals({}, id_list.modules)
2715
def test_valid_list(self):
2716
id_list = self._create_id_list(
2717
['mod1.cl1.meth1', 'mod1.cl1.meth2',
2718
'mod1.func1', 'mod1.cl2.meth2',
2720
'mod1.submod2.cl1.meth1', 'mod1.submod2.cl2.meth2',
2722
self.assertTrue(id_list.refers_to('mod1'))
2723
self.assertTrue(id_list.refers_to('mod1.submod1'))
2724
self.assertTrue(id_list.refers_to('mod1.submod2'))
2725
self.assertTrue(id_list.includes('mod1.cl1.meth1'))
2726
self.assertTrue(id_list.includes('mod1.submod1'))
2727
self.assertTrue(id_list.includes('mod1.func1'))
2729
def test_bad_chars_in_params(self):
2730
id_list = self._create_id_list(['mod1.cl1.meth1(xx.yy)'])
2731
self.assertTrue(id_list.refers_to('mod1'))
2732
self.assertTrue(id_list.includes('mod1.cl1.meth1(xx.yy)'))
2734
def test_module_used(self):
2735
id_list = self._create_id_list(['mod.class.meth'])
2736
self.assertTrue(id_list.refers_to('mod'))
2737
self.assertTrue(id_list.refers_to('mod.class'))
2738
self.assertTrue(id_list.refers_to('mod.class.meth'))
2740
def test_test_suite_matches_id_list_with_unknown(self):
2741
loader = TestUtil.TestLoader()
2742
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2743
test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',
2745
not_found, duplicates = tests.suite_matches_id_list(suite, test_list)
2746
self.assertEquals(['bogus'], not_found)
2747
self.assertEquals([], duplicates)
2749
def test_suite_matches_id_list_with_duplicates(self):
2750
loader = TestUtil.TestLoader()
2751
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2752
dupes = loader.suiteClass()
2753
for test in tests.iter_suite_tests(suite):
2755
dupes.addTest(test) # Add it again
2757
test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',]
2758
not_found, duplicates = tests.suite_matches_id_list(
2760
self.assertEquals([], not_found)
2761
self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
2765
class TestTestSuite(tests.TestCase):
2767
def test__test_suite_testmod_names(self):
2768
# Test that a plausible list of test module names are returned
2769
# by _test_suite_testmod_names.
2770
test_list = tests._test_suite_testmod_names()
2772
'bzrlib.tests.blackbox',
2773
'bzrlib.tests.per_transport',
2774
'bzrlib.tests.test_selftest',
2778
def test__test_suite_modules_to_doctest(self):
2779
# Test that a plausible list of modules to doctest is returned
2780
# by _test_suite_modules_to_doctest.
2781
test_list = tests._test_suite_modules_to_doctest()
2787
def test_test_suite(self):
2788
# test_suite() loads the entire test suite to operate. To avoid this
2789
# overhead, and yet still be confident that things are happening,
2790
# we temporarily replace two functions used by test_suite with
2791
# test doubles that supply a few sample tests to load, and check they
2794
def _test_suite_testmod_names():
2795
calls.append("testmod_names")
2797
'bzrlib.tests.blackbox.test_branch',
2798
'bzrlib.tests.per_transport',
2799
'bzrlib.tests.test_selftest',
2801
original_testmod_names = tests._test_suite_testmod_names
2802
def _test_suite_modules_to_doctest():
2803
calls.append("modules_to_doctest")
2804
return ['bzrlib.timestamp']
2805
orig_modules_to_doctest = tests._test_suite_modules_to_doctest
2806
def restore_names():
2807
tests._test_suite_testmod_names = original_testmod_names
2808
tests._test_suite_modules_to_doctest = orig_modules_to_doctest
2809
self.addCleanup(restore_names)
2810
tests._test_suite_testmod_names = _test_suite_testmod_names
2811
tests._test_suite_modules_to_doctest = _test_suite_modules_to_doctest
2812
expected_test_list = [
2814
'bzrlib.tests.blackbox.test_branch.TestBranch.test_branch',
2815
('bzrlib.tests.per_transport.TransportTests'
2816
'.test_abspath(LocalURLServer)'),
2817
'bzrlib.tests.test_selftest.TestTestSuite.test_test_suite',
2818
# modules_to_doctest
2819
'bzrlib.timestamp.format_highres_date',
2820
# plugins can't be tested that way since selftest may be run with
2823
suite = tests.test_suite()
2824
self.assertEqual(set(["testmod_names", "modules_to_doctest"]),
2826
self.assertSubset(expected_test_list, _test_ids(suite))
2828
def test_test_suite_list_and_start(self):
2829
# We cannot test this at the same time as the main load, because we want
2830
# to know that starting_with == None works. So a second load is
2831
# incurred - note that the starting_with parameter causes a partial load
2832
# rather than a full load so this test should be pretty quick.
2833
test_list = ['bzrlib.tests.test_selftest.TestTestSuite.test_test_suite']
2834
suite = tests.test_suite(test_list,
2835
['bzrlib.tests.test_selftest.TestTestSuite'])
2836
# test_test_suite_list_and_start is not included
2837
self.assertEquals(test_list, _test_ids(suite))
2840
class TestLoadTestIdList(tests.TestCaseInTempDir):
2842
def _create_test_list_file(self, file_name, content):
2843
fl = open(file_name, 'wt')
2847
def test_load_unknown(self):
2848
self.assertRaises(errors.NoSuchFile,
2849
tests.load_test_id_list, 'i_do_not_exist')
2851
def test_load_test_list(self):
2852
test_list_fname = 'test.list'
2853
self._create_test_list_file(test_list_fname,
2854
'mod1.cl1.meth1\nmod2.cl2.meth2\n')
2855
tlist = tests.load_test_id_list(test_list_fname)
2856
self.assertEquals(2, len(tlist))
2857
self.assertEquals('mod1.cl1.meth1', tlist[0])
2858
self.assertEquals('mod2.cl2.meth2', tlist[1])
2860
def test_load_dirty_file(self):
2861
test_list_fname = 'test.list'
2862
self._create_test_list_file(test_list_fname,
2863
' mod1.cl1.meth1\n\nmod2.cl2.meth2 \n'
2865
tlist = tests.load_test_id_list(test_list_fname)
2866
self.assertEquals(4, len(tlist))
2867
self.assertEquals('mod1.cl1.meth1', tlist[0])
2868
self.assertEquals('', tlist[1])
2869
self.assertEquals('mod2.cl2.meth2', tlist[2])
2870
self.assertEquals('bar baz', tlist[3])
2873
class TestFilteredByModuleTestLoader(tests.TestCase):
2875
def _create_loader(self, test_list):
2876
id_filter = tests.TestIdList(test_list)
2877
loader = TestUtil.FilteredByModuleTestLoader(id_filter.refers_to)
2880
def test_load_tests(self):
2881
test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
2882
loader = self._create_loader(test_list)
2884
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2885
self.assertEquals(test_list, _test_ids(suite))
2887
def test_exclude_tests(self):
2888
test_list = ['bogus']
2889
loader = self._create_loader(test_list)
2891
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2892
self.assertEquals([], _test_ids(suite))
2895
class TestFilteredByNameStartTestLoader(tests.TestCase):
2897
def _create_loader(self, name_start):
2898
def needs_module(name):
2899
return name.startswith(name_start) or name_start.startswith(name)
2900
loader = TestUtil.FilteredByModuleTestLoader(needs_module)
2903
def test_load_tests(self):
2904
test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
2905
loader = self._create_loader('bzrlib.tests.test_samp')
2907
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2908
self.assertEquals(test_list, _test_ids(suite))
2910
def test_load_tests_inside_module(self):
2911
test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
2912
loader = self._create_loader('bzrlib.tests.test_sampler.Demo')
2914
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2915
self.assertEquals(test_list, _test_ids(suite))
2917
def test_exclude_tests(self):
2918
test_list = ['bogus']
2919
loader = self._create_loader('bogus')
2921
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2922
self.assertEquals([], _test_ids(suite))
2925
class TestTestPrefixRegistry(tests.TestCase):
2927
def _get_registry(self):
2928
tp_registry = tests.TestPrefixAliasRegistry()
2931
def test_register_new_prefix(self):
2932
tpr = self._get_registry()
2933
tpr.register('foo', 'fff.ooo.ooo')
2934
self.assertEquals('fff.ooo.ooo', tpr.get('foo'))
2936
def test_register_existing_prefix(self):
2937
tpr = self._get_registry()
2938
tpr.register('bar', 'bbb.aaa.rrr')
2939
tpr.register('bar', 'bBB.aAA.rRR')
2940
self.assertEquals('bbb.aaa.rrr', tpr.get('bar'))
2941
self.assertContainsRe(self._get_log(keep_log_file=True),
2942
r'.*bar.*bbb.aaa.rrr.*bBB.aAA.rRR')
2944
def test_get_unknown_prefix(self):
2945
tpr = self._get_registry()
2946
self.assertRaises(KeyError, tpr.get, 'I am not a prefix')
2948
def test_resolve_prefix(self):
2949
tpr = self._get_registry()
2950
tpr.register('bar', 'bb.aa.rr')
2951
self.assertEquals('bb.aa.rr', tpr.resolve_alias('bar'))
2953
def test_resolve_unknown_alias(self):
2954
tpr = self._get_registry()
2955
self.assertRaises(errors.BzrCommandError,
2956
tpr.resolve_alias, 'I am not a prefix')
2958
def test_predefined_prefixes(self):
2959
tpr = tests.test_prefix_alias_registry
2960
self.assertEquals('bzrlib', tpr.resolve_alias('bzrlib'))
2961
self.assertEquals('bzrlib.doc', tpr.resolve_alias('bd'))
2962
self.assertEquals('bzrlib.utils', tpr.resolve_alias('bu'))
2963
self.assertEquals('bzrlib.tests', tpr.resolve_alias('bt'))
2964
self.assertEquals('bzrlib.tests.blackbox', tpr.resolve_alias('bb'))
2965
self.assertEquals('bzrlib.plugins', tpr.resolve_alias('bp'))
2968
class TestRunSuite(tests.TestCase):
2970
def test_runner_class(self):
2971
"""run_suite accepts and uses a runner_class keyword argument."""
2972
class Stub(tests.TestCase):
2975
suite = Stub("test_foo")
2977
class MyRunner(tests.TextTestRunner):
2978
def run(self, test):
2980
return tests.ExtendedTestResult(self.stream, self.descriptions,
2982
tests.run_suite(suite, runner_class=MyRunner, stream=StringIO())
2983
self.assertLength(1, calls)