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
44
from bzrlib.repofmt import (
49
from bzrlib.symbol_versioning import (
54
from bzrlib.tests import (
60
from bzrlib.trace import note
61
from bzrlib.transport.memory import MemoryServer, MemoryTransport
62
from bzrlib.version import _get_bzr_source_tree
65
def _test_ids(test_suite):
66
"""Get the ids for the tests in a test suite."""
67
return [t.id() for t in tests.iter_suite_tests(test_suite)]
70
class SelftestTests(tests.TestCase):
72
def test_import_tests(self):
73
mod = TestUtil._load_module_by_name('bzrlib.tests.test_selftest')
74
self.assertEqual(mod.SelftestTests, SelftestTests)
76
def test_import_test_failure(self):
77
self.assertRaises(ImportError,
78
TestUtil._load_module_by_name,
81
class MetaTestLog(tests.TestCase):
83
def test_logging(self):
84
"""Test logs are captured when a test fails."""
85
self.log('a test message')
86
self._log_file.flush()
87
self.assertContainsRe(self._get_log(keep_log_file=True),
91
class TestUnicodeFilename(tests.TestCase):
93
def test_probe_passes(self):
94
"""UnicodeFilename._probe passes."""
95
# We can't test much more than that because the behaviour depends
97
tests.UnicodeFilename._probe()
100
class TestTreeShape(tests.TestCaseInTempDir):
102
def test_unicode_paths(self):
103
self.requireFeature(tests.UnicodeFilename)
105
filename = u'hell\u00d8'
106
self.build_tree_contents([(filename, 'contents of hello')])
107
self.failUnlessExists(filename)
110
class TestTransportScenarios(tests.TestCase):
111
"""A group of tests that test the transport implementation adaption core.
113
This is a meta test that the tests are applied to all available
116
This will be generalised in the future which is why it is in this
117
test file even though it is specific to transport tests at the moment.
120
def test_get_transport_permutations(self):
121
# this checks that get_test_permutations defined by the module is
122
# called by the get_transport_test_permutations function.
123
class MockModule(object):
124
def get_test_permutations(self):
125
return sample_permutation
126
sample_permutation = [(1,2), (3,4)]
127
from bzrlib.tests.per_transport import get_transport_test_permutations
128
self.assertEqual(sample_permutation,
129
get_transport_test_permutations(MockModule()))
131
def test_scenarios_include_all_modules(self):
132
# this checks that the scenario generator returns as many permutations
133
# as there are in all the registered transport modules - we assume if
134
# this matches its probably doing the right thing especially in
135
# combination with the tests for setting the right classes below.
136
from bzrlib.tests.per_transport import transport_test_permutations
137
from bzrlib.transport import _get_transport_modules
138
modules = _get_transport_modules()
139
permutation_count = 0
140
for module in modules:
142
permutation_count += len(reduce(getattr,
143
(module + ".get_test_permutations").split('.')[1:],
144
__import__(module))())
145
except errors.DependencyNotPresent:
147
scenarios = transport_test_permutations()
148
self.assertEqual(permutation_count, len(scenarios))
150
def test_scenarios_include_transport_class(self):
151
# This test used to know about all the possible transports and the
152
# order they were returned but that seems overly brittle (mbp
154
from bzrlib.tests.per_transport import transport_test_permutations
155
scenarios = transport_test_permutations()
156
# there are at least that many builtin transports
157
self.assertTrue(len(scenarios) > 6)
158
one_scenario = scenarios[0]
159
self.assertIsInstance(one_scenario[0], str)
160
self.assertTrue(issubclass(one_scenario[1]["transport_class"],
161
bzrlib.transport.Transport))
162
self.assertTrue(issubclass(one_scenario[1]["transport_server"],
163
bzrlib.transport.Server))
166
class TestBranchScenarios(tests.TestCase):
168
def test_scenarios(self):
169
# check that constructor parameters are passed through to the adapted
171
from bzrlib.tests.per_branch import make_scenarios
174
formats = [("c", "C"), ("d", "D")]
175
scenarios = make_scenarios(server1, server2, formats)
176
self.assertEqual(2, len(scenarios))
179
{'branch_format': 'c',
180
'bzrdir_format': 'C',
181
'transport_readonly_server': 'b',
182
'transport_server': 'a'}),
184
{'branch_format': 'd',
185
'bzrdir_format': 'D',
186
'transport_readonly_server': 'b',
187
'transport_server': 'a'})],
191
class TestBzrDirScenarios(tests.TestCase):
193
def test_scenarios(self):
194
# check that constructor parameters are passed through to the adapted
196
from bzrlib.tests.per_bzrdir import make_scenarios
201
scenarios = make_scenarios(vfs_factory, server1, server2, formats)
204
{'bzrdir_format': 'c',
205
'transport_readonly_server': 'b',
206
'transport_server': 'a',
207
'vfs_transport_factory': 'v'}),
209
{'bzrdir_format': 'd',
210
'transport_readonly_server': 'b',
211
'transport_server': 'a',
212
'vfs_transport_factory': 'v'})],
216
class TestRepositoryScenarios(tests.TestCase):
218
def test_formats_to_scenarios(self):
219
from bzrlib.tests.per_repository import formats_to_scenarios
220
formats = [("(c)", remote.RemoteRepositoryFormat()),
221
("(d)", repository.format_registry.get(
222
'Bazaar repository format 2a (needs bzr 1.16 or later)\n'))]
223
no_vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
225
vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
226
vfs_transport_factory="vfs")
227
# no_vfs generate scenarios without vfs_transport_factory
229
('RemoteRepositoryFormat(c)',
230
{'bzrdir_format': remote.RemoteBzrDirFormat(),
231
'repository_format': remote.RemoteRepositoryFormat(),
232
'transport_readonly_server': 'readonly',
233
'transport_server': 'server'}),
234
('RepositoryFormat2a(d)',
235
{'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
236
'repository_format': groupcompress_repo.RepositoryFormat2a(),
237
'transport_readonly_server': 'readonly',
238
'transport_server': 'server'})]
239
self.assertEqual(expected, no_vfs_scenarios)
241
('RemoteRepositoryFormat(c)',
242
{'bzrdir_format': remote.RemoteBzrDirFormat(),
243
'repository_format': remote.RemoteRepositoryFormat(),
244
'transport_readonly_server': 'readonly',
245
'transport_server': 'server',
246
'vfs_transport_factory': 'vfs'}),
247
('RepositoryFormat2a(d)',
248
{'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
249
'repository_format': groupcompress_repo.RepositoryFormat2a(),
250
'transport_readonly_server': 'readonly',
251
'transport_server': 'server',
252
'vfs_transport_factory': 'vfs'})],
256
class TestTestScenarioApplication(tests.TestCase):
257
"""Tests for the test adaption facilities."""
259
def test_apply_scenario(self):
260
from bzrlib.tests import apply_scenario
261
input_test = TestTestScenarioApplication("test_apply_scenario")
262
# setup two adapted tests
263
adapted_test1 = apply_scenario(input_test,
265
{"bzrdir_format":"bzr_format",
266
"repository_format":"repo_fmt",
267
"transport_server":"transport_server",
268
"transport_readonly_server":"readonly-server"}))
269
adapted_test2 = apply_scenario(input_test,
270
("new id 2", {"bzrdir_format":None}))
271
# input_test should have been altered.
272
self.assertRaises(AttributeError, getattr, input_test, "bzrdir_format")
273
# the new tests are mutually incompatible, ensuring it has
274
# made new ones, and unspecified elements in the scenario
275
# should not have been altered.
276
self.assertEqual("bzr_format", adapted_test1.bzrdir_format)
277
self.assertEqual("repo_fmt", adapted_test1.repository_format)
278
self.assertEqual("transport_server", adapted_test1.transport_server)
279
self.assertEqual("readonly-server",
280
adapted_test1.transport_readonly_server)
282
"bzrlib.tests.test_selftest.TestTestScenarioApplication."
283
"test_apply_scenario(new id)",
285
self.assertEqual(None, adapted_test2.bzrdir_format)
287
"bzrlib.tests.test_selftest.TestTestScenarioApplication."
288
"test_apply_scenario(new id 2)",
292
class TestInterRepositoryScenarios(tests.TestCase):
294
def test_scenarios(self):
295
# check that constructor parameters are passed through to the adapted
297
from bzrlib.tests.per_interrepository import make_scenarios
300
formats = [("C0", "C1", "C2"), ("D0", "D1", "D2")]
301
scenarios = make_scenarios(server1, server2, formats)
304
{'repository_format': 'C1',
305
'repository_format_to': 'C2',
306
'transport_readonly_server': 'b',
307
'transport_server': 'a'}),
309
{'repository_format': 'D1',
310
'repository_format_to': 'D2',
311
'transport_readonly_server': 'b',
312
'transport_server': 'a'})],
316
class TestWorkingTreeScenarios(tests.TestCase):
318
def test_scenarios(self):
319
# check that constructor parameters are passed through to the adapted
321
from bzrlib.tests.per_workingtree import make_scenarios
324
formats = [workingtree.WorkingTreeFormat2(),
325
workingtree.WorkingTreeFormat3(),]
326
scenarios = make_scenarios(server1, server2, formats)
328
('WorkingTreeFormat2',
329
{'bzrdir_format': formats[0]._matchingbzrdir,
330
'transport_readonly_server': 'b',
331
'transport_server': 'a',
332
'workingtree_format': formats[0]}),
333
('WorkingTreeFormat3',
334
{'bzrdir_format': formats[1]._matchingbzrdir,
335
'transport_readonly_server': 'b',
336
'transport_server': 'a',
337
'workingtree_format': formats[1]})],
341
class TestTreeScenarios(tests.TestCase):
343
def test_scenarios(self):
344
# the tree implementation scenario generator is meant to setup one
345
# instance for each working tree format, and one additional instance
346
# that will use the default wt format, but create a revision tree for
347
# the tests. this means that the wt ones should have the
348
# workingtree_to_test_tree attribute set to 'return_parameter' and the
349
# revision one set to revision_tree_from_workingtree.
351
from bzrlib.tests.per_tree import (
352
_dirstate_tree_from_workingtree,
357
revision_tree_from_workingtree
361
formats = [workingtree.WorkingTreeFormat2(),
362
workingtree.WorkingTreeFormat3(),]
363
scenarios = make_scenarios(server1, server2, formats)
364
self.assertEqual(7, len(scenarios))
365
default_wt_format = workingtree.WorkingTreeFormat4._default_format
366
wt4_format = workingtree.WorkingTreeFormat4()
367
wt5_format = workingtree.WorkingTreeFormat5()
368
expected_scenarios = [
369
('WorkingTreeFormat2',
370
{'bzrdir_format': formats[0]._matchingbzrdir,
371
'transport_readonly_server': 'b',
372
'transport_server': 'a',
373
'workingtree_format': formats[0],
374
'_workingtree_to_test_tree': return_parameter,
376
('WorkingTreeFormat3',
377
{'bzrdir_format': formats[1]._matchingbzrdir,
378
'transport_readonly_server': 'b',
379
'transport_server': 'a',
380
'workingtree_format': formats[1],
381
'_workingtree_to_test_tree': return_parameter,
384
{'_workingtree_to_test_tree': revision_tree_from_workingtree,
385
'bzrdir_format': default_wt_format._matchingbzrdir,
386
'transport_readonly_server': 'b',
387
'transport_server': 'a',
388
'workingtree_format': default_wt_format,
390
('DirStateRevisionTree,WT4',
391
{'_workingtree_to_test_tree': _dirstate_tree_from_workingtree,
392
'bzrdir_format': wt4_format._matchingbzrdir,
393
'transport_readonly_server': 'b',
394
'transport_server': 'a',
395
'workingtree_format': wt4_format,
397
('DirStateRevisionTree,WT5',
398
{'_workingtree_to_test_tree': _dirstate_tree_from_workingtree,
399
'bzrdir_format': wt5_format._matchingbzrdir,
400
'transport_readonly_server': 'b',
401
'transport_server': 'a',
402
'workingtree_format': wt5_format,
405
{'_workingtree_to_test_tree': preview_tree_pre,
406
'bzrdir_format': default_wt_format._matchingbzrdir,
407
'transport_readonly_server': 'b',
408
'transport_server': 'a',
409
'workingtree_format': default_wt_format}),
411
{'_workingtree_to_test_tree': preview_tree_post,
412
'bzrdir_format': default_wt_format._matchingbzrdir,
413
'transport_readonly_server': 'b',
414
'transport_server': 'a',
415
'workingtree_format': default_wt_format}),
417
self.assertEqual(expected_scenarios, scenarios)
420
class TestInterTreeScenarios(tests.TestCase):
421
"""A group of tests that test the InterTreeTestAdapter."""
423
def test_scenarios(self):
424
# check that constructor parameters are passed through to the adapted
426
# for InterTree tests we want the machinery to bring up two trees in
427
# each instance: the base one, and the one we are interacting with.
428
# because each optimiser can be direction specific, we need to test
429
# each optimiser in its chosen direction.
430
# unlike the TestProviderAdapter we dont want to automatically add a
431
# parameterized one for WorkingTree - the optimisers will tell us what
433
from bzrlib.tests.per_tree import (
435
revision_tree_from_workingtree
437
from bzrlib.tests.per_intertree import (
440
from bzrlib.workingtree import WorkingTreeFormat2, WorkingTreeFormat3
441
input_test = TestInterTreeScenarios(
445
format1 = WorkingTreeFormat2()
446
format2 = WorkingTreeFormat3()
447
formats = [("1", str, format1, format2, "converter1"),
448
("2", int, format2, format1, "converter2")]
449
scenarios = make_scenarios(server1, server2, formats)
450
self.assertEqual(2, len(scenarios))
451
expected_scenarios = [
453
"bzrdir_format": format1._matchingbzrdir,
454
"intertree_class": formats[0][1],
455
"workingtree_format": formats[0][2],
456
"workingtree_format_to": formats[0][3],
457
"mutable_trees_to_test_trees": formats[0][4],
458
"_workingtree_to_test_tree": return_parameter,
459
"transport_server": server1,
460
"transport_readonly_server": server2,
463
"bzrdir_format": format2._matchingbzrdir,
464
"intertree_class": formats[1][1],
465
"workingtree_format": formats[1][2],
466
"workingtree_format_to": formats[1][3],
467
"mutable_trees_to_test_trees": formats[1][4],
468
"_workingtree_to_test_tree": return_parameter,
469
"transport_server": server1,
470
"transport_readonly_server": server2,
473
self.assertEqual(scenarios, expected_scenarios)
476
class TestTestCaseInTempDir(tests.TestCaseInTempDir):
478
def test_home_is_not_working(self):
479
self.assertNotEqual(self.test_dir, self.test_home_dir)
480
cwd = osutils.getcwd()
481
self.assertIsSameRealPath(self.test_dir, cwd)
482
self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
484
def test_assertEqualStat_equal(self):
485
from bzrlib.tests.test_dirstate import _FakeStat
486
self.build_tree(["foo"])
487
real = os.lstat("foo")
488
fake = _FakeStat(real.st_size, real.st_mtime, real.st_ctime,
489
real.st_dev, real.st_ino, real.st_mode)
490
self.assertEqualStat(real, fake)
492
def test_assertEqualStat_notequal(self):
493
self.build_tree(["foo", "bar"])
494
self.assertRaises(AssertionError, self.assertEqualStat,
495
os.lstat("foo"), os.lstat("bar"))
498
class TestTestCaseWithMemoryTransport(tests.TestCaseWithMemoryTransport):
500
def test_home_is_non_existant_dir_under_root(self):
501
"""The test_home_dir for TestCaseWithMemoryTransport is missing.
503
This is because TestCaseWithMemoryTransport is for tests that do not
504
need any disk resources: they should be hooked into bzrlib in such a
505
way that no global settings are being changed by the test (only a
506
few tests should need to do that), and having a missing dir as home is
507
an effective way to ensure that this is the case.
509
self.assertIsSameRealPath(
510
self.TEST_ROOT + "/MemoryTransportMissingHomeDir",
512
self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
514
def test_cwd_is_TEST_ROOT(self):
515
self.assertIsSameRealPath(self.test_dir, self.TEST_ROOT)
516
cwd = osutils.getcwd()
517
self.assertIsSameRealPath(self.test_dir, cwd)
519
def test_make_branch_and_memory_tree(self):
520
"""In TestCaseWithMemoryTransport we should not make the branch on disk.
522
This is hard to comprehensively robustly test, so we settle for making
523
a branch and checking no directory was created at its relpath.
525
tree = self.make_branch_and_memory_tree('dir')
526
# Guard against regression into MemoryTransport leaking
527
# files to disk instead of keeping them in memory.
528
self.failIf(osutils.lexists('dir'))
529
self.assertIsInstance(tree, memorytree.MemoryTree)
531
def test_make_branch_and_memory_tree_with_format(self):
532
"""make_branch_and_memory_tree should accept a format option."""
533
format = bzrdir.BzrDirMetaFormat1()
534
format.repository_format = weaverepo.RepositoryFormat7()
535
tree = self.make_branch_and_memory_tree('dir', format=format)
536
# Guard against regression into MemoryTransport leaking
537
# files to disk instead of keeping them in memory.
538
self.failIf(osutils.lexists('dir'))
539
self.assertIsInstance(tree, memorytree.MemoryTree)
540
self.assertEqual(format.repository_format.__class__,
541
tree.branch.repository._format.__class__)
543
def test_make_branch_builder(self):
544
builder = self.make_branch_builder('dir')
545
self.assertIsInstance(builder, branchbuilder.BranchBuilder)
546
# Guard against regression into MemoryTransport leaking
547
# files to disk instead of keeping them in memory.
548
self.failIf(osutils.lexists('dir'))
550
def test_make_branch_builder_with_format(self):
551
# Use a repo layout that doesn't conform to a 'named' layout, to ensure
552
# that the format objects are used.
553
format = bzrdir.BzrDirMetaFormat1()
554
repo_format = weaverepo.RepositoryFormat7()
555
format.repository_format = repo_format
556
builder = self.make_branch_builder('dir', format=format)
557
the_branch = builder.get_branch()
558
# Guard against regression into MemoryTransport leaking
559
# files to disk instead of keeping them in memory.
560
self.failIf(osutils.lexists('dir'))
561
self.assertEqual(format.repository_format.__class__,
562
the_branch.repository._format.__class__)
563
self.assertEqual(repo_format.get_format_string(),
564
self.get_transport().get_bytes(
565
'dir/.bzr/repository/format'))
567
def test_make_branch_builder_with_format_name(self):
568
builder = self.make_branch_builder('dir', format='knit')
569
the_branch = builder.get_branch()
570
# Guard against regression into MemoryTransport leaking
571
# files to disk instead of keeping them in memory.
572
self.failIf(osutils.lexists('dir'))
573
dir_format = bzrdir.format_registry.make_bzrdir('knit')
574
self.assertEqual(dir_format.repository_format.__class__,
575
the_branch.repository._format.__class__)
576
self.assertEqual('Bazaar-NG Knit Repository Format 1',
577
self.get_transport().get_bytes(
578
'dir/.bzr/repository/format'))
580
def test_dangling_locks_cause_failures(self):
581
class TestDanglingLock(tests.TestCaseWithMemoryTransport):
582
def test_function(self):
583
t = self.get_transport('.')
584
l = lockdir.LockDir(t, 'lock')
587
test = TestDanglingLock('test_function')
589
if self._lock_check_thorough:
590
self.assertEqual(1, len(result.errors))
592
# When _lock_check_thorough is disabled, then we don't trigger a
594
self.assertEqual(0, len(result.errors))
597
class TestTestCaseWithTransport(tests.TestCaseWithTransport):
598
"""Tests for the convenience functions TestCaseWithTransport introduces."""
600
def test_get_readonly_url_none(self):
601
from bzrlib.transport import get_transport
602
from bzrlib.transport.memory import MemoryServer
603
from bzrlib.transport.readonly import ReadonlyTransportDecorator
604
self.vfs_transport_factory = MemoryServer
605
self.transport_readonly_server = None
606
# calling get_readonly_transport() constructs a decorator on the url
608
url = self.get_readonly_url()
609
url2 = self.get_readonly_url('foo/bar')
610
t = get_transport(url)
611
t2 = get_transport(url2)
612
self.failUnless(isinstance(t, ReadonlyTransportDecorator))
613
self.failUnless(isinstance(t2, ReadonlyTransportDecorator))
614
self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
616
def test_get_readonly_url_http(self):
617
from bzrlib.tests.http_server import HttpServer
618
from bzrlib.transport import get_transport
619
from bzrlib.transport.local import LocalURLServer
620
from bzrlib.transport.http import HttpTransportBase
621
self.transport_server = LocalURLServer
622
self.transport_readonly_server = HttpServer
623
# calling get_readonly_transport() gives us a HTTP server instance.
624
url = self.get_readonly_url()
625
url2 = self.get_readonly_url('foo/bar')
626
# the transport returned may be any HttpTransportBase subclass
627
t = get_transport(url)
628
t2 = get_transport(url2)
629
self.failUnless(isinstance(t, HttpTransportBase))
630
self.failUnless(isinstance(t2, HttpTransportBase))
631
self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
633
def test_is_directory(self):
634
"""Test assertIsDirectory assertion"""
635
t = self.get_transport()
636
self.build_tree(['a_dir/', 'a_file'], transport=t)
637
self.assertIsDirectory('a_dir', t)
638
self.assertRaises(AssertionError, self.assertIsDirectory, 'a_file', t)
639
self.assertRaises(AssertionError, self.assertIsDirectory, 'not_here', t)
641
def test_make_branch_builder(self):
642
builder = self.make_branch_builder('dir')
643
rev_id = builder.build_commit()
644
self.failUnlessExists('dir')
645
a_dir = bzrdir.BzrDir.open('dir')
646
self.assertRaises(errors.NoWorkingTree, a_dir.open_workingtree)
647
a_branch = a_dir.open_branch()
648
builder_branch = builder.get_branch()
649
self.assertEqual(a_branch.base, builder_branch.base)
650
self.assertEqual((1, rev_id), builder_branch.last_revision_info())
651
self.assertEqual((1, rev_id), a_branch.last_revision_info())
654
class TestTestCaseTransports(tests.TestCaseWithTransport):
657
super(TestTestCaseTransports, self).setUp()
658
self.vfs_transport_factory = MemoryServer
660
def test_make_bzrdir_preserves_transport(self):
661
t = self.get_transport()
662
result_bzrdir = self.make_bzrdir('subdir')
663
self.assertIsInstance(result_bzrdir.transport,
665
# should not be on disk, should only be in memory
666
self.failIfExists('subdir')
669
class TestChrootedTest(tests.ChrootedTestCase):
671
def test_root_is_root(self):
672
from bzrlib.transport import get_transport
673
t = get_transport(self.get_readonly_url())
675
self.assertEqual(url, t.clone('..').base)
678
class TestProfileResult(tests.TestCase):
680
def test_profiles_tests(self):
681
self.requireFeature(test_lsprof.LSProfFeature)
682
terminal = unittest.TestResult()
683
result = tests.ProfileResult(terminal)
684
class Sample(tests.TestCase):
686
self.sample_function()
687
def sample_function(self):
690
test.attrs_to_keep = test.attrs_to_keep + ('_benchcalls',)
692
self.assertLength(1, test._benchcalls)
693
# We must be able to unpack it as the test reporting code wants
694
(_, _, _), stats = test._benchcalls[0]
695
self.assertTrue(callable(stats.pprint))
698
class TestTestResult(tests.TestCase):
700
def check_timing(self, test_case, expected_re):
701
result = bzrlib.tests.TextTestResult(self._log_file,
705
test_case.run(result)
706
timed_string = result._testTimeString(test_case)
707
self.assertContainsRe(timed_string, expected_re)
709
def test_test_reporting(self):
710
class ShortDelayTestCase(tests.TestCase):
711
def test_short_delay(self):
713
def test_short_benchmark(self):
714
self.time(time.sleep, 0.003)
715
self.check_timing(ShortDelayTestCase('test_short_delay'),
717
# if a benchmark time is given, we now show just that time followed by
719
self.check_timing(ShortDelayTestCase('test_short_benchmark'),
722
def test_unittest_reporting_unittest_class(self):
723
# getting the time from a non-bzrlib test works ok
724
class ShortDelayTestCase(unittest.TestCase):
725
def test_short_delay(self):
727
self.check_timing(ShortDelayTestCase('test_short_delay'),
730
def _patch_get_bzr_source_tree(self):
731
# Reading from the actual source tree breaks isolation, but we don't
732
# want to assume that thats *all* that would happen.
733
def _get_bzr_source_tree():
735
orig_get_bzr_source_tree = bzrlib.version._get_bzr_source_tree
736
bzrlib.version._get_bzr_source_tree = _get_bzr_source_tree
738
bzrlib.version._get_bzr_source_tree = orig_get_bzr_source_tree
739
self.addCleanup(restore)
741
def test_assigned_benchmark_file_stores_date(self):
742
self._patch_get_bzr_source_tree()
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
self._patch_get_bzr_source_tree()
757
result_stream = StringIO()
758
result = bzrlib.tests.TextTestResult(
762
bench_history=result_stream
765
# we want profile a call and check that its test duration is recorded
766
# make a new test instance that when run will generate a benchmark
767
example_test_case = TestTestResult("_time_hello_world_encoding")
768
# execute the test, which should succeed and record times
769
example_test_case.run(result)
770
lines = result_stream.getvalue().splitlines()
771
self.assertEqual(2, len(lines))
772
self.assertContainsRe(lines[1],
773
" *[0-9]+ms bzrlib.tests.test_selftest.TestTestResult"
774
"._time_hello_world_encoding")
776
def _time_hello_world_encoding(self):
777
"""Profile two sleep calls
779
This is used to exercise the test framework.
781
self.time(unicode, 'hello', errors='replace')
782
self.time(unicode, 'world', errors='replace')
784
def test_lsprofiling(self):
785
"""Verbose test result prints lsprof statistics from test cases."""
786
self.requireFeature(test_lsprof.LSProfFeature)
787
result_stream = StringIO()
788
result = bzrlib.tests.VerboseTestResult(
789
unittest._WritelnDecorator(result_stream),
793
# we want profile a call of some sort and check it is output by
794
# addSuccess. We dont care about addError or addFailure as they
795
# are not that interesting for performance tuning.
796
# make a new test instance that when run will generate a profile
797
example_test_case = TestTestResult("_time_hello_world_encoding")
798
example_test_case._gather_lsprof_in_benchmarks = True
799
# execute the test, which should succeed and record profiles
800
example_test_case.run(result)
801
# lsprofile_something()
802
# if this worked we want
803
# LSProf output for <built in function unicode> (['hello'], {'errors': 'replace'})
804
# CallCount Recursive Total(ms) Inline(ms) module:lineno(function)
805
# (the lsprof header)
806
# ... an arbitrary number of lines
807
# and the function call which is time.sleep.
808
# 1 0 ??? ??? ???(sleep)
809
# and then repeated but with 'world', rather than 'hello'.
810
# this should appear in the output stream of our test result.
811
output = result_stream.getvalue()
812
self.assertContainsRe(output,
813
r"LSProf output for <type 'unicode'>\(\('hello',\), {'errors': 'replace'}\)")
814
self.assertContainsRe(output,
815
r" *CallCount *Recursive *Total\(ms\) *Inline\(ms\) *module:lineno\(function\)\n")
816
self.assertContainsRe(output,
817
r"( +1 +0 +0\.\d+ +0\.\d+ +<method 'disable' of '_lsprof\.Profiler' objects>\n)?")
818
self.assertContainsRe(output,
819
r"LSProf output for <type 'unicode'>\(\('world',\), {'errors': 'replace'}\)\n")
821
def test_known_failure(self):
822
"""A KnownFailure being raised should trigger several result actions."""
823
class InstrumentedTestResult(tests.ExtendedTestResult):
824
def stopTestRun(self): pass
825
def startTests(self): pass
826
def report_test_start(self, test): pass
827
def report_known_failure(self, test, err):
828
self._call = test, err
829
result = InstrumentedTestResult(None, None, None, None)
830
class Test(tests.TestCase):
831
def test_function(self):
832
raise tests.KnownFailure('failed!')
833
test = Test("test_function")
835
# it should invoke 'report_known_failure'.
836
self.assertEqual(2, len(result._call))
837
self.assertEqual(test, result._call[0])
838
self.assertEqual(tests.KnownFailure, result._call[1][0])
839
self.assertIsInstance(result._call[1][1], tests.KnownFailure)
840
# we dont introspec the traceback, if the rest is ok, it would be
841
# exceptional for it not to be.
842
# it should update the known_failure_count on the object.
843
self.assertEqual(1, result.known_failure_count)
844
# the result should be successful.
845
self.assertTrue(result.wasSuccessful())
847
def test_verbose_report_known_failure(self):
848
# verbose test output formatting
849
result_stream = StringIO()
850
result = bzrlib.tests.VerboseTestResult(
851
unittest._WritelnDecorator(result_stream),
855
test = self.get_passing_test()
856
result.startTest(test)
857
prefix = len(result_stream.getvalue())
858
# the err parameter has the shape:
859
# (class, exception object, traceback)
860
# KnownFailures dont get their tracebacks shown though, so we
862
err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
863
result.report_known_failure(test, err)
864
output = result_stream.getvalue()[prefix:]
865
lines = output.splitlines()
866
self.assertContainsRe(lines[0], r'XFAIL *\d+ms$')
867
self.assertEqual(lines[1], ' foo')
868
self.assertEqual(2, len(lines))
870
def get_passing_test(self):
871
"""Return a test object that can't be run usefully."""
874
return unittest.FunctionTestCase(passing_test)
876
def test_add_not_supported(self):
877
"""Test the behaviour of invoking addNotSupported."""
878
class InstrumentedTestResult(tests.ExtendedTestResult):
879
def stopTestRun(self): pass
880
def startTests(self): pass
881
def report_test_start(self, test): pass
882
def report_unsupported(self, test, feature):
883
self._call = test, feature
884
result = InstrumentedTestResult(None, None, None, None)
885
test = SampleTestCase('_test_pass')
886
feature = tests.Feature()
887
result.startTest(test)
888
result.addNotSupported(test, feature)
889
# it should invoke 'report_unsupported'.
890
self.assertEqual(2, len(result._call))
891
self.assertEqual(test, result._call[0])
892
self.assertEqual(feature, result._call[1])
893
# the result should be successful.
894
self.assertTrue(result.wasSuccessful())
895
# it should record the test against a count of tests not run due to
897
self.assertEqual(1, result.unsupported['Feature'])
898
# and invoking it again should increment that counter
899
result.addNotSupported(test, feature)
900
self.assertEqual(2, result.unsupported['Feature'])
902
def test_verbose_report_unsupported(self):
903
# verbose test output formatting
904
result_stream = StringIO()
905
result = bzrlib.tests.VerboseTestResult(
906
unittest._WritelnDecorator(result_stream),
910
test = self.get_passing_test()
911
feature = tests.Feature()
912
result.startTest(test)
913
prefix = len(result_stream.getvalue())
914
result.report_unsupported(test, feature)
915
output = result_stream.getvalue()[prefix:]
916
lines = output.splitlines()
917
self.assertEqual(lines, ['NODEP 0ms',
918
" The feature 'Feature' is not available."])
920
def test_unavailable_exception(self):
921
"""An UnavailableFeature being raised should invoke addNotSupported."""
922
class InstrumentedTestResult(tests.ExtendedTestResult):
923
def stopTestRun(self): pass
924
def startTests(self): pass
925
def report_test_start(self, test): pass
926
def addNotSupported(self, test, feature):
927
self._call = test, feature
928
result = InstrumentedTestResult(None, None, None, None)
929
feature = tests.Feature()
930
class Test(tests.TestCase):
931
def test_function(self):
932
raise tests.UnavailableFeature(feature)
933
test = Test("test_function")
935
# it should invoke 'addNotSupported'.
936
self.assertEqual(2, len(result._call))
937
self.assertEqual(test, result._call[0])
938
self.assertEqual(feature, result._call[1])
939
# and not count as an error
940
self.assertEqual(0, result.error_count)
942
def test_strict_with_unsupported_feature(self):
943
result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
945
test = self.get_passing_test()
946
feature = "Unsupported Feature"
947
result.addNotSupported(test, feature)
948
self.assertFalse(result.wasStrictlySuccessful())
949
self.assertEqual(None, result._extractBenchmarkTime(test))
951
def test_strict_with_known_failure(self):
952
result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
954
test = self.get_passing_test()
955
err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
956
result.addExpectedFailure(test, err)
957
self.assertFalse(result.wasStrictlySuccessful())
958
self.assertEqual(None, result._extractBenchmarkTime(test))
960
def test_strict_with_success(self):
961
result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
963
test = self.get_passing_test()
964
result.addSuccess(test)
965
self.assertTrue(result.wasStrictlySuccessful())
966
self.assertEqual(None, result._extractBenchmarkTime(test))
968
def test_startTests(self):
969
"""Starting the first test should trigger startTests."""
970
class InstrumentedTestResult(tests.ExtendedTestResult):
972
def startTests(self): self.calls += 1
973
def report_test_start(self, test): pass
974
result = InstrumentedTestResult(None, None, None, None)
977
test = unittest.FunctionTestCase(test_function)
979
self.assertEquals(1, result.calls)
982
class TestUnicodeFilenameFeature(tests.TestCase):
984
def test_probe_passes(self):
985
"""UnicodeFilenameFeature._probe passes."""
986
# We can't test much more than that because the behaviour depends
988
tests.UnicodeFilenameFeature._probe()
991
class TestRunner(tests.TestCase):
993
def dummy_test(self):
996
def run_test_runner(self, testrunner, test):
997
"""Run suite in testrunner, saving global state and restoring it.
999
This current saves and restores:
1000
TestCaseInTempDir.TEST_ROOT
1002
There should be no tests in this file that use
1003
bzrlib.tests.TextTestRunner without using this convenience method,
1004
because of our use of global state.
1006
old_root = tests.TestCaseInTempDir.TEST_ROOT
1007
old_leak = tests.TestCase._first_thread_leaker_id
1009
tests.TestCaseInTempDir.TEST_ROOT = None
1010
tests.TestCase._first_thread_leaker_id = None
1011
return testrunner.run(test)
1013
tests.TestCaseInTempDir.TEST_ROOT = old_root
1014
tests.TestCase._first_thread_leaker_id = old_leak
1016
def test_known_failure_failed_run(self):
1017
# run a test that generates a known failure which should be printed in
1018
# the final output when real failures occur.
1019
class Test(tests.TestCase):
1020
def known_failure_test(self):
1021
raise tests.KnownFailure('failed')
1022
test = unittest.TestSuite()
1023
test.addTest(Test("known_failure_test"))
1025
raise AssertionError('foo')
1026
test.addTest(unittest.FunctionTestCase(failing_test))
1028
runner = tests.TextTestRunner(stream=stream)
1029
result = self.run_test_runner(runner, test)
1030
lines = stream.getvalue().splitlines()
1031
self.assertContainsRe(stream.getvalue(),
1034
'^======================================================================\n'
1035
'^FAIL: unittest.FunctionTestCase \\(failing_test\\)\n'
1036
'^----------------------------------------------------------------------\n'
1037
'Traceback \\(most recent call last\\):\n'
1038
' .*' # File .*, line .*, in failing_test' - but maybe not from .pyc
1039
' raise AssertionError\\(\'foo\'\\)\n'
1041
'^----------------------------------------------------------------------\n'
1043
'FAILED \\(failures=1, known_failure_count=1\\)'
1046
def test_known_failure_ok_run(self):
1047
# run a test that generates a known failure which should be printed in
1049
class Test(tests.TestCase):
1050
def known_failure_test(self):
1051
raise tests.KnownFailure('failed')
1052
test = Test("known_failure_test")
1054
runner = tests.TextTestRunner(stream=stream)
1055
result = self.run_test_runner(runner, test)
1056
self.assertContainsRe(stream.getvalue(),
1059
'Ran 1 test in .*\n'
1061
'OK \\(known_failures=1\\)\n')
1063
def test_result_decorator(self):
1066
class LoggingDecorator(tests.ForwardingResult):
1067
def startTest(self, test):
1068
tests.ForwardingResult.startTest(self, test)
1069
calls.append('start')
1070
test = unittest.FunctionTestCase(lambda:None)
1072
runner = tests.TextTestRunner(stream=stream,
1073
result_decorators=[LoggingDecorator])
1074
result = self.run_test_runner(runner, test)
1075
self.assertLength(1, calls)
1077
def test_skipped_test(self):
1078
# run a test that is skipped, and check the suite as a whole still
1080
# skipping_test must be hidden in here so it's not run as a real test
1081
class SkippingTest(tests.TestCase):
1082
def skipping_test(self):
1083
raise tests.TestSkipped('test intentionally skipped')
1084
runner = tests.TextTestRunner(stream=self._log_file)
1085
test = SkippingTest("skipping_test")
1086
result = self.run_test_runner(runner, test)
1087
self.assertTrue(result.wasSuccessful())
1089
def test_skipped_from_setup(self):
1091
class SkippedSetupTest(tests.TestCase):
1094
calls.append('setUp')
1095
self.addCleanup(self.cleanup)
1096
raise tests.TestSkipped('skipped setup')
1098
def test_skip(self):
1099
self.fail('test reached')
1102
calls.append('cleanup')
1104
runner = tests.TextTestRunner(stream=self._log_file)
1105
test = SkippedSetupTest('test_skip')
1106
result = self.run_test_runner(runner, test)
1107
self.assertTrue(result.wasSuccessful())
1108
# Check if cleanup was called the right number of times.
1109
self.assertEqual(['setUp', 'cleanup'], calls)
1111
def test_skipped_from_test(self):
1113
class SkippedTest(tests.TestCase):
1116
tests.TestCase.setUp(self)
1117
calls.append('setUp')
1118
self.addCleanup(self.cleanup)
1120
def test_skip(self):
1121
raise tests.TestSkipped('skipped test')
1124
calls.append('cleanup')
1126
runner = tests.TextTestRunner(stream=self._log_file)
1127
test = SkippedTest('test_skip')
1128
result = self.run_test_runner(runner, test)
1129
self.assertTrue(result.wasSuccessful())
1130
# Check if cleanup was called the right number of times.
1131
self.assertEqual(['setUp', 'cleanup'], calls)
1133
def test_not_applicable(self):
1134
# run a test that is skipped because it's not applicable
1135
class Test(tests.TestCase):
1136
def not_applicable_test(self):
1137
raise tests.TestNotApplicable('this test never runs')
1139
runner = tests.TextTestRunner(stream=out, verbosity=2)
1140
test = Test("not_applicable_test")
1141
result = self.run_test_runner(runner, test)
1142
self._log_file.write(out.getvalue())
1143
self.assertTrue(result.wasSuccessful())
1144
self.assertTrue(result.wasStrictlySuccessful())
1145
self.assertContainsRe(out.getvalue(),
1146
r'(?m)not_applicable_test * N/A')
1147
self.assertContainsRe(out.getvalue(),
1148
r'(?m)^ this test never runs')
1150
def test_unsupported_features_listed(self):
1151
"""When unsupported features are encountered they are detailed."""
1152
class Feature1(tests.Feature):
1153
def _probe(self): return False
1154
class Feature2(tests.Feature):
1155
def _probe(self): return False
1156
# create sample tests
1157
test1 = SampleTestCase('_test_pass')
1158
test1._test_needs_features = [Feature1()]
1159
test2 = SampleTestCase('_test_pass')
1160
test2._test_needs_features = [Feature2()]
1161
test = unittest.TestSuite()
1165
runner = tests.TextTestRunner(stream=stream)
1166
result = self.run_test_runner(runner, test)
1167
lines = stream.getvalue().splitlines()
1170
"Missing feature 'Feature1' skipped 1 tests.",
1171
"Missing feature 'Feature2' skipped 1 tests.",
1175
def _patch_get_bzr_source_tree(self):
1176
# Reading from the actual source tree breaks isolation, but we don't
1177
# want to assume that thats *all* that would happen.
1178
self._get_source_tree_calls = []
1179
def _get_bzr_source_tree():
1180
self._get_source_tree_calls.append("called")
1182
orig_get_bzr_source_tree = bzrlib.version._get_bzr_source_tree
1183
bzrlib.version._get_bzr_source_tree = _get_bzr_source_tree
1185
bzrlib.version._get_bzr_source_tree = orig_get_bzr_source_tree
1186
self.addCleanup(restore)
1188
def test_bench_history(self):
1189
# tests that the running the benchmark passes bench_history into
1190
# the test result object. We can tell that happens if
1191
# _get_bzr_source_tree is called.
1192
self._patch_get_bzr_source_tree()
1193
test = TestRunner('dummy_test')
1195
runner = tests.TextTestRunner(stream=self._log_file,
1196
bench_history=output)
1197
result = self.run_test_runner(runner, test)
1198
output_string = output.getvalue()
1199
self.assertContainsRe(output_string, "--date [0-9.]+")
1200
self.assertLength(1, self._get_source_tree_calls)
1202
def assertLogDeleted(self, test):
1203
log = test._get_log()
1204
self.assertEqual("DELETED log file to reduce memory footprint", log)
1205
self.assertEqual('', test._log_contents)
1206
self.assertIs(None, test._log_file_name)
1208
def test_success_log_deleted(self):
1209
"""Successful tests have their log deleted"""
1211
class LogTester(tests.TestCase):
1213
def test_success(self):
1214
self.log('this will be removed\n')
1217
runner = tests.TextTestRunner(stream=sio)
1218
test = LogTester('test_success')
1219
result = self.run_test_runner(runner, test)
1221
self.assertLogDeleted(test)
1223
def test_skipped_log_deleted(self):
1224
"""Skipped tests have their log deleted"""
1226
class LogTester(tests.TestCase):
1228
def test_skipped(self):
1229
self.log('this will be removed\n')
1230
raise tests.TestSkipped()
1233
runner = tests.TextTestRunner(stream=sio)
1234
test = LogTester('test_skipped')
1235
result = self.run_test_runner(runner, test)
1237
self.assertLogDeleted(test)
1239
def test_not_aplicable_log_deleted(self):
1240
"""Not applicable tests have their log deleted"""
1242
class LogTester(tests.TestCase):
1244
def test_not_applicable(self):
1245
self.log('this will be removed\n')
1246
raise tests.TestNotApplicable()
1249
runner = tests.TextTestRunner(stream=sio)
1250
test = LogTester('test_not_applicable')
1251
result = self.run_test_runner(runner, test)
1253
self.assertLogDeleted(test)
1255
def test_known_failure_log_deleted(self):
1256
"""Know failure tests have their log deleted"""
1258
class LogTester(tests.TestCase):
1260
def test_known_failure(self):
1261
self.log('this will be removed\n')
1262
raise tests.KnownFailure()
1265
runner = tests.TextTestRunner(stream=sio)
1266
test = LogTester('test_known_failure')
1267
result = self.run_test_runner(runner, test)
1269
self.assertLogDeleted(test)
1271
def test_fail_log_kept(self):
1272
"""Failed tests have their log kept"""
1274
class LogTester(tests.TestCase):
1276
def test_fail(self):
1277
self.log('this will be kept\n')
1278
self.fail('this test fails')
1281
runner = tests.TextTestRunner(stream=sio)
1282
test = LogTester('test_fail')
1283
result = self.run_test_runner(runner, test)
1285
text = sio.getvalue()
1286
self.assertContainsRe(text, 'this will be kept')
1287
self.assertContainsRe(text, 'this test fails')
1289
log = test._get_log()
1290
self.assertContainsRe(log, 'this will be kept')
1291
self.assertEqual(log, test._log_contents)
1293
def test_error_log_kept(self):
1294
"""Tests with errors have their log kept"""
1296
class LogTester(tests.TestCase):
1298
def test_error(self):
1299
self.log('this will be kept\n')
1300
raise ValueError('random exception raised')
1303
runner = tests.TextTestRunner(stream=sio)
1304
test = LogTester('test_error')
1305
result = self.run_test_runner(runner, test)
1307
text = sio.getvalue()
1308
self.assertContainsRe(text, 'this will be kept')
1309
self.assertContainsRe(text, 'random exception raised')
1311
log = test._get_log()
1312
self.assertContainsRe(log, 'this will be kept')
1313
self.assertEqual(log, test._log_contents)
1315
def test_startTestRun(self):
1316
"""run should call result.startTestRun()"""
1318
class LoggingDecorator(tests.ForwardingResult):
1319
def startTestRun(self):
1320
tests.ForwardingResult.startTestRun(self)
1321
calls.append('startTestRun')
1322
test = unittest.FunctionTestCase(lambda:None)
1324
runner = tests.TextTestRunner(stream=stream,
1325
result_decorators=[LoggingDecorator])
1326
result = self.run_test_runner(runner, test)
1327
self.assertLength(1, calls)
1329
def test_stopTestRun(self):
1330
"""run should call result.stopTestRun()"""
1332
class LoggingDecorator(tests.ForwardingResult):
1333
def stopTestRun(self):
1334
tests.ForwardingResult.stopTestRun(self)
1335
calls.append('stopTestRun')
1336
test = unittest.FunctionTestCase(lambda:None)
1338
runner = tests.TextTestRunner(stream=stream,
1339
result_decorators=[LoggingDecorator])
1340
result = self.run_test_runner(runner, test)
1341
self.assertLength(1, calls)
1344
class SampleTestCase(tests.TestCase):
1346
def _test_pass(self):
1349
class _TestException(Exception):
1353
class TestTestCase(tests.TestCase):
1354
"""Tests that test the core bzrlib TestCase."""
1356
def test_assertLength_matches_empty(self):
1358
self.assertLength(0, a_list)
1360
def test_assertLength_matches_nonempty(self):
1362
self.assertLength(3, a_list)
1364
def test_assertLength_fails_different(self):
1366
self.assertRaises(AssertionError, self.assertLength, 1, a_list)
1368
def test_assertLength_shows_sequence_in_failure(self):
1370
exception = self.assertRaises(AssertionError, self.assertLength, 2,
1372
self.assertEqual('Incorrect length: wanted 2, got 3 for [1, 2, 3]',
1375
def test_base_setUp_not_called_causes_failure(self):
1376
class TestCaseWithBrokenSetUp(tests.TestCase):
1378
pass # does not call TestCase.setUp
1381
test = TestCaseWithBrokenSetUp('test_foo')
1382
result = unittest.TestResult()
1384
self.assertFalse(result.wasSuccessful())
1385
self.assertEqual(1, result.testsRun)
1387
def test_base_tearDown_not_called_causes_failure(self):
1388
class TestCaseWithBrokenTearDown(tests.TestCase):
1390
pass # does not call TestCase.tearDown
1393
test = TestCaseWithBrokenTearDown('test_foo')
1394
result = unittest.TestResult()
1396
self.assertFalse(result.wasSuccessful())
1397
self.assertEqual(1, result.testsRun)
1399
def test_debug_flags_sanitised(self):
1400
"""The bzrlib debug flags should be sanitised by setUp."""
1401
if 'allow_debug' in tests.selftest_debug_flags:
1402
raise tests.TestNotApplicable(
1403
'-Eallow_debug option prevents debug flag sanitisation')
1404
# we could set something and run a test that will check
1405
# it gets santised, but this is probably sufficient for now:
1406
# if someone runs the test with -Dsomething it will error.
1408
if self._lock_check_thorough:
1409
flags.add('strict_locks')
1410
self.assertEqual(flags, bzrlib.debug.debug_flags)
1412
def change_selftest_debug_flags(self, new_flags):
1413
orig_selftest_flags = tests.selftest_debug_flags
1414
self.addCleanup(self._restore_selftest_debug_flags, orig_selftest_flags)
1415
tests.selftest_debug_flags = set(new_flags)
1417
def _restore_selftest_debug_flags(self, flags):
1418
tests.selftest_debug_flags = flags
1420
def test_allow_debug_flag(self):
1421
"""The -Eallow_debug flag prevents bzrlib.debug.debug_flags from being
1422
sanitised (i.e. cleared) before running a test.
1424
self.change_selftest_debug_flags(set(['allow_debug']))
1425
bzrlib.debug.debug_flags = set(['a-flag'])
1426
class TestThatRecordsFlags(tests.TestCase):
1427
def test_foo(nested_self):
1428
self.flags = set(bzrlib.debug.debug_flags)
1429
test = TestThatRecordsFlags('test_foo')
1430
test.run(self.make_test_result())
1431
flags = set(['a-flag'])
1432
if 'disable_lock_checks' not in tests.selftest_debug_flags:
1433
flags.add('strict_locks')
1434
self.assertEqual(flags, self.flags)
1436
def test_disable_lock_checks(self):
1437
"""The -Edisable_lock_checks flag disables thorough checks."""
1438
class TestThatRecordsFlags(tests.TestCase):
1439
def test_foo(nested_self):
1440
self.flags = set(bzrlib.debug.debug_flags)
1441
self.test_lock_check_thorough = nested_self._lock_check_thorough
1442
self.change_selftest_debug_flags(set())
1443
test = TestThatRecordsFlags('test_foo')
1444
test.run(self.make_test_result())
1445
# By default we do strict lock checking and thorough lock/unlock
1447
self.assertTrue(self.test_lock_check_thorough)
1448
self.assertEqual(set(['strict_locks']), self.flags)
1449
# Now set the disable_lock_checks flag, and show that this changed.
1450
self.change_selftest_debug_flags(set(['disable_lock_checks']))
1451
test = TestThatRecordsFlags('test_foo')
1452
test.run(self.make_test_result())
1453
self.assertFalse(self.test_lock_check_thorough)
1454
self.assertEqual(set(), self.flags)
1456
def test_this_fails_strict_lock_check(self):
1457
class TestThatRecordsFlags(tests.TestCase):
1458
def test_foo(nested_self):
1459
self.flags1 = set(bzrlib.debug.debug_flags)
1460
self.thisFailsStrictLockCheck()
1461
self.flags2 = set(bzrlib.debug.debug_flags)
1462
# Make sure lock checking is active
1463
self.change_selftest_debug_flags(set())
1464
test = TestThatRecordsFlags('test_foo')
1465
test.run(self.make_test_result())
1466
self.assertEqual(set(['strict_locks']), self.flags1)
1467
self.assertEqual(set(), self.flags2)
1469
def test_debug_flags_restored(self):
1470
"""The bzrlib debug flags should be restored to their original state
1471
after the test was run, even if allow_debug is set.
1473
self.change_selftest_debug_flags(set(['allow_debug']))
1474
# Now run a test that modifies debug.debug_flags.
1475
bzrlib.debug.debug_flags = set(['original-state'])
1476
class TestThatModifiesFlags(tests.TestCase):
1478
bzrlib.debug.debug_flags = set(['modified'])
1479
test = TestThatModifiesFlags('test_foo')
1480
test.run(self.make_test_result())
1481
self.assertEqual(set(['original-state']), bzrlib.debug.debug_flags)
1483
def make_test_result(self):
1484
return tests.TextTestResult(self._log_file, descriptions=0, verbosity=1)
1486
def inner_test(self):
1487
# the inner child test
1490
def outer_child(self):
1491
# the outer child test
1493
self.inner_test = TestTestCase("inner_child")
1494
result = self.make_test_result()
1495
self.inner_test.run(result)
1496
note("outer finish")
1498
def test_trace_nesting(self):
1499
# this tests that each test case nests its trace facility correctly.
1500
# we do this by running a test case manually. That test case (A)
1501
# should setup a new log, log content to it, setup a child case (B),
1502
# which should log independently, then case (A) should log a trailer
1504
# we do two nested children so that we can verify the state of the
1505
# logs after the outer child finishes is correct, which a bad clean
1506
# up routine in tearDown might trigger a fault in our test with only
1507
# one child, we should instead see the bad result inside our test with
1509
# the outer child test
1510
original_trace = bzrlib.trace._trace_file
1511
outer_test = TestTestCase("outer_child")
1512
result = self.make_test_result()
1513
outer_test.run(result)
1514
self.addCleanup(osutils.delete_any, outer_test._log_file_name)
1515
self.assertEqual(original_trace, bzrlib.trace._trace_file)
1517
def method_that_times_a_bit_twice(self):
1518
# call self.time twice to ensure it aggregates
1519
self.time(time.sleep, 0.007)
1520
self.time(time.sleep, 0.007)
1522
def test_time_creates_benchmark_in_result(self):
1523
"""Test that the TestCase.time() method accumulates a benchmark time."""
1524
sample_test = TestTestCase("method_that_times_a_bit_twice")
1525
output_stream = StringIO()
1526
result = bzrlib.tests.VerboseTestResult(
1527
unittest._WritelnDecorator(output_stream),
1530
sample_test.run(result)
1531
self.assertContainsRe(
1532
output_stream.getvalue(),
1535
def test_hooks_sanitised(self):
1536
"""The bzrlib hooks should be sanitised by setUp."""
1537
# Note this test won't fail with hooks that the core library doesn't
1538
# use - but it trigger with a plugin that adds hooks, so its still a
1539
# useful warning in that case.
1540
self.assertEqual(bzrlib.branch.BranchHooks(),
1541
bzrlib.branch.Branch.hooks)
1542
self.assertEqual(bzrlib.smart.server.SmartServerHooks(),
1543
bzrlib.smart.server.SmartTCPServer.hooks)
1544
self.assertEqual(bzrlib.commands.CommandHooks(),
1545
bzrlib.commands.Command.hooks)
1547
def test__gather_lsprof_in_benchmarks(self):
1548
"""When _gather_lsprof_in_benchmarks is on, accumulate profile data.
1550
Each self.time() call is individually and separately profiled.
1552
self.requireFeature(test_lsprof.LSProfFeature)
1553
# overrides the class member with an instance member so no cleanup
1555
self._gather_lsprof_in_benchmarks = True
1556
self.time(time.sleep, 0.000)
1557
self.time(time.sleep, 0.003)
1558
self.assertEqual(2, len(self._benchcalls))
1559
self.assertEqual((time.sleep, (0.000,), {}), self._benchcalls[0][0])
1560
self.assertEqual((time.sleep, (0.003,), {}), self._benchcalls[1][0])
1561
self.assertIsInstance(self._benchcalls[0][1], bzrlib.lsprof.Stats)
1562
self.assertIsInstance(self._benchcalls[1][1], bzrlib.lsprof.Stats)
1563
del self._benchcalls[:]
1565
def test_knownFailure(self):
1566
"""Self.knownFailure() should raise a KnownFailure exception."""
1567
self.assertRaises(tests.KnownFailure, self.knownFailure, "A Failure")
1569
def test_open_bzrdir_safe_roots(self):
1570
# even a memory transport should fail to open when its url isn't
1572
# Manually set one up (TestCase doesn't and shouldn't provide magic
1574
transport_server = MemoryServer()
1575
transport_server.setUp()
1576
self.addCleanup(transport_server.tearDown)
1577
t = transport.get_transport(transport_server.get_url())
1578
bzrdir.BzrDir.create(t.base)
1579
self.assertRaises(errors.BzrError,
1580
bzrdir.BzrDir.open_from_transport, t)
1581
# But if we declare this as safe, we can open the bzrdir.
1582
self.permit_url(t.base)
1583
self._bzr_selftest_roots.append(t.base)
1584
bzrdir.BzrDir.open_from_transport(t)
1586
def test_requireFeature_available(self):
1587
"""self.requireFeature(available) is a no-op."""
1588
class Available(tests.Feature):
1589
def _probe(self):return True
1590
feature = Available()
1591
self.requireFeature(feature)
1593
def test_requireFeature_unavailable(self):
1594
"""self.requireFeature(unavailable) raises UnavailableFeature."""
1595
class Unavailable(tests.Feature):
1596
def _probe(self):return False
1597
feature = Unavailable()
1598
self.assertRaises(tests.UnavailableFeature,
1599
self.requireFeature, feature)
1601
def test_run_no_parameters(self):
1602
test = SampleTestCase('_test_pass')
1605
def test_run_enabled_unittest_result(self):
1606
"""Test we revert to regular behaviour when the test is enabled."""
1607
test = SampleTestCase('_test_pass')
1608
class EnabledFeature(object):
1609
def available(self):
1611
test._test_needs_features = [EnabledFeature()]
1612
result = unittest.TestResult()
1614
self.assertEqual(1, result.testsRun)
1615
self.assertEqual([], result.errors)
1616
self.assertEqual([], result.failures)
1618
def test_run_disabled_unittest_result(self):
1619
"""Test our compatability for disabled tests with unittest results."""
1620
test = SampleTestCase('_test_pass')
1621
class DisabledFeature(object):
1622
def available(self):
1624
test._test_needs_features = [DisabledFeature()]
1625
result = unittest.TestResult()
1627
self.assertEqual(1, result.testsRun)
1628
self.assertEqual([], result.errors)
1629
self.assertEqual([], result.failures)
1631
def test_run_disabled_supporting_result(self):
1632
"""Test disabled tests behaviour with support aware results."""
1633
test = SampleTestCase('_test_pass')
1634
class DisabledFeature(object):
1635
def available(self):
1637
the_feature = DisabledFeature()
1638
test._test_needs_features = [the_feature]
1639
class InstrumentedTestResult(unittest.TestResult):
1641
unittest.TestResult.__init__(self)
1643
def startTest(self, test):
1644
self.calls.append(('startTest', test))
1645
def stopTest(self, test):
1646
self.calls.append(('stopTest', test))
1647
def addNotSupported(self, test, feature):
1648
self.calls.append(('addNotSupported', test, feature))
1649
result = InstrumentedTestResult()
1652
('startTest', test),
1653
('addNotSupported', test, the_feature),
1658
def test_start_server_registers_url(self):
1659
transport_server = MemoryServer()
1660
# A little strict, but unlikely to be changed soon.
1661
self.assertEqual([], self._bzr_selftest_roots)
1662
self.start_server(transport_server)
1663
self.assertSubset([transport_server.get_url()],
1664
self._bzr_selftest_roots)
1666
def test_assert_list_raises_on_generator(self):
1667
def generator_which_will_raise():
1668
# This will not raise until after the first yield
1670
raise _TestException()
1672
e = self.assertListRaises(_TestException, generator_which_will_raise)
1673
self.assertIsInstance(e, _TestException)
1675
e = self.assertListRaises(Exception, generator_which_will_raise)
1676
self.assertIsInstance(e, _TestException)
1678
def test_assert_list_raises_on_plain(self):
1679
def plain_exception():
1680
raise _TestException()
1683
e = self.assertListRaises(_TestException, plain_exception)
1684
self.assertIsInstance(e, _TestException)
1686
e = self.assertListRaises(Exception, plain_exception)
1687
self.assertIsInstance(e, _TestException)
1689
def test_assert_list_raises_assert_wrong_exception(self):
1690
class _NotTestException(Exception):
1693
def wrong_exception():
1694
raise _NotTestException()
1696
def wrong_exception_generator():
1699
raise _NotTestException()
1701
# Wrong exceptions are not intercepted
1702
self.assertRaises(_NotTestException,
1703
self.assertListRaises, _TestException, wrong_exception)
1704
self.assertRaises(_NotTestException,
1705
self.assertListRaises, _TestException, wrong_exception_generator)
1707
def test_assert_list_raises_no_exception(self):
1711
def success_generator():
1715
self.assertRaises(AssertionError,
1716
self.assertListRaises, _TestException, success)
1718
self.assertRaises(AssertionError,
1719
self.assertListRaises, _TestException, success_generator)
1722
# NB: Don't delete this; it's not actually from 0.11!
1723
@deprecated_function(deprecated_in((0, 11, 0)))
1724
def sample_deprecated_function():
1725
"""A deprecated function to test applyDeprecated with."""
1729
def sample_undeprecated_function(a_param):
1730
"""A undeprecated function to test applyDeprecated with."""
1733
class ApplyDeprecatedHelper(object):
1734
"""A helper class for ApplyDeprecated tests."""
1736
@deprecated_method(deprecated_in((0, 11, 0)))
1737
def sample_deprecated_method(self, param_one):
1738
"""A deprecated method for testing with."""
1741
def sample_normal_method(self):
1742
"""A undeprecated method."""
1744
@deprecated_method(deprecated_in((0, 10, 0)))
1745
def sample_nested_deprecation(self):
1746
return sample_deprecated_function()
1749
class TestExtraAssertions(tests.TestCase):
1750
"""Tests for new test assertions in bzrlib test suite"""
1752
def test_assert_isinstance(self):
1753
self.assertIsInstance(2, int)
1754
self.assertIsInstance(u'', basestring)
1755
e = self.assertRaises(AssertionError, self.assertIsInstance, None, int)
1756
self.assertEquals(str(e),
1757
"None is an instance of <type 'NoneType'> rather than <type 'int'>")
1758
self.assertRaises(AssertionError, self.assertIsInstance, 23.3, int)
1759
e = self.assertRaises(AssertionError,
1760
self.assertIsInstance, None, int, "it's just not")
1761
self.assertEquals(str(e),
1762
"None is an instance of <type 'NoneType'> rather than <type 'int'>"
1765
def test_assertEndsWith(self):
1766
self.assertEndsWith('foo', 'oo')
1767
self.assertRaises(AssertionError, self.assertEndsWith, 'o', 'oo')
1769
def test_assertEqualDiff(self):
1770
e = self.assertRaises(AssertionError,
1771
self.assertEqualDiff, '', '\n')
1772
self.assertEquals(str(e),
1773
# Don't blink ! The '+' applies to the second string
1774
'first string is missing a final newline.\n+ \n')
1775
e = self.assertRaises(AssertionError,
1776
self.assertEqualDiff, '\n', '')
1777
self.assertEquals(str(e),
1778
# Don't blink ! The '-' applies to the second string
1779
'second string is missing a final newline.\n- \n')
1782
class TestDeprecations(tests.TestCase):
1784
def test_applyDeprecated_not_deprecated(self):
1785
sample_object = ApplyDeprecatedHelper()
1786
# calling an undeprecated callable raises an assertion
1787
self.assertRaises(AssertionError, self.applyDeprecated,
1788
deprecated_in((0, 11, 0)),
1789
sample_object.sample_normal_method)
1790
self.assertRaises(AssertionError, self.applyDeprecated,
1791
deprecated_in((0, 11, 0)),
1792
sample_undeprecated_function, "a param value")
1793
# calling a deprecated callable (function or method) with the wrong
1794
# expected deprecation fails.
1795
self.assertRaises(AssertionError, self.applyDeprecated,
1796
deprecated_in((0, 10, 0)),
1797
sample_object.sample_deprecated_method, "a param value")
1798
self.assertRaises(AssertionError, self.applyDeprecated,
1799
deprecated_in((0, 10, 0)),
1800
sample_deprecated_function)
1801
# calling a deprecated callable (function or method) with the right
1802
# expected deprecation returns the functions result.
1803
self.assertEqual("a param value",
1804
self.applyDeprecated(deprecated_in((0, 11, 0)),
1805
sample_object.sample_deprecated_method, "a param value"))
1806
self.assertEqual(2, self.applyDeprecated(deprecated_in((0, 11, 0)),
1807
sample_deprecated_function))
1808
# calling a nested deprecation with the wrong deprecation version
1809
# fails even if a deeper nested function was deprecated with the
1811
self.assertRaises(AssertionError, self.applyDeprecated,
1812
deprecated_in((0, 11, 0)), sample_object.sample_nested_deprecation)
1813
# calling a nested deprecation with the right deprecation value
1814
# returns the calls result.
1815
self.assertEqual(2, self.applyDeprecated(deprecated_in((0, 10, 0)),
1816
sample_object.sample_nested_deprecation))
1818
def test_callDeprecated(self):
1819
def testfunc(be_deprecated, result=None):
1820
if be_deprecated is True:
1821
symbol_versioning.warn('i am deprecated', DeprecationWarning,
1824
result = self.callDeprecated(['i am deprecated'], testfunc, True)
1825
self.assertIs(None, result)
1826
result = self.callDeprecated([], testfunc, False, 'result')
1827
self.assertEqual('result', result)
1828
self.callDeprecated(['i am deprecated'], testfunc, be_deprecated=True)
1829
self.callDeprecated([], testfunc, be_deprecated=False)
1832
class TestWarningTests(tests.TestCase):
1833
"""Tests for calling methods that raise warnings."""
1835
def test_callCatchWarnings(self):
1837
warnings.warn("this is your last warning")
1839
wlist, result = self.callCatchWarnings(meth, 1, 2)
1840
self.assertEquals(3, result)
1841
# would like just to compare them, but UserWarning doesn't implement
1844
self.assertIsInstance(w0, UserWarning)
1845
self.assertEquals("this is your last warning", str(w0))
1848
class TestConvenienceMakers(tests.TestCaseWithTransport):
1849
"""Test for the make_* convenience functions."""
1851
def test_make_branch_and_tree_with_format(self):
1852
# we should be able to supply a format to make_branch_and_tree
1853
self.make_branch_and_tree('a', format=bzrlib.bzrdir.BzrDirMetaFormat1())
1854
self.make_branch_and_tree('b', format=bzrlib.bzrdir.BzrDirFormat6())
1855
self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('a')._format,
1856
bzrlib.bzrdir.BzrDirMetaFormat1)
1857
self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('b')._format,
1858
bzrlib.bzrdir.BzrDirFormat6)
1860
def test_make_branch_and_memory_tree(self):
1861
# we should be able to get a new branch and a mutable tree from
1862
# TestCaseWithTransport
1863
tree = self.make_branch_and_memory_tree('a')
1864
self.assertIsInstance(tree, bzrlib.memorytree.MemoryTree)
1866
def test_make_tree_for_local_vfs_backed_transport(self):
1867
# make_branch_and_tree has to use local branch and repositories
1868
# when the vfs transport and local disk are colocated, even if
1869
# a different transport is in use for url generation.
1870
from bzrlib.transport.fakevfat import FakeVFATServer
1871
self.transport_server = FakeVFATServer
1872
self.assertFalse(self.get_url('t1').startswith('file://'))
1873
tree = self.make_branch_and_tree('t1')
1874
base = tree.bzrdir.root_transport.base
1875
self.assertStartsWith(base, 'file://')
1876
self.assertEquals(tree.bzrdir.root_transport,
1877
tree.branch.bzrdir.root_transport)
1878
self.assertEquals(tree.bzrdir.root_transport,
1879
tree.branch.repository.bzrdir.root_transport)
1882
class SelfTestHelper:
1884
def run_selftest(self, **kwargs):
1885
"""Run selftest returning its output."""
1887
old_transport = bzrlib.tests.default_transport
1888
old_root = tests.TestCaseWithMemoryTransport.TEST_ROOT
1889
tests.TestCaseWithMemoryTransport.TEST_ROOT = None
1891
self.assertEqual(True, tests.selftest(stream=output, **kwargs))
1893
bzrlib.tests.default_transport = old_transport
1894
tests.TestCaseWithMemoryTransport.TEST_ROOT = old_root
1899
class TestSelftest(tests.TestCase, SelfTestHelper):
1900
"""Tests of bzrlib.tests.selftest."""
1902
def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
1905
factory_called.append(True)
1906
return TestUtil.TestSuite()
1909
self.apply_redirected(out, err, None, bzrlib.tests.selftest,
1910
test_suite_factory=factory)
1911
self.assertEqual([True], factory_called)
1914
"""A test suite factory."""
1915
class Test(tests.TestCase):
1922
return TestUtil.TestSuite([Test("a"), Test("b"), Test("c")])
1924
def test_list_only(self):
1925
output = self.run_selftest(test_suite_factory=self.factory,
1927
self.assertEqual(3, len(output.readlines()))
1929
def test_list_only_filtered(self):
1930
output = self.run_selftest(test_suite_factory=self.factory,
1931
list_only=True, pattern="Test.b")
1932
self.assertEndsWith(output.getvalue(), "Test.b\n")
1933
self.assertLength(1, output.readlines())
1935
def test_list_only_excludes(self):
1936
output = self.run_selftest(test_suite_factory=self.factory,
1937
list_only=True, exclude_pattern="Test.b")
1938
self.assertNotContainsRe("Test.b", output.getvalue())
1939
self.assertLength(2, output.readlines())
1941
def test_lsprof_tests(self):
1942
self.requireFeature(test_lsprof.LSProfFeature)
1945
def __call__(test, result):
1947
def run(test, result):
1948
self.assertIsInstance(result, tests.ForwardingResult)
1949
calls.append("called")
1950
def countTestCases(self):
1952
self.run_selftest(test_suite_factory=Test, lsprof_tests=True)
1953
self.assertLength(1, calls)
1955
def test_random(self):
1956
# test randomising by listing a number of tests.
1957
output_123 = self.run_selftest(test_suite_factory=self.factory,
1958
list_only=True, random_seed="123")
1959
output_234 = self.run_selftest(test_suite_factory=self.factory,
1960
list_only=True, random_seed="234")
1961
self.assertNotEqual(output_123, output_234)
1962
# "Randominzing test order..\n\n
1963
self.assertLength(5, output_123.readlines())
1964
self.assertLength(5, output_234.readlines())
1966
def test_random_reuse_is_same_order(self):
1967
# test randomising by listing a number of tests.
1968
expected = self.run_selftest(test_suite_factory=self.factory,
1969
list_only=True, random_seed="123")
1970
repeated = self.run_selftest(test_suite_factory=self.factory,
1971
list_only=True, random_seed="123")
1972
self.assertEqual(expected.getvalue(), repeated.getvalue())
1974
def test_runner_class(self):
1975
self.requireFeature(SubUnitFeature)
1976
from subunit import ProtocolTestCase
1977
stream = self.run_selftest(runner_class=tests.SubUnitBzrRunner,
1978
test_suite_factory=self.factory)
1979
test = ProtocolTestCase(stream)
1980
result = unittest.TestResult()
1982
self.assertEqual(3, result.testsRun)
1984
def test_starting_with_single_argument(self):
1985
output = self.run_selftest(test_suite_factory=self.factory,
1986
starting_with=['bzrlib.tests.test_selftest.Test.a'],
1988
self.assertEqual('bzrlib.tests.test_selftest.Test.a\n',
1991
def test_starting_with_multiple_argument(self):
1992
output = self.run_selftest(test_suite_factory=self.factory,
1993
starting_with=['bzrlib.tests.test_selftest.Test.a',
1994
'bzrlib.tests.test_selftest.Test.b'],
1996
self.assertEqual('bzrlib.tests.test_selftest.Test.a\n'
1997
'bzrlib.tests.test_selftest.Test.b\n',
2000
def check_transport_set(self, transport_server):
2001
captured_transport = []
2002
def seen_transport(a_transport):
2003
captured_transport.append(a_transport)
2004
class Capture(tests.TestCase):
2006
seen_transport(bzrlib.tests.default_transport)
2008
return TestUtil.TestSuite([Capture("a")])
2009
self.run_selftest(transport=transport_server, test_suite_factory=factory)
2010
self.assertEqual(transport_server, captured_transport[0])
2012
def test_transport_sftp(self):
2014
import bzrlib.transport.sftp
2015
except errors.ParamikoNotPresent:
2016
raise tests.TestSkipped("Paramiko not present")
2017
self.check_transport_set(bzrlib.transport.sftp.SFTPAbsoluteServer)
2019
def test_transport_memory(self):
2020
self.check_transport_set(bzrlib.transport.memory.MemoryServer)
2023
class TestSelftestWithIdList(tests.TestCaseInTempDir, SelfTestHelper):
2024
# Does IO: reads test.list
2026
def test_load_list(self):
2027
# Provide a list with one test - this test.
2028
test_id_line = '%s\n' % self.id()
2029
self.build_tree_contents([('test.list', test_id_line)])
2030
# And generate a list of the tests in the suite.
2031
stream = self.run_selftest(load_list='test.list', list_only=True)
2032
self.assertEqual(test_id_line, stream.getvalue())
2034
def test_load_unknown(self):
2035
# Provide a list with one test - this test.
2036
# And generate a list of the tests in the suite.
2037
err = self.assertRaises(errors.NoSuchFile, self.run_selftest,
2038
load_list='missing file name', list_only=True)
2041
class TestRunBzr(tests.TestCase):
2046
def _run_bzr_core(self, argv, retcode=0, encoding=None, stdin=None,
2048
"""Override _run_bzr_core to test how it is invoked by run_bzr.
2050
Attempts to run bzr from inside this class don't actually run it.
2052
We test how run_bzr actually invokes bzr in another location. Here we
2053
only need to test that it passes the right parameters to run_bzr.
2055
self.argv = list(argv)
2056
self.retcode = retcode
2057
self.encoding = encoding
2059
self.working_dir = working_dir
2060
return self.retcode, self.out, self.err
2062
def test_run_bzr_error(self):
2063
self.out = "It sure does!\n"
2064
out, err = self.run_bzr_error(['^$'], ['rocks'], retcode=34)
2065
self.assertEqual(['rocks'], self.argv)
2066
self.assertEqual(34, self.retcode)
2067
self.assertEqual('It sure does!\n', out)
2068
self.assertEquals(out, self.out)
2069
self.assertEqual('', err)
2070
self.assertEquals(err, self.err)
2072
def test_run_bzr_error_regexes(self):
2074
self.err = "bzr: ERROR: foobarbaz is not versioned"
2075
out, err = self.run_bzr_error(
2076
["bzr: ERROR: foobarbaz is not versioned"],
2077
['file-id', 'foobarbaz'])
2079
def test_encoding(self):
2080
"""Test that run_bzr passes encoding to _run_bzr_core"""
2081
self.run_bzr('foo bar')
2082
self.assertEqual(None, self.encoding)
2083
self.assertEqual(['foo', 'bar'], self.argv)
2085
self.run_bzr('foo bar', encoding='baz')
2086
self.assertEqual('baz', self.encoding)
2087
self.assertEqual(['foo', 'bar'], self.argv)
2089
def test_retcode(self):
2090
"""Test that run_bzr passes retcode to _run_bzr_core"""
2091
# Default is retcode == 0
2092
self.run_bzr('foo bar')
2093
self.assertEqual(0, self.retcode)
2094
self.assertEqual(['foo', 'bar'], self.argv)
2096
self.run_bzr('foo bar', retcode=1)
2097
self.assertEqual(1, self.retcode)
2098
self.assertEqual(['foo', 'bar'], self.argv)
2100
self.run_bzr('foo bar', retcode=None)
2101
self.assertEqual(None, self.retcode)
2102
self.assertEqual(['foo', 'bar'], self.argv)
2104
self.run_bzr(['foo', 'bar'], retcode=3)
2105
self.assertEqual(3, self.retcode)
2106
self.assertEqual(['foo', 'bar'], self.argv)
2108
def test_stdin(self):
2109
# test that the stdin keyword to run_bzr is passed through to
2110
# _run_bzr_core as-is. We do this by overriding
2111
# _run_bzr_core in this class, and then calling run_bzr,
2112
# which is a convenience function for _run_bzr_core, so
2114
self.run_bzr('foo bar', stdin='gam')
2115
self.assertEqual('gam', self.stdin)
2116
self.assertEqual(['foo', 'bar'], self.argv)
2118
self.run_bzr('foo bar', stdin='zippy')
2119
self.assertEqual('zippy', self.stdin)
2120
self.assertEqual(['foo', 'bar'], self.argv)
2122
def test_working_dir(self):
2123
"""Test that run_bzr passes working_dir to _run_bzr_core"""
2124
self.run_bzr('foo bar')
2125
self.assertEqual(None, self.working_dir)
2126
self.assertEqual(['foo', 'bar'], self.argv)
2128
self.run_bzr('foo bar', working_dir='baz')
2129
self.assertEqual('baz', self.working_dir)
2130
self.assertEqual(['foo', 'bar'], self.argv)
2132
def test_reject_extra_keyword_arguments(self):
2133
self.assertRaises(TypeError, self.run_bzr, "foo bar",
2134
error_regex=['error message'])
2137
class TestRunBzrCaptured(tests.TestCaseWithTransport):
2138
# Does IO when testing the working_dir parameter.
2140
def apply_redirected(self, stdin=None, stdout=None, stderr=None,
2141
a_callable=None, *args, **kwargs):
2143
self.factory_stdin = getattr(bzrlib.ui.ui_factory, "stdin", None)
2144
self.factory = bzrlib.ui.ui_factory
2145
self.working_dir = osutils.getcwd()
2146
stdout.write('foo\n')
2147
stderr.write('bar\n')
2150
def test_stdin(self):
2151
# test that the stdin keyword to _run_bzr_core is passed through to
2152
# apply_redirected as a StringIO. We do this by overriding
2153
# apply_redirected in this class, and then calling _run_bzr_core,
2154
# which calls apply_redirected.
2155
self.run_bzr(['foo', 'bar'], stdin='gam')
2156
self.assertEqual('gam', self.stdin.read())
2157
self.assertTrue(self.stdin is self.factory_stdin)
2158
self.run_bzr(['foo', 'bar'], stdin='zippy')
2159
self.assertEqual('zippy', self.stdin.read())
2160
self.assertTrue(self.stdin is self.factory_stdin)
2162
def test_ui_factory(self):
2163
# each invocation of self.run_bzr should get its
2164
# own UI factory, which is an instance of TestUIFactory,
2165
# with stdin, stdout and stderr attached to the stdin,
2166
# stdout and stderr of the invoked run_bzr
2167
current_factory = bzrlib.ui.ui_factory
2168
self.run_bzr(['foo'])
2169
self.failIf(current_factory is self.factory)
2170
self.assertNotEqual(sys.stdout, self.factory.stdout)
2171
self.assertNotEqual(sys.stderr, self.factory.stderr)
2172
self.assertEqual('foo\n', self.factory.stdout.getvalue())
2173
self.assertEqual('bar\n', self.factory.stderr.getvalue())
2174
self.assertIsInstance(self.factory, tests.TestUIFactory)
2176
def test_working_dir(self):
2177
self.build_tree(['one/', 'two/'])
2178
cwd = osutils.getcwd()
2180
# Default is to work in the current directory
2181
self.run_bzr(['foo', 'bar'])
2182
self.assertEqual(cwd, self.working_dir)
2184
self.run_bzr(['foo', 'bar'], working_dir=None)
2185
self.assertEqual(cwd, self.working_dir)
2187
# The function should be run in the alternative directory
2188
# but afterwards the current working dir shouldn't be changed
2189
self.run_bzr(['foo', 'bar'], working_dir='one')
2190
self.assertNotEqual(cwd, self.working_dir)
2191
self.assertEndsWith(self.working_dir, 'one')
2192
self.assertEqual(cwd, osutils.getcwd())
2194
self.run_bzr(['foo', 'bar'], working_dir='two')
2195
self.assertNotEqual(cwd, self.working_dir)
2196
self.assertEndsWith(self.working_dir, 'two')
2197
self.assertEqual(cwd, osutils.getcwd())
2200
class StubProcess(object):
2201
"""A stub process for testing run_bzr_subprocess."""
2203
def __init__(self, out="", err="", retcode=0):
2206
self.returncode = retcode
2208
def communicate(self):
2209
return self.out, self.err
2212
class TestWithFakedStartBzrSubprocess(tests.TestCaseWithTransport):
2213
"""Base class for tests testing how we might run bzr."""
2216
tests.TestCaseWithTransport.setUp(self)
2217
self.subprocess_calls = []
2219
def start_bzr_subprocess(self, process_args, env_changes=None,
2220
skip_if_plan_to_signal=False,
2222
allow_plugins=False):
2223
"""capture what run_bzr_subprocess tries to do."""
2224
self.subprocess_calls.append({'process_args':process_args,
2225
'env_changes':env_changes,
2226
'skip_if_plan_to_signal':skip_if_plan_to_signal,
2227
'working_dir':working_dir, 'allow_plugins':allow_plugins})
2228
return self.next_subprocess
2231
class TestRunBzrSubprocess(TestWithFakedStartBzrSubprocess):
2233
def assertRunBzrSubprocess(self, expected_args, process, *args, **kwargs):
2234
"""Run run_bzr_subprocess with args and kwargs using a stubbed process.
2236
Inside TestRunBzrSubprocessCommands we use a stub start_bzr_subprocess
2237
that will return static results. This assertion method populates those
2238
results and also checks the arguments run_bzr_subprocess generates.
2240
self.next_subprocess = process
2242
result = self.run_bzr_subprocess(*args, **kwargs)
2244
self.next_subprocess = None
2245
for key, expected in expected_args.iteritems():
2246
self.assertEqual(expected, self.subprocess_calls[-1][key])
2249
self.next_subprocess = None
2250
for key, expected in expected_args.iteritems():
2251
self.assertEqual(expected, self.subprocess_calls[-1][key])
2254
def test_run_bzr_subprocess(self):
2255
"""The run_bzr_helper_external command behaves nicely."""
2256
self.assertRunBzrSubprocess({'process_args':['--version']},
2257
StubProcess(), '--version')
2258
self.assertRunBzrSubprocess({'process_args':['--version']},
2259
StubProcess(), ['--version'])
2260
# retcode=None disables retcode checking
2261
result = self.assertRunBzrSubprocess({},
2262
StubProcess(retcode=3), '--version', retcode=None)
2263
result = self.assertRunBzrSubprocess({},
2264
StubProcess(out="is free software"), '--version')
2265
self.assertContainsRe(result[0], 'is free software')
2266
# Running a subcommand that is missing errors
2267
self.assertRaises(AssertionError, self.assertRunBzrSubprocess,
2268
{'process_args':['--versionn']}, StubProcess(retcode=3),
2270
# Unless it is told to expect the error from the subprocess
2271
result = self.assertRunBzrSubprocess({},
2272
StubProcess(retcode=3), '--versionn', retcode=3)
2273
# Or to ignore retcode checking
2274
result = self.assertRunBzrSubprocess({},
2275
StubProcess(err="unknown command", retcode=3), '--versionn',
2277
self.assertContainsRe(result[1], 'unknown command')
2279
def test_env_change_passes_through(self):
2280
self.assertRunBzrSubprocess(
2281
{'env_changes':{'new':'value', 'changed':'newvalue', 'deleted':None}},
2283
env_changes={'new':'value', 'changed':'newvalue', 'deleted':None})
2285
def test_no_working_dir_passed_as_None(self):
2286
self.assertRunBzrSubprocess({'working_dir': None}, StubProcess(), '')
2288
def test_no_working_dir_passed_through(self):
2289
self.assertRunBzrSubprocess({'working_dir': 'dir'}, StubProcess(), '',
2292
def test_run_bzr_subprocess_no_plugins(self):
2293
self.assertRunBzrSubprocess({'allow_plugins': False},
2296
def test_allow_plugins(self):
2297
self.assertRunBzrSubprocess({'allow_plugins': True},
2298
StubProcess(), '', allow_plugins=True)
2301
class TestFinishBzrSubprocess(TestWithFakedStartBzrSubprocess):
2303
def test_finish_bzr_subprocess_with_error(self):
2304
"""finish_bzr_subprocess allows specification of the desired exit code.
2306
process = StubProcess(err="unknown command", retcode=3)
2307
result = self.finish_bzr_subprocess(process, retcode=3)
2308
self.assertEqual('', result[0])
2309
self.assertContainsRe(result[1], 'unknown command')
2311
def test_finish_bzr_subprocess_ignoring_retcode(self):
2312
"""finish_bzr_subprocess allows the exit code to be ignored."""
2313
process = StubProcess(err="unknown command", retcode=3)
2314
result = self.finish_bzr_subprocess(process, retcode=None)
2315
self.assertEqual('', result[0])
2316
self.assertContainsRe(result[1], 'unknown command')
2318
def test_finish_subprocess_with_unexpected_retcode(self):
2319
"""finish_bzr_subprocess raises self.failureException if the retcode is
2320
not the expected one.
2322
process = StubProcess(err="unknown command", retcode=3)
2323
self.assertRaises(self.failureException, self.finish_bzr_subprocess,
2327
class _DontSpawnProcess(Exception):
2328
"""A simple exception which just allows us to skip unnecessary steps"""
2331
class TestStartBzrSubProcess(tests.TestCase):
2333
def check_popen_state(self):
2334
"""Replace to make assertions when popen is called."""
2336
def _popen(self, *args, **kwargs):
2337
"""Record the command that is run, so that we can ensure it is correct"""
2338
self.check_popen_state()
2339
self._popen_args = args
2340
self._popen_kwargs = kwargs
2341
raise _DontSpawnProcess()
2343
def test_run_bzr_subprocess_no_plugins(self):
2344
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [])
2345
command = self._popen_args[0]
2346
self.assertEqual(sys.executable, command[0])
2347
self.assertEqual(self.get_bzr_path(), command[1])
2348
self.assertEqual(['--no-plugins'], command[2:])
2350
def test_allow_plugins(self):
2351
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2353
command = self._popen_args[0]
2354
self.assertEqual([], command[2:])
2356
def test_set_env(self):
2357
self.failIf('EXISTANT_ENV_VAR' in os.environ)
2359
def check_environment():
2360
self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2361
self.check_popen_state = check_environment
2362
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2363
env_changes={'EXISTANT_ENV_VAR':'set variable'})
2364
# not set in theparent
2365
self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2367
def test_run_bzr_subprocess_env_del(self):
2368
"""run_bzr_subprocess can remove environment variables too."""
2369
self.failIf('EXISTANT_ENV_VAR' in os.environ)
2370
def check_environment():
2371
self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2372
os.environ['EXISTANT_ENV_VAR'] = 'set variable'
2373
self.check_popen_state = check_environment
2374
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2375
env_changes={'EXISTANT_ENV_VAR':None})
2376
# Still set in parent
2377
self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2378
del os.environ['EXISTANT_ENV_VAR']
2380
def test_env_del_missing(self):
2381
self.failIf('NON_EXISTANT_ENV_VAR' in os.environ)
2382
def check_environment():
2383
self.assertFalse('NON_EXISTANT_ENV_VAR' in os.environ)
2384
self.check_popen_state = check_environment
2385
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2386
env_changes={'NON_EXISTANT_ENV_VAR':None})
2388
def test_working_dir(self):
2389
"""Test that we can specify the working dir for the child"""
2390
orig_getcwd = osutils.getcwd
2391
orig_chdir = os.chdir
2399
osutils.getcwd = getcwd
2401
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2404
osutils.getcwd = orig_getcwd
2406
os.chdir = orig_chdir
2407
self.assertEqual(['foo', 'current'], chdirs)
2410
class TestActuallyStartBzrSubprocess(tests.TestCaseWithTransport):
2411
"""Tests that really need to do things with an external bzr."""
2413
def test_start_and_stop_bzr_subprocess_send_signal(self):
2414
"""finish_bzr_subprocess raises self.failureException if the retcode is
2415
not the expected one.
2417
self.disable_missing_extensions_warning()
2418
process = self.start_bzr_subprocess(['wait-until-signalled'],
2419
skip_if_plan_to_signal=True)
2420
self.assertEqual('running\n', process.stdout.readline())
2421
result = self.finish_bzr_subprocess(process, send_signal=signal.SIGINT,
2423
self.assertEqual('', result[0])
2424
self.assertEqual('bzr: interrupted\n', result[1])
2427
class TestKnownFailure(tests.TestCase):
2429
def test_known_failure(self):
2430
"""Check that KnownFailure is defined appropriately."""
2431
# a KnownFailure is an assertion error for compatability with unaware
2433
self.assertIsInstance(tests.KnownFailure(""), AssertionError)
2435
def test_expect_failure(self):
2437
self.expectFailure("Doomed to failure", self.assertTrue, False)
2438
except tests.KnownFailure, e:
2439
self.assertEqual('Doomed to failure', e.args[0])
2441
self.expectFailure("Doomed to failure", self.assertTrue, True)
2442
except AssertionError, e:
2443
self.assertEqual('Unexpected success. Should have failed:'
2444
' Doomed to failure', e.args[0])
2446
self.fail('Assertion not raised')
2449
class TestFeature(tests.TestCase):
2451
def test_caching(self):
2452
"""Feature._probe is called by the feature at most once."""
2453
class InstrumentedFeature(tests.Feature):
2455
super(InstrumentedFeature, self).__init__()
2458
self.calls.append('_probe')
2460
feature = InstrumentedFeature()
2462
self.assertEqual(['_probe'], feature.calls)
2464
self.assertEqual(['_probe'], feature.calls)
2466
def test_named_str(self):
2467
"""Feature.__str__ should thunk to feature_name()."""
2468
class NamedFeature(tests.Feature):
2469
def feature_name(self):
2471
feature = NamedFeature()
2472
self.assertEqual('symlinks', str(feature))
2474
def test_default_str(self):
2475
"""Feature.__str__ should default to __class__.__name__."""
2476
class NamedFeature(tests.Feature):
2478
feature = NamedFeature()
2479
self.assertEqual('NamedFeature', str(feature))
2482
class TestUnavailableFeature(tests.TestCase):
2484
def test_access_feature(self):
2485
feature = tests.Feature()
2486
exception = tests.UnavailableFeature(feature)
2487
self.assertIs(feature, exception.args[0])
2490
class TestSelftestFiltering(tests.TestCase):
2493
tests.TestCase.setUp(self)
2494
self.suite = TestUtil.TestSuite()
2495
self.loader = TestUtil.TestLoader()
2496
self.suite.addTest(self.loader.loadTestsFromModule(
2497
sys.modules['bzrlib.tests.test_selftest']))
2498
self.all_names = _test_ids(self.suite)
2500
def test_condition_id_re(self):
2501
test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2502
'test_condition_id_re')
2503
filtered_suite = tests.filter_suite_by_condition(
2504
self.suite, tests.condition_id_re('test_condition_id_re'))
2505
self.assertEqual([test_name], _test_ids(filtered_suite))
2507
def test_condition_id_in_list(self):
2508
test_names = ['bzrlib.tests.test_selftest.TestSelftestFiltering.'
2509
'test_condition_id_in_list']
2510
id_list = tests.TestIdList(test_names)
2511
filtered_suite = tests.filter_suite_by_condition(
2512
self.suite, tests.condition_id_in_list(id_list))
2513
my_pattern = 'TestSelftestFiltering.*test_condition_id_in_list'
2514
re_filtered = tests.filter_suite_by_re(self.suite, my_pattern)
2515
self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
2517
def test_condition_id_startswith(self):
2518
klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
2519
start1 = klass + 'test_condition_id_starts'
2520
start2 = klass + 'test_condition_id_in'
2521
test_names = [ klass + 'test_condition_id_in_list',
2522
klass + 'test_condition_id_startswith',
2524
filtered_suite = tests.filter_suite_by_condition(
2525
self.suite, tests.condition_id_startswith([start1, start2]))
2526
self.assertEqual(test_names, _test_ids(filtered_suite))
2528
def test_condition_isinstance(self):
2529
filtered_suite = tests.filter_suite_by_condition(
2530
self.suite, tests.condition_isinstance(self.__class__))
2531
class_pattern = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
2532
re_filtered = tests.filter_suite_by_re(self.suite, class_pattern)
2533
self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
2535
def test_exclude_tests_by_condition(self):
2536
excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2537
'test_exclude_tests_by_condition')
2538
filtered_suite = tests.exclude_tests_by_condition(self.suite,
2539
lambda x:x.id() == excluded_name)
2540
self.assertEqual(len(self.all_names) - 1,
2541
filtered_suite.countTestCases())
2542
self.assertFalse(excluded_name in _test_ids(filtered_suite))
2543
remaining_names = list(self.all_names)
2544
remaining_names.remove(excluded_name)
2545
self.assertEqual(remaining_names, _test_ids(filtered_suite))
2547
def test_exclude_tests_by_re(self):
2548
self.all_names = _test_ids(self.suite)
2549
filtered_suite = tests.exclude_tests_by_re(self.suite,
2550
'exclude_tests_by_re')
2551
excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2552
'test_exclude_tests_by_re')
2553
self.assertEqual(len(self.all_names) - 1,
2554
filtered_suite.countTestCases())
2555
self.assertFalse(excluded_name in _test_ids(filtered_suite))
2556
remaining_names = list(self.all_names)
2557
remaining_names.remove(excluded_name)
2558
self.assertEqual(remaining_names, _test_ids(filtered_suite))
2560
def test_filter_suite_by_condition(self):
2561
test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2562
'test_filter_suite_by_condition')
2563
filtered_suite = tests.filter_suite_by_condition(self.suite,
2564
lambda x:x.id() == test_name)
2565
self.assertEqual([test_name], _test_ids(filtered_suite))
2567
def test_filter_suite_by_re(self):
2568
filtered_suite = tests.filter_suite_by_re(self.suite,
2569
'test_filter_suite_by_r')
2570
filtered_names = _test_ids(filtered_suite)
2571
self.assertEqual(filtered_names, ['bzrlib.tests.test_selftest.'
2572
'TestSelftestFiltering.test_filter_suite_by_re'])
2574
def test_filter_suite_by_id_list(self):
2575
test_list = ['bzrlib.tests.test_selftest.'
2576
'TestSelftestFiltering.test_filter_suite_by_id_list']
2577
filtered_suite = tests.filter_suite_by_id_list(
2578
self.suite, tests.TestIdList(test_list))
2579
filtered_names = _test_ids(filtered_suite)
2582
['bzrlib.tests.test_selftest.'
2583
'TestSelftestFiltering.test_filter_suite_by_id_list'])
2585
def test_filter_suite_by_id_startswith(self):
2586
# By design this test may fail if another test is added whose name also
2587
# begins with one of the start value used.
2588
klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
2589
start1 = klass + 'test_filter_suite_by_id_starts'
2590
start2 = klass + 'test_filter_suite_by_id_li'
2591
test_list = [klass + 'test_filter_suite_by_id_list',
2592
klass + 'test_filter_suite_by_id_startswith',
2594
filtered_suite = tests.filter_suite_by_id_startswith(
2595
self.suite, [start1, start2])
2598
_test_ids(filtered_suite),
2601
def test_preserve_input(self):
2602
# NB: Surely this is something in the stdlib to do this?
2603
self.assertTrue(self.suite is tests.preserve_input(self.suite))
2604
self.assertTrue("@#$" is tests.preserve_input("@#$"))
2606
def test_randomize_suite(self):
2607
randomized_suite = tests.randomize_suite(self.suite)
2608
# randomizing should not add or remove test names.
2609
self.assertEqual(set(_test_ids(self.suite)),
2610
set(_test_ids(randomized_suite)))
2611
# Technically, this *can* fail, because random.shuffle(list) can be
2612
# equal to list. Trying multiple times just pushes the frequency back.
2613
# As its len(self.all_names)!:1, the failure frequency should be low
2614
# enough to ignore. RBC 20071021.
2615
# It should change the order.
2616
self.assertNotEqual(self.all_names, _test_ids(randomized_suite))
2617
# But not the length. (Possibly redundant with the set test, but not
2619
self.assertEqual(len(self.all_names), len(_test_ids(randomized_suite)))
2621
def test_split_suit_by_condition(self):
2622
self.all_names = _test_ids(self.suite)
2623
condition = tests.condition_id_re('test_filter_suite_by_r')
2624
split_suite = tests.split_suite_by_condition(self.suite, condition)
2625
filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2626
'test_filter_suite_by_re')
2627
self.assertEqual([filtered_name], _test_ids(split_suite[0]))
2628
self.assertFalse(filtered_name in _test_ids(split_suite[1]))
2629
remaining_names = list(self.all_names)
2630
remaining_names.remove(filtered_name)
2631
self.assertEqual(remaining_names, _test_ids(split_suite[1]))
2633
def test_split_suit_by_re(self):
2634
self.all_names = _test_ids(self.suite)
2635
split_suite = tests.split_suite_by_re(self.suite,
2636
'test_filter_suite_by_r')
2637
filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2638
'test_filter_suite_by_re')
2639
self.assertEqual([filtered_name], _test_ids(split_suite[0]))
2640
self.assertFalse(filtered_name in _test_ids(split_suite[1]))
2641
remaining_names = list(self.all_names)
2642
remaining_names.remove(filtered_name)
2643
self.assertEqual(remaining_names, _test_ids(split_suite[1]))
2646
class TestCheckInventoryShape(tests.TestCaseWithTransport):
2648
def test_check_inventory_shape(self):
2649
files = ['a', 'b/', 'b/c']
2650
tree = self.make_branch_and_tree('.')
2651
self.build_tree(files)
2655
self.check_inventory_shape(tree.inventory, files)
2660
class TestBlackboxSupport(tests.TestCase):
2661
"""Tests for testsuite blackbox features."""
2663
def test_run_bzr_failure_not_caught(self):
2664
# When we run bzr in blackbox mode, we want any unexpected errors to
2665
# propagate up to the test suite so that it can show the error in the
2666
# usual way, and we won't get a double traceback.
2667
e = self.assertRaises(
2669
self.run_bzr, ['assert-fail'])
2670
# make sure we got the real thing, not an error from somewhere else in
2671
# the test framework
2672
self.assertEquals('always fails', str(e))
2673
# check that there's no traceback in the test log
2674
self.assertNotContainsRe(self._get_log(keep_log_file=True),
2677
def test_run_bzr_user_error_caught(self):
2678
# Running bzr in blackbox mode, normal/expected/user errors should be
2679
# caught in the regular way and turned into an error message plus exit
2681
transport_server = MemoryServer()
2682
transport_server.setUp()
2683
self.addCleanup(transport_server.tearDown)
2684
url = transport_server.get_url()
2685
self.permit_url(url)
2686
out, err = self.run_bzr(["log", "%s/nonexistantpath" % url], retcode=3)
2687
self.assertEqual(out, '')
2688
self.assertContainsRe(err,
2689
'bzr: ERROR: Not a branch: ".*nonexistantpath/".\n')
2692
class TestTestLoader(tests.TestCase):
2693
"""Tests for the test loader."""
2695
def _get_loader_and_module(self):
2696
"""Gets a TestLoader and a module with one test in it."""
2697
loader = TestUtil.TestLoader()
2699
class Stub(tests.TestCase):
2702
class MyModule(object):
2704
MyModule.a_class = Stub
2706
return loader, module
2708
def test_module_no_load_tests_attribute_loads_classes(self):
2709
loader, module = self._get_loader_and_module()
2710
self.assertEqual(1, loader.loadTestsFromModule(module).countTestCases())
2712
def test_module_load_tests_attribute_gets_called(self):
2713
loader, module = self._get_loader_and_module()
2714
# 'self' is here because we're faking the module with a class. Regular
2715
# load_tests do not need that :)
2716
def load_tests(self, standard_tests, module, loader):
2717
result = loader.suiteClass()
2718
for test in tests.iter_suite_tests(standard_tests):
2719
result.addTests([test, test])
2721
# add a load_tests() method which multiplies the tests from the module.
2722
module.__class__.load_tests = load_tests
2723
self.assertEqual(2, loader.loadTestsFromModule(module).countTestCases())
2725
def test_load_tests_from_module_name_smoke_test(self):
2726
loader = TestUtil.TestLoader()
2727
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2728
self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
2731
def test_load_tests_from_module_name_with_bogus_module_name(self):
2732
loader = TestUtil.TestLoader()
2733
self.assertRaises(ImportError, loader.loadTestsFromModuleName, 'bogus')
2736
class TestTestIdList(tests.TestCase):
2738
def _create_id_list(self, test_list):
2739
return tests.TestIdList(test_list)
2741
def _create_suite(self, test_id_list):
2743
class Stub(tests.TestCase):
2747
def _create_test_id(id):
2750
suite = TestUtil.TestSuite()
2751
for id in test_id_list:
2752
t = Stub('test_foo')
2753
t.id = _create_test_id(id)
2757
def _test_ids(self, test_suite):
2758
"""Get the ids for the tests in a test suite."""
2759
return [t.id() for t in tests.iter_suite_tests(test_suite)]
2761
def test_empty_list(self):
2762
id_list = self._create_id_list([])
2763
self.assertEquals({}, id_list.tests)
2764
self.assertEquals({}, id_list.modules)
2766
def test_valid_list(self):
2767
id_list = self._create_id_list(
2768
['mod1.cl1.meth1', 'mod1.cl1.meth2',
2769
'mod1.func1', 'mod1.cl2.meth2',
2771
'mod1.submod2.cl1.meth1', 'mod1.submod2.cl2.meth2',
2773
self.assertTrue(id_list.refers_to('mod1'))
2774
self.assertTrue(id_list.refers_to('mod1.submod1'))
2775
self.assertTrue(id_list.refers_to('mod1.submod2'))
2776
self.assertTrue(id_list.includes('mod1.cl1.meth1'))
2777
self.assertTrue(id_list.includes('mod1.submod1'))
2778
self.assertTrue(id_list.includes('mod1.func1'))
2780
def test_bad_chars_in_params(self):
2781
id_list = self._create_id_list(['mod1.cl1.meth1(xx.yy)'])
2782
self.assertTrue(id_list.refers_to('mod1'))
2783
self.assertTrue(id_list.includes('mod1.cl1.meth1(xx.yy)'))
2785
def test_module_used(self):
2786
id_list = self._create_id_list(['mod.class.meth'])
2787
self.assertTrue(id_list.refers_to('mod'))
2788
self.assertTrue(id_list.refers_to('mod.class'))
2789
self.assertTrue(id_list.refers_to('mod.class.meth'))
2791
def test_test_suite_matches_id_list_with_unknown(self):
2792
loader = TestUtil.TestLoader()
2793
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2794
test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',
2796
not_found, duplicates = tests.suite_matches_id_list(suite, test_list)
2797
self.assertEquals(['bogus'], not_found)
2798
self.assertEquals([], duplicates)
2800
def test_suite_matches_id_list_with_duplicates(self):
2801
loader = TestUtil.TestLoader()
2802
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2803
dupes = loader.suiteClass()
2804
for test in tests.iter_suite_tests(suite):
2806
dupes.addTest(test) # Add it again
2808
test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',]
2809
not_found, duplicates = tests.suite_matches_id_list(
2811
self.assertEquals([], not_found)
2812
self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
2816
class TestTestSuite(tests.TestCase):
2818
def test__test_suite_testmod_names(self):
2819
# Test that a plausible list of test module names are returned
2820
# by _test_suite_testmod_names.
2821
test_list = tests._test_suite_testmod_names()
2823
'bzrlib.tests.blackbox',
2824
'bzrlib.tests.per_transport',
2825
'bzrlib.tests.test_selftest',
2829
def test__test_suite_modules_to_doctest(self):
2830
# Test that a plausible list of modules to doctest is returned
2831
# by _test_suite_modules_to_doctest.
2832
test_list = tests._test_suite_modules_to_doctest()
2838
def test_test_suite(self):
2839
# test_suite() loads the entire test suite to operate. To avoid this
2840
# overhead, and yet still be confident that things are happening,
2841
# we temporarily replace two functions used by test_suite with
2842
# test doubles that supply a few sample tests to load, and check they
2845
def _test_suite_testmod_names():
2846
calls.append("testmod_names")
2848
'bzrlib.tests.blackbox.test_branch',
2849
'bzrlib.tests.per_transport',
2850
'bzrlib.tests.test_selftest',
2852
original_testmod_names = tests._test_suite_testmod_names
2853
def _test_suite_modules_to_doctest():
2854
calls.append("modules_to_doctest")
2855
return ['bzrlib.timestamp']
2856
orig_modules_to_doctest = tests._test_suite_modules_to_doctest
2857
def restore_names():
2858
tests._test_suite_testmod_names = original_testmod_names
2859
tests._test_suite_modules_to_doctest = orig_modules_to_doctest
2860
self.addCleanup(restore_names)
2861
tests._test_suite_testmod_names = _test_suite_testmod_names
2862
tests._test_suite_modules_to_doctest = _test_suite_modules_to_doctest
2863
expected_test_list = [
2865
'bzrlib.tests.blackbox.test_branch.TestBranch.test_branch',
2866
('bzrlib.tests.per_transport.TransportTests'
2867
'.test_abspath(LocalTransport,LocalURLServer)'),
2868
'bzrlib.tests.test_selftest.TestTestSuite.test_test_suite',
2869
# modules_to_doctest
2870
'bzrlib.timestamp.format_highres_date',
2871
# plugins can't be tested that way since selftest may be run with
2874
suite = tests.test_suite()
2875
self.assertEqual(set(["testmod_names", "modules_to_doctest"]),
2877
self.assertSubset(expected_test_list, _test_ids(suite))
2879
def test_test_suite_list_and_start(self):
2880
# We cannot test this at the same time as the main load, because we want
2881
# to know that starting_with == None works. So a second load is
2882
# incurred - note that the starting_with parameter causes a partial load
2883
# rather than a full load so this test should be pretty quick.
2884
test_list = ['bzrlib.tests.test_selftest.TestTestSuite.test_test_suite']
2885
suite = tests.test_suite(test_list,
2886
['bzrlib.tests.test_selftest.TestTestSuite'])
2887
# test_test_suite_list_and_start is not included
2888
self.assertEquals(test_list, _test_ids(suite))
2891
class TestLoadTestIdList(tests.TestCaseInTempDir):
2893
def _create_test_list_file(self, file_name, content):
2894
fl = open(file_name, 'wt')
2898
def test_load_unknown(self):
2899
self.assertRaises(errors.NoSuchFile,
2900
tests.load_test_id_list, 'i_do_not_exist')
2902
def test_load_test_list(self):
2903
test_list_fname = 'test.list'
2904
self._create_test_list_file(test_list_fname,
2905
'mod1.cl1.meth1\nmod2.cl2.meth2\n')
2906
tlist = tests.load_test_id_list(test_list_fname)
2907
self.assertEquals(2, len(tlist))
2908
self.assertEquals('mod1.cl1.meth1', tlist[0])
2909
self.assertEquals('mod2.cl2.meth2', tlist[1])
2911
def test_load_dirty_file(self):
2912
test_list_fname = 'test.list'
2913
self._create_test_list_file(test_list_fname,
2914
' mod1.cl1.meth1\n\nmod2.cl2.meth2 \n'
2916
tlist = tests.load_test_id_list(test_list_fname)
2917
self.assertEquals(4, len(tlist))
2918
self.assertEquals('mod1.cl1.meth1', tlist[0])
2919
self.assertEquals('', tlist[1])
2920
self.assertEquals('mod2.cl2.meth2', tlist[2])
2921
self.assertEquals('bar baz', tlist[3])
2924
class TestFilteredByModuleTestLoader(tests.TestCase):
2926
def _create_loader(self, test_list):
2927
id_filter = tests.TestIdList(test_list)
2928
loader = TestUtil.FilteredByModuleTestLoader(id_filter.refers_to)
2931
def test_load_tests(self):
2932
test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
2933
loader = self._create_loader(test_list)
2935
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2936
self.assertEquals(test_list, _test_ids(suite))
2938
def test_exclude_tests(self):
2939
test_list = ['bogus']
2940
loader = self._create_loader(test_list)
2942
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2943
self.assertEquals([], _test_ids(suite))
2946
class TestFilteredByNameStartTestLoader(tests.TestCase):
2948
def _create_loader(self, name_start):
2949
def needs_module(name):
2950
return name.startswith(name_start) or name_start.startswith(name)
2951
loader = TestUtil.FilteredByModuleTestLoader(needs_module)
2954
def test_load_tests(self):
2955
test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
2956
loader = self._create_loader('bzrlib.tests.test_samp')
2958
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2959
self.assertEquals(test_list, _test_ids(suite))
2961
def test_load_tests_inside_module(self):
2962
test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
2963
loader = self._create_loader('bzrlib.tests.test_sampler.Demo')
2965
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2966
self.assertEquals(test_list, _test_ids(suite))
2968
def test_exclude_tests(self):
2969
test_list = ['bogus']
2970
loader = self._create_loader('bogus')
2972
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2973
self.assertEquals([], _test_ids(suite))
2976
class TestTestPrefixRegistry(tests.TestCase):
2978
def _get_registry(self):
2979
tp_registry = tests.TestPrefixAliasRegistry()
2982
def test_register_new_prefix(self):
2983
tpr = self._get_registry()
2984
tpr.register('foo', 'fff.ooo.ooo')
2985
self.assertEquals('fff.ooo.ooo', tpr.get('foo'))
2987
def test_register_existing_prefix(self):
2988
tpr = self._get_registry()
2989
tpr.register('bar', 'bbb.aaa.rrr')
2990
tpr.register('bar', 'bBB.aAA.rRR')
2991
self.assertEquals('bbb.aaa.rrr', tpr.get('bar'))
2992
self.assertContainsRe(self._get_log(keep_log_file=True),
2993
r'.*bar.*bbb.aaa.rrr.*bBB.aAA.rRR')
2995
def test_get_unknown_prefix(self):
2996
tpr = self._get_registry()
2997
self.assertRaises(KeyError, tpr.get, 'I am not a prefix')
2999
def test_resolve_prefix(self):
3000
tpr = self._get_registry()
3001
tpr.register('bar', 'bb.aa.rr')
3002
self.assertEquals('bb.aa.rr', tpr.resolve_alias('bar'))
3004
def test_resolve_unknown_alias(self):
3005
tpr = self._get_registry()
3006
self.assertRaises(errors.BzrCommandError,
3007
tpr.resolve_alias, 'I am not a prefix')
3009
def test_predefined_prefixes(self):
3010
tpr = tests.test_prefix_alias_registry
3011
self.assertEquals('bzrlib', tpr.resolve_alias('bzrlib'))
3012
self.assertEquals('bzrlib.doc', tpr.resolve_alias('bd'))
3013
self.assertEquals('bzrlib.utils', tpr.resolve_alias('bu'))
3014
self.assertEquals('bzrlib.tests', tpr.resolve_alias('bt'))
3015
self.assertEquals('bzrlib.tests.blackbox', tpr.resolve_alias('bb'))
3016
self.assertEquals('bzrlib.plugins', tpr.resolve_alias('bp'))
3019
class TestRunSuite(tests.TestCase):
3021
def test_runner_class(self):
3022
"""run_suite accepts and uses a runner_class keyword argument."""
3023
class Stub(tests.TestCase):
3026
suite = Stub("test_foo")
3028
class MyRunner(tests.TextTestRunner):
3029
def run(self, test):
3031
return tests.ExtendedTestResult(self.stream, self.descriptions,
3033
tests.run_suite(suite, runner_class=MyRunner, stream=StringIO())
3034
self.assertLength(1, calls)