1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
"""Tests for the test framework."""
21
from StringIO import StringIO
37
from bzrlib.progress import _BaseProgressBar
38
from bzrlib.repofmt import weaverepo
39
from bzrlib.symbol_versioning import (
44
from bzrlib.tests import (
51
TestCaseWithMemoryTransport,
52
TestCaseWithTransport,
61
exclude_tests_by_condition,
63
filter_suite_by_condition,
73
from bzrlib.tests.test_sftp_transport import TestCaseWithSFTPServer
74
from bzrlib.tests.TestUtil import _load_module_by_name
75
from bzrlib.trace import note
76
from bzrlib.transport.memory import MemoryServer, MemoryTransport
77
from bzrlib.version import _get_bzr_source_tree
80
def _test_ids(test_suite):
81
"""Get the ids for the tests in a test suite."""
82
return [t.id() for t in iter_suite_tests(test_suite)]
85
class SelftestTests(TestCase):
87
def test_import_tests(self):
88
mod = _load_module_by_name('bzrlib.tests.test_selftest')
89
self.assertEqual(mod.SelftestTests, SelftestTests)
91
def test_import_test_failure(self):
92
self.assertRaises(ImportError,
96
class MetaTestLog(TestCase):
98
def test_logging(self):
99
"""Test logs are captured when a test fails."""
100
self.log('a test message')
101
self._log_file.flush()
102
self.assertContainsRe(self._get_log(keep_log_file=True),
106
class TestTreeShape(TestCaseInTempDir):
108
def test_unicode_paths(self):
109
filename = u'hell\u00d8'
111
self.build_tree_contents([(filename, 'contents of hello')])
112
except UnicodeEncodeError:
113
raise TestSkipped("can't build unicode working tree in "
114
"filesystem encoding %s" % sys.getfilesystemencoding())
115
self.failUnlessExists(filename)
118
class TestTransportProviderAdapter(TestCase):
119
"""A group of tests that test the transport implementation adaption core.
121
This is a meta test that the tests are applied to all available
124
This will be generalised in the future which is why it is in this
125
test file even though it is specific to transport tests at the moment.
128
def test_get_transport_permutations(self):
129
# this checks that we the module get_test_permutations call
130
# is made by the adapter get_transport_test_permitations method.
131
class MockModule(object):
132
def get_test_permutations(self):
133
return sample_permutation
134
sample_permutation = [(1,2), (3,4)]
135
from bzrlib.tests.test_transport_implementations \
136
import TransportTestProviderAdapter
137
adapter = TransportTestProviderAdapter()
138
self.assertEqual(sample_permutation,
139
adapter.get_transport_test_permutations(MockModule()))
141
def test_adapter_checks_all_modules(self):
142
# this checks that the adapter returns as many permurtations as
143
# there are in all the registered# transport modules for there
144
# - we assume if this matches its probably doing the right thing
145
# especially in combination with the tests for setting the right
147
from bzrlib.tests.test_transport_implementations \
148
import TransportTestProviderAdapter
149
from bzrlib.transport import _get_transport_modules
150
modules = _get_transport_modules()
151
permutation_count = 0
152
for module in modules:
154
permutation_count += len(reduce(getattr,
155
(module + ".get_test_permutations").split('.')[1:],
156
__import__(module))())
157
except errors.DependencyNotPresent:
159
input_test = TestTransportProviderAdapter(
160
"test_adapter_sets_transport_class")
161
adapter = TransportTestProviderAdapter()
162
self.assertEqual(permutation_count,
163
len(list(iter(adapter.adapt(input_test)))))
165
def test_adapter_sets_transport_class(self):
166
# Check that the test adapter inserts a transport and server into the
169
# This test used to know about all the possible transports and the
170
# order they were returned but that seems overly brittle (mbp
172
from bzrlib.tests.test_transport_implementations \
173
import TransportTestProviderAdapter
174
scenarios = TransportTestProviderAdapter().scenarios
175
# there are at least that many builtin transports
176
self.assertTrue(len(scenarios) > 6)
177
one_scenario = scenarios[0]
178
self.assertIsInstance(one_scenario[0], str)
179
self.assertTrue(issubclass(one_scenario[1]["transport_class"],
180
bzrlib.transport.Transport))
181
self.assertTrue(issubclass(one_scenario[1]["transport_server"],
182
bzrlib.transport.Server))
185
class TestBranchProviderAdapter(TestCase):
186
"""A group of tests that test the branch implementation test adapter."""
188
def test_constructor(self):
189
# check that constructor parameters are passed through to the adapted
191
from bzrlib.tests.branch_implementations import BranchTestProviderAdapter
194
formats = [("c", "C"), ("d", "D")]
195
adapter = BranchTestProviderAdapter(server1, server2, formats)
196
self.assertEqual(2, len(adapter.scenarios))
199
{'branch_format': 'c',
200
'bzrdir_format': 'C',
201
'transport_readonly_server': 'b',
202
'transport_server': 'a'}),
204
{'branch_format': 'd',
205
'bzrdir_format': 'D',
206
'transport_readonly_server': 'b',
207
'transport_server': 'a'})],
211
class TestBzrDirProviderAdapter(TestCase):
212
"""A group of tests that test the bzr dir implementation test adapter."""
214
def test_adapted_tests(self):
215
# check that constructor parameters are passed through to the adapted
217
from bzrlib.tests.bzrdir_implementations import BzrDirTestProviderAdapter
222
adapter = BzrDirTestProviderAdapter(vfs_factory,
223
server1, server2, formats)
226
{'bzrdir_format': 'c',
227
'transport_readonly_server': 'b',
228
'transport_server': 'a',
229
'vfs_transport_factory': 'v'}),
231
{'bzrdir_format': 'd',
232
'transport_readonly_server': 'b',
233
'transport_server': 'a',
234
'vfs_transport_factory': 'v'})],
238
class TestRepositoryProviderAdapter(TestCase):
239
"""A group of tests that test the repository implementation test adapter."""
241
def test_constructor(self):
242
# check that constructor parameters are passed through to the
244
from bzrlib.tests.repository_implementations import RepositoryTestProviderAdapter
247
formats = [("c", "C"), ("d", "D")]
248
adapter = RepositoryTestProviderAdapter(server1, server2, formats)
251
{'bzrdir_format': 'C',
252
'repository_format': 'c',
253
'transport_readonly_server': 'b',
254
'transport_server': 'a'}),
256
{'bzrdir_format': 'D',
257
'repository_format': 'd',
258
'transport_readonly_server': 'b',
259
'transport_server': 'a'})],
262
def test_setting_vfs_transport(self):
263
"""The vfs_transport_factory can be set optionally."""
264
from bzrlib.tests.repository_implementations import RepositoryTestProviderAdapter
265
formats = [("a", "b"), ("c", "d")]
266
adapter = RepositoryTestProviderAdapter(None, None, formats,
267
vfs_transport_factory="vfs")
270
{'bzrdir_format': 'b',
271
'repository_format': 'a',
272
'transport_readonly_server': None,
273
'transport_server': None,
274
'vfs_transport_factory': 'vfs'}),
276
{'bzrdir_format': 'd',
277
'repository_format': 'c',
278
'transport_readonly_server': None,
279
'transport_server': None,
280
'vfs_transport_factory': 'vfs'})],
283
def test_formats_to_scenarios(self):
284
"""The adapter can generate all the scenarios needed."""
285
from bzrlib.tests.repository_implementations import RepositoryTestProviderAdapter
286
no_vfs_adapter = RepositoryTestProviderAdapter("server", "readonly",
288
vfs_adapter = RepositoryTestProviderAdapter("server", "readonly",
289
[], vfs_transport_factory="vfs")
290
# no_vfs generate scenarios without vfs_transport_factor
291
formats = [("c", "C"), (1, "D")]
294
{'bzrdir_format': 'C',
295
'repository_format': 'c',
296
'transport_readonly_server': 'readonly',
297
'transport_server': 'server'}),
299
{'bzrdir_format': 'D',
300
'repository_format': 1,
301
'transport_readonly_server': 'readonly',
302
'transport_server': 'server'})],
303
no_vfs_adapter.formats_to_scenarios(formats))
306
{'bzrdir_format': 'C',
307
'repository_format': 'c',
308
'transport_readonly_server': 'readonly',
309
'transport_server': 'server',
310
'vfs_transport_factory': 'vfs'}),
312
{'bzrdir_format': 'D',
313
'repository_format': 1,
314
'transport_readonly_server': 'readonly',
315
'transport_server': 'server',
316
'vfs_transport_factory': 'vfs'})],
317
vfs_adapter.formats_to_scenarios(formats))
320
class TestTestScenarioApplier(TestCase):
321
"""Tests for the test adaption facilities."""
323
def test_adapt_applies_scenarios(self):
324
from bzrlib.tests.repository_implementations import TestScenarioApplier
325
input_test = TestTestScenarioApplier("test_adapt_test_to_scenario")
326
adapter = TestScenarioApplier()
327
adapter.scenarios = [("1", "dict"), ("2", "settings")]
329
def capture_call(test, scenario):
330
calls.append((test, scenario))
332
adapter.adapt_test_to_scenario = capture_call
333
adapter.adapt(input_test)
334
self.assertEqual([(input_test, ("1", "dict")),
335
(input_test, ("2", "settings"))], calls)
337
def test_adapt_test_to_scenario(self):
338
from bzrlib.tests.repository_implementations import TestScenarioApplier
339
input_test = TestTestScenarioApplier("test_adapt_test_to_scenario")
340
adapter = TestScenarioApplier()
341
# setup two adapted tests
342
adapted_test1 = adapter.adapt_test_to_scenario(input_test,
344
{"bzrdir_format":"bzr_format",
345
"repository_format":"repo_fmt",
346
"transport_server":"transport_server",
347
"transport_readonly_server":"readonly-server"}))
348
adapted_test2 = adapter.adapt_test_to_scenario(input_test,
349
("new id 2", {"bzrdir_format":None}))
350
# input_test should have been altered.
351
self.assertRaises(AttributeError, getattr, input_test, "bzrdir_format")
352
# the new tests are mutually incompatible, ensuring it has
353
# made new ones, and unspecified elements in the scenario
354
# should not have been altered.
355
self.assertEqual("bzr_format", adapted_test1.bzrdir_format)
356
self.assertEqual("repo_fmt", adapted_test1.repository_format)
357
self.assertEqual("transport_server", adapted_test1.transport_server)
358
self.assertEqual("readonly-server",
359
adapted_test1.transport_readonly_server)
361
"bzrlib.tests.test_selftest.TestTestScenarioApplier."
362
"test_adapt_test_to_scenario(new id)",
364
self.assertEqual(None, adapted_test2.bzrdir_format)
366
"bzrlib.tests.test_selftest.TestTestScenarioApplier."
367
"test_adapt_test_to_scenario(new id 2)",
371
class TestInterRepositoryProviderAdapter(TestCase):
372
"""A group of tests that test the InterRepository test adapter."""
374
def test_adapted_tests(self):
375
# check that constructor parameters are passed through to the adapted
377
from bzrlib.tests.interrepository_implementations import \
378
InterRepositoryTestProviderAdapter
381
formats = [(str, "C1", "C2"), (int, "D1", "D2")]
382
adapter = InterRepositoryTestProviderAdapter(server1, server2, formats)
385
{'interrepo_class': str,
386
'repository_format': 'C1',
387
'repository_format_to': 'C2',
388
'transport_readonly_server': 'b',
389
'transport_server': 'a'}),
391
{'interrepo_class': int,
392
'repository_format': 'D1',
393
'repository_format_to': 'D2',
394
'transport_readonly_server': 'b',
395
'transport_server': 'a'})],
396
adapter.formats_to_scenarios(formats))
399
class TestInterVersionedFileProviderAdapter(TestCase):
400
"""A group of tests that test the InterVersionedFile test adapter."""
402
def test_scenarios(self):
403
# check that constructor parameters are passed through to the adapted
405
from bzrlib.tests.interversionedfile_implementations \
406
import InterVersionedFileTestProviderAdapter
409
formats = [(str, "C1", "C2"), (int, "D1", "D2")]
410
adapter = InterVersionedFileTestProviderAdapter(server1, server2, formats)
413
{'interversionedfile_class':str,
414
'transport_readonly_server': 'b',
415
'transport_server': 'a',
416
'versionedfile_factory': 'C1',
417
'versionedfile_factory_to': 'C2'}),
419
{'interversionedfile_class': int,
420
'transport_readonly_server': 'b',
421
'transport_server': 'a',
422
'versionedfile_factory': 'D1',
423
'versionedfile_factory_to': 'D2'})],
427
class TestRevisionStoreProviderAdapter(TestCase):
428
"""A group of tests that test the RevisionStore test adapter."""
430
def test_scenarios(self):
431
# check that constructor parameters are passed through to the adapted
433
from bzrlib.tests.revisionstore_implementations \
434
import RevisionStoreTestProviderAdapter
435
# revision stores need a store factory - i.e. RevisionKnit
436
#, a readonly and rw transport
440
store_factories = ["c", "d"]
441
adapter = RevisionStoreTestProviderAdapter(server1, server2, store_factories)
444
{'store_factory': 'c',
445
'transport_readonly_server': 'b',
446
'transport_server': 'a'}),
448
{'store_factory': 'd',
449
'transport_readonly_server': 'b',
450
'transport_server': 'a'})],
454
class TestWorkingTreeProviderAdapter(TestCase):
455
"""A group of tests that test the workingtree implementation test adapter."""
457
def test_scenarios(self):
458
# check that constructor parameters are passed through to the adapted
460
from bzrlib.tests.workingtree_implementations \
461
import WorkingTreeTestProviderAdapter
464
formats = [("c", "C"), ("d", "D")]
465
adapter = WorkingTreeTestProviderAdapter(server1, server2, formats)
468
{'bzrdir_format': 'C',
469
'transport_readonly_server': 'b',
470
'transport_server': 'a',
471
'workingtree_format': 'c'}),
473
{'bzrdir_format': 'D',
474
'transport_readonly_server': 'b',
475
'transport_server': 'a',
476
'workingtree_format': 'd'})],
480
class TestTreeProviderAdapter(TestCase):
481
"""Test the setup of tree_implementation tests."""
483
def test_adapted_tests(self):
484
# the tree implementation adapter is meant to setup one instance for
485
# each working tree format, and one additional instance that will
486
# use the default wt format, but create a revision tree for the tests.
487
# this means that the wt ones should have the workingtree_to_test_tree
488
# attribute set to 'return_parameter' and the revision one set to
489
# revision_tree_from_workingtree.
491
from bzrlib.tests.tree_implementations import (
492
TreeTestProviderAdapter,
494
revision_tree_from_workingtree
496
from bzrlib.workingtree import WorkingTreeFormat, WorkingTreeFormat3
497
input_test = TestTreeProviderAdapter(
498
"test_adapted_tests")
501
formats = [("c", "C"), ("d", "D")]
502
adapter = TreeTestProviderAdapter(server1, server2, formats)
503
suite = adapter.adapt(input_test)
504
tests = list(iter(suite))
505
self.assertEqual(4, len(tests))
506
# this must match the default format setp up in
507
# TreeTestProviderAdapter.adapt
508
default_format = WorkingTreeFormat3
509
self.assertEqual(tests[0].workingtree_format, formats[0][0])
510
self.assertEqual(tests[0].bzrdir_format, formats[0][1])
511
self.assertEqual(tests[0].transport_server, server1)
512
self.assertEqual(tests[0].transport_readonly_server, server2)
513
self.assertEqual(tests[0].workingtree_to_test_tree, return_parameter)
514
self.assertEqual(tests[1].workingtree_format, formats[1][0])
515
self.assertEqual(tests[1].bzrdir_format, formats[1][1])
516
self.assertEqual(tests[1].transport_server, server1)
517
self.assertEqual(tests[1].transport_readonly_server, server2)
518
self.assertEqual(tests[1].workingtree_to_test_tree, return_parameter)
519
self.assertIsInstance(tests[2].workingtree_format, default_format)
520
#self.assertEqual(tests[2].bzrdir_format,
521
# default_format._matchingbzrdir)
522
self.assertEqual(tests[2].transport_server, server1)
523
self.assertEqual(tests[2].transport_readonly_server, server2)
524
self.assertEqual(tests[2].workingtree_to_test_tree,
525
revision_tree_from_workingtree)
528
class TestInterTreeProviderAdapter(TestCase):
529
"""A group of tests that test the InterTreeTestAdapter."""
531
def test_adapted_tests(self):
532
# check that constructor parameters are passed through to the adapted
534
# for InterTree tests we want the machinery to bring up two trees in
535
# each instance: the base one, and the one we are interacting with.
536
# because each optimiser can be direction specific, we need to test
537
# each optimiser in its chosen direction.
538
# unlike the TestProviderAdapter we dont want to automatically add a
539
# parameterized one for WorkingTree - the optimisers will tell us what
541
from bzrlib.tests.tree_implementations import (
543
revision_tree_from_workingtree
545
from bzrlib.tests.intertree_implementations import (
546
InterTreeTestProviderAdapter,
548
from bzrlib.workingtree import WorkingTreeFormat2, WorkingTreeFormat3
549
input_test = TestInterTreeProviderAdapter(
550
"test_adapted_tests")
553
format1 = WorkingTreeFormat2()
554
format2 = WorkingTreeFormat3()
555
formats = [(str, format1, format2, "converter1"),
556
(int, format2, format1, "converter2")]
557
adapter = InterTreeTestProviderAdapter(server1, server2, formats)
558
suite = adapter.adapt(input_test)
559
tests = list(iter(suite))
560
self.assertEqual(2, len(tests))
561
self.assertEqual(tests[0].intertree_class, formats[0][0])
562
self.assertEqual(tests[0].workingtree_format, formats[0][1])
563
self.assertEqual(tests[0].workingtree_format_to, formats[0][2])
564
self.assertEqual(tests[0].mutable_trees_to_test_trees, formats[0][3])
565
self.assertEqual(tests[0].workingtree_to_test_tree, return_parameter)
566
self.assertEqual(tests[0].transport_server, server1)
567
self.assertEqual(tests[0].transport_readonly_server, server2)
568
self.assertEqual(tests[1].intertree_class, formats[1][0])
569
self.assertEqual(tests[1].workingtree_format, formats[1][1])
570
self.assertEqual(tests[1].workingtree_format_to, formats[1][2])
571
self.assertEqual(tests[1].mutable_trees_to_test_trees, formats[1][3])
572
self.assertEqual(tests[1].workingtree_to_test_tree, return_parameter)
573
self.assertEqual(tests[1].transport_server, server1)
574
self.assertEqual(tests[1].transport_readonly_server, server2)
577
class TestTestCaseInTempDir(TestCaseInTempDir):
579
def test_home_is_not_working(self):
580
self.assertNotEqual(self.test_dir, self.test_home_dir)
581
cwd = osutils.getcwd()
582
self.assertIsSameRealPath(self.test_dir, cwd)
583
self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
586
class TestTestCaseWithMemoryTransport(TestCaseWithMemoryTransport):
588
def test_home_is_non_existant_dir_under_root(self):
589
"""The test_home_dir for TestCaseWithMemoryTransport is missing.
591
This is because TestCaseWithMemoryTransport is for tests that do not
592
need any disk resources: they should be hooked into bzrlib in such a
593
way that no global settings are being changed by the test (only a
594
few tests should need to do that), and having a missing dir as home is
595
an effective way to ensure that this is the case.
597
self.assertIsSameRealPath(
598
self.TEST_ROOT + "/MemoryTransportMissingHomeDir",
600
self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
602
def test_cwd_is_TEST_ROOT(self):
603
self.assertIsSameRealPath(self.test_dir, self.TEST_ROOT)
604
cwd = osutils.getcwd()
605
self.assertIsSameRealPath(self.test_dir, cwd)
607
def test_make_branch_and_memory_tree(self):
608
"""In TestCaseWithMemoryTransport we should not make the branch on disk.
610
This is hard to comprehensively robustly test, so we settle for making
611
a branch and checking no directory was created at its relpath.
613
tree = self.make_branch_and_memory_tree('dir')
614
# Guard against regression into MemoryTransport leaking
615
# files to disk instead of keeping them in memory.
616
self.failIf(osutils.lexists('dir'))
617
self.assertIsInstance(tree, memorytree.MemoryTree)
619
def test_make_branch_and_memory_tree_with_format(self):
620
"""make_branch_and_memory_tree should accept a format option."""
621
format = bzrdir.BzrDirMetaFormat1()
622
format.repository_format = weaverepo.RepositoryFormat7()
623
tree = self.make_branch_and_memory_tree('dir', format=format)
624
# Guard against regression into MemoryTransport leaking
625
# files to disk instead of keeping them in memory.
626
self.failIf(osutils.lexists('dir'))
627
self.assertIsInstance(tree, memorytree.MemoryTree)
628
self.assertEqual(format.repository_format.__class__,
629
tree.branch.repository._format.__class__)
631
def test_safety_net(self):
632
"""No test should modify the safety .bzr directory.
634
We just test that the _check_safety_net private method raises
635
AssertionError, it's easier than building a test suite with the same
638
# Oops, a commit in the current directory (i.e. without local .bzr
639
# directory) will crawl up the hierarchy to find a .bzr directory.
640
self.run_bzr(['commit', '-mfoo', '--unchanged'])
641
# But we have a safety net in place.
642
self.assertRaises(AssertionError, self._check_safety_net)
645
class TestTestCaseWithTransport(TestCaseWithTransport):
646
"""Tests for the convenience functions TestCaseWithTransport introduces."""
648
def test_get_readonly_url_none(self):
649
from bzrlib.transport import get_transport
650
from bzrlib.transport.memory import MemoryServer
651
from bzrlib.transport.readonly import ReadonlyTransportDecorator
652
self.vfs_transport_factory = MemoryServer
653
self.transport_readonly_server = None
654
# calling get_readonly_transport() constructs a decorator on the url
656
url = self.get_readonly_url()
657
url2 = self.get_readonly_url('foo/bar')
658
t = get_transport(url)
659
t2 = get_transport(url2)
660
self.failUnless(isinstance(t, ReadonlyTransportDecorator))
661
self.failUnless(isinstance(t2, ReadonlyTransportDecorator))
662
self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
664
def test_get_readonly_url_http(self):
665
from bzrlib.tests.http_server import HttpServer
666
from bzrlib.transport import get_transport
667
from bzrlib.transport.local import LocalURLServer
668
from bzrlib.transport.http import HttpTransportBase
669
self.transport_server = LocalURLServer
670
self.transport_readonly_server = HttpServer
671
# calling get_readonly_transport() gives us a HTTP server instance.
672
url = self.get_readonly_url()
673
url2 = self.get_readonly_url('foo/bar')
674
# the transport returned may be any HttpTransportBase subclass
675
t = get_transport(url)
676
t2 = get_transport(url2)
677
self.failUnless(isinstance(t, HttpTransportBase))
678
self.failUnless(isinstance(t2, HttpTransportBase))
679
self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
681
def test_is_directory(self):
682
"""Test assertIsDirectory assertion"""
683
t = self.get_transport()
684
self.build_tree(['a_dir/', 'a_file'], transport=t)
685
self.assertIsDirectory('a_dir', t)
686
self.assertRaises(AssertionError, self.assertIsDirectory, 'a_file', t)
687
self.assertRaises(AssertionError, self.assertIsDirectory, 'not_here', t)
690
class TestTestCaseTransports(TestCaseWithTransport):
693
super(TestTestCaseTransports, self).setUp()
694
self.vfs_transport_factory = MemoryServer
696
def test_make_bzrdir_preserves_transport(self):
697
t = self.get_transport()
698
result_bzrdir = self.make_bzrdir('subdir')
699
self.assertIsInstance(result_bzrdir.transport,
701
# should not be on disk, should only be in memory
702
self.failIfExists('subdir')
705
class TestChrootedTest(ChrootedTestCase):
707
def test_root_is_root(self):
708
from bzrlib.transport import get_transport
709
t = get_transport(self.get_readonly_url())
711
self.assertEqual(url, t.clone('..').base)
714
class MockProgress(_BaseProgressBar):
715
"""Progress-bar standin that records calls.
717
Useful for testing pb using code.
721
_BaseProgressBar.__init__(self)
725
self.calls.append(('tick',))
727
def update(self, msg=None, current=None, total=None):
728
self.calls.append(('update', msg, current, total))
731
self.calls.append(('clear',))
733
def note(self, msg, *args):
734
self.calls.append(('note', msg, args))
737
class TestTestResult(TestCase):
739
def check_timing(self, test_case, expected_re):
740
result = bzrlib.tests.TextTestResult(self._log_file,
744
test_case.run(result)
745
timed_string = result._testTimeString(test_case)
746
self.assertContainsRe(timed_string, expected_re)
748
def test_test_reporting(self):
749
class ShortDelayTestCase(TestCase):
750
def test_short_delay(self):
752
def test_short_benchmark(self):
753
self.time(time.sleep, 0.003)
754
self.check_timing(ShortDelayTestCase('test_short_delay'),
756
# if a benchmark time is given, we want a x of y style result.
757
self.check_timing(ShortDelayTestCase('test_short_benchmark'),
758
r"^ +[0-9]+ms/ +[0-9]+ms$")
760
def test_unittest_reporting_unittest_class(self):
761
# getting the time from a non-bzrlib test works ok
762
class ShortDelayTestCase(unittest.TestCase):
763
def test_short_delay(self):
765
self.check_timing(ShortDelayTestCase('test_short_delay'),
768
def test_assigned_benchmark_file_stores_date(self):
770
result = bzrlib.tests.TextTestResult(self._log_file,
775
output_string = output.getvalue()
776
# if you are wondering about the regexp please read the comment in
777
# test_bench_history (bzrlib.tests.test_selftest.TestRunner)
778
# XXX: what comment? -- Andrew Bennetts
779
self.assertContainsRe(output_string, "--date [0-9.]+")
781
def test_benchhistory_records_test_times(self):
782
result_stream = StringIO()
783
result = bzrlib.tests.TextTestResult(
787
bench_history=result_stream
790
# we want profile a call and check that its test duration is recorded
791
# make a new test instance that when run will generate a benchmark
792
example_test_case = TestTestResult("_time_hello_world_encoding")
793
# execute the test, which should succeed and record times
794
example_test_case.run(result)
795
lines = result_stream.getvalue().splitlines()
796
self.assertEqual(2, len(lines))
797
self.assertContainsRe(lines[1],
798
" *[0-9]+ms bzrlib.tests.test_selftest.TestTestResult"
799
"._time_hello_world_encoding")
801
def _time_hello_world_encoding(self):
802
"""Profile two sleep calls
804
This is used to exercise the test framework.
806
self.time(unicode, 'hello', errors='replace')
807
self.time(unicode, 'world', errors='replace')
809
def test_lsprofiling(self):
810
"""Verbose test result prints lsprof statistics from test cases."""
811
self.requireFeature(test_lsprof.LSProfFeature)
812
result_stream = StringIO()
813
result = bzrlib.tests.VerboseTestResult(
814
unittest._WritelnDecorator(result_stream),
818
# we want profile a call of some sort and check it is output by
819
# addSuccess. We dont care about addError or addFailure as they
820
# are not that interesting for performance tuning.
821
# make a new test instance that when run will generate a profile
822
example_test_case = TestTestResult("_time_hello_world_encoding")
823
example_test_case._gather_lsprof_in_benchmarks = True
824
# execute the test, which should succeed and record profiles
825
example_test_case.run(result)
826
# lsprofile_something()
827
# if this worked we want
828
# LSProf output for <built in function unicode> (['hello'], {'errors': 'replace'})
829
# CallCount Recursive Total(ms) Inline(ms) module:lineno(function)
830
# (the lsprof header)
831
# ... an arbitrary number of lines
832
# and the function call which is time.sleep.
833
# 1 0 ??? ??? ???(sleep)
834
# and then repeated but with 'world', rather than 'hello'.
835
# this should appear in the output stream of our test result.
836
output = result_stream.getvalue()
837
self.assertContainsRe(output,
838
r"LSProf output for <type 'unicode'>\(\('hello',\), {'errors': 'replace'}\)")
839
self.assertContainsRe(output,
840
r" *CallCount *Recursive *Total\(ms\) *Inline\(ms\) *module:lineno\(function\)\n")
841
self.assertContainsRe(output,
842
r"( +1 +0 +0\.\d+ +0\.\d+ +<method 'disable' of '_lsprof\.Profiler' objects>\n)?")
843
self.assertContainsRe(output,
844
r"LSProf output for <type 'unicode'>\(\('world',\), {'errors': 'replace'}\)\n")
846
def test_known_failure(self):
847
"""A KnownFailure being raised should trigger several result actions."""
848
class InstrumentedTestResult(ExtendedTestResult):
850
def report_test_start(self, test): pass
851
def report_known_failure(self, test, err):
852
self._call = test, err
853
result = InstrumentedTestResult(None, None, None, None)
855
raise KnownFailure('failed!')
856
test = unittest.FunctionTestCase(test_function)
858
# it should invoke 'report_known_failure'.
859
self.assertEqual(2, len(result._call))
860
self.assertEqual(test, result._call[0])
861
self.assertEqual(KnownFailure, result._call[1][0])
862
self.assertIsInstance(result._call[1][1], KnownFailure)
863
# we dont introspec the traceback, if the rest is ok, it would be
864
# exceptional for it not to be.
865
# it should update the known_failure_count on the object.
866
self.assertEqual(1, result.known_failure_count)
867
# the result should be successful.
868
self.assertTrue(result.wasSuccessful())
870
def test_verbose_report_known_failure(self):
871
# verbose test output formatting
872
result_stream = StringIO()
873
result = bzrlib.tests.VerboseTestResult(
874
unittest._WritelnDecorator(result_stream),
878
test = self.get_passing_test()
879
result.startTest(test)
880
prefix = len(result_stream.getvalue())
881
# the err parameter has the shape:
882
# (class, exception object, traceback)
883
# KnownFailures dont get their tracebacks shown though, so we
885
err = (KnownFailure, KnownFailure('foo'), None)
886
result.report_known_failure(test, err)
887
output = result_stream.getvalue()[prefix:]
888
lines = output.splitlines()
889
self.assertContainsRe(lines[0], r'XFAIL *\d+ms$')
890
self.assertEqual(lines[1], ' foo')
891
self.assertEqual(2, len(lines))
893
def test_text_report_known_failure(self):
894
# text test output formatting
896
result = bzrlib.tests.TextTestResult(
902
test = self.get_passing_test()
903
# this seeds the state to handle reporting the test.
904
result.startTest(test)
905
# the err parameter has the shape:
906
# (class, exception object, traceback)
907
# KnownFailures dont get their tracebacks shown though, so we
909
err = (KnownFailure, KnownFailure('foo'), None)
910
result.report_known_failure(test, err)
913
('update', '[1 in 0s] passing_test', None, None),
914
('note', 'XFAIL: %s\n%s\n', ('passing_test', err[1]))
917
# known_failures should be printed in the summary, so if we run a test
918
# after there are some known failures, the update prefix should match
920
result.known_failure_count = 3
924
('update', '[2 in 0s, 3 known failures] passing_test', None, None),
928
def get_passing_test(self):
929
"""Return a test object that can't be run usefully."""
932
return unittest.FunctionTestCase(passing_test)
934
def test_add_not_supported(self):
935
"""Test the behaviour of invoking addNotSupported."""
936
class InstrumentedTestResult(ExtendedTestResult):
937
def report_test_start(self, test): pass
938
def report_unsupported(self, test, feature):
939
self._call = test, feature
940
result = InstrumentedTestResult(None, None, None, None)
941
test = SampleTestCase('_test_pass')
943
result.startTest(test)
944
result.addNotSupported(test, feature)
945
# it should invoke 'report_unsupported'.
946
self.assertEqual(2, len(result._call))
947
self.assertEqual(test, result._call[0])
948
self.assertEqual(feature, result._call[1])
949
# the result should be successful.
950
self.assertTrue(result.wasSuccessful())
951
# it should record the test against a count of tests not run due to
953
self.assertEqual(1, result.unsupported['Feature'])
954
# and invoking it again should increment that counter
955
result.addNotSupported(test, feature)
956
self.assertEqual(2, result.unsupported['Feature'])
958
def test_verbose_report_unsupported(self):
959
# verbose test output formatting
960
result_stream = StringIO()
961
result = bzrlib.tests.VerboseTestResult(
962
unittest._WritelnDecorator(result_stream),
966
test = self.get_passing_test()
968
result.startTest(test)
969
prefix = len(result_stream.getvalue())
970
result.report_unsupported(test, feature)
971
output = result_stream.getvalue()[prefix:]
972
lines = output.splitlines()
973
self.assertEqual(lines, ['NODEP 0ms', " The feature 'Feature' is not available."])
975
def test_text_report_unsupported(self):
976
# text test output formatting
978
result = bzrlib.tests.TextTestResult(
984
test = self.get_passing_test()
986
# this seeds the state to handle reporting the test.
987
result.startTest(test)
988
result.report_unsupported(test, feature)
989
# no output on unsupported features
991
[('update', '[1 in 0s] passing_test', None, None)
994
# the number of missing features should be printed in the progress
995
# summary, so check for that.
996
result.unsupported = {'foo':0, 'bar':0}
1000
('update', '[2 in 0s, 2 missing features] passing_test', None, None),
1004
def test_unavailable_exception(self):
1005
"""An UnavailableFeature being raised should invoke addNotSupported."""
1006
class InstrumentedTestResult(ExtendedTestResult):
1008
def report_test_start(self, test): pass
1009
def addNotSupported(self, test, feature):
1010
self._call = test, feature
1011
result = InstrumentedTestResult(None, None, None, None)
1013
def test_function():
1014
raise UnavailableFeature(feature)
1015
test = unittest.FunctionTestCase(test_function)
1017
# it should invoke 'addNotSupported'.
1018
self.assertEqual(2, len(result._call))
1019
self.assertEqual(test, result._call[0])
1020
self.assertEqual(feature, result._call[1])
1021
# and not count as an error
1022
self.assertEqual(0, result.error_count)
1024
def test_strict_with_unsupported_feature(self):
1025
result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
1027
test = self.get_passing_test()
1028
feature = "Unsupported Feature"
1029
result.addNotSupported(test, feature)
1030
self.assertFalse(result.wasStrictlySuccessful())
1031
self.assertEqual(None, result._extractBenchmarkTime(test))
1033
def test_strict_with_known_failure(self):
1034
result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
1036
test = self.get_passing_test()
1037
err = (KnownFailure, KnownFailure('foo'), None)
1038
result._addKnownFailure(test, err)
1039
self.assertFalse(result.wasStrictlySuccessful())
1040
self.assertEqual(None, result._extractBenchmarkTime(test))
1042
def test_strict_with_success(self):
1043
result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
1045
test = self.get_passing_test()
1046
result.addSuccess(test)
1047
self.assertTrue(result.wasStrictlySuccessful())
1048
self.assertEqual(None, result._extractBenchmarkTime(test))
1051
class TestRunner(TestCase):
1053
def dummy_test(self):
1056
def run_test_runner(self, testrunner, test):
1057
"""Run suite in testrunner, saving global state and restoring it.
1059
This current saves and restores:
1060
TestCaseInTempDir.TEST_ROOT
1062
There should be no tests in this file that use bzrlib.tests.TextTestRunner
1063
without using this convenience method, because of our use of global state.
1065
old_root = TestCaseInTempDir.TEST_ROOT
1067
TestCaseInTempDir.TEST_ROOT = None
1068
return testrunner.run(test)
1070
TestCaseInTempDir.TEST_ROOT = old_root
1072
def test_known_failure_failed_run(self):
1073
# run a test that generates a known failure which should be printed in
1074
# the final output when real failures occur.
1075
def known_failure_test():
1076
raise KnownFailure('failed')
1077
test = unittest.TestSuite()
1078
test.addTest(unittest.FunctionTestCase(known_failure_test))
1080
raise AssertionError('foo')
1081
test.addTest(unittest.FunctionTestCase(failing_test))
1083
runner = TextTestRunner(stream=stream)
1084
result = self.run_test_runner(runner, test)
1085
lines = stream.getvalue().splitlines()
1088
'======================================================================',
1089
'FAIL: unittest.FunctionTestCase (failing_test)',
1090
'----------------------------------------------------------------------',
1091
'Traceback (most recent call last):',
1092
' raise AssertionError(\'foo\')',
1093
'AssertionError: foo',
1095
'----------------------------------------------------------------------',
1097
'FAILED (failures=1, known_failure_count=1)'],
1098
lines[0:5] + lines[6:10] + lines[11:])
1100
def test_known_failure_ok_run(self):
1101
# run a test that generates a known failure which should be printed in the final output.
1102
def known_failure_test():
1103
raise KnownFailure('failed')
1104
test = unittest.FunctionTestCase(known_failure_test)
1106
runner = TextTestRunner(stream=stream)
1107
result = self.run_test_runner(runner, test)
1108
self.assertContainsRe(stream.getvalue(),
1111
'Ran 1 test in .*\n'
1113
'OK \\(known_failures=1\\)\n')
1115
def test_skipped_test(self):
1116
# run a test that is skipped, and check the suite as a whole still
1118
# skipping_test must be hidden in here so it's not run as a real test
1119
def skipping_test():
1120
raise TestSkipped('test intentionally skipped')
1122
runner = TextTestRunner(stream=self._log_file)
1123
test = unittest.FunctionTestCase(skipping_test)
1124
result = self.run_test_runner(runner, test)
1125
self.assertTrue(result.wasSuccessful())
1127
def test_skipped_from_setup(self):
1128
class SkippedSetupTest(TestCase):
1132
self.addCleanup(self.cleanup)
1133
raise TestSkipped('skipped setup')
1135
def test_skip(self):
1136
self.fail('test reached')
1141
runner = TextTestRunner(stream=self._log_file)
1142
test = SkippedSetupTest('test_skip')
1143
result = self.run_test_runner(runner, test)
1144
self.assertTrue(result.wasSuccessful())
1145
# Check if cleanup was called the right number of times.
1146
self.assertEqual(0, test.counter)
1148
def test_skipped_from_test(self):
1149
class SkippedTest(TestCase):
1153
self.addCleanup(self.cleanup)
1155
def test_skip(self):
1156
raise TestSkipped('skipped test')
1161
runner = TextTestRunner(stream=self._log_file)
1162
test = SkippedTest('test_skip')
1163
result = self.run_test_runner(runner, test)
1164
self.assertTrue(result.wasSuccessful())
1165
# Check if cleanup was called the right number of times.
1166
self.assertEqual(0, test.counter)
1168
def test_not_applicable(self):
1169
# run a test that is skipped because it's not applicable
1170
def not_applicable_test():
1171
from bzrlib.tests import TestNotApplicable
1172
raise TestNotApplicable('this test never runs')
1174
runner = TextTestRunner(stream=out, verbosity=2)
1175
test = unittest.FunctionTestCase(not_applicable_test)
1176
result = self.run_test_runner(runner, test)
1177
self._log_file.write(out.getvalue())
1178
self.assertTrue(result.wasSuccessful())
1179
self.assertTrue(result.wasStrictlySuccessful())
1180
self.assertContainsRe(out.getvalue(),
1181
r'(?m)not_applicable_test * N/A')
1182
self.assertContainsRe(out.getvalue(),
1183
r'(?m)^ this test never runs')
1185
def test_not_applicable_demo(self):
1186
# just so you can see it in the test output
1187
raise TestNotApplicable('this test is just a demonstation')
1189
def test_unsupported_features_listed(self):
1190
"""When unsupported features are encountered they are detailed."""
1191
class Feature1(Feature):
1192
def _probe(self): return False
1193
class Feature2(Feature):
1194
def _probe(self): return False
1195
# create sample tests
1196
test1 = SampleTestCase('_test_pass')
1197
test1._test_needs_features = [Feature1()]
1198
test2 = SampleTestCase('_test_pass')
1199
test2._test_needs_features = [Feature2()]
1200
test = unittest.TestSuite()
1204
runner = TextTestRunner(stream=stream)
1205
result = self.run_test_runner(runner, test)
1206
lines = stream.getvalue().splitlines()
1209
"Missing feature 'Feature1' skipped 1 tests.",
1210
"Missing feature 'Feature2' skipped 1 tests.",
1214
def test_bench_history(self):
1215
# tests that the running the benchmark produces a history file
1216
# containing a timestamp and the revision id of the bzrlib source which
1218
workingtree = _get_bzr_source_tree()
1219
test = TestRunner('dummy_test')
1221
runner = TextTestRunner(stream=self._log_file, bench_history=output)
1222
result = self.run_test_runner(runner, test)
1223
output_string = output.getvalue()
1224
self.assertContainsRe(output_string, "--date [0-9.]+")
1225
if workingtree is not None:
1226
revision_id = workingtree.get_parent_ids()[0]
1227
self.assertEndsWith(output_string.rstrip(), revision_id)
1229
def assertLogDeleted(self, test):
1230
log = test._get_log()
1231
self.assertEqual("DELETED log file to reduce memory footprint", log)
1232
self.assertEqual('', test._log_contents)
1233
self.assertIs(None, test._log_file_name)
1235
def test_success_log_deleted(self):
1236
"""Successful tests have their log deleted"""
1238
class LogTester(TestCase):
1240
def test_success(self):
1241
self.log('this will be removed\n')
1243
sio = cStringIO.StringIO()
1244
runner = TextTestRunner(stream=sio)
1245
test = LogTester('test_success')
1246
result = self.run_test_runner(runner, test)
1248
self.assertLogDeleted(test)
1250
def test_skipped_log_deleted(self):
1251
"""Skipped tests have their log deleted"""
1253
class LogTester(TestCase):
1255
def test_skipped(self):
1256
self.log('this will be removed\n')
1257
raise tests.TestSkipped()
1259
sio = cStringIO.StringIO()
1260
runner = TextTestRunner(stream=sio)
1261
test = LogTester('test_skipped')
1262
result = self.run_test_runner(runner, test)
1264
self.assertLogDeleted(test)
1266
def test_not_aplicable_log_deleted(self):
1267
"""Not applicable tests have their log deleted"""
1269
class LogTester(TestCase):
1271
def test_not_applicable(self):
1272
self.log('this will be removed\n')
1273
raise tests.TestNotApplicable()
1275
sio = cStringIO.StringIO()
1276
runner = TextTestRunner(stream=sio)
1277
test = LogTester('test_not_applicable')
1278
result = self.run_test_runner(runner, test)
1280
self.assertLogDeleted(test)
1282
def test_known_failure_log_deleted(self):
1283
"""Know failure tests have their log deleted"""
1285
class LogTester(TestCase):
1287
def test_known_failure(self):
1288
self.log('this will be removed\n')
1289
raise tests.KnownFailure()
1291
sio = cStringIO.StringIO()
1292
runner = TextTestRunner(stream=sio)
1293
test = LogTester('test_known_failure')
1294
result = self.run_test_runner(runner, test)
1296
self.assertLogDeleted(test)
1298
def test_fail_log_kept(self):
1299
"""Failed tests have their log kept"""
1301
class LogTester(TestCase):
1303
def test_fail(self):
1304
self.log('this will be kept\n')
1305
self.fail('this test fails')
1307
sio = cStringIO.StringIO()
1308
runner = TextTestRunner(stream=sio)
1309
test = LogTester('test_fail')
1310
result = self.run_test_runner(runner, test)
1312
text = sio.getvalue()
1313
self.assertContainsRe(text, 'this will be kept')
1314
self.assertContainsRe(text, 'this test fails')
1316
log = test._get_log()
1317
self.assertContainsRe(log, 'this will be kept')
1318
self.assertEqual(log, test._log_contents)
1320
def test_error_log_kept(self):
1321
"""Tests with errors have their log kept"""
1323
class LogTester(TestCase):
1325
def test_error(self):
1326
self.log('this will be kept\n')
1327
raise ValueError('random exception raised')
1329
sio = cStringIO.StringIO()
1330
runner = TextTestRunner(stream=sio)
1331
test = LogTester('test_error')
1332
result = self.run_test_runner(runner, test)
1334
text = sio.getvalue()
1335
self.assertContainsRe(text, 'this will be kept')
1336
self.assertContainsRe(text, 'random exception raised')
1338
log = test._get_log()
1339
self.assertContainsRe(log, 'this will be kept')
1340
self.assertEqual(log, test._log_contents)
1343
class SampleTestCase(TestCase):
1345
def _test_pass(self):
1349
class TestTestCase(TestCase):
1350
"""Tests that test the core bzrlib TestCase."""
1352
def test_debug_flags_sanitised(self):
1353
"""The bzrlib debug flags should be sanitised by setUp."""
1354
# we could set something and run a test that will check
1355
# it gets santised, but this is probably sufficient for now:
1356
# if someone runs the test with -Dsomething it will error.
1357
self.assertEqual(set(), bzrlib.debug.debug_flags)
1359
def inner_test(self):
1360
# the inner child test
1363
def outer_child(self):
1364
# the outer child test
1366
self.inner_test = TestTestCase("inner_child")
1367
result = bzrlib.tests.TextTestResult(self._log_file,
1370
self.inner_test.run(result)
1371
note("outer finish")
1373
def test_trace_nesting(self):
1374
# this tests that each test case nests its trace facility correctly.
1375
# we do this by running a test case manually. That test case (A)
1376
# should setup a new log, log content to it, setup a child case (B),
1377
# which should log independently, then case (A) should log a trailer
1379
# we do two nested children so that we can verify the state of the
1380
# logs after the outer child finishes is correct, which a bad clean
1381
# up routine in tearDown might trigger a fault in our test with only
1382
# one child, we should instead see the bad result inside our test with
1384
# the outer child test
1385
original_trace = bzrlib.trace._trace_file
1386
outer_test = TestTestCase("outer_child")
1387
result = bzrlib.tests.TextTestResult(self._log_file,
1390
outer_test.run(result)
1391
self.assertEqual(original_trace, bzrlib.trace._trace_file)
1393
def method_that_times_a_bit_twice(self):
1394
# call self.time twice to ensure it aggregates
1395
self.time(time.sleep, 0.007)
1396
self.time(time.sleep, 0.007)
1398
def test_time_creates_benchmark_in_result(self):
1399
"""Test that the TestCase.time() method accumulates a benchmark time."""
1400
sample_test = TestTestCase("method_that_times_a_bit_twice")
1401
output_stream = StringIO()
1402
result = bzrlib.tests.VerboseTestResult(
1403
unittest._WritelnDecorator(output_stream),
1406
num_tests=sample_test.countTestCases())
1407
sample_test.run(result)
1408
self.assertContainsRe(
1409
output_stream.getvalue(),
1410
r"\d+ms/ +\d+ms\n$")
1412
def test_hooks_sanitised(self):
1413
"""The bzrlib hooks should be sanitised by setUp."""
1414
self.assertEqual(bzrlib.branch.BranchHooks(),
1415
bzrlib.branch.Branch.hooks)
1416
self.assertEqual(bzrlib.smart.server.SmartServerHooks(),
1417
bzrlib.smart.server.SmartTCPServer.hooks)
1419
def test__gather_lsprof_in_benchmarks(self):
1420
"""When _gather_lsprof_in_benchmarks is on, accumulate profile data.
1422
Each self.time() call is individually and separately profiled.
1424
self.requireFeature(test_lsprof.LSProfFeature)
1425
# overrides the class member with an instance member so no cleanup
1427
self._gather_lsprof_in_benchmarks = True
1428
self.time(time.sleep, 0.000)
1429
self.time(time.sleep, 0.003)
1430
self.assertEqual(2, len(self._benchcalls))
1431
self.assertEqual((time.sleep, (0.000,), {}), self._benchcalls[0][0])
1432
self.assertEqual((time.sleep, (0.003,), {}), self._benchcalls[1][0])
1433
self.assertIsInstance(self._benchcalls[0][1], bzrlib.lsprof.Stats)
1434
self.assertIsInstance(self._benchcalls[1][1], bzrlib.lsprof.Stats)
1436
def test_knownFailure(self):
1437
"""Self.knownFailure() should raise a KnownFailure exception."""
1438
self.assertRaises(KnownFailure, self.knownFailure, "A Failure")
1440
def test_requireFeature_available(self):
1441
"""self.requireFeature(available) is a no-op."""
1442
class Available(Feature):
1443
def _probe(self):return True
1444
feature = Available()
1445
self.requireFeature(feature)
1447
def test_requireFeature_unavailable(self):
1448
"""self.requireFeature(unavailable) raises UnavailableFeature."""
1449
class Unavailable(Feature):
1450
def _probe(self):return False
1451
feature = Unavailable()
1452
self.assertRaises(UnavailableFeature, self.requireFeature, feature)
1454
def test_run_no_parameters(self):
1455
test = SampleTestCase('_test_pass')
1458
def test_run_enabled_unittest_result(self):
1459
"""Test we revert to regular behaviour when the test is enabled."""
1460
test = SampleTestCase('_test_pass')
1461
class EnabledFeature(object):
1462
def available(self):
1464
test._test_needs_features = [EnabledFeature()]
1465
result = unittest.TestResult()
1467
self.assertEqual(1, result.testsRun)
1468
self.assertEqual([], result.errors)
1469
self.assertEqual([], result.failures)
1471
def test_run_disabled_unittest_result(self):
1472
"""Test our compatability for disabled tests with unittest results."""
1473
test = SampleTestCase('_test_pass')
1474
class DisabledFeature(object):
1475
def available(self):
1477
test._test_needs_features = [DisabledFeature()]
1478
result = unittest.TestResult()
1480
self.assertEqual(1, result.testsRun)
1481
self.assertEqual([], result.errors)
1482
self.assertEqual([], result.failures)
1484
def test_run_disabled_supporting_result(self):
1485
"""Test disabled tests behaviour with support aware results."""
1486
test = SampleTestCase('_test_pass')
1487
class DisabledFeature(object):
1488
def available(self):
1490
the_feature = DisabledFeature()
1491
test._test_needs_features = [the_feature]
1492
class InstrumentedTestResult(unittest.TestResult):
1494
unittest.TestResult.__init__(self)
1496
def startTest(self, test):
1497
self.calls.append(('startTest', test))
1498
def stopTest(self, test):
1499
self.calls.append(('stopTest', test))
1500
def addNotSupported(self, test, feature):
1501
self.calls.append(('addNotSupported', test, feature))
1502
result = InstrumentedTestResult()
1505
('startTest', test),
1506
('addNotSupported', test, the_feature),
1512
@symbol_versioning.deprecated_function(zero_eleven)
1513
def sample_deprecated_function():
1514
"""A deprecated function to test applyDeprecated with."""
1518
def sample_undeprecated_function(a_param):
1519
"""A undeprecated function to test applyDeprecated with."""
1522
class ApplyDeprecatedHelper(object):
1523
"""A helper class for ApplyDeprecated tests."""
1525
@symbol_versioning.deprecated_method(zero_eleven)
1526
def sample_deprecated_method(self, param_one):
1527
"""A deprecated method for testing with."""
1530
def sample_normal_method(self):
1531
"""A undeprecated method."""
1533
@symbol_versioning.deprecated_method(zero_ten)
1534
def sample_nested_deprecation(self):
1535
return sample_deprecated_function()
1538
class TestExtraAssertions(TestCase):
1539
"""Tests for new test assertions in bzrlib test suite"""
1541
def test_assert_isinstance(self):
1542
self.assertIsInstance(2, int)
1543
self.assertIsInstance(u'', basestring)
1544
self.assertRaises(AssertionError, self.assertIsInstance, None, int)
1545
self.assertRaises(AssertionError, self.assertIsInstance, 23.3, int)
1547
def test_assertEndsWith(self):
1548
self.assertEndsWith('foo', 'oo')
1549
self.assertRaises(AssertionError, self.assertEndsWith, 'o', 'oo')
1551
def test_applyDeprecated_not_deprecated(self):
1552
sample_object = ApplyDeprecatedHelper()
1553
# calling an undeprecated callable raises an assertion
1554
self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
1555
sample_object.sample_normal_method)
1556
self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
1557
sample_undeprecated_function, "a param value")
1558
# calling a deprecated callable (function or method) with the wrong
1559
# expected deprecation fails.
1560
self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
1561
sample_object.sample_deprecated_method, "a param value")
1562
self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
1563
sample_deprecated_function)
1564
# calling a deprecated callable (function or method) with the right
1565
# expected deprecation returns the functions result.
1566
self.assertEqual("a param value", self.applyDeprecated(zero_eleven,
1567
sample_object.sample_deprecated_method, "a param value"))
1568
self.assertEqual(2, self.applyDeprecated(zero_eleven,
1569
sample_deprecated_function))
1570
# calling a nested deprecation with the wrong deprecation version
1571
# fails even if a deeper nested function was deprecated with the
1573
self.assertRaises(AssertionError, self.applyDeprecated,
1574
zero_eleven, sample_object.sample_nested_deprecation)
1575
# calling a nested deprecation with the right deprecation value
1576
# returns the calls result.
1577
self.assertEqual(2, self.applyDeprecated(zero_ten,
1578
sample_object.sample_nested_deprecation))
1580
def test_callDeprecated(self):
1581
def testfunc(be_deprecated, result=None):
1582
if be_deprecated is True:
1583
symbol_versioning.warn('i am deprecated', DeprecationWarning,
1586
result = self.callDeprecated(['i am deprecated'], testfunc, True)
1587
self.assertIs(None, result)
1588
result = self.callDeprecated([], testfunc, False, 'result')
1589
self.assertEqual('result', result)
1590
self.callDeprecated(['i am deprecated'], testfunc, be_deprecated=True)
1591
self.callDeprecated([], testfunc, be_deprecated=False)
1594
class TestWarningTests(TestCase):
1595
"""Tests for calling methods that raise warnings."""
1597
def test_callCatchWarnings(self):
1599
warnings.warn("this is your last warning")
1601
wlist, result = self.callCatchWarnings(meth, 1, 2)
1602
self.assertEquals(3, result)
1603
# would like just to compare them, but UserWarning doesn't implement
1606
self.assertIsInstance(w0, UserWarning)
1607
self.assertEquals("this is your last warning", str(w0))
1610
class TestConvenienceMakers(TestCaseWithTransport):
1611
"""Test for the make_* convenience functions."""
1613
def test_make_branch_and_tree_with_format(self):
1614
# we should be able to supply a format to make_branch_and_tree
1615
self.make_branch_and_tree('a', format=bzrlib.bzrdir.BzrDirMetaFormat1())
1616
self.make_branch_and_tree('b', format=bzrlib.bzrdir.BzrDirFormat6())
1617
self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('a')._format,
1618
bzrlib.bzrdir.BzrDirMetaFormat1)
1619
self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('b')._format,
1620
bzrlib.bzrdir.BzrDirFormat6)
1622
def test_make_branch_and_memory_tree(self):
1623
# we should be able to get a new branch and a mutable tree from
1624
# TestCaseWithTransport
1625
tree = self.make_branch_and_memory_tree('a')
1626
self.assertIsInstance(tree, bzrlib.memorytree.MemoryTree)
1629
class TestSFTPMakeBranchAndTree(TestCaseWithSFTPServer):
1631
def test_make_tree_for_sftp_branch(self):
1632
"""Transports backed by local directories create local trees."""
1634
tree = self.make_branch_and_tree('t1')
1635
base = tree.bzrdir.root_transport.base
1636
self.failIf(base.startswith('sftp'),
1637
'base %r is on sftp but should be local' % base)
1638
self.assertEquals(tree.bzrdir.root_transport,
1639
tree.branch.bzrdir.root_transport)
1640
self.assertEquals(tree.bzrdir.root_transport,
1641
tree.branch.repository.bzrdir.root_transport)
1644
class TestSelftest(TestCase):
1645
"""Tests of bzrlib.tests.selftest."""
1647
def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
1650
factory_called.append(True)
1654
self.apply_redirected(out, err, None, bzrlib.tests.selftest,
1655
test_suite_factory=factory)
1656
self.assertEqual([True], factory_called)
1659
class TestKnownFailure(TestCase):
1661
def test_known_failure(self):
1662
"""Check that KnownFailure is defined appropriately."""
1663
# a KnownFailure is an assertion error for compatability with unaware
1665
self.assertIsInstance(KnownFailure(""), AssertionError)
1667
def test_expect_failure(self):
1669
self.expectFailure("Doomed to failure", self.assertTrue, False)
1670
except KnownFailure, e:
1671
self.assertEqual('Doomed to failure', e.args[0])
1673
self.expectFailure("Doomed to failure", self.assertTrue, True)
1674
except AssertionError, e:
1675
self.assertEqual('Unexpected success. Should have failed:'
1676
' Doomed to failure', e.args[0])
1678
self.fail('Assertion not raised')
1681
class TestFeature(TestCase):
1683
def test_caching(self):
1684
"""Feature._probe is called by the feature at most once."""
1685
class InstrumentedFeature(Feature):
1687
Feature.__init__(self)
1690
self.calls.append('_probe')
1692
feature = InstrumentedFeature()
1694
self.assertEqual(['_probe'], feature.calls)
1696
self.assertEqual(['_probe'], feature.calls)
1698
def test_named_str(self):
1699
"""Feature.__str__ should thunk to feature_name()."""
1700
class NamedFeature(Feature):
1701
def feature_name(self):
1703
feature = NamedFeature()
1704
self.assertEqual('symlinks', str(feature))
1706
def test_default_str(self):
1707
"""Feature.__str__ should default to __class__.__name__."""
1708
class NamedFeature(Feature):
1710
feature = NamedFeature()
1711
self.assertEqual('NamedFeature', str(feature))
1714
class TestUnavailableFeature(TestCase):
1716
def test_access_feature(self):
1718
exception = UnavailableFeature(feature)
1719
self.assertIs(feature, exception.args[0])
1722
class TestSelftestFiltering(TestCase):
1725
self.suite = TestUtil.TestSuite()
1726
self.loader = TestUtil.TestLoader()
1727
self.suite.addTest(self.loader.loadTestsFromModuleNames([
1728
'bzrlib.tests.test_selftest']))
1729
self.all_names = _test_ids(self.suite)
1731
def test_condition_id_re(self):
1732
test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1733
'test_condition_id_re')
1734
filtered_suite = filter_suite_by_condition(self.suite,
1735
condition_id_re('test_condition_id_re'))
1736
self.assertEqual([test_name], _test_ids(filtered_suite))
1738
def test_condition_id_in_list(self):
1739
test_names = ['bzrlib.tests.test_selftest.TestSelftestFiltering.'
1740
'test_condition_id_in_list']
1741
id_list = tests.TestIdList(test_names)
1742
filtered_suite = filter_suite_by_condition(
1743
self.suite, tests.condition_id_in_list(id_list))
1744
my_pattern = 'TestSelftestFiltering.*test_condition_id_in_list'
1745
re_filtered = filter_suite_by_re(self.suite, my_pattern)
1746
self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
1748
def test_condition_isinstance(self):
1749
filtered_suite = filter_suite_by_condition(self.suite,
1750
condition_isinstance(self.__class__))
1751
class_pattern = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
1752
re_filtered = filter_suite_by_re(self.suite, class_pattern)
1753
self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
1755
def test_exclude_tests_by_condition(self):
1756
excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1757
'test_exclude_tests_by_condition')
1758
filtered_suite = exclude_tests_by_condition(self.suite,
1759
lambda x:x.id() == excluded_name)
1760
self.assertEqual(len(self.all_names) - 1,
1761
filtered_suite.countTestCases())
1762
self.assertFalse(excluded_name in _test_ids(filtered_suite))
1763
remaining_names = list(self.all_names)
1764
remaining_names.remove(excluded_name)
1765
self.assertEqual(remaining_names, _test_ids(filtered_suite))
1767
def test_exclude_tests_by_re(self):
1768
self.all_names = _test_ids(self.suite)
1769
filtered_suite = exclude_tests_by_re(self.suite, 'exclude_tests_by_re')
1770
excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1771
'test_exclude_tests_by_re')
1772
self.assertEqual(len(self.all_names) - 1,
1773
filtered_suite.countTestCases())
1774
self.assertFalse(excluded_name in _test_ids(filtered_suite))
1775
remaining_names = list(self.all_names)
1776
remaining_names.remove(excluded_name)
1777
self.assertEqual(remaining_names, _test_ids(filtered_suite))
1779
def test_filter_suite_by_condition(self):
1780
test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1781
'test_filter_suite_by_condition')
1782
filtered_suite = filter_suite_by_condition(self.suite,
1783
lambda x:x.id() == test_name)
1784
self.assertEqual([test_name], _test_ids(filtered_suite))
1786
def test_filter_suite_by_re(self):
1787
filtered_suite = filter_suite_by_re(self.suite, 'test_filter_suite_by_r')
1788
filtered_names = _test_ids(filtered_suite)
1789
self.assertEqual(filtered_names, ['bzrlib.tests.test_selftest.'
1790
'TestSelftestFiltering.test_filter_suite_by_re'])
1792
def test_filter_suite_by_id_list(self):
1793
test_list = ['bzrlib.tests.test_selftest.'
1794
'TestSelftestFiltering.test_filter_suite_by_id_list']
1795
filtered_suite = tests.filter_suite_by_id_list(
1796
self.suite, tests.TestIdList(test_list))
1797
filtered_names = _test_ids(filtered_suite)
1800
['bzrlib.tests.test_selftest.'
1801
'TestSelftestFiltering.test_filter_suite_by_id_list'])
1803
def test_preserve_input(self):
1804
# NB: Surely this is something in the stdlib to do this?
1805
self.assertTrue(self.suite is preserve_input(self.suite))
1806
self.assertTrue("@#$" is preserve_input("@#$"))
1808
def test_randomize_suite(self):
1809
randomized_suite = randomize_suite(self.suite)
1810
# randomizing should not add or remove test names.
1811
self.assertEqual(set(_test_ids(self.suite)),
1812
set(_test_ids(randomized_suite)))
1813
# Technically, this *can* fail, because random.shuffle(list) can be
1814
# equal to list. Trying multiple times just pushes the frequency back.
1815
# As its len(self.all_names)!:1, the failure frequency should be low
1816
# enough to ignore. RBC 20071021.
1817
# It should change the order.
1818
self.assertNotEqual(self.all_names, _test_ids(randomized_suite))
1819
# But not the length. (Possibly redundant with the set test, but not
1821
self.assertEqual(len(self.all_names), len(_test_ids(randomized_suite)))
1823
def test_sort_suite_by_re(self):
1824
sorted_suite = self.applyDeprecated(one_zero,
1825
sort_suite_by_re, self.suite, 'test_filter_suite_by_r')
1826
sorted_names = _test_ids(sorted_suite)
1827
self.assertEqual(sorted_names[0], 'bzrlib.tests.test_selftest.'
1828
'TestSelftestFiltering.test_filter_suite_by_re')
1829
self.assertEquals(sorted(self.all_names), sorted(sorted_names))
1831
def test_split_suit_by_re(self):
1832
self.all_names = _test_ids(self.suite)
1833
split_suite = split_suite_by_re(self.suite, 'test_filter_suite_by_r')
1834
filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1835
'test_filter_suite_by_re')
1836
self.assertEqual([filtered_name], _test_ids(split_suite[0]))
1837
self.assertFalse(filtered_name in _test_ids(split_suite[1]))
1838
remaining_names = list(self.all_names)
1839
remaining_names.remove(filtered_name)
1840
self.assertEqual(remaining_names, _test_ids(split_suite[1]))
1843
class TestCheckInventoryShape(TestCaseWithTransport):
1845
def test_check_inventory_shape(self):
1846
files = ['a', 'b/', 'b/c']
1847
tree = self.make_branch_and_tree('.')
1848
self.build_tree(files)
1852
self.check_inventory_shape(tree.inventory, files)
1857
class TestBlackboxSupport(TestCase):
1858
"""Tests for testsuite blackbox features."""
1860
def test_run_bzr_failure_not_caught(self):
1861
# When we run bzr in blackbox mode, we want any unexpected errors to
1862
# propagate up to the test suite so that it can show the error in the
1863
# usual way, and we won't get a double traceback.
1864
e = self.assertRaises(
1866
self.run_bzr, ['assert-fail'])
1867
# make sure we got the real thing, not an error from somewhere else in
1868
# the test framework
1869
self.assertEquals('always fails', str(e))
1870
# check that there's no traceback in the test log
1871
self.assertNotContainsRe(self._get_log(keep_log_file=True),
1874
def test_run_bzr_user_error_caught(self):
1875
# Running bzr in blackbox mode, normal/expected/user errors should be
1876
# caught in the regular way and turned into an error message plus exit
1878
out, err = self.run_bzr(["log", "/nonexistantpath"], retcode=3)
1879
self.assertEqual(out, '')
1880
self.assertContainsRe(err,
1881
'bzr: ERROR: Not a branch: ".*nonexistantpath/".\n')
1884
class TestTestLoader(TestCase):
1885
"""Tests for the test loader."""
1887
def _get_loader_and_module(self):
1888
"""Gets a TestLoader and a module with one test in it."""
1889
loader = TestUtil.TestLoader()
1891
class Stub(TestCase):
1894
class MyModule(object):
1896
MyModule.a_class = Stub
1898
return loader, module
1900
def test_module_no_load_tests_attribute_loads_classes(self):
1901
loader, module = self._get_loader_and_module()
1902
self.assertEqual(1, loader.loadTestsFromModule(module).countTestCases())
1904
def test_module_load_tests_attribute_gets_called(self):
1905
loader, module = self._get_loader_and_module()
1906
# 'self' is here because we're faking the module with a class. Regular
1907
# load_tests do not need that :)
1908
def load_tests(self, standard_tests, module, loader):
1909
result = loader.suiteClass()
1910
for test in iter_suite_tests(standard_tests):
1911
result.addTests([test, test])
1913
# add a load_tests() method which multiplies the tests from the module.
1914
module.__class__.load_tests = load_tests
1915
self.assertEqual(2, loader.loadTestsFromModule(module).countTestCases())
1917
def test_load_tests_from_module_name_smoke_test(self):
1918
loader = TestUtil.TestLoader()
1919
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
1920
self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
1923
def test_load_tests_from_module_name_with_bogus_module_name(self):
1924
loader = TestUtil.TestLoader()
1925
self.assertRaises(ImportError, loader.loadTestsFromModuleName, 'bogus')
1928
class TestTestIdList(tests.TestCase):
1930
def _create_id_list(self, test_list):
1931
return tests.TestIdList(test_list)
1933
def _create_suite(self, test_id_list):
1935
class Stub(TestCase):
1939
def _create_test_id(id):
1942
suite = TestUtil.TestSuite()
1943
for id in test_id_list:
1944
t = Stub('test_foo')
1945
t.id = _create_test_id(id)
1949
def _test_ids(self, test_suite):
1950
"""Get the ids for the tests in a test suite."""
1951
return [t.id() for t in iter_suite_tests(test_suite)]
1953
def test_empty_list(self):
1954
id_list = self._create_id_list([])
1955
self.assertEquals({}, id_list.tests)
1956
self.assertEquals({}, id_list.modules)
1958
def test_valid_list(self):
1959
id_list = self._create_id_list(
1960
['mod1.cl1.meth1', 'mod1.cl1.meth2',
1961
'mod1.func1', 'mod1.cl2.meth2',
1963
'mod1.submod2.cl1.meth1', 'mod1.submod2.cl2.meth2',
1965
self.assertTrue(id_list.is_module_name_used('mod1'))
1966
self.assertTrue(id_list.is_module_name_used('mod1.submod1'))
1967
self.assertTrue(id_list.is_module_name_used('mod1.submod2'))
1968
self.assertTrue(id_list.test_in('mod1.cl1.meth1'))
1969
self.assertTrue(id_list.test_in('mod1.submod1'))
1970
self.assertTrue(id_list.test_in('mod1.func1'))
1972
def test_bad_chars_in_params(self):
1973
id_list = self._create_id_list(['mod1.cl1.meth1(xx.yy)'])
1974
self.assertTrue(id_list.is_module_name_used('mod1'))
1975
self.assertTrue(id_list.test_in('mod1.cl1.meth1(xx.yy)'))
1977
def test_module_used(self):
1978
id_list = self._create_id_list(['mod.class.meth'])
1979
self.assertTrue(id_list.is_module_name_used('mod'))
1980
self.assertTrue(id_list.is_module_name_used('mod.class'))
1981
self.assertTrue(id_list.is_module_name_used('mod.class.meth'))
1983
def test_test_suite(self):
1984
# This test is slow, so we do a single test with one test in each
1988
'bzrlib.tests.test_selftest.TestTestIdList.test_test_suite',
1989
# transport implementations
1990
'bzrlib.tests.test_transport_implementations.TransportTests'
1991
'.test_abspath(LocalURLServer)',
1992
# packages_to_test()
1993
'bzrlib.tests.blackbox.test_branch.TestBranch.test_branch',
1994
# MODULES_TO_DOCTEST
1995
'bzrlib.timestamp.format_highres_date',
1996
# plugins can't be tested that way since selftest may be run with
1999
suite = tests.test_suite(test_list)
2000
self.assertEquals(test_list, _test_ids(suite))
2002
def test_test_suite_matches_id_list_with_unknown(self):
2003
loader = TestUtil.TestLoader()
2004
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2005
test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',
2007
not_found, duplicates = tests.suite_matches_id_list(suite, test_list)
2008
self.assertEquals(['bogus'], not_found)
2009
self.assertEquals([], duplicates)
2011
def test_suite_matches_id_list_with_duplicates(self):
2012
loader = TestUtil.TestLoader()
2013
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2014
dupes = loader.suiteClass()
2015
for test in iter_suite_tests(suite):
2017
dupes.addTest(test) # Add it again
2019
test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',]
2020
not_found, duplicates = tests.suite_matches_id_list(
2022
self.assertEquals([], not_found)
2023
self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
2027
class TestLoadTestIdList(tests.TestCaseInTempDir):
2029
def _create_test_list_file(self, file_name, content):
2030
fl = open(file_name, 'wt')
2034
def test_load_unknown(self):
2035
self.assertRaises(errors.NoSuchFile,
2036
tests.load_test_id_list, 'i_do_not_exist')
2038
def test_load_test_list(self):
2039
test_list_fname = 'test.list'
2040
self._create_test_list_file(test_list_fname,
2041
'mod1.cl1.meth1\nmod2.cl2.meth2\n')
2042
tlist = tests.load_test_id_list(test_list_fname)
2043
self.assertEquals(2, len(tlist))
2044
self.assertEquals('mod1.cl1.meth1', tlist[0])
2045
self.assertEquals('mod2.cl2.meth2', tlist[1])
2047
def test_load_dirty_file(self):
2048
test_list_fname = 'test.list'
2049
self._create_test_list_file(test_list_fname,
2050
' mod1.cl1.meth1\n\nmod2.cl2.meth2 \n'
2052
tlist = tests.load_test_id_list(test_list_fname)
2053
self.assertEquals(4, len(tlist))
2054
self.assertEquals('mod1.cl1.meth1', tlist[0])
2055
self.assertEquals('', tlist[1])
2056
self.assertEquals('mod2.cl2.meth2', tlist[2])
2057
self.assertEquals('bar baz', tlist[3])