1
# Copyright (C) 2005-2010 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
20
from doctest import ELLIPSIS
28
from testtools import MultiTestResult
29
from testtools.content_type import ContentType
30
from testtools.matchers import (
34
import testtools.tests.helpers
53
from bzrlib.repofmt import (
58
from bzrlib.symbol_versioning import (
63
from bzrlib.tests import (
70
from bzrlib.trace import note
71
from bzrlib.transport import memory
72
from bzrlib.version import _get_bzr_source_tree
75
def _test_ids(test_suite):
76
"""Get the ids for the tests in a test suite."""
77
return [t.id() for t in tests.iter_suite_tests(test_suite)]
80
class SelftestTests(tests.TestCase):
82
def test_import_tests(self):
83
mod = TestUtil._load_module_by_name('bzrlib.tests.test_selftest')
84
self.assertEqual(mod.SelftestTests, SelftestTests)
86
def test_import_test_failure(self):
87
self.assertRaises(ImportError,
88
TestUtil._load_module_by_name,
92
class MetaTestLog(tests.TestCase):
94
def test_logging(self):
95
"""Test logs are captured when a test fails."""
96
self.log('a test message')
97
details = self.getDetails()
99
self.assertThat(log.content_type, Equals(ContentType(
100
"text", "plain", {"charset": "utf8"})))
101
self.assertThat(u"".join(log.iter_text()), Equals(self.get_log()))
102
self.assertThat(self.get_log(),
103
DocTestMatches(u"...a test message\n", ELLIPSIS))
106
class TestUnicodeFilename(tests.TestCase):
108
def test_probe_passes(self):
109
"""UnicodeFilename._probe passes."""
110
# We can't test much more than that because the behaviour depends
112
tests.UnicodeFilename._probe()
115
class TestTreeShape(tests.TestCaseInTempDir):
117
def test_unicode_paths(self):
118
self.requireFeature(tests.UnicodeFilename)
120
filename = u'hell\u00d8'
121
self.build_tree_contents([(filename, 'contents of hello')])
122
self.failUnlessExists(filename)
125
class TestTransportScenarios(tests.TestCase):
126
"""A group of tests that test the transport implementation adaption core.
128
This is a meta test that the tests are applied to all available
131
This will be generalised in the future which is why it is in this
132
test file even though it is specific to transport tests at the moment.
135
def test_get_transport_permutations(self):
136
# this checks that get_test_permutations defined by the module is
137
# called by the get_transport_test_permutations function.
138
class MockModule(object):
139
def get_test_permutations(self):
140
return sample_permutation
141
sample_permutation = [(1,2), (3,4)]
142
from bzrlib.tests.per_transport import get_transport_test_permutations
143
self.assertEqual(sample_permutation,
144
get_transport_test_permutations(MockModule()))
146
def test_scenarios_include_all_modules(self):
147
# this checks that the scenario generator returns as many permutations
148
# as there are in all the registered transport modules - we assume if
149
# this matches its probably doing the right thing especially in
150
# combination with the tests for setting the right classes below.
151
from bzrlib.tests.per_transport import transport_test_permutations
152
from bzrlib.transport import _get_transport_modules
153
modules = _get_transport_modules()
154
permutation_count = 0
155
for module in modules:
157
permutation_count += len(reduce(getattr,
158
(module + ".get_test_permutations").split('.')[1:],
159
__import__(module))())
160
except errors.DependencyNotPresent:
162
scenarios = transport_test_permutations()
163
self.assertEqual(permutation_count, len(scenarios))
165
def test_scenarios_include_transport_class(self):
166
# This test used to know about all the possible transports and the
167
# order they were returned but that seems overly brittle (mbp
169
from bzrlib.tests.per_transport import transport_test_permutations
170
scenarios = transport_test_permutations()
171
# there are at least that many builtin transports
172
self.assertTrue(len(scenarios) > 6)
173
one_scenario = scenarios[0]
174
self.assertIsInstance(one_scenario[0], str)
175
self.assertTrue(issubclass(one_scenario[1]["transport_class"],
176
bzrlib.transport.Transport))
177
self.assertTrue(issubclass(one_scenario[1]["transport_server"],
178
bzrlib.transport.Server))
181
class TestBranchScenarios(tests.TestCase):
183
def test_scenarios(self):
184
# check that constructor parameters are passed through to the adapted
186
from bzrlib.tests.per_branch import make_scenarios
189
formats = [("c", "C"), ("d", "D")]
190
scenarios = make_scenarios(server1, server2, formats)
191
self.assertEqual(2, len(scenarios))
194
{'branch_format': 'c',
195
'bzrdir_format': 'C',
196
'transport_readonly_server': 'b',
197
'transport_server': 'a'}),
199
{'branch_format': 'd',
200
'bzrdir_format': 'D',
201
'transport_readonly_server': 'b',
202
'transport_server': 'a'})],
206
class TestBzrDirScenarios(tests.TestCase):
208
def test_scenarios(self):
209
# check that constructor parameters are passed through to the adapted
211
from bzrlib.tests.per_bzrdir import make_scenarios
216
scenarios = make_scenarios(vfs_factory, server1, server2, formats)
219
{'bzrdir_format': 'c',
220
'transport_readonly_server': 'b',
221
'transport_server': 'a',
222
'vfs_transport_factory': 'v'}),
224
{'bzrdir_format': 'd',
225
'transport_readonly_server': 'b',
226
'transport_server': 'a',
227
'vfs_transport_factory': 'v'})],
231
class TestRepositoryScenarios(tests.TestCase):
233
def test_formats_to_scenarios(self):
234
from bzrlib.tests.per_repository import formats_to_scenarios
235
formats = [("(c)", remote.RemoteRepositoryFormat()),
236
("(d)", repository.format_registry.get(
237
'Bazaar repository format 2a (needs bzr 1.16 or later)\n'))]
238
no_vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
240
vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
241
vfs_transport_factory="vfs")
242
# no_vfs generate scenarios without vfs_transport_factory
244
('RemoteRepositoryFormat(c)',
245
{'bzrdir_format': remote.RemoteBzrDirFormat(),
246
'repository_format': remote.RemoteRepositoryFormat(),
247
'transport_readonly_server': 'readonly',
248
'transport_server': 'server'}),
249
('RepositoryFormat2a(d)',
250
{'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
251
'repository_format': groupcompress_repo.RepositoryFormat2a(),
252
'transport_readonly_server': 'readonly',
253
'transport_server': 'server'})]
254
self.assertEqual(expected, no_vfs_scenarios)
256
('RemoteRepositoryFormat(c)',
257
{'bzrdir_format': remote.RemoteBzrDirFormat(),
258
'repository_format': remote.RemoteRepositoryFormat(),
259
'transport_readonly_server': 'readonly',
260
'transport_server': 'server',
261
'vfs_transport_factory': 'vfs'}),
262
('RepositoryFormat2a(d)',
263
{'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
264
'repository_format': groupcompress_repo.RepositoryFormat2a(),
265
'transport_readonly_server': 'readonly',
266
'transport_server': 'server',
267
'vfs_transport_factory': 'vfs'})],
271
class TestTestScenarioApplication(tests.TestCase):
272
"""Tests for the test adaption facilities."""
274
def test_apply_scenario(self):
275
from bzrlib.tests import apply_scenario
276
input_test = TestTestScenarioApplication("test_apply_scenario")
277
# setup two adapted tests
278
adapted_test1 = apply_scenario(input_test,
280
{"bzrdir_format":"bzr_format",
281
"repository_format":"repo_fmt",
282
"transport_server":"transport_server",
283
"transport_readonly_server":"readonly-server"}))
284
adapted_test2 = apply_scenario(input_test,
285
("new id 2", {"bzrdir_format":None}))
286
# input_test should have been altered.
287
self.assertRaises(AttributeError, getattr, input_test, "bzrdir_format")
288
# the new tests are mutually incompatible, ensuring it has
289
# made new ones, and unspecified elements in the scenario
290
# should not have been altered.
291
self.assertEqual("bzr_format", adapted_test1.bzrdir_format)
292
self.assertEqual("repo_fmt", adapted_test1.repository_format)
293
self.assertEqual("transport_server", adapted_test1.transport_server)
294
self.assertEqual("readonly-server",
295
adapted_test1.transport_readonly_server)
297
"bzrlib.tests.test_selftest.TestTestScenarioApplication."
298
"test_apply_scenario(new id)",
300
self.assertEqual(None, adapted_test2.bzrdir_format)
302
"bzrlib.tests.test_selftest.TestTestScenarioApplication."
303
"test_apply_scenario(new id 2)",
307
class TestInterRepositoryScenarios(tests.TestCase):
309
def test_scenarios(self):
310
# check that constructor parameters are passed through to the adapted
312
from bzrlib.tests.per_interrepository import make_scenarios
315
formats = [("C0", "C1", "C2"), ("D0", "D1", "D2")]
316
scenarios = make_scenarios(server1, server2, formats)
319
{'repository_format': 'C1',
320
'repository_format_to': 'C2',
321
'transport_readonly_server': 'b',
322
'transport_server': 'a'}),
324
{'repository_format': 'D1',
325
'repository_format_to': 'D2',
326
'transport_readonly_server': 'b',
327
'transport_server': 'a'})],
331
class TestWorkingTreeScenarios(tests.TestCase):
333
def test_scenarios(self):
334
# check that constructor parameters are passed through to the adapted
336
from bzrlib.tests.per_workingtree import make_scenarios
339
formats = [workingtree.WorkingTreeFormat2(),
340
workingtree.WorkingTreeFormat3(),]
341
scenarios = make_scenarios(server1, server2, formats)
343
('WorkingTreeFormat2',
344
{'bzrdir_format': formats[0]._matchingbzrdir,
345
'transport_readonly_server': 'b',
346
'transport_server': 'a',
347
'workingtree_format': formats[0]}),
348
('WorkingTreeFormat3',
349
{'bzrdir_format': formats[1]._matchingbzrdir,
350
'transport_readonly_server': 'b',
351
'transport_server': 'a',
352
'workingtree_format': formats[1]})],
356
class TestTreeScenarios(tests.TestCase):
358
def test_scenarios(self):
359
# the tree implementation scenario generator is meant to setup one
360
# instance for each working tree format, and one additional instance
361
# that will use the default wt format, but create a revision tree for
362
# the tests. this means that the wt ones should have the
363
# workingtree_to_test_tree attribute set to 'return_parameter' and the
364
# revision one set to revision_tree_from_workingtree.
366
from bzrlib.tests.per_tree import (
367
_dirstate_tree_from_workingtree,
372
revision_tree_from_workingtree
376
formats = [workingtree.WorkingTreeFormat2(),
377
workingtree.WorkingTreeFormat3(),]
378
scenarios = make_scenarios(server1, server2, formats)
379
self.assertEqual(7, len(scenarios))
380
default_wt_format = workingtree.WorkingTreeFormat4._default_format
381
wt4_format = workingtree.WorkingTreeFormat4()
382
wt5_format = workingtree.WorkingTreeFormat5()
383
expected_scenarios = [
384
('WorkingTreeFormat2',
385
{'bzrdir_format': formats[0]._matchingbzrdir,
386
'transport_readonly_server': 'b',
387
'transport_server': 'a',
388
'workingtree_format': formats[0],
389
'_workingtree_to_test_tree': return_parameter,
391
('WorkingTreeFormat3',
392
{'bzrdir_format': formats[1]._matchingbzrdir,
393
'transport_readonly_server': 'b',
394
'transport_server': 'a',
395
'workingtree_format': formats[1],
396
'_workingtree_to_test_tree': return_parameter,
399
{'_workingtree_to_test_tree': revision_tree_from_workingtree,
400
'bzrdir_format': default_wt_format._matchingbzrdir,
401
'transport_readonly_server': 'b',
402
'transport_server': 'a',
403
'workingtree_format': default_wt_format,
405
('DirStateRevisionTree,WT4',
406
{'_workingtree_to_test_tree': _dirstate_tree_from_workingtree,
407
'bzrdir_format': wt4_format._matchingbzrdir,
408
'transport_readonly_server': 'b',
409
'transport_server': 'a',
410
'workingtree_format': wt4_format,
412
('DirStateRevisionTree,WT5',
413
{'_workingtree_to_test_tree': _dirstate_tree_from_workingtree,
414
'bzrdir_format': wt5_format._matchingbzrdir,
415
'transport_readonly_server': 'b',
416
'transport_server': 'a',
417
'workingtree_format': wt5_format,
420
{'_workingtree_to_test_tree': preview_tree_pre,
421
'bzrdir_format': default_wt_format._matchingbzrdir,
422
'transport_readonly_server': 'b',
423
'transport_server': 'a',
424
'workingtree_format': default_wt_format}),
426
{'_workingtree_to_test_tree': preview_tree_post,
427
'bzrdir_format': default_wt_format._matchingbzrdir,
428
'transport_readonly_server': 'b',
429
'transport_server': 'a',
430
'workingtree_format': default_wt_format}),
432
self.assertEqual(expected_scenarios, scenarios)
435
class TestInterTreeScenarios(tests.TestCase):
436
"""A group of tests that test the InterTreeTestAdapter."""
438
def test_scenarios(self):
439
# check that constructor parameters are passed through to the adapted
441
# for InterTree tests we want the machinery to bring up two trees in
442
# each instance: the base one, and the one we are interacting with.
443
# because each optimiser can be direction specific, we need to test
444
# each optimiser in its chosen direction.
445
# unlike the TestProviderAdapter we dont want to automatically add a
446
# parameterized one for WorkingTree - the optimisers will tell us what
448
from bzrlib.tests.per_tree import (
450
revision_tree_from_workingtree
452
from bzrlib.tests.per_intertree import (
455
from bzrlib.workingtree import WorkingTreeFormat2, WorkingTreeFormat3
456
input_test = TestInterTreeScenarios(
460
format1 = WorkingTreeFormat2()
461
format2 = WorkingTreeFormat3()
462
formats = [("1", str, format1, format2, "converter1"),
463
("2", int, format2, format1, "converter2")]
464
scenarios = make_scenarios(server1, server2, formats)
465
self.assertEqual(2, len(scenarios))
466
expected_scenarios = [
468
"bzrdir_format": format1._matchingbzrdir,
469
"intertree_class": formats[0][1],
470
"workingtree_format": formats[0][2],
471
"workingtree_format_to": formats[0][3],
472
"mutable_trees_to_test_trees": formats[0][4],
473
"_workingtree_to_test_tree": return_parameter,
474
"transport_server": server1,
475
"transport_readonly_server": server2,
478
"bzrdir_format": format2._matchingbzrdir,
479
"intertree_class": formats[1][1],
480
"workingtree_format": formats[1][2],
481
"workingtree_format_to": formats[1][3],
482
"mutable_trees_to_test_trees": formats[1][4],
483
"_workingtree_to_test_tree": return_parameter,
484
"transport_server": server1,
485
"transport_readonly_server": server2,
488
self.assertEqual(scenarios, expected_scenarios)
491
class TestTestCaseInTempDir(tests.TestCaseInTempDir):
493
def test_home_is_not_working(self):
494
self.assertNotEqual(self.test_dir, self.test_home_dir)
495
cwd = osutils.getcwd()
496
self.assertIsSameRealPath(self.test_dir, cwd)
497
self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
499
def test_assertEqualStat_equal(self):
500
from bzrlib.tests.test_dirstate import _FakeStat
501
self.build_tree(["foo"])
502
real = os.lstat("foo")
503
fake = _FakeStat(real.st_size, real.st_mtime, real.st_ctime,
504
real.st_dev, real.st_ino, real.st_mode)
505
self.assertEqualStat(real, fake)
507
def test_assertEqualStat_notequal(self):
508
self.build_tree(["foo", "longname"])
509
self.assertRaises(AssertionError, self.assertEqualStat,
510
os.lstat("foo"), os.lstat("longname"))
513
class TestTestCaseWithMemoryTransport(tests.TestCaseWithMemoryTransport):
515
def test_home_is_non_existant_dir_under_root(self):
516
"""The test_home_dir for TestCaseWithMemoryTransport is missing.
518
This is because TestCaseWithMemoryTransport is for tests that do not
519
need any disk resources: they should be hooked into bzrlib in such a
520
way that no global settings are being changed by the test (only a
521
few tests should need to do that), and having a missing dir as home is
522
an effective way to ensure that this is the case.
524
self.assertIsSameRealPath(
525
self.TEST_ROOT + "/MemoryTransportMissingHomeDir",
527
self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
529
def test_cwd_is_TEST_ROOT(self):
530
self.assertIsSameRealPath(self.test_dir, self.TEST_ROOT)
531
cwd = osutils.getcwd()
532
self.assertIsSameRealPath(self.test_dir, cwd)
534
def test_BZR_HOME_and_HOME_are_bytestrings(self):
535
"""The $BZR_HOME and $HOME environment variables should not be unicode.
537
See https://bugs.launchpad.net/bzr/+bug/464174
539
self.assertIsInstance(os.environ['BZR_HOME'], str)
540
self.assertIsInstance(os.environ['HOME'], str)
542
def test_make_branch_and_memory_tree(self):
543
"""In TestCaseWithMemoryTransport we should not make the branch on disk.
545
This is hard to comprehensively robustly test, so we settle for making
546
a branch and checking no directory was created at its relpath.
548
tree = self.make_branch_and_memory_tree('dir')
549
# Guard against regression into MemoryTransport leaking
550
# files to disk instead of keeping them in memory.
551
self.failIf(osutils.lexists('dir'))
552
self.assertIsInstance(tree, memorytree.MemoryTree)
554
def test_make_branch_and_memory_tree_with_format(self):
555
"""make_branch_and_memory_tree should accept a format option."""
556
format = bzrdir.BzrDirMetaFormat1()
557
format.repository_format = weaverepo.RepositoryFormat7()
558
tree = self.make_branch_and_memory_tree('dir', format=format)
559
# Guard against regression into MemoryTransport leaking
560
# files to disk instead of keeping them in memory.
561
self.failIf(osutils.lexists('dir'))
562
self.assertIsInstance(tree, memorytree.MemoryTree)
563
self.assertEqual(format.repository_format.__class__,
564
tree.branch.repository._format.__class__)
566
def test_make_branch_builder(self):
567
builder = self.make_branch_builder('dir')
568
self.assertIsInstance(builder, branchbuilder.BranchBuilder)
569
# Guard against regression into MemoryTransport leaking
570
# files to disk instead of keeping them in memory.
571
self.failIf(osutils.lexists('dir'))
573
def test_make_branch_builder_with_format(self):
574
# Use a repo layout that doesn't conform to a 'named' layout, to ensure
575
# that the format objects are used.
576
format = bzrdir.BzrDirMetaFormat1()
577
repo_format = weaverepo.RepositoryFormat7()
578
format.repository_format = repo_format
579
builder = self.make_branch_builder('dir', format=format)
580
the_branch = builder.get_branch()
581
# Guard against regression into MemoryTransport leaking
582
# files to disk instead of keeping them in memory.
583
self.failIf(osutils.lexists('dir'))
584
self.assertEqual(format.repository_format.__class__,
585
the_branch.repository._format.__class__)
586
self.assertEqual(repo_format.get_format_string(),
587
self.get_transport().get_bytes(
588
'dir/.bzr/repository/format'))
590
def test_make_branch_builder_with_format_name(self):
591
builder = self.make_branch_builder('dir', format='knit')
592
the_branch = builder.get_branch()
593
# Guard against regression into MemoryTransport leaking
594
# files to disk instead of keeping them in memory.
595
self.failIf(osutils.lexists('dir'))
596
dir_format = bzrdir.format_registry.make_bzrdir('knit')
597
self.assertEqual(dir_format.repository_format.__class__,
598
the_branch.repository._format.__class__)
599
self.assertEqual('Bazaar-NG Knit Repository Format 1',
600
self.get_transport().get_bytes(
601
'dir/.bzr/repository/format'))
603
def test_dangling_locks_cause_failures(self):
604
class TestDanglingLock(tests.TestCaseWithMemoryTransport):
605
def test_function(self):
606
t = self.get_transport('.')
607
l = lockdir.LockDir(t, 'lock')
610
test = TestDanglingLock('test_function')
612
total_failures = result.errors + result.failures
613
if self._lock_check_thorough:
614
self.assertLength(1, total_failures)
616
# When _lock_check_thorough is disabled, then we don't trigger a
618
self.assertLength(0, total_failures)
621
class TestTestCaseWithTransport(tests.TestCaseWithTransport):
622
"""Tests for the convenience functions TestCaseWithTransport introduces."""
624
def test_get_readonly_url_none(self):
625
from bzrlib.transport.readonly import ReadonlyTransportDecorator
626
self.vfs_transport_factory = memory.MemoryServer
627
self.transport_readonly_server = None
628
# calling get_readonly_transport() constructs a decorator on the url
630
url = self.get_readonly_url()
631
url2 = self.get_readonly_url('foo/bar')
632
t = transport.get_transport(url)
633
t2 = transport.get_transport(url2)
634
self.failUnless(isinstance(t, ReadonlyTransportDecorator))
635
self.failUnless(isinstance(t2, ReadonlyTransportDecorator))
636
self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
638
def test_get_readonly_url_http(self):
639
from bzrlib.tests.http_server import HttpServer
640
from bzrlib.transport.http import HttpTransportBase
641
self.transport_server = test_server.LocalURLServer
642
self.transport_readonly_server = HttpServer
643
# calling get_readonly_transport() gives us a HTTP server instance.
644
url = self.get_readonly_url()
645
url2 = self.get_readonly_url('foo/bar')
646
# the transport returned may be any HttpTransportBase subclass
647
t = transport.get_transport(url)
648
t2 = transport.get_transport(url2)
649
self.failUnless(isinstance(t, HttpTransportBase))
650
self.failUnless(isinstance(t2, HttpTransportBase))
651
self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
653
def test_is_directory(self):
654
"""Test assertIsDirectory assertion"""
655
t = self.get_transport()
656
self.build_tree(['a_dir/', 'a_file'], transport=t)
657
self.assertIsDirectory('a_dir', t)
658
self.assertRaises(AssertionError, self.assertIsDirectory, 'a_file', t)
659
self.assertRaises(AssertionError, self.assertIsDirectory, 'not_here', t)
661
def test_make_branch_builder(self):
662
builder = self.make_branch_builder('dir')
663
rev_id = builder.build_commit()
664
self.failUnlessExists('dir')
665
a_dir = bzrdir.BzrDir.open('dir')
666
self.assertRaises(errors.NoWorkingTree, a_dir.open_workingtree)
667
a_branch = a_dir.open_branch()
668
builder_branch = builder.get_branch()
669
self.assertEqual(a_branch.base, builder_branch.base)
670
self.assertEqual((1, rev_id), builder_branch.last_revision_info())
671
self.assertEqual((1, rev_id), a_branch.last_revision_info())
674
class TestTestCaseTransports(tests.TestCaseWithTransport):
677
super(TestTestCaseTransports, self).setUp()
678
self.vfs_transport_factory = memory.MemoryServer
680
def test_make_bzrdir_preserves_transport(self):
681
t = self.get_transport()
682
result_bzrdir = self.make_bzrdir('subdir')
683
self.assertIsInstance(result_bzrdir.transport,
684
memory.MemoryTransport)
685
# should not be on disk, should only be in memory
686
self.failIfExists('subdir')
689
class TestChrootedTest(tests.ChrootedTestCase):
691
def test_root_is_root(self):
692
t = transport.get_transport(self.get_readonly_url())
694
self.assertEqual(url, t.clone('..').base)
697
class TestProfileResult(tests.TestCase):
699
def test_profiles_tests(self):
700
self.requireFeature(test_lsprof.LSProfFeature)
701
terminal = testtools.tests.helpers.ExtendedTestResult()
702
result = tests.ProfileResult(terminal)
703
class Sample(tests.TestCase):
705
self.sample_function()
706
def sample_function(self):
710
case = terminal._events[0][1]
711
self.assertLength(1, case._benchcalls)
712
# We must be able to unpack it as the test reporting code wants
713
(_, _, _), stats = case._benchcalls[0]
714
self.assertTrue(callable(stats.pprint))
717
class TestTestResult(tests.TestCase):
719
def check_timing(self, test_case, expected_re):
720
result = bzrlib.tests.TextTestResult(self._log_file,
724
capture = testtools.tests.helpers.ExtendedTestResult()
725
test_case.run(MultiTestResult(result, capture))
726
run_case = capture._events[0][1]
727
timed_string = result._testTimeString(run_case)
728
self.assertContainsRe(timed_string, expected_re)
730
def test_test_reporting(self):
731
class ShortDelayTestCase(tests.TestCase):
732
def test_short_delay(self):
734
def test_short_benchmark(self):
735
self.time(time.sleep, 0.003)
736
self.check_timing(ShortDelayTestCase('test_short_delay'),
738
# if a benchmark time is given, we now show just that time followed by
740
self.check_timing(ShortDelayTestCase('test_short_benchmark'),
743
def test_unittest_reporting_unittest_class(self):
744
# getting the time from a non-bzrlib test works ok
745
class ShortDelayTestCase(unittest.TestCase):
746
def test_short_delay(self):
748
self.check_timing(ShortDelayTestCase('test_short_delay'),
751
def _patch_get_bzr_source_tree(self):
752
# Reading from the actual source tree breaks isolation, but we don't
753
# want to assume that thats *all* that would happen.
754
self.overrideAttr(bzrlib.version, '_get_bzr_source_tree', lambda: None)
756
def test_assigned_benchmark_file_stores_date(self):
757
self._patch_get_bzr_source_tree()
759
result = bzrlib.tests.TextTestResult(self._log_file,
764
output_string = output.getvalue()
765
# if you are wondering about the regexp please read the comment in
766
# test_bench_history (bzrlib.tests.test_selftest.TestRunner)
767
# XXX: what comment? -- Andrew Bennetts
768
self.assertContainsRe(output_string, "--date [0-9.]+")
770
def test_benchhistory_records_test_times(self):
771
self._patch_get_bzr_source_tree()
772
result_stream = StringIO()
773
result = bzrlib.tests.TextTestResult(
777
bench_history=result_stream
780
# we want profile a call and check that its test duration is recorded
781
# make a new test instance that when run will generate a benchmark
782
example_test_case = TestTestResult("_time_hello_world_encoding")
783
# execute the test, which should succeed and record times
784
example_test_case.run(result)
785
lines = result_stream.getvalue().splitlines()
786
self.assertEqual(2, len(lines))
787
self.assertContainsRe(lines[1],
788
" *[0-9]+ms bzrlib.tests.test_selftest.TestTestResult"
789
"._time_hello_world_encoding")
791
def _time_hello_world_encoding(self):
792
"""Profile two sleep calls
794
This is used to exercise the test framework.
796
self.time(unicode, 'hello', errors='replace')
797
self.time(unicode, 'world', errors='replace')
799
def test_lsprofiling(self):
800
"""Verbose test result prints lsprof statistics from test cases."""
801
self.requireFeature(test_lsprof.LSProfFeature)
802
result_stream = StringIO()
803
result = bzrlib.tests.VerboseTestResult(
804
unittest._WritelnDecorator(result_stream),
808
# we want profile a call of some sort and check it is output by
809
# addSuccess. We dont care about addError or addFailure as they
810
# are not that interesting for performance tuning.
811
# make a new test instance that when run will generate a profile
812
example_test_case = TestTestResult("_time_hello_world_encoding")
813
example_test_case._gather_lsprof_in_benchmarks = True
814
# execute the test, which should succeed and record profiles
815
example_test_case.run(result)
816
# lsprofile_something()
817
# if this worked we want
818
# LSProf output for <built in function unicode> (['hello'], {'errors': 'replace'})
819
# CallCount Recursive Total(ms) Inline(ms) module:lineno(function)
820
# (the lsprof header)
821
# ... an arbitrary number of lines
822
# and the function call which is time.sleep.
823
# 1 0 ??? ??? ???(sleep)
824
# and then repeated but with 'world', rather than 'hello'.
825
# this should appear in the output stream of our test result.
826
output = result_stream.getvalue()
827
self.assertContainsRe(output,
828
r"LSProf output for <type 'unicode'>\(\('hello',\), {'errors': 'replace'}\)")
829
self.assertContainsRe(output,
830
r" *CallCount *Recursive *Total\(ms\) *Inline\(ms\) *module:lineno\(function\)\n")
831
self.assertContainsRe(output,
832
r"( +1 +0 +0\.\d+ +0\.\d+ +<method 'disable' of '_lsprof\.Profiler' objects>\n)?")
833
self.assertContainsRe(output,
834
r"LSProf output for <type 'unicode'>\(\('world',\), {'errors': 'replace'}\)\n")
836
def test_known_failure(self):
837
"""A KnownFailure being raised should trigger several result actions."""
838
class InstrumentedTestResult(tests.ExtendedTestResult):
839
def stopTestRun(self): pass
840
def startTests(self): pass
841
def report_test_start(self, test): pass
842
def report_known_failure(self, test, err=None, details=None):
843
self._call = test, 'known failure'
844
result = InstrumentedTestResult(None, None, None, None)
845
class Test(tests.TestCase):
846
def test_function(self):
847
raise tests.KnownFailure('failed!')
848
test = Test("test_function")
850
# it should invoke 'report_known_failure'.
851
self.assertEqual(2, len(result._call))
852
self.assertEqual(test.id(), result._call[0].id())
853
self.assertEqual('known failure', result._call[1])
854
# we dont introspec the traceback, if the rest is ok, it would be
855
# exceptional for it not to be.
856
# it should update the known_failure_count on the object.
857
self.assertEqual(1, result.known_failure_count)
858
# the result should be successful.
859
self.assertTrue(result.wasSuccessful())
861
def test_verbose_report_known_failure(self):
862
# verbose test output formatting
863
result_stream = StringIO()
864
result = bzrlib.tests.VerboseTestResult(
865
unittest._WritelnDecorator(result_stream),
869
test = self.get_passing_test()
870
result.startTest(test)
871
prefix = len(result_stream.getvalue())
872
# the err parameter has the shape:
873
# (class, exception object, traceback)
874
# KnownFailures dont get their tracebacks shown though, so we
876
err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
877
result.report_known_failure(test, err)
878
output = result_stream.getvalue()[prefix:]
879
lines = output.splitlines()
880
self.assertContainsRe(lines[0], r'XFAIL *\d+ms$')
881
self.assertEqual(lines[1], ' foo')
882
self.assertEqual(2, len(lines))
884
def get_passing_test(self):
885
"""Return a test object that can't be run usefully."""
888
return unittest.FunctionTestCase(passing_test)
890
def test_add_not_supported(self):
891
"""Test the behaviour of invoking addNotSupported."""
892
class InstrumentedTestResult(tests.ExtendedTestResult):
893
def stopTestRun(self): pass
894
def startTests(self): pass
895
def report_test_start(self, test): pass
896
def report_unsupported(self, test, feature):
897
self._call = test, feature
898
result = InstrumentedTestResult(None, None, None, None)
899
test = SampleTestCase('_test_pass')
900
feature = tests.Feature()
901
result.startTest(test)
902
result.addNotSupported(test, feature)
903
# it should invoke 'report_unsupported'.
904
self.assertEqual(2, len(result._call))
905
self.assertEqual(test, result._call[0])
906
self.assertEqual(feature, result._call[1])
907
# the result should be successful.
908
self.assertTrue(result.wasSuccessful())
909
# it should record the test against a count of tests not run due to
911
self.assertEqual(1, result.unsupported['Feature'])
912
# and invoking it again should increment that counter
913
result.addNotSupported(test, feature)
914
self.assertEqual(2, result.unsupported['Feature'])
916
def test_verbose_report_unsupported(self):
917
# verbose test output formatting
918
result_stream = StringIO()
919
result = bzrlib.tests.VerboseTestResult(
920
unittest._WritelnDecorator(result_stream),
924
test = self.get_passing_test()
925
feature = tests.Feature()
926
result.startTest(test)
927
prefix = len(result_stream.getvalue())
928
result.report_unsupported(test, feature)
929
output = result_stream.getvalue()[prefix:]
930
lines = output.splitlines()
931
# We don't check for the final '0ms' since it may fail on slow hosts
932
self.assertStartsWith(lines[0], 'NODEP')
933
self.assertEqual(lines[1],
934
" The feature 'Feature' is not available.")
936
def test_unavailable_exception(self):
937
"""An UnavailableFeature being raised should invoke addNotSupported."""
938
class InstrumentedTestResult(tests.ExtendedTestResult):
939
def stopTestRun(self): pass
940
def startTests(self): pass
941
def report_test_start(self, test): pass
942
def addNotSupported(self, test, feature):
943
self._call = test, feature
944
result = InstrumentedTestResult(None, None, None, None)
945
feature = tests.Feature()
946
class Test(tests.TestCase):
947
def test_function(self):
948
raise tests.UnavailableFeature(feature)
949
test = Test("test_function")
951
# it should invoke 'addNotSupported'.
952
self.assertEqual(2, len(result._call))
953
self.assertEqual(test.id(), result._call[0].id())
954
self.assertEqual(feature, result._call[1])
955
# and not count as an error
956
self.assertEqual(0, result.error_count)
958
def test_strict_with_unsupported_feature(self):
959
result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
961
test = self.get_passing_test()
962
feature = "Unsupported Feature"
963
result.addNotSupported(test, feature)
964
self.assertFalse(result.wasStrictlySuccessful())
965
self.assertEqual(None, result._extractBenchmarkTime(test))
967
def test_strict_with_known_failure(self):
968
result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
970
test = self.get_passing_test()
971
err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
972
result.addExpectedFailure(test, err)
973
self.assertFalse(result.wasStrictlySuccessful())
974
self.assertEqual(None, result._extractBenchmarkTime(test))
976
def test_strict_with_success(self):
977
result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
979
test = self.get_passing_test()
980
result.addSuccess(test)
981
self.assertTrue(result.wasStrictlySuccessful())
982
self.assertEqual(None, result._extractBenchmarkTime(test))
984
def test_startTests(self):
985
"""Starting the first test should trigger startTests."""
986
class InstrumentedTestResult(tests.ExtendedTestResult):
988
def startTests(self): self.calls += 1
989
def report_test_start(self, test): pass
990
result = InstrumentedTestResult(None, None, None, None)
993
test = unittest.FunctionTestCase(test_function)
995
self.assertEquals(1, result.calls)
998
class TestUnicodeFilenameFeature(tests.TestCase):
1000
def test_probe_passes(self):
1001
"""UnicodeFilenameFeature._probe passes."""
1002
# We can't test much more than that because the behaviour depends
1004
tests.UnicodeFilenameFeature._probe()
1007
class TestRunner(tests.TestCase):
1009
def dummy_test(self):
1012
def run_test_runner(self, testrunner, test):
1013
"""Run suite in testrunner, saving global state and restoring it.
1015
This current saves and restores:
1016
TestCaseInTempDir.TEST_ROOT
1018
There should be no tests in this file that use
1019
bzrlib.tests.TextTestRunner without using this convenience method,
1020
because of our use of global state.
1022
old_root = tests.TestCaseInTempDir.TEST_ROOT
1023
old_leak = tests.TestCase._first_thread_leaker_id
1025
tests.TestCaseInTempDir.TEST_ROOT = None
1026
tests.TestCase._first_thread_leaker_id = None
1027
return testrunner.run(test)
1029
tests.TestCaseInTempDir.TEST_ROOT = old_root
1030
tests.TestCase._first_thread_leaker_id = old_leak
1032
def test_known_failure_failed_run(self):
1033
# run a test that generates a known failure which should be printed in
1034
# the final output when real failures occur.
1035
class Test(tests.TestCase):
1036
def known_failure_test(self):
1037
self.expectFailure('failed', self.assertTrue, False)
1038
test = unittest.TestSuite()
1039
test.addTest(Test("known_failure_test"))
1042
test.addTest(unittest.FunctionTestCase(failing_test))
1044
runner = tests.TextTestRunner(stream=stream)
1045
result = self.run_test_runner(runner, test)
1046
lines = stream.getvalue().splitlines()
1047
self.assertContainsRe(stream.getvalue(),
1048
'(?sm)^bzr selftest.*$'
1050
'^======================================================================\n'
1051
'^FAIL: failing_test\n'
1052
'^----------------------------------------------------------------------\n'
1053
'Traceback \\(most recent call last\\):\n'
1054
' .*' # File .*, line .*, in failing_test' - but maybe not from .pyc
1055
' self.fail\\(\'foo\'\\)\n'
1057
'^----------------------------------------------------------------------\n'
1059
'FAILED \\(failures=1, known_failure_count=1\\)'
1062
def test_known_failure_ok_run(self):
1063
# run a test that generates a known failure which should be printed in
1065
class Test(tests.TestCase):
1066
def known_failure_test(self):
1067
self.expectFailure('failed', self.assertTrue, False)
1068
test = Test("known_failure_test")
1070
runner = tests.TextTestRunner(stream=stream)
1071
result = self.run_test_runner(runner, test)
1072
self.assertContainsRe(stream.getvalue(),
1075
'Ran 1 test in .*\n'
1077
'OK \\(known_failures=1\\)\n')
1079
def test_result_decorator(self):
1082
class LoggingDecorator(tests.ForwardingResult):
1083
def startTest(self, test):
1084
tests.ForwardingResult.startTest(self, test)
1085
calls.append('start')
1086
test = unittest.FunctionTestCase(lambda:None)
1088
runner = tests.TextTestRunner(stream=stream,
1089
result_decorators=[LoggingDecorator])
1090
result = self.run_test_runner(runner, test)
1091
self.assertLength(1, calls)
1093
def test_skipped_test(self):
1094
# run a test that is skipped, and check the suite as a whole still
1096
# skipping_test must be hidden in here so it's not run as a real test
1097
class SkippingTest(tests.TestCase):
1098
def skipping_test(self):
1099
raise tests.TestSkipped('test intentionally skipped')
1100
runner = tests.TextTestRunner(stream=self._log_file)
1101
test = SkippingTest("skipping_test")
1102
result = self.run_test_runner(runner, test)
1103
self.assertTrue(result.wasSuccessful())
1105
def test_skipped_from_setup(self):
1107
class SkippedSetupTest(tests.TestCase):
1110
calls.append('setUp')
1111
self.addCleanup(self.cleanup)
1112
raise tests.TestSkipped('skipped setup')
1114
def test_skip(self):
1115
self.fail('test reached')
1118
calls.append('cleanup')
1120
runner = tests.TextTestRunner(stream=self._log_file)
1121
test = SkippedSetupTest('test_skip')
1122
result = self.run_test_runner(runner, test)
1123
self.assertTrue(result.wasSuccessful())
1124
# Check if cleanup was called the right number of times.
1125
self.assertEqual(['setUp', 'cleanup'], calls)
1127
def test_skipped_from_test(self):
1129
class SkippedTest(tests.TestCase):
1132
tests.TestCase.setUp(self)
1133
calls.append('setUp')
1134
self.addCleanup(self.cleanup)
1136
def test_skip(self):
1137
raise tests.TestSkipped('skipped test')
1140
calls.append('cleanup')
1142
runner = tests.TextTestRunner(stream=self._log_file)
1143
test = SkippedTest('test_skip')
1144
result = self.run_test_runner(runner, test)
1145
self.assertTrue(result.wasSuccessful())
1146
# Check if cleanup was called the right number of times.
1147
self.assertEqual(['setUp', 'cleanup'], calls)
1149
def test_not_applicable(self):
1150
# run a test that is skipped because it's not applicable
1151
class Test(tests.TestCase):
1152
def not_applicable_test(self):
1153
raise tests.TestNotApplicable('this test never runs')
1155
runner = tests.TextTestRunner(stream=out, verbosity=2)
1156
test = Test("not_applicable_test")
1157
result = self.run_test_runner(runner, test)
1158
self._log_file.write(out.getvalue())
1159
self.assertTrue(result.wasSuccessful())
1160
self.assertTrue(result.wasStrictlySuccessful())
1161
self.assertContainsRe(out.getvalue(),
1162
r'(?m)not_applicable_test * N/A')
1163
self.assertContainsRe(out.getvalue(),
1164
r'(?m)^ this test never runs')
1166
def test_unsupported_features_listed(self):
1167
"""When unsupported features are encountered they are detailed."""
1168
class Feature1(tests.Feature):
1169
def _probe(self): return False
1170
class Feature2(tests.Feature):
1171
def _probe(self): return False
1172
# create sample tests
1173
test1 = SampleTestCase('_test_pass')
1174
test1._test_needs_features = [Feature1()]
1175
test2 = SampleTestCase('_test_pass')
1176
test2._test_needs_features = [Feature2()]
1177
test = unittest.TestSuite()
1181
runner = tests.TextTestRunner(stream=stream)
1182
result = self.run_test_runner(runner, test)
1183
lines = stream.getvalue().splitlines()
1186
"Missing feature 'Feature1' skipped 1 tests.",
1187
"Missing feature 'Feature2' skipped 1 tests.",
1191
def _patch_get_bzr_source_tree(self):
1192
# Reading from the actual source tree breaks isolation, but we don't
1193
# want to assume that thats *all* that would happen.
1194
self._get_source_tree_calls = []
1196
self._get_source_tree_calls.append("called")
1198
self.overrideAttr(bzrlib.version, '_get_bzr_source_tree', new_get)
1200
def test_bench_history(self):
1201
# tests that the running the benchmark passes bench_history into
1202
# the test result object. We can tell that happens if
1203
# _get_bzr_source_tree is called.
1204
self._patch_get_bzr_source_tree()
1205
test = TestRunner('dummy_test')
1207
runner = tests.TextTestRunner(stream=self._log_file,
1208
bench_history=output)
1209
result = self.run_test_runner(runner, test)
1210
output_string = output.getvalue()
1211
self.assertContainsRe(output_string, "--date [0-9.]+")
1212
self.assertLength(1, self._get_source_tree_calls)
1214
def test_startTestRun(self):
1215
"""run should call result.startTestRun()"""
1217
class LoggingDecorator(tests.ForwardingResult):
1218
def startTestRun(self):
1219
tests.ForwardingResult.startTestRun(self)
1220
calls.append('startTestRun')
1221
test = unittest.FunctionTestCase(lambda:None)
1223
runner = tests.TextTestRunner(stream=stream,
1224
result_decorators=[LoggingDecorator])
1225
result = self.run_test_runner(runner, test)
1226
self.assertLength(1, calls)
1228
def test_stopTestRun(self):
1229
"""run should call result.stopTestRun()"""
1231
class LoggingDecorator(tests.ForwardingResult):
1232
def stopTestRun(self):
1233
tests.ForwardingResult.stopTestRun(self)
1234
calls.append('stopTestRun')
1235
test = unittest.FunctionTestCase(lambda:None)
1237
runner = tests.TextTestRunner(stream=stream,
1238
result_decorators=[LoggingDecorator])
1239
result = self.run_test_runner(runner, test)
1240
self.assertLength(1, calls)
1243
class SampleTestCase(tests.TestCase):
1245
def _test_pass(self):
1248
class _TestException(Exception):
1252
class TestTestCase(tests.TestCase):
1253
"""Tests that test the core bzrlib TestCase."""
1255
def test_assertLength_matches_empty(self):
1257
self.assertLength(0, a_list)
1259
def test_assertLength_matches_nonempty(self):
1261
self.assertLength(3, a_list)
1263
def test_assertLength_fails_different(self):
1265
self.assertRaises(AssertionError, self.assertLength, 1, a_list)
1267
def test_assertLength_shows_sequence_in_failure(self):
1269
exception = self.assertRaises(AssertionError, self.assertLength, 2,
1271
self.assertEqual('Incorrect length: wanted 2, got 3 for [1, 2, 3]',
1274
def test_base_setUp_not_called_causes_failure(self):
1275
class TestCaseWithBrokenSetUp(tests.TestCase):
1277
pass # does not call TestCase.setUp
1280
test = TestCaseWithBrokenSetUp('test_foo')
1281
result = unittest.TestResult()
1283
self.assertFalse(result.wasSuccessful())
1284
self.assertEqual(1, result.testsRun)
1286
def test_base_tearDown_not_called_causes_failure(self):
1287
class TestCaseWithBrokenTearDown(tests.TestCase):
1289
pass # does not call TestCase.tearDown
1292
test = TestCaseWithBrokenTearDown('test_foo')
1293
result = unittest.TestResult()
1295
self.assertFalse(result.wasSuccessful())
1296
self.assertEqual(1, result.testsRun)
1298
def test_debug_flags_sanitised(self):
1299
"""The bzrlib debug flags should be sanitised by setUp."""
1300
if 'allow_debug' in tests.selftest_debug_flags:
1301
raise tests.TestNotApplicable(
1302
'-Eallow_debug option prevents debug flag sanitisation')
1303
# we could set something and run a test that will check
1304
# it gets santised, but this is probably sufficient for now:
1305
# if someone runs the test with -Dsomething it will error.
1307
if self._lock_check_thorough:
1308
flags.add('strict_locks')
1309
self.assertEqual(flags, bzrlib.debug.debug_flags)
1311
def change_selftest_debug_flags(self, new_flags):
1312
self.overrideAttr(tests, 'selftest_debug_flags', set(new_flags))
1314
def test_allow_debug_flag(self):
1315
"""The -Eallow_debug flag prevents bzrlib.debug.debug_flags from being
1316
sanitised (i.e. cleared) before running a test.
1318
self.change_selftest_debug_flags(set(['allow_debug']))
1319
bzrlib.debug.debug_flags = set(['a-flag'])
1320
class TestThatRecordsFlags(tests.TestCase):
1321
def test_foo(nested_self):
1322
self.flags = set(bzrlib.debug.debug_flags)
1323
test = TestThatRecordsFlags('test_foo')
1324
test.run(self.make_test_result())
1325
flags = set(['a-flag'])
1326
if 'disable_lock_checks' not in tests.selftest_debug_flags:
1327
flags.add('strict_locks')
1328
self.assertEqual(flags, self.flags)
1330
def test_disable_lock_checks(self):
1331
"""The -Edisable_lock_checks flag disables thorough checks."""
1332
class TestThatRecordsFlags(tests.TestCase):
1333
def test_foo(nested_self):
1334
self.flags = set(bzrlib.debug.debug_flags)
1335
self.test_lock_check_thorough = nested_self._lock_check_thorough
1336
self.change_selftest_debug_flags(set())
1337
test = TestThatRecordsFlags('test_foo')
1338
test.run(self.make_test_result())
1339
# By default we do strict lock checking and thorough lock/unlock
1341
self.assertTrue(self.test_lock_check_thorough)
1342
self.assertEqual(set(['strict_locks']), self.flags)
1343
# Now set the disable_lock_checks flag, and show that this changed.
1344
self.change_selftest_debug_flags(set(['disable_lock_checks']))
1345
test = TestThatRecordsFlags('test_foo')
1346
test.run(self.make_test_result())
1347
self.assertFalse(self.test_lock_check_thorough)
1348
self.assertEqual(set(), self.flags)
1350
def test_this_fails_strict_lock_check(self):
1351
class TestThatRecordsFlags(tests.TestCase):
1352
def test_foo(nested_self):
1353
self.flags1 = set(bzrlib.debug.debug_flags)
1354
self.thisFailsStrictLockCheck()
1355
self.flags2 = set(bzrlib.debug.debug_flags)
1356
# Make sure lock checking is active
1357
self.change_selftest_debug_flags(set())
1358
test = TestThatRecordsFlags('test_foo')
1359
test.run(self.make_test_result())
1360
self.assertEqual(set(['strict_locks']), self.flags1)
1361
self.assertEqual(set(), self.flags2)
1363
def test_debug_flags_restored(self):
1364
"""The bzrlib debug flags should be restored to their original state
1365
after the test was run, even if allow_debug is set.
1367
self.change_selftest_debug_flags(set(['allow_debug']))
1368
# Now run a test that modifies debug.debug_flags.
1369
bzrlib.debug.debug_flags = set(['original-state'])
1370
class TestThatModifiesFlags(tests.TestCase):
1372
bzrlib.debug.debug_flags = set(['modified'])
1373
test = TestThatModifiesFlags('test_foo')
1374
test.run(self.make_test_result())
1375
self.assertEqual(set(['original-state']), bzrlib.debug.debug_flags)
1377
def make_test_result(self):
1378
"""Get a test result that writes to the test log file."""
1379
return tests.TextTestResult(self._log_file, descriptions=0, verbosity=1)
1381
def inner_test(self):
1382
# the inner child test
1385
def outer_child(self):
1386
# the outer child test
1388
self.inner_test = TestTestCase("inner_child")
1389
result = self.make_test_result()
1390
self.inner_test.run(result)
1391
note("outer finish")
1392
self.addCleanup(osutils.delete_any, self._log_file_name)
1394
def test_trace_nesting(self):
1395
# this tests that each test case nests its trace facility correctly.
1396
# we do this by running a test case manually. That test case (A)
1397
# should setup a new log, log content to it, setup a child case (B),
1398
# which should log independently, then case (A) should log a trailer
1400
# we do two nested children so that we can verify the state of the
1401
# logs after the outer child finishes is correct, which a bad clean
1402
# up routine in tearDown might trigger a fault in our test with only
1403
# one child, we should instead see the bad result inside our test with
1405
# the outer child test
1406
original_trace = bzrlib.trace._trace_file
1407
outer_test = TestTestCase("outer_child")
1408
result = self.make_test_result()
1409
outer_test.run(result)
1410
self.assertEqual(original_trace, bzrlib.trace._trace_file)
1412
def method_that_times_a_bit_twice(self):
1413
# call self.time twice to ensure it aggregates
1414
self.time(time.sleep, 0.007)
1415
self.time(time.sleep, 0.007)
1417
def test_time_creates_benchmark_in_result(self):
1418
"""Test that the TestCase.time() method accumulates a benchmark time."""
1419
sample_test = TestTestCase("method_that_times_a_bit_twice")
1420
output_stream = StringIO()
1421
result = bzrlib.tests.VerboseTestResult(
1422
unittest._WritelnDecorator(output_stream),
1425
sample_test.run(result)
1426
self.assertContainsRe(
1427
output_stream.getvalue(),
1430
def test_hooks_sanitised(self):
1431
"""The bzrlib hooks should be sanitised by setUp."""
1432
# Note this test won't fail with hooks that the core library doesn't
1433
# use - but it trigger with a plugin that adds hooks, so its still a
1434
# useful warning in that case.
1435
self.assertEqual(bzrlib.branch.BranchHooks(),
1436
bzrlib.branch.Branch.hooks)
1437
self.assertEqual(bzrlib.smart.server.SmartServerHooks(),
1438
bzrlib.smart.server.SmartTCPServer.hooks)
1439
self.assertEqual(bzrlib.commands.CommandHooks(),
1440
bzrlib.commands.Command.hooks)
1442
def test__gather_lsprof_in_benchmarks(self):
1443
"""When _gather_lsprof_in_benchmarks is on, accumulate profile data.
1445
Each self.time() call is individually and separately profiled.
1447
self.requireFeature(test_lsprof.LSProfFeature)
1448
# overrides the class member with an instance member so no cleanup
1450
self._gather_lsprof_in_benchmarks = True
1451
self.time(time.sleep, 0.000)
1452
self.time(time.sleep, 0.003)
1453
self.assertEqual(2, len(self._benchcalls))
1454
self.assertEqual((time.sleep, (0.000,), {}), self._benchcalls[0][0])
1455
self.assertEqual((time.sleep, (0.003,), {}), self._benchcalls[1][0])
1456
self.assertIsInstance(self._benchcalls[0][1], bzrlib.lsprof.Stats)
1457
self.assertIsInstance(self._benchcalls[1][1], bzrlib.lsprof.Stats)
1458
del self._benchcalls[:]
1460
def test_knownFailure(self):
1461
"""Self.knownFailure() should raise a KnownFailure exception."""
1462
self.assertRaises(tests.KnownFailure, self.knownFailure, "A Failure")
1464
def test_open_bzrdir_safe_roots(self):
1465
# even a memory transport should fail to open when its url isn't
1467
# Manually set one up (TestCase doesn't and shouldn't provide magic
1469
transport_server = memory.MemoryServer()
1470
transport_server.start_server()
1471
self.addCleanup(transport_server.stop_server)
1472
t = transport.get_transport(transport_server.get_url())
1473
bzrdir.BzrDir.create(t.base)
1474
self.assertRaises(errors.BzrError,
1475
bzrdir.BzrDir.open_from_transport, t)
1476
# But if we declare this as safe, we can open the bzrdir.
1477
self.permit_url(t.base)
1478
self._bzr_selftest_roots.append(t.base)
1479
bzrdir.BzrDir.open_from_transport(t)
1481
def test_requireFeature_available(self):
1482
"""self.requireFeature(available) is a no-op."""
1483
class Available(tests.Feature):
1484
def _probe(self):return True
1485
feature = Available()
1486
self.requireFeature(feature)
1488
def test_requireFeature_unavailable(self):
1489
"""self.requireFeature(unavailable) raises UnavailableFeature."""
1490
class Unavailable(tests.Feature):
1491
def _probe(self):return False
1492
feature = Unavailable()
1493
self.assertRaises(tests.UnavailableFeature,
1494
self.requireFeature, feature)
1496
def test_run_no_parameters(self):
1497
test = SampleTestCase('_test_pass')
1500
def test_run_enabled_unittest_result(self):
1501
"""Test we revert to regular behaviour when the test is enabled."""
1502
test = SampleTestCase('_test_pass')
1503
class EnabledFeature(object):
1504
def available(self):
1506
test._test_needs_features = [EnabledFeature()]
1507
result = unittest.TestResult()
1509
self.assertEqual(1, result.testsRun)
1510
self.assertEqual([], result.errors)
1511
self.assertEqual([], result.failures)
1513
def test_run_disabled_unittest_result(self):
1514
"""Test our compatability for disabled tests with unittest results."""
1515
test = SampleTestCase('_test_pass')
1516
class DisabledFeature(object):
1517
def available(self):
1519
test._test_needs_features = [DisabledFeature()]
1520
result = unittest.TestResult()
1522
self.assertEqual(1, result.testsRun)
1523
self.assertEqual([], result.errors)
1524
self.assertEqual([], result.failures)
1526
def test_run_disabled_supporting_result(self):
1527
"""Test disabled tests behaviour with support aware results."""
1528
test = SampleTestCase('_test_pass')
1529
class DisabledFeature(object):
1530
def __eq__(self, other):
1531
return isinstance(other, DisabledFeature)
1532
def available(self):
1534
the_feature = DisabledFeature()
1535
test._test_needs_features = [the_feature]
1536
class InstrumentedTestResult(unittest.TestResult):
1538
unittest.TestResult.__init__(self)
1540
def startTest(self, test):
1541
self.calls.append(('startTest', test))
1542
def stopTest(self, test):
1543
self.calls.append(('stopTest', test))
1544
def addNotSupported(self, test, feature):
1545
self.calls.append(('addNotSupported', test, feature))
1546
result = InstrumentedTestResult()
1548
case = result.calls[0][1]
1550
('startTest', case),
1551
('addNotSupported', case, the_feature),
1556
def test_start_server_registers_url(self):
1557
transport_server = memory.MemoryServer()
1558
# A little strict, but unlikely to be changed soon.
1559
self.assertEqual([], self._bzr_selftest_roots)
1560
self.start_server(transport_server)
1561
self.assertSubset([transport_server.get_url()],
1562
self._bzr_selftest_roots)
1564
def test_assert_list_raises_on_generator(self):
1565
def generator_which_will_raise():
1566
# This will not raise until after the first yield
1568
raise _TestException()
1570
e = self.assertListRaises(_TestException, generator_which_will_raise)
1571
self.assertIsInstance(e, _TestException)
1573
e = self.assertListRaises(Exception, generator_which_will_raise)
1574
self.assertIsInstance(e, _TestException)
1576
def test_assert_list_raises_on_plain(self):
1577
def plain_exception():
1578
raise _TestException()
1581
e = self.assertListRaises(_TestException, plain_exception)
1582
self.assertIsInstance(e, _TestException)
1584
e = self.assertListRaises(Exception, plain_exception)
1585
self.assertIsInstance(e, _TestException)
1587
def test_assert_list_raises_assert_wrong_exception(self):
1588
class _NotTestException(Exception):
1591
def wrong_exception():
1592
raise _NotTestException()
1594
def wrong_exception_generator():
1597
raise _NotTestException()
1599
# Wrong exceptions are not intercepted
1600
self.assertRaises(_NotTestException,
1601
self.assertListRaises, _TestException, wrong_exception)
1602
self.assertRaises(_NotTestException,
1603
self.assertListRaises, _TestException, wrong_exception_generator)
1605
def test_assert_list_raises_no_exception(self):
1609
def success_generator():
1613
self.assertRaises(AssertionError,
1614
self.assertListRaises, _TestException, success)
1616
self.assertRaises(AssertionError,
1617
self.assertListRaises, _TestException, success_generator)
1619
def test_overrideAttr_without_value(self):
1620
self.test_attr = 'original' # Define a test attribute
1621
obj = self # Make 'obj' visible to the embedded test
1622
class Test(tests.TestCase):
1625
tests.TestCase.setUp(self)
1626
self.orig = self.overrideAttr(obj, 'test_attr')
1628
def test_value(self):
1629
self.assertEqual('original', self.orig)
1630
self.assertEqual('original', obj.test_attr)
1631
obj.test_attr = 'modified'
1632
self.assertEqual('modified', obj.test_attr)
1634
test = Test('test_value')
1635
test.run(unittest.TestResult())
1636
self.assertEqual('original', obj.test_attr)
1638
def test_overrideAttr_with_value(self):
1639
self.test_attr = 'original' # Define a test attribute
1640
obj = self # Make 'obj' visible to the embedded test
1641
class Test(tests.TestCase):
1644
tests.TestCase.setUp(self)
1645
self.orig = self.overrideAttr(obj, 'test_attr', new='modified')
1647
def test_value(self):
1648
self.assertEqual('original', self.orig)
1649
self.assertEqual('modified', obj.test_attr)
1651
test = Test('test_value')
1652
test.run(unittest.TestResult())
1653
self.assertEqual('original', obj.test_attr)
1656
# NB: Don't delete this; it's not actually from 0.11!
1657
@deprecated_function(deprecated_in((0, 11, 0)))
1658
def sample_deprecated_function():
1659
"""A deprecated function to test applyDeprecated with."""
1663
def sample_undeprecated_function(a_param):
1664
"""A undeprecated function to test applyDeprecated with."""
1667
class ApplyDeprecatedHelper(object):
1668
"""A helper class for ApplyDeprecated tests."""
1670
@deprecated_method(deprecated_in((0, 11, 0)))
1671
def sample_deprecated_method(self, param_one):
1672
"""A deprecated method for testing with."""
1675
def sample_normal_method(self):
1676
"""A undeprecated method."""
1678
@deprecated_method(deprecated_in((0, 10, 0)))
1679
def sample_nested_deprecation(self):
1680
return sample_deprecated_function()
1683
class TestExtraAssertions(tests.TestCase):
1684
"""Tests for new test assertions in bzrlib test suite"""
1686
def test_assert_isinstance(self):
1687
self.assertIsInstance(2, int)
1688
self.assertIsInstance(u'', basestring)
1689
e = self.assertRaises(AssertionError, self.assertIsInstance, None, int)
1690
self.assertEquals(str(e),
1691
"None is an instance of <type 'NoneType'> rather than <type 'int'>")
1692
self.assertRaises(AssertionError, self.assertIsInstance, 23.3, int)
1693
e = self.assertRaises(AssertionError,
1694
self.assertIsInstance, None, int, "it's just not")
1695
self.assertEquals(str(e),
1696
"None is an instance of <type 'NoneType'> rather than <type 'int'>"
1699
def test_assertEndsWith(self):
1700
self.assertEndsWith('foo', 'oo')
1701
self.assertRaises(AssertionError, self.assertEndsWith, 'o', 'oo')
1703
def test_assertEqualDiff(self):
1704
e = self.assertRaises(AssertionError,
1705
self.assertEqualDiff, '', '\n')
1706
self.assertEquals(str(e),
1707
# Don't blink ! The '+' applies to the second string
1708
'first string is missing a final newline.\n+ \n')
1709
e = self.assertRaises(AssertionError,
1710
self.assertEqualDiff, '\n', '')
1711
self.assertEquals(str(e),
1712
# Don't blink ! The '-' applies to the second string
1713
'second string is missing a final newline.\n- \n')
1716
class TestDeprecations(tests.TestCase):
1718
def test_applyDeprecated_not_deprecated(self):
1719
sample_object = ApplyDeprecatedHelper()
1720
# calling an undeprecated callable raises an assertion
1721
self.assertRaises(AssertionError, self.applyDeprecated,
1722
deprecated_in((0, 11, 0)),
1723
sample_object.sample_normal_method)
1724
self.assertRaises(AssertionError, self.applyDeprecated,
1725
deprecated_in((0, 11, 0)),
1726
sample_undeprecated_function, "a param value")
1727
# calling a deprecated callable (function or method) with the wrong
1728
# expected deprecation fails.
1729
self.assertRaises(AssertionError, self.applyDeprecated,
1730
deprecated_in((0, 10, 0)),
1731
sample_object.sample_deprecated_method, "a param value")
1732
self.assertRaises(AssertionError, self.applyDeprecated,
1733
deprecated_in((0, 10, 0)),
1734
sample_deprecated_function)
1735
# calling a deprecated callable (function or method) with the right
1736
# expected deprecation returns the functions result.
1737
self.assertEqual("a param value",
1738
self.applyDeprecated(deprecated_in((0, 11, 0)),
1739
sample_object.sample_deprecated_method, "a param value"))
1740
self.assertEqual(2, self.applyDeprecated(deprecated_in((0, 11, 0)),
1741
sample_deprecated_function))
1742
# calling a nested deprecation with the wrong deprecation version
1743
# fails even if a deeper nested function was deprecated with the
1745
self.assertRaises(AssertionError, self.applyDeprecated,
1746
deprecated_in((0, 11, 0)), sample_object.sample_nested_deprecation)
1747
# calling a nested deprecation with the right deprecation value
1748
# returns the calls result.
1749
self.assertEqual(2, self.applyDeprecated(deprecated_in((0, 10, 0)),
1750
sample_object.sample_nested_deprecation))
1752
def test_callDeprecated(self):
1753
def testfunc(be_deprecated, result=None):
1754
if be_deprecated is True:
1755
symbol_versioning.warn('i am deprecated', DeprecationWarning,
1758
result = self.callDeprecated(['i am deprecated'], testfunc, True)
1759
self.assertIs(None, result)
1760
result = self.callDeprecated([], testfunc, False, 'result')
1761
self.assertEqual('result', result)
1762
self.callDeprecated(['i am deprecated'], testfunc, be_deprecated=True)
1763
self.callDeprecated([], testfunc, be_deprecated=False)
1766
class TestWarningTests(tests.TestCase):
1767
"""Tests for calling methods that raise warnings."""
1769
def test_callCatchWarnings(self):
1771
warnings.warn("this is your last warning")
1773
wlist, result = self.callCatchWarnings(meth, 1, 2)
1774
self.assertEquals(3, result)
1775
# would like just to compare them, but UserWarning doesn't implement
1778
self.assertIsInstance(w0, UserWarning)
1779
self.assertEquals("this is your last warning", str(w0))
1782
class TestConvenienceMakers(tests.TestCaseWithTransport):
1783
"""Test for the make_* convenience functions."""
1785
def test_make_branch_and_tree_with_format(self):
1786
# we should be able to supply a format to make_branch_and_tree
1787
self.make_branch_and_tree('a', format=bzrlib.bzrdir.BzrDirMetaFormat1())
1788
self.make_branch_and_tree('b', format=bzrlib.bzrdir.BzrDirFormat6())
1789
self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('a')._format,
1790
bzrlib.bzrdir.BzrDirMetaFormat1)
1791
self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('b')._format,
1792
bzrlib.bzrdir.BzrDirFormat6)
1794
def test_make_branch_and_memory_tree(self):
1795
# we should be able to get a new branch and a mutable tree from
1796
# TestCaseWithTransport
1797
tree = self.make_branch_and_memory_tree('a')
1798
self.assertIsInstance(tree, bzrlib.memorytree.MemoryTree)
1800
def test_make_tree_for_local_vfs_backed_transport(self):
1801
# make_branch_and_tree has to use local branch and repositories
1802
# when the vfs transport and local disk are colocated, even if
1803
# a different transport is in use for url generation.
1804
self.transport_server = test_server.FakeVFATServer
1805
self.assertFalse(self.get_url('t1').startswith('file://'))
1806
tree = self.make_branch_and_tree('t1')
1807
base = tree.bzrdir.root_transport.base
1808
self.assertStartsWith(base, 'file://')
1809
self.assertEquals(tree.bzrdir.root_transport,
1810
tree.branch.bzrdir.root_transport)
1811
self.assertEquals(tree.bzrdir.root_transport,
1812
tree.branch.repository.bzrdir.root_transport)
1815
class SelfTestHelper:
1817
def run_selftest(self, **kwargs):
1818
"""Run selftest returning its output."""
1820
old_transport = bzrlib.tests.default_transport
1821
old_root = tests.TestCaseWithMemoryTransport.TEST_ROOT
1822
tests.TestCaseWithMemoryTransport.TEST_ROOT = None
1824
self.assertEqual(True, tests.selftest(stream=output, **kwargs))
1826
bzrlib.tests.default_transport = old_transport
1827
tests.TestCaseWithMemoryTransport.TEST_ROOT = old_root
1832
class TestSelftest(tests.TestCase, SelfTestHelper):
1833
"""Tests of bzrlib.tests.selftest."""
1835
def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
1838
factory_called.append(True)
1839
return TestUtil.TestSuite()
1842
self.apply_redirected(out, err, None, bzrlib.tests.selftest,
1843
test_suite_factory=factory)
1844
self.assertEqual([True], factory_called)
1847
"""A test suite factory."""
1848
class Test(tests.TestCase):
1855
return TestUtil.TestSuite([Test("a"), Test("b"), Test("c")])
1857
def test_list_only(self):
1858
output = self.run_selftest(test_suite_factory=self.factory,
1860
self.assertEqual(3, len(output.readlines()))
1862
def test_list_only_filtered(self):
1863
output = self.run_selftest(test_suite_factory=self.factory,
1864
list_only=True, pattern="Test.b")
1865
self.assertEndsWith(output.getvalue(), "Test.b\n")
1866
self.assertLength(1, output.readlines())
1868
def test_list_only_excludes(self):
1869
output = self.run_selftest(test_suite_factory=self.factory,
1870
list_only=True, exclude_pattern="Test.b")
1871
self.assertNotContainsRe("Test.b", output.getvalue())
1872
self.assertLength(2, output.readlines())
1874
def test_lsprof_tests(self):
1875
self.requireFeature(test_lsprof.LSProfFeature)
1878
def __call__(test, result):
1880
def run(test, result):
1881
self.assertIsInstance(result, tests.ForwardingResult)
1882
calls.append("called")
1883
def countTestCases(self):
1885
self.run_selftest(test_suite_factory=Test, lsprof_tests=True)
1886
self.assertLength(1, calls)
1888
def test_random(self):
1889
# test randomising by listing a number of tests.
1890
output_123 = self.run_selftest(test_suite_factory=self.factory,
1891
list_only=True, random_seed="123")
1892
output_234 = self.run_selftest(test_suite_factory=self.factory,
1893
list_only=True, random_seed="234")
1894
self.assertNotEqual(output_123, output_234)
1895
# "Randominzing test order..\n\n
1896
self.assertLength(5, output_123.readlines())
1897
self.assertLength(5, output_234.readlines())
1899
def test_random_reuse_is_same_order(self):
1900
# test randomising by listing a number of tests.
1901
expected = self.run_selftest(test_suite_factory=self.factory,
1902
list_only=True, random_seed="123")
1903
repeated = self.run_selftest(test_suite_factory=self.factory,
1904
list_only=True, random_seed="123")
1905
self.assertEqual(expected.getvalue(), repeated.getvalue())
1907
def test_runner_class(self):
1908
self.requireFeature(features.subunit)
1909
from subunit import ProtocolTestCase
1910
stream = self.run_selftest(runner_class=tests.SubUnitBzrRunner,
1911
test_suite_factory=self.factory)
1912
test = ProtocolTestCase(stream)
1913
result = unittest.TestResult()
1915
self.assertEqual(3, result.testsRun)
1917
def test_starting_with_single_argument(self):
1918
output = self.run_selftest(test_suite_factory=self.factory,
1919
starting_with=['bzrlib.tests.test_selftest.Test.a'],
1921
self.assertEqual('bzrlib.tests.test_selftest.Test.a\n',
1924
def test_starting_with_multiple_argument(self):
1925
output = self.run_selftest(test_suite_factory=self.factory,
1926
starting_with=['bzrlib.tests.test_selftest.Test.a',
1927
'bzrlib.tests.test_selftest.Test.b'],
1929
self.assertEqual('bzrlib.tests.test_selftest.Test.a\n'
1930
'bzrlib.tests.test_selftest.Test.b\n',
1933
def check_transport_set(self, transport_server):
1934
captured_transport = []
1935
def seen_transport(a_transport):
1936
captured_transport.append(a_transport)
1937
class Capture(tests.TestCase):
1939
seen_transport(bzrlib.tests.default_transport)
1941
return TestUtil.TestSuite([Capture("a")])
1942
self.run_selftest(transport=transport_server, test_suite_factory=factory)
1943
self.assertEqual(transport_server, captured_transport[0])
1945
def test_transport_sftp(self):
1946
self.requireFeature(features.paramiko)
1947
from bzrlib.tests import stub_sftp
1948
self.check_transport_set(stub_sftp.SFTPAbsoluteServer)
1950
def test_transport_memory(self):
1951
self.check_transport_set(memory.MemoryServer)
1954
class TestSelftestWithIdList(tests.TestCaseInTempDir, SelfTestHelper):
1955
# Does IO: reads test.list
1957
def test_load_list(self):
1958
# Provide a list with one test - this test.
1959
test_id_line = '%s\n' % self.id()
1960
self.build_tree_contents([('test.list', test_id_line)])
1961
# And generate a list of the tests in the suite.
1962
stream = self.run_selftest(load_list='test.list', list_only=True)
1963
self.assertEqual(test_id_line, stream.getvalue())
1965
def test_load_unknown(self):
1966
# Provide a list with one test - this test.
1967
# And generate a list of the tests in the suite.
1968
err = self.assertRaises(errors.NoSuchFile, self.run_selftest,
1969
load_list='missing file name', list_only=True)
1972
class TestRunBzr(tests.TestCase):
1977
def _run_bzr_core(self, argv, retcode=0, encoding=None, stdin=None,
1979
"""Override _run_bzr_core to test how it is invoked by run_bzr.
1981
Attempts to run bzr from inside this class don't actually run it.
1983
We test how run_bzr actually invokes bzr in another location. Here we
1984
only need to test that it passes the right parameters to run_bzr.
1986
self.argv = list(argv)
1987
self.retcode = retcode
1988
self.encoding = encoding
1990
self.working_dir = working_dir
1991
return self.retcode, self.out, self.err
1993
def test_run_bzr_error(self):
1994
self.out = "It sure does!\n"
1995
out, err = self.run_bzr_error(['^$'], ['rocks'], retcode=34)
1996
self.assertEqual(['rocks'], self.argv)
1997
self.assertEqual(34, self.retcode)
1998
self.assertEqual('It sure does!\n', out)
1999
self.assertEquals(out, self.out)
2000
self.assertEqual('', err)
2001
self.assertEquals(err, self.err)
2003
def test_run_bzr_error_regexes(self):
2005
self.err = "bzr: ERROR: foobarbaz is not versioned"
2006
out, err = self.run_bzr_error(
2007
["bzr: ERROR: foobarbaz is not versioned"],
2008
['file-id', 'foobarbaz'])
2010
def test_encoding(self):
2011
"""Test that run_bzr passes encoding to _run_bzr_core"""
2012
self.run_bzr('foo bar')
2013
self.assertEqual(None, self.encoding)
2014
self.assertEqual(['foo', 'bar'], self.argv)
2016
self.run_bzr('foo bar', encoding='baz')
2017
self.assertEqual('baz', self.encoding)
2018
self.assertEqual(['foo', 'bar'], self.argv)
2020
def test_retcode(self):
2021
"""Test that run_bzr passes retcode to _run_bzr_core"""
2022
# Default is retcode == 0
2023
self.run_bzr('foo bar')
2024
self.assertEqual(0, self.retcode)
2025
self.assertEqual(['foo', 'bar'], self.argv)
2027
self.run_bzr('foo bar', retcode=1)
2028
self.assertEqual(1, self.retcode)
2029
self.assertEqual(['foo', 'bar'], self.argv)
2031
self.run_bzr('foo bar', retcode=None)
2032
self.assertEqual(None, self.retcode)
2033
self.assertEqual(['foo', 'bar'], self.argv)
2035
self.run_bzr(['foo', 'bar'], retcode=3)
2036
self.assertEqual(3, self.retcode)
2037
self.assertEqual(['foo', 'bar'], self.argv)
2039
def test_stdin(self):
2040
# test that the stdin keyword to run_bzr is passed through to
2041
# _run_bzr_core as-is. We do this by overriding
2042
# _run_bzr_core in this class, and then calling run_bzr,
2043
# which is a convenience function for _run_bzr_core, so
2045
self.run_bzr('foo bar', stdin='gam')
2046
self.assertEqual('gam', self.stdin)
2047
self.assertEqual(['foo', 'bar'], self.argv)
2049
self.run_bzr('foo bar', stdin='zippy')
2050
self.assertEqual('zippy', self.stdin)
2051
self.assertEqual(['foo', 'bar'], self.argv)
2053
def test_working_dir(self):
2054
"""Test that run_bzr passes working_dir to _run_bzr_core"""
2055
self.run_bzr('foo bar')
2056
self.assertEqual(None, self.working_dir)
2057
self.assertEqual(['foo', 'bar'], self.argv)
2059
self.run_bzr('foo bar', working_dir='baz')
2060
self.assertEqual('baz', self.working_dir)
2061
self.assertEqual(['foo', 'bar'], self.argv)
2063
def test_reject_extra_keyword_arguments(self):
2064
self.assertRaises(TypeError, self.run_bzr, "foo bar",
2065
error_regex=['error message'])
2068
class TestRunBzrCaptured(tests.TestCaseWithTransport):
2069
# Does IO when testing the working_dir parameter.
2071
def apply_redirected(self, stdin=None, stdout=None, stderr=None,
2072
a_callable=None, *args, **kwargs):
2074
self.factory_stdin = getattr(bzrlib.ui.ui_factory, "stdin", None)
2075
self.factory = bzrlib.ui.ui_factory
2076
self.working_dir = osutils.getcwd()
2077
stdout.write('foo\n')
2078
stderr.write('bar\n')
2081
def test_stdin(self):
2082
# test that the stdin keyword to _run_bzr_core is passed through to
2083
# apply_redirected as a StringIO. We do this by overriding
2084
# apply_redirected in this class, and then calling _run_bzr_core,
2085
# which calls apply_redirected.
2086
self.run_bzr(['foo', 'bar'], stdin='gam')
2087
self.assertEqual('gam', self.stdin.read())
2088
self.assertTrue(self.stdin is self.factory_stdin)
2089
self.run_bzr(['foo', 'bar'], stdin='zippy')
2090
self.assertEqual('zippy', self.stdin.read())
2091
self.assertTrue(self.stdin is self.factory_stdin)
2093
def test_ui_factory(self):
2094
# each invocation of self.run_bzr should get its
2095
# own UI factory, which is an instance of TestUIFactory,
2096
# with stdin, stdout and stderr attached to the stdin,
2097
# stdout and stderr of the invoked run_bzr
2098
current_factory = bzrlib.ui.ui_factory
2099
self.run_bzr(['foo'])
2100
self.failIf(current_factory is self.factory)
2101
self.assertNotEqual(sys.stdout, self.factory.stdout)
2102
self.assertNotEqual(sys.stderr, self.factory.stderr)
2103
self.assertEqual('foo\n', self.factory.stdout.getvalue())
2104
self.assertEqual('bar\n', self.factory.stderr.getvalue())
2105
self.assertIsInstance(self.factory, tests.TestUIFactory)
2107
def test_working_dir(self):
2108
self.build_tree(['one/', 'two/'])
2109
cwd = osutils.getcwd()
2111
# Default is to work in the current directory
2112
self.run_bzr(['foo', 'bar'])
2113
self.assertEqual(cwd, self.working_dir)
2115
self.run_bzr(['foo', 'bar'], working_dir=None)
2116
self.assertEqual(cwd, self.working_dir)
2118
# The function should be run in the alternative directory
2119
# but afterwards the current working dir shouldn't be changed
2120
self.run_bzr(['foo', 'bar'], working_dir='one')
2121
self.assertNotEqual(cwd, self.working_dir)
2122
self.assertEndsWith(self.working_dir, 'one')
2123
self.assertEqual(cwd, osutils.getcwd())
2125
self.run_bzr(['foo', 'bar'], working_dir='two')
2126
self.assertNotEqual(cwd, self.working_dir)
2127
self.assertEndsWith(self.working_dir, 'two')
2128
self.assertEqual(cwd, osutils.getcwd())
2131
class StubProcess(object):
2132
"""A stub process for testing run_bzr_subprocess."""
2134
def __init__(self, out="", err="", retcode=0):
2137
self.returncode = retcode
2139
def communicate(self):
2140
return self.out, self.err
2143
class TestWithFakedStartBzrSubprocess(tests.TestCaseWithTransport):
2144
"""Base class for tests testing how we might run bzr."""
2147
tests.TestCaseWithTransport.setUp(self)
2148
self.subprocess_calls = []
2150
def start_bzr_subprocess(self, process_args, env_changes=None,
2151
skip_if_plan_to_signal=False,
2153
allow_plugins=False):
2154
"""capture what run_bzr_subprocess tries to do."""
2155
self.subprocess_calls.append({'process_args':process_args,
2156
'env_changes':env_changes,
2157
'skip_if_plan_to_signal':skip_if_plan_to_signal,
2158
'working_dir':working_dir, 'allow_plugins':allow_plugins})
2159
return self.next_subprocess
2162
class TestRunBzrSubprocess(TestWithFakedStartBzrSubprocess):
2164
def assertRunBzrSubprocess(self, expected_args, process, *args, **kwargs):
2165
"""Run run_bzr_subprocess with args and kwargs using a stubbed process.
2167
Inside TestRunBzrSubprocessCommands we use a stub start_bzr_subprocess
2168
that will return static results. This assertion method populates those
2169
results and also checks the arguments run_bzr_subprocess generates.
2171
self.next_subprocess = process
2173
result = self.run_bzr_subprocess(*args, **kwargs)
2175
self.next_subprocess = None
2176
for key, expected in expected_args.iteritems():
2177
self.assertEqual(expected, self.subprocess_calls[-1][key])
2180
self.next_subprocess = None
2181
for key, expected in expected_args.iteritems():
2182
self.assertEqual(expected, self.subprocess_calls[-1][key])
2185
def test_run_bzr_subprocess(self):
2186
"""The run_bzr_helper_external command behaves nicely."""
2187
self.assertRunBzrSubprocess({'process_args':['--version']},
2188
StubProcess(), '--version')
2189
self.assertRunBzrSubprocess({'process_args':['--version']},
2190
StubProcess(), ['--version'])
2191
# retcode=None disables retcode checking
2192
result = self.assertRunBzrSubprocess({},
2193
StubProcess(retcode=3), '--version', retcode=None)
2194
result = self.assertRunBzrSubprocess({},
2195
StubProcess(out="is free software"), '--version')
2196
self.assertContainsRe(result[0], 'is free software')
2197
# Running a subcommand that is missing errors
2198
self.assertRaises(AssertionError, self.assertRunBzrSubprocess,
2199
{'process_args':['--versionn']}, StubProcess(retcode=3),
2201
# Unless it is told to expect the error from the subprocess
2202
result = self.assertRunBzrSubprocess({},
2203
StubProcess(retcode=3), '--versionn', retcode=3)
2204
# Or to ignore retcode checking
2205
result = self.assertRunBzrSubprocess({},
2206
StubProcess(err="unknown command", retcode=3), '--versionn',
2208
self.assertContainsRe(result[1], 'unknown command')
2210
def test_env_change_passes_through(self):
2211
self.assertRunBzrSubprocess(
2212
{'env_changes':{'new':'value', 'changed':'newvalue', 'deleted':None}},
2214
env_changes={'new':'value', 'changed':'newvalue', 'deleted':None})
2216
def test_no_working_dir_passed_as_None(self):
2217
self.assertRunBzrSubprocess({'working_dir': None}, StubProcess(), '')
2219
def test_no_working_dir_passed_through(self):
2220
self.assertRunBzrSubprocess({'working_dir': 'dir'}, StubProcess(), '',
2223
def test_run_bzr_subprocess_no_plugins(self):
2224
self.assertRunBzrSubprocess({'allow_plugins': False},
2227
def test_allow_plugins(self):
2228
self.assertRunBzrSubprocess({'allow_plugins': True},
2229
StubProcess(), '', allow_plugins=True)
2232
class TestFinishBzrSubprocess(TestWithFakedStartBzrSubprocess):
2234
def test_finish_bzr_subprocess_with_error(self):
2235
"""finish_bzr_subprocess allows specification of the desired exit code.
2237
process = StubProcess(err="unknown command", retcode=3)
2238
result = self.finish_bzr_subprocess(process, retcode=3)
2239
self.assertEqual('', result[0])
2240
self.assertContainsRe(result[1], 'unknown command')
2242
def test_finish_bzr_subprocess_ignoring_retcode(self):
2243
"""finish_bzr_subprocess allows the exit code to be ignored."""
2244
process = StubProcess(err="unknown command", retcode=3)
2245
result = self.finish_bzr_subprocess(process, retcode=None)
2246
self.assertEqual('', result[0])
2247
self.assertContainsRe(result[1], 'unknown command')
2249
def test_finish_subprocess_with_unexpected_retcode(self):
2250
"""finish_bzr_subprocess raises self.failureException if the retcode is
2251
not the expected one.
2253
process = StubProcess(err="unknown command", retcode=3)
2254
self.assertRaises(self.failureException, self.finish_bzr_subprocess,
2258
class _DontSpawnProcess(Exception):
2259
"""A simple exception which just allows us to skip unnecessary steps"""
2262
class TestStartBzrSubProcess(tests.TestCase):
2264
def check_popen_state(self):
2265
"""Replace to make assertions when popen is called."""
2267
def _popen(self, *args, **kwargs):
2268
"""Record the command that is run, so that we can ensure it is correct"""
2269
self.check_popen_state()
2270
self._popen_args = args
2271
self._popen_kwargs = kwargs
2272
raise _DontSpawnProcess()
2274
def test_run_bzr_subprocess_no_plugins(self):
2275
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [])
2276
command = self._popen_args[0]
2277
self.assertEqual(sys.executable, command[0])
2278
self.assertEqual(self.get_bzr_path(), command[1])
2279
self.assertEqual(['--no-plugins'], command[2:])
2281
def test_allow_plugins(self):
2282
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2284
command = self._popen_args[0]
2285
self.assertEqual([], command[2:])
2287
def test_set_env(self):
2288
self.failIf('EXISTANT_ENV_VAR' in os.environ)
2290
def check_environment():
2291
self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2292
self.check_popen_state = check_environment
2293
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2294
env_changes={'EXISTANT_ENV_VAR':'set variable'})
2295
# not set in theparent
2296
self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2298
def test_run_bzr_subprocess_env_del(self):
2299
"""run_bzr_subprocess can remove environment variables too."""
2300
self.failIf('EXISTANT_ENV_VAR' in os.environ)
2301
def check_environment():
2302
self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2303
os.environ['EXISTANT_ENV_VAR'] = 'set variable'
2304
self.check_popen_state = check_environment
2305
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2306
env_changes={'EXISTANT_ENV_VAR':None})
2307
# Still set in parent
2308
self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2309
del os.environ['EXISTANT_ENV_VAR']
2311
def test_env_del_missing(self):
2312
self.failIf('NON_EXISTANT_ENV_VAR' in os.environ)
2313
def check_environment():
2314
self.assertFalse('NON_EXISTANT_ENV_VAR' in os.environ)
2315
self.check_popen_state = check_environment
2316
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2317
env_changes={'NON_EXISTANT_ENV_VAR':None})
2319
def test_working_dir(self):
2320
"""Test that we can specify the working dir for the child"""
2321
orig_getcwd = osutils.getcwd
2322
orig_chdir = os.chdir
2330
osutils.getcwd = getcwd
2332
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2335
osutils.getcwd = orig_getcwd
2337
os.chdir = orig_chdir
2338
self.assertEqual(['foo', 'current'], chdirs)
2340
def test_get_bzr_path_with_cwd_bzrlib(self):
2341
self.get_source_path = lambda: ""
2342
self.overrideAttr(os.path, "isfile", lambda path: True)
2343
self.assertEqual(self.get_bzr_path(), "bzr")
2346
class TestActuallyStartBzrSubprocess(tests.TestCaseWithTransport):
2347
"""Tests that really need to do things with an external bzr."""
2349
def test_start_and_stop_bzr_subprocess_send_signal(self):
2350
"""finish_bzr_subprocess raises self.failureException if the retcode is
2351
not the expected one.
2353
self.disable_missing_extensions_warning()
2354
process = self.start_bzr_subprocess(['wait-until-signalled'],
2355
skip_if_plan_to_signal=True)
2356
self.assertEqual('running\n', process.stdout.readline())
2357
result = self.finish_bzr_subprocess(process, send_signal=signal.SIGINT,
2359
self.assertEqual('', result[0])
2360
self.assertEqual('bzr: interrupted\n', result[1])
2363
class TestFeature(tests.TestCase):
2365
def test_caching(self):
2366
"""Feature._probe is called by the feature at most once."""
2367
class InstrumentedFeature(tests.Feature):
2369
super(InstrumentedFeature, self).__init__()
2372
self.calls.append('_probe')
2374
feature = InstrumentedFeature()
2376
self.assertEqual(['_probe'], feature.calls)
2378
self.assertEqual(['_probe'], feature.calls)
2380
def test_named_str(self):
2381
"""Feature.__str__ should thunk to feature_name()."""
2382
class NamedFeature(tests.Feature):
2383
def feature_name(self):
2385
feature = NamedFeature()
2386
self.assertEqual('symlinks', str(feature))
2388
def test_default_str(self):
2389
"""Feature.__str__ should default to __class__.__name__."""
2390
class NamedFeature(tests.Feature):
2392
feature = NamedFeature()
2393
self.assertEqual('NamedFeature', str(feature))
2396
class TestUnavailableFeature(tests.TestCase):
2398
def test_access_feature(self):
2399
feature = tests.Feature()
2400
exception = tests.UnavailableFeature(feature)
2401
self.assertIs(feature, exception.args[0])
2404
simple_thunk_feature = tests._CompatabilityThunkFeature(
2405
deprecated_in((2, 1, 0)),
2406
'bzrlib.tests.test_selftest',
2407
'simple_thunk_feature','UnicodeFilename',
2408
replacement_module='bzrlib.tests'
2411
class Test_CompatibilityFeature(tests.TestCase):
2413
def test_does_thunk(self):
2414
res = self.callDeprecated(
2415
['bzrlib.tests.test_selftest.simple_thunk_feature was deprecated'
2416
' in version 2.1.0. Use bzrlib.tests.UnicodeFilename instead.'],
2417
simple_thunk_feature.available)
2418
self.assertEqual(tests.UnicodeFilename.available(), res)
2421
class TestModuleAvailableFeature(tests.TestCase):
2423
def test_available_module(self):
2424
feature = tests.ModuleAvailableFeature('bzrlib.tests')
2425
self.assertEqual('bzrlib.tests', feature.module_name)
2426
self.assertEqual('bzrlib.tests', str(feature))
2427
self.assertTrue(feature.available())
2428
self.assertIs(tests, feature.module)
2430
def test_unavailable_module(self):
2431
feature = tests.ModuleAvailableFeature('bzrlib.no_such_module_exists')
2432
self.assertEqual('bzrlib.no_such_module_exists', str(feature))
2433
self.assertFalse(feature.available())
2434
self.assertIs(None, feature.module)
2437
class TestSelftestFiltering(tests.TestCase):
2440
tests.TestCase.setUp(self)
2441
self.suite = TestUtil.TestSuite()
2442
self.loader = TestUtil.TestLoader()
2443
self.suite.addTest(self.loader.loadTestsFromModule(
2444
sys.modules['bzrlib.tests.test_selftest']))
2445
self.all_names = _test_ids(self.suite)
2447
def test_condition_id_re(self):
2448
test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2449
'test_condition_id_re')
2450
filtered_suite = tests.filter_suite_by_condition(
2451
self.suite, tests.condition_id_re('test_condition_id_re'))
2452
self.assertEqual([test_name], _test_ids(filtered_suite))
2454
def test_condition_id_in_list(self):
2455
test_names = ['bzrlib.tests.test_selftest.TestSelftestFiltering.'
2456
'test_condition_id_in_list']
2457
id_list = tests.TestIdList(test_names)
2458
filtered_suite = tests.filter_suite_by_condition(
2459
self.suite, tests.condition_id_in_list(id_list))
2460
my_pattern = 'TestSelftestFiltering.*test_condition_id_in_list'
2461
re_filtered = tests.filter_suite_by_re(self.suite, my_pattern)
2462
self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
2464
def test_condition_id_startswith(self):
2465
klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
2466
start1 = klass + 'test_condition_id_starts'
2467
start2 = klass + 'test_condition_id_in'
2468
test_names = [ klass + 'test_condition_id_in_list',
2469
klass + 'test_condition_id_startswith',
2471
filtered_suite = tests.filter_suite_by_condition(
2472
self.suite, tests.condition_id_startswith([start1, start2]))
2473
self.assertEqual(test_names, _test_ids(filtered_suite))
2475
def test_condition_isinstance(self):
2476
filtered_suite = tests.filter_suite_by_condition(
2477
self.suite, tests.condition_isinstance(self.__class__))
2478
class_pattern = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
2479
re_filtered = tests.filter_suite_by_re(self.suite, class_pattern)
2480
self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
2482
def test_exclude_tests_by_condition(self):
2483
excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2484
'test_exclude_tests_by_condition')
2485
filtered_suite = tests.exclude_tests_by_condition(self.suite,
2486
lambda x:x.id() == excluded_name)
2487
self.assertEqual(len(self.all_names) - 1,
2488
filtered_suite.countTestCases())
2489
self.assertFalse(excluded_name in _test_ids(filtered_suite))
2490
remaining_names = list(self.all_names)
2491
remaining_names.remove(excluded_name)
2492
self.assertEqual(remaining_names, _test_ids(filtered_suite))
2494
def test_exclude_tests_by_re(self):
2495
self.all_names = _test_ids(self.suite)
2496
filtered_suite = tests.exclude_tests_by_re(self.suite,
2497
'exclude_tests_by_re')
2498
excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2499
'test_exclude_tests_by_re')
2500
self.assertEqual(len(self.all_names) - 1,
2501
filtered_suite.countTestCases())
2502
self.assertFalse(excluded_name in _test_ids(filtered_suite))
2503
remaining_names = list(self.all_names)
2504
remaining_names.remove(excluded_name)
2505
self.assertEqual(remaining_names, _test_ids(filtered_suite))
2507
def test_filter_suite_by_condition(self):
2508
test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2509
'test_filter_suite_by_condition')
2510
filtered_suite = tests.filter_suite_by_condition(self.suite,
2511
lambda x:x.id() == test_name)
2512
self.assertEqual([test_name], _test_ids(filtered_suite))
2514
def test_filter_suite_by_re(self):
2515
filtered_suite = tests.filter_suite_by_re(self.suite,
2516
'test_filter_suite_by_r')
2517
filtered_names = _test_ids(filtered_suite)
2518
self.assertEqual(filtered_names, ['bzrlib.tests.test_selftest.'
2519
'TestSelftestFiltering.test_filter_suite_by_re'])
2521
def test_filter_suite_by_id_list(self):
2522
test_list = ['bzrlib.tests.test_selftest.'
2523
'TestSelftestFiltering.test_filter_suite_by_id_list']
2524
filtered_suite = tests.filter_suite_by_id_list(
2525
self.suite, tests.TestIdList(test_list))
2526
filtered_names = _test_ids(filtered_suite)
2529
['bzrlib.tests.test_selftest.'
2530
'TestSelftestFiltering.test_filter_suite_by_id_list'])
2532
def test_filter_suite_by_id_startswith(self):
2533
# By design this test may fail if another test is added whose name also
2534
# begins with one of the start value used.
2535
klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
2536
start1 = klass + 'test_filter_suite_by_id_starts'
2537
start2 = klass + 'test_filter_suite_by_id_li'
2538
test_list = [klass + 'test_filter_suite_by_id_list',
2539
klass + 'test_filter_suite_by_id_startswith',
2541
filtered_suite = tests.filter_suite_by_id_startswith(
2542
self.suite, [start1, start2])
2545
_test_ids(filtered_suite),
2548
def test_preserve_input(self):
2549
# NB: Surely this is something in the stdlib to do this?
2550
self.assertTrue(self.suite is tests.preserve_input(self.suite))
2551
self.assertTrue("@#$" is tests.preserve_input("@#$"))
2553
def test_randomize_suite(self):
2554
randomized_suite = tests.randomize_suite(self.suite)
2555
# randomizing should not add or remove test names.
2556
self.assertEqual(set(_test_ids(self.suite)),
2557
set(_test_ids(randomized_suite)))
2558
# Technically, this *can* fail, because random.shuffle(list) can be
2559
# equal to list. Trying multiple times just pushes the frequency back.
2560
# As its len(self.all_names)!:1, the failure frequency should be low
2561
# enough to ignore. RBC 20071021.
2562
# It should change the order.
2563
self.assertNotEqual(self.all_names, _test_ids(randomized_suite))
2564
# But not the length. (Possibly redundant with the set test, but not
2566
self.assertEqual(len(self.all_names), len(_test_ids(randomized_suite)))
2568
def test_split_suit_by_condition(self):
2569
self.all_names = _test_ids(self.suite)
2570
condition = tests.condition_id_re('test_filter_suite_by_r')
2571
split_suite = tests.split_suite_by_condition(self.suite, condition)
2572
filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2573
'test_filter_suite_by_re')
2574
self.assertEqual([filtered_name], _test_ids(split_suite[0]))
2575
self.assertFalse(filtered_name in _test_ids(split_suite[1]))
2576
remaining_names = list(self.all_names)
2577
remaining_names.remove(filtered_name)
2578
self.assertEqual(remaining_names, _test_ids(split_suite[1]))
2580
def test_split_suit_by_re(self):
2581
self.all_names = _test_ids(self.suite)
2582
split_suite = tests.split_suite_by_re(self.suite,
2583
'test_filter_suite_by_r')
2584
filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2585
'test_filter_suite_by_re')
2586
self.assertEqual([filtered_name], _test_ids(split_suite[0]))
2587
self.assertFalse(filtered_name in _test_ids(split_suite[1]))
2588
remaining_names = list(self.all_names)
2589
remaining_names.remove(filtered_name)
2590
self.assertEqual(remaining_names, _test_ids(split_suite[1]))
2593
class TestCheckInventoryShape(tests.TestCaseWithTransport):
2595
def test_check_inventory_shape(self):
2596
files = ['a', 'b/', 'b/c']
2597
tree = self.make_branch_and_tree('.')
2598
self.build_tree(files)
2602
self.check_inventory_shape(tree.inventory, files)
2607
class TestBlackboxSupport(tests.TestCase):
2608
"""Tests for testsuite blackbox features."""
2610
def test_run_bzr_failure_not_caught(self):
2611
# When we run bzr in blackbox mode, we want any unexpected errors to
2612
# propagate up to the test suite so that it can show the error in the
2613
# usual way, and we won't get a double traceback.
2614
e = self.assertRaises(
2616
self.run_bzr, ['assert-fail'])
2617
# make sure we got the real thing, not an error from somewhere else in
2618
# the test framework
2619
self.assertEquals('always fails', str(e))
2620
# check that there's no traceback in the test log
2621
self.assertNotContainsRe(self.get_log(), r'Traceback')
2623
def test_run_bzr_user_error_caught(self):
2624
# Running bzr in blackbox mode, normal/expected/user errors should be
2625
# caught in the regular way and turned into an error message plus exit
2627
transport_server = memory.MemoryServer()
2628
transport_server.start_server()
2629
self.addCleanup(transport_server.stop_server)
2630
url = transport_server.get_url()
2631
self.permit_url(url)
2632
out, err = self.run_bzr(["log", "%s/nonexistantpath" % url], retcode=3)
2633
self.assertEqual(out, '')
2634
self.assertContainsRe(err,
2635
'bzr: ERROR: Not a branch: ".*nonexistantpath/".\n')
2638
class TestTestLoader(tests.TestCase):
2639
"""Tests for the test loader."""
2641
def _get_loader_and_module(self):
2642
"""Gets a TestLoader and a module with one test in it."""
2643
loader = TestUtil.TestLoader()
2645
class Stub(tests.TestCase):
2648
class MyModule(object):
2650
MyModule.a_class = Stub
2652
return loader, module
2654
def test_module_no_load_tests_attribute_loads_classes(self):
2655
loader, module = self._get_loader_and_module()
2656
self.assertEqual(1, loader.loadTestsFromModule(module).countTestCases())
2658
def test_module_load_tests_attribute_gets_called(self):
2659
loader, module = self._get_loader_and_module()
2660
# 'self' is here because we're faking the module with a class. Regular
2661
# load_tests do not need that :)
2662
def load_tests(self, standard_tests, module, loader):
2663
result = loader.suiteClass()
2664
for test in tests.iter_suite_tests(standard_tests):
2665
result.addTests([test, test])
2667
# add a load_tests() method which multiplies the tests from the module.
2668
module.__class__.load_tests = load_tests
2669
self.assertEqual(2, loader.loadTestsFromModule(module).countTestCases())
2671
def test_load_tests_from_module_name_smoke_test(self):
2672
loader = TestUtil.TestLoader()
2673
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2674
self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
2677
def test_load_tests_from_module_name_with_bogus_module_name(self):
2678
loader = TestUtil.TestLoader()
2679
self.assertRaises(ImportError, loader.loadTestsFromModuleName, 'bogus')
2682
class TestTestIdList(tests.TestCase):
2684
def _create_id_list(self, test_list):
2685
return tests.TestIdList(test_list)
2687
def _create_suite(self, test_id_list):
2689
class Stub(tests.TestCase):
2693
def _create_test_id(id):
2696
suite = TestUtil.TestSuite()
2697
for id in test_id_list:
2698
t = Stub('test_foo')
2699
t.id = _create_test_id(id)
2703
def _test_ids(self, test_suite):
2704
"""Get the ids for the tests in a test suite."""
2705
return [t.id() for t in tests.iter_suite_tests(test_suite)]
2707
def test_empty_list(self):
2708
id_list = self._create_id_list([])
2709
self.assertEquals({}, id_list.tests)
2710
self.assertEquals({}, id_list.modules)
2712
def test_valid_list(self):
2713
id_list = self._create_id_list(
2714
['mod1.cl1.meth1', 'mod1.cl1.meth2',
2715
'mod1.func1', 'mod1.cl2.meth2',
2717
'mod1.submod2.cl1.meth1', 'mod1.submod2.cl2.meth2',
2719
self.assertTrue(id_list.refers_to('mod1'))
2720
self.assertTrue(id_list.refers_to('mod1.submod1'))
2721
self.assertTrue(id_list.refers_to('mod1.submod2'))
2722
self.assertTrue(id_list.includes('mod1.cl1.meth1'))
2723
self.assertTrue(id_list.includes('mod1.submod1'))
2724
self.assertTrue(id_list.includes('mod1.func1'))
2726
def test_bad_chars_in_params(self):
2727
id_list = self._create_id_list(['mod1.cl1.meth1(xx.yy)'])
2728
self.assertTrue(id_list.refers_to('mod1'))
2729
self.assertTrue(id_list.includes('mod1.cl1.meth1(xx.yy)'))
2731
def test_module_used(self):
2732
id_list = self._create_id_list(['mod.class.meth'])
2733
self.assertTrue(id_list.refers_to('mod'))
2734
self.assertTrue(id_list.refers_to('mod.class'))
2735
self.assertTrue(id_list.refers_to('mod.class.meth'))
2737
def test_test_suite_matches_id_list_with_unknown(self):
2738
loader = TestUtil.TestLoader()
2739
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2740
test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',
2742
not_found, duplicates = tests.suite_matches_id_list(suite, test_list)
2743
self.assertEquals(['bogus'], not_found)
2744
self.assertEquals([], duplicates)
2746
def test_suite_matches_id_list_with_duplicates(self):
2747
loader = TestUtil.TestLoader()
2748
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2749
dupes = loader.suiteClass()
2750
for test in tests.iter_suite_tests(suite):
2752
dupes.addTest(test) # Add it again
2754
test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',]
2755
not_found, duplicates = tests.suite_matches_id_list(
2757
self.assertEquals([], not_found)
2758
self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
2762
class TestTestSuite(tests.TestCase):
2764
def test__test_suite_testmod_names(self):
2765
# Test that a plausible list of test module names are returned
2766
# by _test_suite_testmod_names.
2767
test_list = tests._test_suite_testmod_names()
2769
'bzrlib.tests.blackbox',
2770
'bzrlib.tests.per_transport',
2771
'bzrlib.tests.test_selftest',
2775
def test__test_suite_modules_to_doctest(self):
2776
# Test that a plausible list of modules to doctest is returned
2777
# by _test_suite_modules_to_doctest.
2778
test_list = tests._test_suite_modules_to_doctest()
2780
# When docstrings are stripped, there are no modules to doctest
2781
self.assertEqual([], test_list)
2788
def test_test_suite(self):
2789
# test_suite() loads the entire test suite to operate. To avoid this
2790
# overhead, and yet still be confident that things are happening,
2791
# we temporarily replace two functions used by test_suite with
2792
# test doubles that supply a few sample tests to load, and check they
2795
def testmod_names():
2796
calls.append("testmod_names")
2798
'bzrlib.tests.blackbox.test_branch',
2799
'bzrlib.tests.per_transport',
2800
'bzrlib.tests.test_selftest',
2802
self.overrideAttr(tests, '_test_suite_testmod_names', testmod_names)
2804
calls.append("modules_to_doctest")
2807
return ['bzrlib.timestamp']
2808
self.overrideAttr(tests, '_test_suite_modules_to_doctest', doctests)
2809
expected_test_list = [
2811
'bzrlib.tests.blackbox.test_branch.TestBranch.test_branch',
2812
('bzrlib.tests.per_transport.TransportTests'
2813
'.test_abspath(LocalTransport,LocalURLServer)'),
2814
'bzrlib.tests.test_selftest.TestTestSuite.test_test_suite',
2815
# plugins can't be tested that way since selftest may be run with
2818
if __doc__ is not None:
2819
expected_test_list.extend([
2820
# modules_to_doctest
2821
'bzrlib.timestamp.format_highres_date',
2823
suite = tests.test_suite()
2824
self.assertEqual(set(["testmod_names", "modules_to_doctest"]),
2826
self.assertSubset(expected_test_list, _test_ids(suite))
2828
def test_test_suite_list_and_start(self):
2829
# We cannot test this at the same time as the main load, because we want
2830
# to know that starting_with == None works. So a second load is
2831
# incurred - note that the starting_with parameter causes a partial load
2832
# rather than a full load so this test should be pretty quick.
2833
test_list = ['bzrlib.tests.test_selftest.TestTestSuite.test_test_suite']
2834
suite = tests.test_suite(test_list,
2835
['bzrlib.tests.test_selftest.TestTestSuite'])
2836
# test_test_suite_list_and_start is not included
2837
self.assertEquals(test_list, _test_ids(suite))
2840
class TestLoadTestIdList(tests.TestCaseInTempDir):
2842
def _create_test_list_file(self, file_name, content):
2843
fl = open(file_name, 'wt')
2847
def test_load_unknown(self):
2848
self.assertRaises(errors.NoSuchFile,
2849
tests.load_test_id_list, 'i_do_not_exist')
2851
def test_load_test_list(self):
2852
test_list_fname = 'test.list'
2853
self._create_test_list_file(test_list_fname,
2854
'mod1.cl1.meth1\nmod2.cl2.meth2\n')
2855
tlist = tests.load_test_id_list(test_list_fname)
2856
self.assertEquals(2, len(tlist))
2857
self.assertEquals('mod1.cl1.meth1', tlist[0])
2858
self.assertEquals('mod2.cl2.meth2', tlist[1])
2860
def test_load_dirty_file(self):
2861
test_list_fname = 'test.list'
2862
self._create_test_list_file(test_list_fname,
2863
' mod1.cl1.meth1\n\nmod2.cl2.meth2 \n'
2865
tlist = tests.load_test_id_list(test_list_fname)
2866
self.assertEquals(4, len(tlist))
2867
self.assertEquals('mod1.cl1.meth1', tlist[0])
2868
self.assertEquals('', tlist[1])
2869
self.assertEquals('mod2.cl2.meth2', tlist[2])
2870
self.assertEquals('bar baz', tlist[3])
2873
class TestFilteredByModuleTestLoader(tests.TestCase):
2875
def _create_loader(self, test_list):
2876
id_filter = tests.TestIdList(test_list)
2877
loader = TestUtil.FilteredByModuleTestLoader(id_filter.refers_to)
2880
def test_load_tests(self):
2881
test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
2882
loader = self._create_loader(test_list)
2883
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2884
self.assertEquals(test_list, _test_ids(suite))
2886
def test_exclude_tests(self):
2887
test_list = ['bogus']
2888
loader = self._create_loader(test_list)
2889
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2890
self.assertEquals([], _test_ids(suite))
2893
class TestFilteredByNameStartTestLoader(tests.TestCase):
2895
def _create_loader(self, name_start):
2896
def needs_module(name):
2897
return name.startswith(name_start) or name_start.startswith(name)
2898
loader = TestUtil.FilteredByModuleTestLoader(needs_module)
2901
def test_load_tests(self):
2902
test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
2903
loader = self._create_loader('bzrlib.tests.test_samp')
2905
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2906
self.assertEquals(test_list, _test_ids(suite))
2908
def test_load_tests_inside_module(self):
2909
test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
2910
loader = self._create_loader('bzrlib.tests.test_sampler.Demo')
2912
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2913
self.assertEquals(test_list, _test_ids(suite))
2915
def test_exclude_tests(self):
2916
test_list = ['bogus']
2917
loader = self._create_loader('bogus')
2919
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2920
self.assertEquals([], _test_ids(suite))
2923
class TestTestPrefixRegistry(tests.TestCase):
2925
def _get_registry(self):
2926
tp_registry = tests.TestPrefixAliasRegistry()
2929
def test_register_new_prefix(self):
2930
tpr = self._get_registry()
2931
tpr.register('foo', 'fff.ooo.ooo')
2932
self.assertEquals('fff.ooo.ooo', tpr.get('foo'))
2934
def test_register_existing_prefix(self):
2935
tpr = self._get_registry()
2936
tpr.register('bar', 'bbb.aaa.rrr')
2937
tpr.register('bar', 'bBB.aAA.rRR')
2938
self.assertEquals('bbb.aaa.rrr', tpr.get('bar'))
2939
self.assertThat(self.get_log(),
2940
DocTestMatches("...bar...bbb.aaa.rrr...BB.aAA.rRR", ELLIPSIS))
2942
def test_get_unknown_prefix(self):
2943
tpr = self._get_registry()
2944
self.assertRaises(KeyError, tpr.get, 'I am not a prefix')
2946
def test_resolve_prefix(self):
2947
tpr = self._get_registry()
2948
tpr.register('bar', 'bb.aa.rr')
2949
self.assertEquals('bb.aa.rr', tpr.resolve_alias('bar'))
2951
def test_resolve_unknown_alias(self):
2952
tpr = self._get_registry()
2953
self.assertRaises(errors.BzrCommandError,
2954
tpr.resolve_alias, 'I am not a prefix')
2956
def test_predefined_prefixes(self):
2957
tpr = tests.test_prefix_alias_registry
2958
self.assertEquals('bzrlib', tpr.resolve_alias('bzrlib'))
2959
self.assertEquals('bzrlib.doc', tpr.resolve_alias('bd'))
2960
self.assertEquals('bzrlib.utils', tpr.resolve_alias('bu'))
2961
self.assertEquals('bzrlib.tests', tpr.resolve_alias('bt'))
2962
self.assertEquals('bzrlib.tests.blackbox', tpr.resolve_alias('bb'))
2963
self.assertEquals('bzrlib.plugins', tpr.resolve_alias('bp'))
2966
class TestRunSuite(tests.TestCase):
2968
def test_runner_class(self):
2969
"""run_suite accepts and uses a runner_class keyword argument."""
2970
class Stub(tests.TestCase):
2973
suite = Stub("test_foo")
2975
class MyRunner(tests.TextTestRunner):
2976
def run(self, test):
2978
return tests.ExtendedTestResult(self.stream, self.descriptions,
2980
tests.run_suite(suite, runner_class=MyRunner, stream=StringIO())
2981
self.assertLength(1, calls)