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
class SelftestTests(TestCase):
82
def test_import_tests(self):
83
mod = _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,
91
class MetaTestLog(TestCase):
93
def test_logging(self):
94
"""Test logs are captured when a test fails."""
95
self.log('a test message')
96
self._log_file.flush()
97
self.assertContainsRe(self._get_log(keep_log_file=True),
101
class TestTreeShape(TestCaseInTempDir):
103
def test_unicode_paths(self):
104
filename = u'hell\u00d8'
106
self.build_tree_contents([(filename, 'contents of hello')])
107
except UnicodeEncodeError:
108
raise TestSkipped("can't build unicode working tree in "
109
"filesystem encoding %s" % sys.getfilesystemencoding())
110
self.failUnlessExists(filename)
113
class TestTransportProviderAdapter(TestCase):
114
"""A group of tests that test the transport implementation adaption core.
116
This is a meta test that the tests are applied to all available
119
This will be generalised in the future which is why it is in this
120
test file even though it is specific to transport tests at the moment.
123
def test_get_transport_permutations(self):
124
# this checks that we the module get_test_permutations call
125
# is made by the adapter get_transport_test_permitations method.
126
class MockModule(object):
127
def get_test_permutations(self):
128
return sample_permutation
129
sample_permutation = [(1,2), (3,4)]
130
from bzrlib.tests.test_transport_implementations \
131
import TransportTestProviderAdapter
132
adapter = TransportTestProviderAdapter()
133
self.assertEqual(sample_permutation,
134
adapter.get_transport_test_permutations(MockModule()))
136
def test_adapter_checks_all_modules(self):
137
# this checks that the adapter returns as many permurtations as
138
# there are in all the registered# transport modules for there
139
# - we assume if this matches its probably doing the right thing
140
# especially in combination with the tests for setting the right
142
from bzrlib.tests.test_transport_implementations \
143
import TransportTestProviderAdapter
144
from bzrlib.transport import _get_transport_modules
145
modules = _get_transport_modules()
146
permutation_count = 0
147
for module in modules:
149
permutation_count += len(reduce(getattr,
150
(module + ".get_test_permutations").split('.')[1:],
151
__import__(module))())
152
except errors.DependencyNotPresent:
154
input_test = TestTransportProviderAdapter(
155
"test_adapter_sets_transport_class")
156
adapter = TransportTestProviderAdapter()
157
self.assertEqual(permutation_count,
158
len(list(iter(adapter.adapt(input_test)))))
160
def test_adapter_sets_transport_class(self):
161
# Check that the test adapter inserts a transport and server into the
164
# This test used to know about all the possible transports and the
165
# order they were returned but that seems overly brittle (mbp
167
from bzrlib.tests.test_transport_implementations \
168
import TransportTestProviderAdapter
169
scenarios = TransportTestProviderAdapter().scenarios
170
# there are at least that many builtin transports
171
self.assertTrue(len(scenarios) > 6)
172
one_scenario = scenarios[0]
173
self.assertIsInstance(one_scenario[0], str)
174
self.assertTrue(issubclass(one_scenario[1]["transport_class"],
175
bzrlib.transport.Transport))
176
self.assertTrue(issubclass(one_scenario[1]["transport_server"],
177
bzrlib.transport.Server))
180
class TestBranchProviderAdapter(TestCase):
181
"""A group of tests that test the branch implementation test adapter."""
183
def test_constructor(self):
184
# check that constructor parameters are passed through to the adapted
186
from bzrlib.tests.branch_implementations import BranchTestProviderAdapter
189
formats = [("c", "C"), ("d", "D")]
190
adapter = BranchTestProviderAdapter(server1, server2, formats)
191
self.assertEqual(2, len(adapter.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 TestBzrDirProviderAdapter(TestCase):
207
"""A group of tests that test the bzr dir implementation test adapter."""
209
def test_adapted_tests(self):
210
# check that constructor parameters are passed through to the adapted
212
from bzrlib.tests.bzrdir_implementations import BzrDirTestProviderAdapter
217
adapter = BzrDirTestProviderAdapter(vfs_factory,
218
server1, server2, formats)
221
{'bzrdir_format': 'c',
222
'transport_readonly_server': 'b',
223
'transport_server': 'a',
224
'vfs_transport_factory': 'v'}),
226
{'bzrdir_format': 'd',
227
'transport_readonly_server': 'b',
228
'transport_server': 'a',
229
'vfs_transport_factory': 'v'})],
233
class TestRepositoryProviderAdapter(TestCase):
234
"""A group of tests that test the repository implementation test adapter."""
236
def test_constructor(self):
237
# check that constructor parameters are passed through to the
239
from bzrlib.tests.repository_implementations import RepositoryTestProviderAdapter
242
formats = [("c", "C"), ("d", "D")]
243
adapter = RepositoryTestProviderAdapter(server1, server2, formats)
246
{'bzrdir_format': 'C',
247
'repository_format': 'c',
248
'transport_readonly_server': 'b',
249
'transport_server': 'a'}),
251
{'bzrdir_format': 'D',
252
'repository_format': 'd',
253
'transport_readonly_server': 'b',
254
'transport_server': 'a'})],
257
def test_setting_vfs_transport(self):
258
"""The vfs_transport_factory can be set optionally."""
259
from bzrlib.tests.repository_implementations import RepositoryTestProviderAdapter
260
formats = [("a", "b"), ("c", "d")]
261
adapter = RepositoryTestProviderAdapter(None, None, formats,
262
vfs_transport_factory="vfs")
265
{'bzrdir_format': 'b',
266
'repository_format': 'a',
267
'transport_readonly_server': None,
268
'transport_server': None,
269
'vfs_transport_factory': 'vfs'}),
271
{'bzrdir_format': 'd',
272
'repository_format': 'c',
273
'transport_readonly_server': None,
274
'transport_server': None,
275
'vfs_transport_factory': 'vfs'})],
278
def test_formats_to_scenarios(self):
279
"""The adapter can generate all the scenarios needed."""
280
from bzrlib.tests.repository_implementations import RepositoryTestProviderAdapter
281
no_vfs_adapter = RepositoryTestProviderAdapter("server", "readonly",
283
vfs_adapter = RepositoryTestProviderAdapter("server", "readonly",
284
[], vfs_transport_factory="vfs")
285
# no_vfs generate scenarios without vfs_transport_factor
286
formats = [("c", "C"), (1, "D")]
289
{'bzrdir_format': 'C',
290
'repository_format': 'c',
291
'transport_readonly_server': 'readonly',
292
'transport_server': 'server'}),
294
{'bzrdir_format': 'D',
295
'repository_format': 1,
296
'transport_readonly_server': 'readonly',
297
'transport_server': 'server'})],
298
no_vfs_adapter.formats_to_scenarios(formats))
301
{'bzrdir_format': 'C',
302
'repository_format': 'c',
303
'transport_readonly_server': 'readonly',
304
'transport_server': 'server',
305
'vfs_transport_factory': 'vfs'}),
307
{'bzrdir_format': 'D',
308
'repository_format': 1,
309
'transport_readonly_server': 'readonly',
310
'transport_server': 'server',
311
'vfs_transport_factory': 'vfs'})],
312
vfs_adapter.formats_to_scenarios(formats))
315
class TestTestScenarioApplier(TestCase):
316
"""Tests for the test adaption facilities."""
318
def test_adapt_applies_scenarios(self):
319
from bzrlib.tests.repository_implementations import TestScenarioApplier
320
input_test = TestTestScenarioApplier("test_adapt_test_to_scenario")
321
adapter = TestScenarioApplier()
322
adapter.scenarios = [("1", "dict"), ("2", "settings")]
324
def capture_call(test, scenario):
325
calls.append((test, scenario))
327
adapter.adapt_test_to_scenario = capture_call
328
adapter.adapt(input_test)
329
self.assertEqual([(input_test, ("1", "dict")),
330
(input_test, ("2", "settings"))], calls)
332
def test_adapt_test_to_scenario(self):
333
from bzrlib.tests.repository_implementations import TestScenarioApplier
334
input_test = TestTestScenarioApplier("test_adapt_test_to_scenario")
335
adapter = TestScenarioApplier()
336
# setup two adapted tests
337
adapted_test1 = adapter.adapt_test_to_scenario(input_test,
339
{"bzrdir_format":"bzr_format",
340
"repository_format":"repo_fmt",
341
"transport_server":"transport_server",
342
"transport_readonly_server":"readonly-server"}))
343
adapted_test2 = adapter.adapt_test_to_scenario(input_test,
344
("new id 2", {"bzrdir_format":None}))
345
# input_test should have been altered.
346
self.assertRaises(AttributeError, getattr, input_test, "bzrdir_format")
347
# the new tests are mutually incompatible, ensuring it has
348
# made new ones, and unspecified elements in the scenario
349
# should not have been altered.
350
self.assertEqual("bzr_format", adapted_test1.bzrdir_format)
351
self.assertEqual("repo_fmt", adapted_test1.repository_format)
352
self.assertEqual("transport_server", adapted_test1.transport_server)
353
self.assertEqual("readonly-server",
354
adapted_test1.transport_readonly_server)
356
"bzrlib.tests.test_selftest.TestTestScenarioApplier."
357
"test_adapt_test_to_scenario(new id)",
359
self.assertEqual(None, adapted_test2.bzrdir_format)
361
"bzrlib.tests.test_selftest.TestTestScenarioApplier."
362
"test_adapt_test_to_scenario(new id 2)",
366
class TestInterRepositoryProviderAdapter(TestCase):
367
"""A group of tests that test the InterRepository test adapter."""
369
def test_adapted_tests(self):
370
# check that constructor parameters are passed through to the adapted
372
from bzrlib.tests.interrepository_implementations import \
373
InterRepositoryTestProviderAdapter
376
formats = [(str, "C1", "C2"), (int, "D1", "D2")]
377
adapter = InterRepositoryTestProviderAdapter(server1, server2, formats)
380
{'interrepo_class': str,
381
'repository_format': 'C1',
382
'repository_format_to': 'C2',
383
'transport_readonly_server': 'b',
384
'transport_server': 'a'}),
386
{'interrepo_class': int,
387
'repository_format': 'D1',
388
'repository_format_to': 'D2',
389
'transport_readonly_server': 'b',
390
'transport_server': 'a'})],
391
adapter.formats_to_scenarios(formats))
394
class TestInterVersionedFileProviderAdapter(TestCase):
395
"""A group of tests that test the InterVersionedFile test adapter."""
397
def test_scenarios(self):
398
# check that constructor parameters are passed through to the adapted
400
from bzrlib.tests.interversionedfile_implementations \
401
import InterVersionedFileTestProviderAdapter
404
formats = [(str, "C1", "C2"), (int, "D1", "D2")]
405
adapter = InterVersionedFileTestProviderAdapter(server1, server2, formats)
408
{'interversionedfile_class':str,
409
'transport_readonly_server': 'b',
410
'transport_server': 'a',
411
'versionedfile_factory': 'C1',
412
'versionedfile_factory_to': 'C2'}),
414
{'interversionedfile_class': int,
415
'transport_readonly_server': 'b',
416
'transport_server': 'a',
417
'versionedfile_factory': 'D1',
418
'versionedfile_factory_to': 'D2'})],
422
class TestRevisionStoreProviderAdapter(TestCase):
423
"""A group of tests that test the RevisionStore test adapter."""
425
def test_scenarios(self):
426
# check that constructor parameters are passed through to the adapted
428
from bzrlib.tests.revisionstore_implementations \
429
import RevisionStoreTestProviderAdapter
430
# revision stores need a store factory - i.e. RevisionKnit
431
#, a readonly and rw transport
435
store_factories = ["c", "d"]
436
adapter = RevisionStoreTestProviderAdapter(server1, server2, store_factories)
439
{'store_factory': 'c',
440
'transport_readonly_server': 'b',
441
'transport_server': 'a'}),
443
{'store_factory': 'd',
444
'transport_readonly_server': 'b',
445
'transport_server': 'a'})],
449
class TestWorkingTreeProviderAdapter(TestCase):
450
"""A group of tests that test the workingtree implementation test adapter."""
452
def test_scenarios(self):
453
# check that constructor parameters are passed through to the adapted
455
from bzrlib.tests.workingtree_implementations \
456
import WorkingTreeTestProviderAdapter
459
formats = [("c", "C"), ("d", "D")]
460
adapter = WorkingTreeTestProviderAdapter(server1, server2, formats)
463
{'bzrdir_format': 'C',
464
'transport_readonly_server': 'b',
465
'transport_server': 'a',
466
'workingtree_format': 'c'}),
468
{'bzrdir_format': 'D',
469
'transport_readonly_server': 'b',
470
'transport_server': 'a',
471
'workingtree_format': 'd'})],
475
class TestTreeProviderAdapter(TestCase):
476
"""Test the setup of tree_implementation tests."""
478
def test_adapted_tests(self):
479
# the tree implementation adapter is meant to setup one instance for
480
# each working tree format, and one additional instance that will
481
# use the default wt format, but create a revision tree for the tests.
482
# this means that the wt ones should have the workingtree_to_test_tree
483
# attribute set to 'return_parameter' and the revision one set to
484
# revision_tree_from_workingtree.
486
from bzrlib.tests.tree_implementations import (
487
TreeTestProviderAdapter,
489
revision_tree_from_workingtree
491
from bzrlib.workingtree import WorkingTreeFormat, WorkingTreeFormat3
492
input_test = TestTreeProviderAdapter(
493
"test_adapted_tests")
496
formats = [("c", "C"), ("d", "D")]
497
adapter = TreeTestProviderAdapter(server1, server2, formats)
498
suite = adapter.adapt(input_test)
499
tests = list(iter(suite))
500
self.assertEqual(4, len(tests))
501
# this must match the default format setp up in
502
# TreeTestProviderAdapter.adapt
503
default_format = WorkingTreeFormat3
504
self.assertEqual(tests[0].workingtree_format, formats[0][0])
505
self.assertEqual(tests[0].bzrdir_format, formats[0][1])
506
self.assertEqual(tests[0].transport_server, server1)
507
self.assertEqual(tests[0].transport_readonly_server, server2)
508
self.assertEqual(tests[0].workingtree_to_test_tree, return_parameter)
509
self.assertEqual(tests[1].workingtree_format, formats[1][0])
510
self.assertEqual(tests[1].bzrdir_format, formats[1][1])
511
self.assertEqual(tests[1].transport_server, server1)
512
self.assertEqual(tests[1].transport_readonly_server, server2)
513
self.assertEqual(tests[1].workingtree_to_test_tree, return_parameter)
514
self.assertIsInstance(tests[2].workingtree_format, default_format)
515
#self.assertEqual(tests[2].bzrdir_format,
516
# default_format._matchingbzrdir)
517
self.assertEqual(tests[2].transport_server, server1)
518
self.assertEqual(tests[2].transport_readonly_server, server2)
519
self.assertEqual(tests[2].workingtree_to_test_tree,
520
revision_tree_from_workingtree)
523
class TestInterTreeProviderAdapter(TestCase):
524
"""A group of tests that test the InterTreeTestAdapter."""
526
def test_adapted_tests(self):
527
# check that constructor parameters are passed through to the adapted
529
# for InterTree tests we want the machinery to bring up two trees in
530
# each instance: the base one, and the one we are interacting with.
531
# because each optimiser can be direction specific, we need to test
532
# each optimiser in its chosen direction.
533
# unlike the TestProviderAdapter we dont want to automatically add a
534
# parameterized one for WorkingTree - the optimisers will tell us what
536
from bzrlib.tests.tree_implementations import (
538
revision_tree_from_workingtree
540
from bzrlib.tests.intertree_implementations import (
541
InterTreeTestProviderAdapter,
543
from bzrlib.workingtree import WorkingTreeFormat2, WorkingTreeFormat3
544
input_test = TestInterTreeProviderAdapter(
545
"test_adapted_tests")
548
format1 = WorkingTreeFormat2()
549
format2 = WorkingTreeFormat3()
550
formats = [(str, format1, format2, "converter1"),
551
(int, format2, format1, "converter2")]
552
adapter = InterTreeTestProviderAdapter(server1, server2, formats)
553
suite = adapter.adapt(input_test)
554
tests = list(iter(suite))
555
self.assertEqual(2, len(tests))
556
self.assertEqual(tests[0].intertree_class, formats[0][0])
557
self.assertEqual(tests[0].workingtree_format, formats[0][1])
558
self.assertEqual(tests[0].workingtree_format_to, formats[0][2])
559
self.assertEqual(tests[0].mutable_trees_to_test_trees, formats[0][3])
560
self.assertEqual(tests[0].workingtree_to_test_tree, return_parameter)
561
self.assertEqual(tests[0].transport_server, server1)
562
self.assertEqual(tests[0].transport_readonly_server, server2)
563
self.assertEqual(tests[1].intertree_class, formats[1][0])
564
self.assertEqual(tests[1].workingtree_format, formats[1][1])
565
self.assertEqual(tests[1].workingtree_format_to, formats[1][2])
566
self.assertEqual(tests[1].mutable_trees_to_test_trees, formats[1][3])
567
self.assertEqual(tests[1].workingtree_to_test_tree, return_parameter)
568
self.assertEqual(tests[1].transport_server, server1)
569
self.assertEqual(tests[1].transport_readonly_server, server2)
572
class TestTestCaseInTempDir(TestCaseInTempDir):
574
def test_home_is_not_working(self):
575
self.assertNotEqual(self.test_dir, self.test_home_dir)
576
cwd = osutils.getcwd()
577
self.assertIsSameRealPath(self.test_dir, cwd)
578
self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
581
class TestTestCaseWithMemoryTransport(TestCaseWithMemoryTransport):
583
def test_home_is_non_existant_dir_under_root(self):
584
"""The test_home_dir for TestCaseWithMemoryTransport is missing.
586
This is because TestCaseWithMemoryTransport is for tests that do not
587
need any disk resources: they should be hooked into bzrlib in such a
588
way that no global settings are being changed by the test (only a
589
few tests should need to do that), and having a missing dir as home is
590
an effective way to ensure that this is the case.
592
self.assertIsSameRealPath(
593
self.TEST_ROOT + "/MemoryTransportMissingHomeDir",
595
self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
597
def test_cwd_is_TEST_ROOT(self):
598
self.assertIsSameRealPath(self.test_dir, self.TEST_ROOT)
599
cwd = osutils.getcwd()
600
self.assertIsSameRealPath(self.test_dir, cwd)
602
def test_make_branch_and_memory_tree(self):
603
"""In TestCaseWithMemoryTransport we should not make the branch on disk.
605
This is hard to comprehensively robustly test, so we settle for making
606
a branch and checking no directory was created at its relpath.
608
tree = self.make_branch_and_memory_tree('dir')
609
# Guard against regression into MemoryTransport leaking
610
# files to disk instead of keeping them in memory.
611
self.failIf(osutils.lexists('dir'))
612
self.assertIsInstance(tree, memorytree.MemoryTree)
614
def test_make_branch_and_memory_tree_with_format(self):
615
"""make_branch_and_memory_tree should accept a format option."""
616
format = bzrdir.BzrDirMetaFormat1()
617
format.repository_format = weaverepo.RepositoryFormat7()
618
tree = self.make_branch_and_memory_tree('dir', format=format)
619
# Guard against regression into MemoryTransport leaking
620
# files to disk instead of keeping them in memory.
621
self.failIf(osutils.lexists('dir'))
622
self.assertIsInstance(tree, memorytree.MemoryTree)
623
self.assertEqual(format.repository_format.__class__,
624
tree.branch.repository._format.__class__)
626
def test_safety_net(self):
627
"""No test should modify the safety .bzr directory.
629
We just test that the _check_safety_net private method raises
630
AssertionError, it's easier than building a test suite with the same
633
# Oops, a commit in the current directory (i.e. without local .bzr
634
# directory) will crawl up the hierarchy to find a .bzr directory.
635
self.run_bzr(['commit', '-mfoo', '--unchanged'])
636
# But we have a safety net in place.
637
self.assertRaises(AssertionError, self._check_safety_net)
640
class TestTestCaseWithTransport(TestCaseWithTransport):
641
"""Tests for the convenience functions TestCaseWithTransport introduces."""
643
def test_get_readonly_url_none(self):
644
from bzrlib.transport import get_transport
645
from bzrlib.transport.memory import MemoryServer
646
from bzrlib.transport.readonly import ReadonlyTransportDecorator
647
self.vfs_transport_factory = MemoryServer
648
self.transport_readonly_server = None
649
# calling get_readonly_transport() constructs a decorator on the url
651
url = self.get_readonly_url()
652
url2 = self.get_readonly_url('foo/bar')
653
t = get_transport(url)
654
t2 = get_transport(url2)
655
self.failUnless(isinstance(t, ReadonlyTransportDecorator))
656
self.failUnless(isinstance(t2, ReadonlyTransportDecorator))
657
self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
659
def test_get_readonly_url_http(self):
660
from bzrlib.tests.http_server import HttpServer
661
from bzrlib.transport import get_transport
662
from bzrlib.transport.local import LocalURLServer
663
from bzrlib.transport.http import HttpTransportBase
664
self.transport_server = LocalURLServer
665
self.transport_readonly_server = HttpServer
666
# calling get_readonly_transport() gives us a HTTP server instance.
667
url = self.get_readonly_url()
668
url2 = self.get_readonly_url('foo/bar')
669
# the transport returned may be any HttpTransportBase subclass
670
t = get_transport(url)
671
t2 = get_transport(url2)
672
self.failUnless(isinstance(t, HttpTransportBase))
673
self.failUnless(isinstance(t2, HttpTransportBase))
674
self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
676
def test_is_directory(self):
677
"""Test assertIsDirectory assertion"""
678
t = self.get_transport()
679
self.build_tree(['a_dir/', 'a_file'], transport=t)
680
self.assertIsDirectory('a_dir', t)
681
self.assertRaises(AssertionError, self.assertIsDirectory, 'a_file', t)
682
self.assertRaises(AssertionError, self.assertIsDirectory, 'not_here', t)
685
class TestTestCaseTransports(TestCaseWithTransport):
688
super(TestTestCaseTransports, self).setUp()
689
self.vfs_transport_factory = MemoryServer
691
def test_make_bzrdir_preserves_transport(self):
692
t = self.get_transport()
693
result_bzrdir = self.make_bzrdir('subdir')
694
self.assertIsInstance(result_bzrdir.transport,
696
# should not be on disk, should only be in memory
697
self.failIfExists('subdir')
700
class TestChrootedTest(ChrootedTestCase):
702
def test_root_is_root(self):
703
from bzrlib.transport import get_transport
704
t = get_transport(self.get_readonly_url())
706
self.assertEqual(url, t.clone('..').base)
709
class MockProgress(_BaseProgressBar):
710
"""Progress-bar standin that records calls.
712
Useful for testing pb using code.
716
_BaseProgressBar.__init__(self)
720
self.calls.append(('tick',))
722
def update(self, msg=None, current=None, total=None):
723
self.calls.append(('update', msg, current, total))
726
self.calls.append(('clear',))
728
def note(self, msg, *args):
729
self.calls.append(('note', msg, args))
732
class TestTestResult(TestCase):
734
def check_timing(self, test_case, expected_re):
735
result = bzrlib.tests.TextTestResult(self._log_file,
739
test_case.run(result)
740
timed_string = result._testTimeString(test_case)
741
self.assertContainsRe(timed_string, expected_re)
743
def test_test_reporting(self):
744
class ShortDelayTestCase(TestCase):
745
def test_short_delay(self):
747
def test_short_benchmark(self):
748
self.time(time.sleep, 0.003)
749
self.check_timing(ShortDelayTestCase('test_short_delay'),
751
# if a benchmark time is given, we want a x of y style result.
752
self.check_timing(ShortDelayTestCase('test_short_benchmark'),
753
r"^ +[0-9]+ms/ +[0-9]+ms$")
755
def test_unittest_reporting_unittest_class(self):
756
# getting the time from a non-bzrlib test works ok
757
class ShortDelayTestCase(unittest.TestCase):
758
def test_short_delay(self):
760
self.check_timing(ShortDelayTestCase('test_short_delay'),
763
def test_assigned_benchmark_file_stores_date(self):
765
result = bzrlib.tests.TextTestResult(self._log_file,
770
output_string = output.getvalue()
771
# if you are wondering about the regexp please read the comment in
772
# test_bench_history (bzrlib.tests.test_selftest.TestRunner)
773
# XXX: what comment? -- Andrew Bennetts
774
self.assertContainsRe(output_string, "--date [0-9.]+")
776
def test_benchhistory_records_test_times(self):
777
result_stream = StringIO()
778
result = bzrlib.tests.TextTestResult(
782
bench_history=result_stream
785
# we want profile a call and check that its test duration is recorded
786
# make a new test instance that when run will generate a benchmark
787
example_test_case = TestTestResult("_time_hello_world_encoding")
788
# execute the test, which should succeed and record times
789
example_test_case.run(result)
790
lines = result_stream.getvalue().splitlines()
791
self.assertEqual(2, len(lines))
792
self.assertContainsRe(lines[1],
793
" *[0-9]+ms bzrlib.tests.test_selftest.TestTestResult"
794
"._time_hello_world_encoding")
796
def _time_hello_world_encoding(self):
797
"""Profile two sleep calls
799
This is used to exercise the test framework.
801
self.time(unicode, 'hello', errors='replace')
802
self.time(unicode, 'world', errors='replace')
804
def test_lsprofiling(self):
805
"""Verbose test result prints lsprof statistics from test cases."""
806
self.requireFeature(test_lsprof.LSProfFeature)
807
result_stream = StringIO()
808
result = bzrlib.tests.VerboseTestResult(
809
unittest._WritelnDecorator(result_stream),
813
# we want profile a call of some sort and check it is output by
814
# addSuccess. We dont care about addError or addFailure as they
815
# are not that interesting for performance tuning.
816
# make a new test instance that when run will generate a profile
817
example_test_case = TestTestResult("_time_hello_world_encoding")
818
example_test_case._gather_lsprof_in_benchmarks = True
819
# execute the test, which should succeed and record profiles
820
example_test_case.run(result)
821
# lsprofile_something()
822
# if this worked we want
823
# LSProf output for <built in function unicode> (['hello'], {'errors': 'replace'})
824
# CallCount Recursive Total(ms) Inline(ms) module:lineno(function)
825
# (the lsprof header)
826
# ... an arbitrary number of lines
827
# and the function call which is time.sleep.
828
# 1 0 ??? ??? ???(sleep)
829
# and then repeated but with 'world', rather than 'hello'.
830
# this should appear in the output stream of our test result.
831
output = result_stream.getvalue()
832
self.assertContainsRe(output,
833
r"LSProf output for <type 'unicode'>\(\('hello',\), {'errors': 'replace'}\)")
834
self.assertContainsRe(output,
835
r" *CallCount *Recursive *Total\(ms\) *Inline\(ms\) *module:lineno\(function\)\n")
836
self.assertContainsRe(output,
837
r"( +1 +0 +0\.\d+ +0\.\d+ +<method 'disable' of '_lsprof\.Profiler' objects>\n)?")
838
self.assertContainsRe(output,
839
r"LSProf output for <type 'unicode'>\(\('world',\), {'errors': 'replace'}\)\n")
841
def test_known_failure(self):
842
"""A KnownFailure being raised should trigger several result actions."""
843
class InstrumentedTestResult(ExtendedTestResult):
845
def report_test_start(self, test): pass
846
def report_known_failure(self, test, err):
847
self._call = test, err
848
result = InstrumentedTestResult(None, None, None, None)
850
raise KnownFailure('failed!')
851
test = unittest.FunctionTestCase(test_function)
853
# it should invoke 'report_known_failure'.
854
self.assertEqual(2, len(result._call))
855
self.assertEqual(test, result._call[0])
856
self.assertEqual(KnownFailure, result._call[1][0])
857
self.assertIsInstance(result._call[1][1], KnownFailure)
858
# we dont introspec the traceback, if the rest is ok, it would be
859
# exceptional for it not to be.
860
# it should update the known_failure_count on the object.
861
self.assertEqual(1, result.known_failure_count)
862
# the result should be successful.
863
self.assertTrue(result.wasSuccessful())
865
def test_verbose_report_known_failure(self):
866
# verbose test output formatting
867
result_stream = StringIO()
868
result = bzrlib.tests.VerboseTestResult(
869
unittest._WritelnDecorator(result_stream),
873
test = self.get_passing_test()
874
result.startTest(test)
875
prefix = len(result_stream.getvalue())
876
# the err parameter has the shape:
877
# (class, exception object, traceback)
878
# KnownFailures dont get their tracebacks shown though, so we
880
err = (KnownFailure, KnownFailure('foo'), None)
881
result.report_known_failure(test, err)
882
output = result_stream.getvalue()[prefix:]
883
lines = output.splitlines()
884
self.assertContainsRe(lines[0], r'XFAIL *\d+ms$')
885
self.assertEqual(lines[1], ' foo')
886
self.assertEqual(2, len(lines))
888
def test_text_report_known_failure(self):
889
# text test output formatting
891
result = bzrlib.tests.TextTestResult(
897
test = self.get_passing_test()
898
# this seeds the state to handle reporting the test.
899
result.startTest(test)
900
# the err parameter has the shape:
901
# (class, exception object, traceback)
902
# KnownFailures dont get their tracebacks shown though, so we
904
err = (KnownFailure, KnownFailure('foo'), None)
905
result.report_known_failure(test, err)
908
('update', '[1 in 0s] passing_test', None, None),
909
('note', 'XFAIL: %s\n%s\n', ('passing_test', err[1]))
912
# known_failures should be printed in the summary, so if we run a test
913
# after there are some known failures, the update prefix should match
915
result.known_failure_count = 3
919
('update', '[2 in 0s, 3 known failures] passing_test', None, None),
923
def get_passing_test(self):
924
"""Return a test object that can't be run usefully."""
927
return unittest.FunctionTestCase(passing_test)
929
def test_add_not_supported(self):
930
"""Test the behaviour of invoking addNotSupported."""
931
class InstrumentedTestResult(ExtendedTestResult):
932
def report_test_start(self, test): pass
933
def report_unsupported(self, test, feature):
934
self._call = test, feature
935
result = InstrumentedTestResult(None, None, None, None)
936
test = SampleTestCase('_test_pass')
938
result.startTest(test)
939
result.addNotSupported(test, feature)
940
# it should invoke 'report_unsupported'.
941
self.assertEqual(2, len(result._call))
942
self.assertEqual(test, result._call[0])
943
self.assertEqual(feature, result._call[1])
944
# the result should be successful.
945
self.assertTrue(result.wasSuccessful())
946
# it should record the test against a count of tests not run due to
948
self.assertEqual(1, result.unsupported['Feature'])
949
# and invoking it again should increment that counter
950
result.addNotSupported(test, feature)
951
self.assertEqual(2, result.unsupported['Feature'])
953
def test_verbose_report_unsupported(self):
954
# verbose test output formatting
955
result_stream = StringIO()
956
result = bzrlib.tests.VerboseTestResult(
957
unittest._WritelnDecorator(result_stream),
961
test = self.get_passing_test()
963
result.startTest(test)
964
prefix = len(result_stream.getvalue())
965
result.report_unsupported(test, feature)
966
output = result_stream.getvalue()[prefix:]
967
lines = output.splitlines()
968
self.assertEqual(lines, ['NODEP 0ms', " The feature 'Feature' is not available."])
970
def test_text_report_unsupported(self):
971
# text test output formatting
973
result = bzrlib.tests.TextTestResult(
979
test = self.get_passing_test()
981
# this seeds the state to handle reporting the test.
982
result.startTest(test)
983
result.report_unsupported(test, feature)
984
# no output on unsupported features
986
[('update', '[1 in 0s] passing_test', None, None)
989
# the number of missing features should be printed in the progress
990
# summary, so check for that.
991
result.unsupported = {'foo':0, 'bar':0}
995
('update', '[2 in 0s, 2 missing features] passing_test', None, None),
999
def test_unavailable_exception(self):
1000
"""An UnavailableFeature being raised should invoke addNotSupported."""
1001
class InstrumentedTestResult(ExtendedTestResult):
1003
def report_test_start(self, test): pass
1004
def addNotSupported(self, test, feature):
1005
self._call = test, feature
1006
result = InstrumentedTestResult(None, None, None, None)
1008
def test_function():
1009
raise UnavailableFeature(feature)
1010
test = unittest.FunctionTestCase(test_function)
1012
# it should invoke 'addNotSupported'.
1013
self.assertEqual(2, len(result._call))
1014
self.assertEqual(test, result._call[0])
1015
self.assertEqual(feature, result._call[1])
1016
# and not count as an error
1017
self.assertEqual(0, result.error_count)
1019
def test_strict_with_unsupported_feature(self):
1020
result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
1022
test = self.get_passing_test()
1023
feature = "Unsupported Feature"
1024
result.addNotSupported(test, feature)
1025
self.assertFalse(result.wasStrictlySuccessful())
1026
self.assertEqual(None, result._extractBenchmarkTime(test))
1028
def test_strict_with_known_failure(self):
1029
result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
1031
test = self.get_passing_test()
1032
err = (KnownFailure, KnownFailure('foo'), None)
1033
result._addKnownFailure(test, err)
1034
self.assertFalse(result.wasStrictlySuccessful())
1035
self.assertEqual(None, result._extractBenchmarkTime(test))
1037
def test_strict_with_success(self):
1038
result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
1040
test = self.get_passing_test()
1041
result.addSuccess(test)
1042
self.assertTrue(result.wasStrictlySuccessful())
1043
self.assertEqual(None, result._extractBenchmarkTime(test))
1046
class TestRunner(TestCase):
1048
def dummy_test(self):
1051
def run_test_runner(self, testrunner, test):
1052
"""Run suite in testrunner, saving global state and restoring it.
1054
This current saves and restores:
1055
TestCaseInTempDir.TEST_ROOT
1057
There should be no tests in this file that use bzrlib.tests.TextTestRunner
1058
without using this convenience method, because of our use of global state.
1060
old_root = TestCaseInTempDir.TEST_ROOT
1062
TestCaseInTempDir.TEST_ROOT = None
1063
return testrunner.run(test)
1065
TestCaseInTempDir.TEST_ROOT = old_root
1067
def test_known_failure_failed_run(self):
1068
# run a test that generates a known failure which should be printed in
1069
# the final output when real failures occur.
1070
def known_failure_test():
1071
raise KnownFailure('failed')
1072
test = unittest.TestSuite()
1073
test.addTest(unittest.FunctionTestCase(known_failure_test))
1075
raise AssertionError('foo')
1076
test.addTest(unittest.FunctionTestCase(failing_test))
1078
runner = TextTestRunner(stream=stream)
1079
result = self.run_test_runner(runner, test)
1080
lines = stream.getvalue().splitlines()
1083
'======================================================================',
1084
'FAIL: unittest.FunctionTestCase (failing_test)',
1085
'----------------------------------------------------------------------',
1086
'Traceback (most recent call last):',
1087
' raise AssertionError(\'foo\')',
1088
'AssertionError: foo',
1090
'----------------------------------------------------------------------',
1092
'FAILED (failures=1, known_failure_count=1)'],
1093
lines[0:5] + lines[6:10] + lines[11:])
1095
def test_known_failure_ok_run(self):
1096
# run a test that generates a known failure which should be printed in the final output.
1097
def known_failure_test():
1098
raise KnownFailure('failed')
1099
test = unittest.FunctionTestCase(known_failure_test)
1101
runner = TextTestRunner(stream=stream)
1102
result = self.run_test_runner(runner, test)
1103
self.assertContainsRe(stream.getvalue(),
1106
'Ran 1 test in .*\n'
1108
'OK \\(known_failures=1\\)\n')
1110
def test_skipped_test(self):
1111
# run a test that is skipped, and check the suite as a whole still
1113
# skipping_test must be hidden in here so it's not run as a real test
1114
def skipping_test():
1115
raise TestSkipped('test intentionally skipped')
1117
runner = TextTestRunner(stream=self._log_file)
1118
test = unittest.FunctionTestCase(skipping_test)
1119
result = self.run_test_runner(runner, test)
1120
self.assertTrue(result.wasSuccessful())
1122
def test_skipped_from_setup(self):
1123
class SkippedSetupTest(TestCase):
1127
self.addCleanup(self.cleanup)
1128
raise TestSkipped('skipped setup')
1130
def test_skip(self):
1131
self.fail('test reached')
1136
runner = TextTestRunner(stream=self._log_file)
1137
test = SkippedSetupTest('test_skip')
1138
result = self.run_test_runner(runner, test)
1139
self.assertTrue(result.wasSuccessful())
1140
# Check if cleanup was called the right number of times.
1141
self.assertEqual(0, test.counter)
1143
def test_skipped_from_test(self):
1144
class SkippedTest(TestCase):
1148
self.addCleanup(self.cleanup)
1150
def test_skip(self):
1151
raise TestSkipped('skipped test')
1156
runner = TextTestRunner(stream=self._log_file)
1157
test = SkippedTest('test_skip')
1158
result = self.run_test_runner(runner, test)
1159
self.assertTrue(result.wasSuccessful())
1160
# Check if cleanup was called the right number of times.
1161
self.assertEqual(0, test.counter)
1163
def test_not_applicable(self):
1164
# run a test that is skipped because it's not applicable
1165
def not_applicable_test():
1166
from bzrlib.tests import TestNotApplicable
1167
raise TestNotApplicable('this test never runs')
1169
runner = TextTestRunner(stream=out, verbosity=2)
1170
test = unittest.FunctionTestCase(not_applicable_test)
1171
result = self.run_test_runner(runner, test)
1172
self._log_file.write(out.getvalue())
1173
self.assertTrue(result.wasSuccessful())
1174
self.assertTrue(result.wasStrictlySuccessful())
1175
self.assertContainsRe(out.getvalue(),
1176
r'(?m)not_applicable_test * N/A')
1177
self.assertContainsRe(out.getvalue(),
1178
r'(?m)^ this test never runs')
1180
def test_not_applicable_demo(self):
1181
# just so you can see it in the test output
1182
raise TestNotApplicable('this test is just a demonstation')
1184
def test_unsupported_features_listed(self):
1185
"""When unsupported features are encountered they are detailed."""
1186
class Feature1(Feature):
1187
def _probe(self): return False
1188
class Feature2(Feature):
1189
def _probe(self): return False
1190
# create sample tests
1191
test1 = SampleTestCase('_test_pass')
1192
test1._test_needs_features = [Feature1()]
1193
test2 = SampleTestCase('_test_pass')
1194
test2._test_needs_features = [Feature2()]
1195
test = unittest.TestSuite()
1199
runner = TextTestRunner(stream=stream)
1200
result = self.run_test_runner(runner, test)
1201
lines = stream.getvalue().splitlines()
1204
"Missing feature 'Feature1' skipped 1 tests.",
1205
"Missing feature 'Feature2' skipped 1 tests.",
1209
def test_bench_history(self):
1210
# tests that the running the benchmark produces a history file
1211
# containing a timestamp and the revision id of the bzrlib source which
1213
workingtree = _get_bzr_source_tree()
1214
test = TestRunner('dummy_test')
1216
runner = TextTestRunner(stream=self._log_file, bench_history=output)
1217
result = self.run_test_runner(runner, test)
1218
output_string = output.getvalue()
1219
self.assertContainsRe(output_string, "--date [0-9.]+")
1220
if workingtree is not None:
1221
revision_id = workingtree.get_parent_ids()[0]
1222
self.assertEndsWith(output_string.rstrip(), revision_id)
1224
def test_success_log_deleted(self):
1225
"""Successful tests have their log deleted"""
1227
class LogTester(TestCase):
1229
def test_success(self):
1230
self.log('this will be removed\n')
1232
sio = cStringIO.StringIO()
1233
runner = TextTestRunner(stream=sio)
1234
test = LogTester('test_success')
1235
result = self.run_test_runner(runner, test)
1237
log = test._get_log()
1238
self.assertEqual("DELETED log file to reduce memory footprint", log)
1239
self.assertEqual('', test._log_contents)
1240
self.assertIs(None, test._log_file_name)
1242
def test_fail_log_kept(self):
1243
"""Failed tests have their log kept"""
1245
class LogTester(TestCase):
1247
def test_fail(self):
1248
self.log('this will be kept\n')
1249
self.fail('this test fails')
1251
sio = cStringIO.StringIO()
1252
runner = TextTestRunner(stream=sio)
1253
test = LogTester('test_fail')
1254
result = self.run_test_runner(runner, test)
1256
text = sio.getvalue()
1257
self.assertContainsRe(text, 'this will be kept')
1258
self.assertContainsRe(text, 'this test fails')
1260
log = test._get_log()
1261
self.assertContainsRe(log, 'this will be kept')
1262
self.assertEqual(log, test._log_contents)
1264
def test_error_log_kept(self):
1265
"""Tests with errors have their log kept"""
1267
class LogTester(TestCase):
1269
def test_error(self):
1270
self.log('this will be kept\n')
1271
raise ValueError('random exception raised')
1273
sio = cStringIO.StringIO()
1274
runner = TextTestRunner(stream=sio)
1275
test = LogTester('test_error')
1276
result = self.run_test_runner(runner, test)
1278
text = sio.getvalue()
1279
self.assertContainsRe(text, 'this will be kept')
1280
self.assertContainsRe(text, 'random exception raised')
1282
log = test._get_log()
1283
self.assertContainsRe(log, 'this will be kept')
1284
self.assertEqual(log, test._log_contents)
1287
class SampleTestCase(TestCase):
1289
def _test_pass(self):
1293
class TestTestCase(TestCase):
1294
"""Tests that test the core bzrlib TestCase."""
1296
def test_debug_flags_sanitised(self):
1297
"""The bzrlib debug flags should be sanitised by setUp."""
1298
# we could set something and run a test that will check
1299
# it gets santised, but this is probably sufficient for now:
1300
# if someone runs the test with -Dsomething it will error.
1301
self.assertEqual(set(), bzrlib.debug.debug_flags)
1303
def inner_test(self):
1304
# the inner child test
1307
def outer_child(self):
1308
# the outer child test
1310
self.inner_test = TestTestCase("inner_child")
1311
result = bzrlib.tests.TextTestResult(self._log_file,
1314
self.inner_test.run(result)
1315
note("outer finish")
1317
def test_trace_nesting(self):
1318
# this tests that each test case nests its trace facility correctly.
1319
# we do this by running a test case manually. That test case (A)
1320
# should setup a new log, log content to it, setup a child case (B),
1321
# which should log independently, then case (A) should log a trailer
1323
# we do two nested children so that we can verify the state of the
1324
# logs after the outer child finishes is correct, which a bad clean
1325
# up routine in tearDown might trigger a fault in our test with only
1326
# one child, we should instead see the bad result inside our test with
1328
# the outer child test
1329
original_trace = bzrlib.trace._trace_file
1330
outer_test = TestTestCase("outer_child")
1331
result = bzrlib.tests.TextTestResult(self._log_file,
1334
outer_test.run(result)
1335
self.assertEqual(original_trace, bzrlib.trace._trace_file)
1337
def method_that_times_a_bit_twice(self):
1338
# call self.time twice to ensure it aggregates
1339
self.time(time.sleep, 0.007)
1340
self.time(time.sleep, 0.007)
1342
def test_time_creates_benchmark_in_result(self):
1343
"""Test that the TestCase.time() method accumulates a benchmark time."""
1344
sample_test = TestTestCase("method_that_times_a_bit_twice")
1345
output_stream = StringIO()
1346
result = bzrlib.tests.VerboseTestResult(
1347
unittest._WritelnDecorator(output_stream),
1350
num_tests=sample_test.countTestCases())
1351
sample_test.run(result)
1352
self.assertContainsRe(
1353
output_stream.getvalue(),
1354
r"\d+ms/ +\d+ms\n$")
1356
def test_hooks_sanitised(self):
1357
"""The bzrlib hooks should be sanitised by setUp."""
1358
self.assertEqual(bzrlib.branch.BranchHooks(),
1359
bzrlib.branch.Branch.hooks)
1360
self.assertEqual(bzrlib.smart.server.SmartServerHooks(),
1361
bzrlib.smart.server.SmartTCPServer.hooks)
1363
def test__gather_lsprof_in_benchmarks(self):
1364
"""When _gather_lsprof_in_benchmarks is on, accumulate profile data.
1366
Each self.time() call is individually and separately profiled.
1368
self.requireFeature(test_lsprof.LSProfFeature)
1369
# overrides the class member with an instance member so no cleanup
1371
self._gather_lsprof_in_benchmarks = True
1372
self.time(time.sleep, 0.000)
1373
self.time(time.sleep, 0.003)
1374
self.assertEqual(2, len(self._benchcalls))
1375
self.assertEqual((time.sleep, (0.000,), {}), self._benchcalls[0][0])
1376
self.assertEqual((time.sleep, (0.003,), {}), self._benchcalls[1][0])
1377
self.assertIsInstance(self._benchcalls[0][1], bzrlib.lsprof.Stats)
1378
self.assertIsInstance(self._benchcalls[1][1], bzrlib.lsprof.Stats)
1380
def test_knownFailure(self):
1381
"""Self.knownFailure() should raise a KnownFailure exception."""
1382
self.assertRaises(KnownFailure, self.knownFailure, "A Failure")
1384
def test_requireFeature_available(self):
1385
"""self.requireFeature(available) is a no-op."""
1386
class Available(Feature):
1387
def _probe(self):return True
1388
feature = Available()
1389
self.requireFeature(feature)
1391
def test_requireFeature_unavailable(self):
1392
"""self.requireFeature(unavailable) raises UnavailableFeature."""
1393
class Unavailable(Feature):
1394
def _probe(self):return False
1395
feature = Unavailable()
1396
self.assertRaises(UnavailableFeature, self.requireFeature, feature)
1398
def test_run_no_parameters(self):
1399
test = SampleTestCase('_test_pass')
1402
def test_run_enabled_unittest_result(self):
1403
"""Test we revert to regular behaviour when the test is enabled."""
1404
test = SampleTestCase('_test_pass')
1405
class EnabledFeature(object):
1406
def available(self):
1408
test._test_needs_features = [EnabledFeature()]
1409
result = unittest.TestResult()
1411
self.assertEqual(1, result.testsRun)
1412
self.assertEqual([], result.errors)
1413
self.assertEqual([], result.failures)
1415
def test_run_disabled_unittest_result(self):
1416
"""Test our compatability for disabled tests with unittest results."""
1417
test = SampleTestCase('_test_pass')
1418
class DisabledFeature(object):
1419
def available(self):
1421
test._test_needs_features = [DisabledFeature()]
1422
result = unittest.TestResult()
1424
self.assertEqual(1, result.testsRun)
1425
self.assertEqual([], result.errors)
1426
self.assertEqual([], result.failures)
1428
def test_run_disabled_supporting_result(self):
1429
"""Test disabled tests behaviour with support aware results."""
1430
test = SampleTestCase('_test_pass')
1431
class DisabledFeature(object):
1432
def available(self):
1434
the_feature = DisabledFeature()
1435
test._test_needs_features = [the_feature]
1436
class InstrumentedTestResult(unittest.TestResult):
1438
unittest.TestResult.__init__(self)
1440
def startTest(self, test):
1441
self.calls.append(('startTest', test))
1442
def stopTest(self, test):
1443
self.calls.append(('stopTest', test))
1444
def addNotSupported(self, test, feature):
1445
self.calls.append(('addNotSupported', test, feature))
1446
result = InstrumentedTestResult()
1449
('startTest', test),
1450
('addNotSupported', test, the_feature),
1456
@symbol_versioning.deprecated_function(zero_eleven)
1457
def sample_deprecated_function():
1458
"""A deprecated function to test applyDeprecated with."""
1462
def sample_undeprecated_function(a_param):
1463
"""A undeprecated function to test applyDeprecated with."""
1466
class ApplyDeprecatedHelper(object):
1467
"""A helper class for ApplyDeprecated tests."""
1469
@symbol_versioning.deprecated_method(zero_eleven)
1470
def sample_deprecated_method(self, param_one):
1471
"""A deprecated method for testing with."""
1474
def sample_normal_method(self):
1475
"""A undeprecated method."""
1477
@symbol_versioning.deprecated_method(zero_ten)
1478
def sample_nested_deprecation(self):
1479
return sample_deprecated_function()
1482
class TestExtraAssertions(TestCase):
1483
"""Tests for new test assertions in bzrlib test suite"""
1485
def test_assert_isinstance(self):
1486
self.assertIsInstance(2, int)
1487
self.assertIsInstance(u'', basestring)
1488
self.assertRaises(AssertionError, self.assertIsInstance, None, int)
1489
self.assertRaises(AssertionError, self.assertIsInstance, 23.3, int)
1491
def test_assertEndsWith(self):
1492
self.assertEndsWith('foo', 'oo')
1493
self.assertRaises(AssertionError, self.assertEndsWith, 'o', 'oo')
1495
def test_applyDeprecated_not_deprecated(self):
1496
sample_object = ApplyDeprecatedHelper()
1497
# calling an undeprecated callable raises an assertion
1498
self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
1499
sample_object.sample_normal_method)
1500
self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
1501
sample_undeprecated_function, "a param value")
1502
# calling a deprecated callable (function or method) with the wrong
1503
# expected deprecation fails.
1504
self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
1505
sample_object.sample_deprecated_method, "a param value")
1506
self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
1507
sample_deprecated_function)
1508
# calling a deprecated callable (function or method) with the right
1509
# expected deprecation returns the functions result.
1510
self.assertEqual("a param value", self.applyDeprecated(zero_eleven,
1511
sample_object.sample_deprecated_method, "a param value"))
1512
self.assertEqual(2, self.applyDeprecated(zero_eleven,
1513
sample_deprecated_function))
1514
# calling a nested deprecation with the wrong deprecation version
1515
# fails even if a deeper nested function was deprecated with the
1517
self.assertRaises(AssertionError, self.applyDeprecated,
1518
zero_eleven, sample_object.sample_nested_deprecation)
1519
# calling a nested deprecation with the right deprecation value
1520
# returns the calls result.
1521
self.assertEqual(2, self.applyDeprecated(zero_ten,
1522
sample_object.sample_nested_deprecation))
1524
def test_callDeprecated(self):
1525
def testfunc(be_deprecated, result=None):
1526
if be_deprecated is True:
1527
symbol_versioning.warn('i am deprecated', DeprecationWarning,
1530
result = self.callDeprecated(['i am deprecated'], testfunc, True)
1531
self.assertIs(None, result)
1532
result = self.callDeprecated([], testfunc, False, 'result')
1533
self.assertEqual('result', result)
1534
self.callDeprecated(['i am deprecated'], testfunc, be_deprecated=True)
1535
self.callDeprecated([], testfunc, be_deprecated=False)
1538
class TestWarningTests(TestCase):
1539
"""Tests for calling methods that raise warnings."""
1541
def test_callCatchWarnings(self):
1543
warnings.warn("this is your last warning")
1545
wlist, result = self.callCatchWarnings(meth, 1, 2)
1546
self.assertEquals(3, result)
1547
# would like just to compare them, but UserWarning doesn't implement
1550
self.assertIsInstance(w0, UserWarning)
1551
self.assertEquals("this is your last warning", str(w0))
1554
class TestConvenienceMakers(TestCaseWithTransport):
1555
"""Test for the make_* convenience functions."""
1557
def test_make_branch_and_tree_with_format(self):
1558
# we should be able to supply a format to make_branch_and_tree
1559
self.make_branch_and_tree('a', format=bzrlib.bzrdir.BzrDirMetaFormat1())
1560
self.make_branch_and_tree('b', format=bzrlib.bzrdir.BzrDirFormat6())
1561
self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('a')._format,
1562
bzrlib.bzrdir.BzrDirMetaFormat1)
1563
self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('b')._format,
1564
bzrlib.bzrdir.BzrDirFormat6)
1566
def test_make_branch_and_memory_tree(self):
1567
# we should be able to get a new branch and a mutable tree from
1568
# TestCaseWithTransport
1569
tree = self.make_branch_and_memory_tree('a')
1570
self.assertIsInstance(tree, bzrlib.memorytree.MemoryTree)
1573
class TestSFTPMakeBranchAndTree(TestCaseWithSFTPServer):
1575
def test_make_tree_for_sftp_branch(self):
1576
"""Transports backed by local directories create local trees."""
1578
tree = self.make_branch_and_tree('t1')
1579
base = tree.bzrdir.root_transport.base
1580
self.failIf(base.startswith('sftp'),
1581
'base %r is on sftp but should be local' % base)
1582
self.assertEquals(tree.bzrdir.root_transport,
1583
tree.branch.bzrdir.root_transport)
1584
self.assertEquals(tree.bzrdir.root_transport,
1585
tree.branch.repository.bzrdir.root_transport)
1588
class TestSelftest(TestCase):
1589
"""Tests of bzrlib.tests.selftest."""
1591
def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
1594
factory_called.append(True)
1598
self.apply_redirected(out, err, None, bzrlib.tests.selftest,
1599
test_suite_factory=factory)
1600
self.assertEqual([True], factory_called)
1603
class TestKnownFailure(TestCase):
1605
def test_known_failure(self):
1606
"""Check that KnownFailure is defined appropriately."""
1607
# a KnownFailure is an assertion error for compatability with unaware
1609
self.assertIsInstance(KnownFailure(""), AssertionError)
1611
def test_expect_failure(self):
1613
self.expectFailure("Doomed to failure", self.assertTrue, False)
1614
except KnownFailure, e:
1615
self.assertEqual('Doomed to failure', e.args[0])
1617
self.expectFailure("Doomed to failure", self.assertTrue, True)
1618
except AssertionError, e:
1619
self.assertEqual('Unexpected success. Should have failed:'
1620
' Doomed to failure', e.args[0])
1622
self.fail('Assertion not raised')
1625
class TestFeature(TestCase):
1627
def test_caching(self):
1628
"""Feature._probe is called by the feature at most once."""
1629
class InstrumentedFeature(Feature):
1631
Feature.__init__(self)
1634
self.calls.append('_probe')
1636
feature = InstrumentedFeature()
1638
self.assertEqual(['_probe'], feature.calls)
1640
self.assertEqual(['_probe'], feature.calls)
1642
def test_named_str(self):
1643
"""Feature.__str__ should thunk to feature_name()."""
1644
class NamedFeature(Feature):
1645
def feature_name(self):
1647
feature = NamedFeature()
1648
self.assertEqual('symlinks', str(feature))
1650
def test_default_str(self):
1651
"""Feature.__str__ should default to __class__.__name__."""
1652
class NamedFeature(Feature):
1654
feature = NamedFeature()
1655
self.assertEqual('NamedFeature', str(feature))
1658
class TestUnavailableFeature(TestCase):
1660
def test_access_feature(self):
1662
exception = UnavailableFeature(feature)
1663
self.assertIs(feature, exception.args[0])
1666
class TestSelftestFiltering(TestCase):
1669
self.suite = TestUtil.TestSuite()
1670
self.loader = TestUtil.TestLoader()
1671
self.suite.addTest(self.loader.loadTestsFromModuleNames([
1672
'bzrlib.tests.test_selftest']))
1673
self.all_names = self._test_ids(self.suite)
1675
def _test_ids(self, test_suite):
1676
"""Get the ids for the tests in a test suite."""
1677
return [t.id() for t in iter_suite_tests(test_suite)]
1679
def test_condition_id_re(self):
1680
test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1681
'test_condition_id_re')
1682
filtered_suite = filter_suite_by_condition(self.suite,
1683
condition_id_re('test_condition_id_re'))
1684
self.assertEqual([test_name], self._test_ids(filtered_suite))
1686
def test_condition_id_in_list(self):
1687
test_names = ['bzrlib.tests.test_selftest.TestSelftestFiltering.'
1688
'test_condition_id_in_list']
1689
id_list = tests.TestIdList(test_names)
1690
filtered_suite = filter_suite_by_condition(
1691
self.suite, tests.condition_id_in_list(id_list))
1692
my_pattern = 'TestSelftestFiltering.*test_condition_id_in_list'
1693
re_filtered = filter_suite_by_re(self.suite, my_pattern)
1694
self.assertEqual(self._test_ids(re_filtered),
1695
self._test_ids(filtered_suite))
1697
def test_condition_isinstance(self):
1698
filtered_suite = filter_suite_by_condition(self.suite,
1699
condition_isinstance(self.__class__))
1700
class_pattern = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
1701
re_filtered = filter_suite_by_re(self.suite, class_pattern)
1702
self.assertEqual(self._test_ids(re_filtered),
1703
self._test_ids(filtered_suite))
1705
def test_exclude_tests_by_condition(self):
1706
excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1707
'test_exclude_tests_by_condition')
1708
filtered_suite = exclude_tests_by_condition(self.suite,
1709
lambda x:x.id() == excluded_name)
1710
self.assertEqual(len(self.all_names) - 1,
1711
filtered_suite.countTestCases())
1712
self.assertFalse(excluded_name in self._test_ids(filtered_suite))
1713
remaining_names = list(self.all_names)
1714
remaining_names.remove(excluded_name)
1715
self.assertEqual(remaining_names, self._test_ids(filtered_suite))
1717
def test_exclude_tests_by_re(self):
1718
self.all_names = self._test_ids(self.suite)
1719
filtered_suite = exclude_tests_by_re(self.suite, 'exclude_tests_by_re')
1720
excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1721
'test_exclude_tests_by_re')
1722
self.assertEqual(len(self.all_names) - 1,
1723
filtered_suite.countTestCases())
1724
self.assertFalse(excluded_name in self._test_ids(filtered_suite))
1725
remaining_names = list(self.all_names)
1726
remaining_names.remove(excluded_name)
1727
self.assertEqual(remaining_names, self._test_ids(filtered_suite))
1729
def test_filter_suite_by_condition(self):
1730
test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1731
'test_filter_suite_by_condition')
1732
filtered_suite = filter_suite_by_condition(self.suite,
1733
lambda x:x.id() == test_name)
1734
self.assertEqual([test_name], self._test_ids(filtered_suite))
1736
def test_filter_suite_by_re(self):
1737
filtered_suite = filter_suite_by_re(self.suite, 'test_filter_suite_by_r')
1738
filtered_names = self._test_ids(filtered_suite)
1739
self.assertEqual(filtered_names, ['bzrlib.tests.test_selftest.'
1740
'TestSelftestFiltering.test_filter_suite_by_re'])
1742
def test_filter_suite_by_id_list(self):
1743
test_list = ['bzrlib.tests.test_selftest.'
1744
'TestSelftestFiltering.test_filter_suite_by_id_list']
1745
filtered_suite = tests.filter_suite_by_id_list(
1746
self.suite, tests.TestIdList(test_list))
1747
filtered_names = self._test_ids(filtered_suite)
1750
['bzrlib.tests.test_selftest.'
1751
'TestSelftestFiltering.test_filter_suite_by_id_list'])
1753
def test_preserve_input(self):
1754
# NB: Surely this is something in the stdlib to do this?
1755
self.assertTrue(self.suite is preserve_input(self.suite))
1756
self.assertTrue("@#$" is preserve_input("@#$"))
1758
def test_randomize_suite(self):
1759
randomized_suite = randomize_suite(self.suite)
1760
# randomizing should not add or remove test names.
1761
self.assertEqual(set(self._test_ids(self.suite)),
1762
set(self._test_ids(randomized_suite)))
1763
# Technically, this *can* fail, because random.shuffle(list) can be
1764
# equal to list. Trying multiple times just pushes the frequency back.
1765
# As its len(self.all_names)!:1, the failure frequency should be low
1766
# enough to ignore. RBC 20071021.
1767
# It should change the order.
1768
self.assertNotEqual(self.all_names, self._test_ids(randomized_suite))
1769
# But not the length. (Possibly redundant with the set test, but not
1771
self.assertEqual(len(self.all_names),
1772
len(self._test_ids(randomized_suite)))
1774
def test_sort_suite_by_re(self):
1775
sorted_suite = self.applyDeprecated(one_zero,
1776
sort_suite_by_re, self.suite, 'test_filter_suite_by_r')
1777
sorted_names = self._test_ids(sorted_suite)
1778
self.assertEqual(sorted_names[0], 'bzrlib.tests.test_selftest.'
1779
'TestSelftestFiltering.test_filter_suite_by_re')
1780
self.assertEquals(sorted(self.all_names), sorted(sorted_names))
1782
def test_split_suit_by_re(self):
1783
self.all_names = self._test_ids(self.suite)
1784
split_suite = split_suite_by_re(self.suite, 'test_filter_suite_by_r')
1785
filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1786
'test_filter_suite_by_re')
1787
self.assertEqual([filtered_name], self._test_ids(split_suite[0]))
1788
self.assertFalse(filtered_name in self._test_ids(split_suite[1]))
1789
remaining_names = list(self.all_names)
1790
remaining_names.remove(filtered_name)
1791
self.assertEqual(remaining_names, self._test_ids(split_suite[1]))
1794
class TestCheckInventoryShape(TestCaseWithTransport):
1796
def test_check_inventory_shape(self):
1797
files = ['a', 'b/', 'b/c']
1798
tree = self.make_branch_and_tree('.')
1799
self.build_tree(files)
1803
self.check_inventory_shape(tree.inventory, files)
1808
class TestBlackboxSupport(TestCase):
1809
"""Tests for testsuite blackbox features."""
1811
def test_run_bzr_failure_not_caught(self):
1812
# When we run bzr in blackbox mode, we want any unexpected errors to
1813
# propagate up to the test suite so that it can show the error in the
1814
# usual way, and we won't get a double traceback.
1815
e = self.assertRaises(
1817
self.run_bzr, ['assert-fail'])
1818
# make sure we got the real thing, not an error from somewhere else in
1819
# the test framework
1820
self.assertEquals('always fails', str(e))
1821
# check that there's no traceback in the test log
1822
self.assertNotContainsRe(self._get_log(keep_log_file=True),
1825
def test_run_bzr_user_error_caught(self):
1826
# Running bzr in blackbox mode, normal/expected/user errors should be
1827
# caught in the regular way and turned into an error message plus exit
1829
out, err = self.run_bzr(["log", "/nonexistantpath"], retcode=3)
1830
self.assertEqual(out, '')
1831
self.assertContainsRe(err,
1832
'bzr: ERROR: Not a branch: ".*nonexistantpath/".\n')
1835
class TestTestLoader(TestCase):
1836
"""Tests for the test loader."""
1838
def _get_loader_and_module(self):
1839
"""Gets a TestLoader and a module with one test in it."""
1840
loader = TestUtil.TestLoader()
1842
class Stub(TestCase):
1845
class MyModule(object):
1847
MyModule.a_class = Stub
1849
return loader, module
1851
def test_module_no_load_tests_attribute_loads_classes(self):
1852
loader, module = self._get_loader_and_module()
1853
self.assertEqual(1, loader.loadTestsFromModule(module).countTestCases())
1855
def test_module_load_tests_attribute_gets_called(self):
1856
loader, module = self._get_loader_and_module()
1857
# 'self' is here because we're faking the module with a class. Regular
1858
# load_tests do not need that :)
1859
def load_tests(self, standard_tests, module, loader):
1860
result = loader.suiteClass()
1861
for test in iter_suite_tests(standard_tests):
1862
result.addTests([test, test])
1864
# add a load_tests() method which multiplies the tests from the module.
1865
module.__class__.load_tests = load_tests
1866
self.assertEqual(2, loader.loadTestsFromModule(module).countTestCases())
1869
class TestTestIdList(tests.TestCase):
1871
def _create_id_list(self, test_list):
1872
return tests.TestIdList(test_list)
1874
def _create_suite(self, test_id_list):
1876
class Stub(TestCase):
1880
def _create_test_id(id):
1883
suite = TestUtil.TestSuite()
1884
for id in test_id_list:
1885
t = Stub('test_foo')
1886
t.id = _create_test_id(id)
1890
def _test_ids(self, test_suite):
1891
"""Get the ids for the tests in a test suite."""
1892
return [t.id() for t in iter_suite_tests(test_suite)]
1894
def test_empty_list(self):
1895
id_list = self._create_id_list([])
1896
self.assertEquals({}, id_list.tests)
1897
self.assertEquals({}, id_list.modules)
1899
def test_valid_list(self):
1900
id_list = self._create_id_list(
1901
['mod1.cl1.meth1', 'mod1.cl1.meth2',
1902
'mod1.func1', 'mod1.cl2.meth2',
1904
'mod1.submod2.cl1.meth1', 'mod1.submod2.cl2.meth2',
1906
self.assertTrue(id_list.is_module_name_used('mod1'))
1907
self.assertTrue(id_list.is_module_name_used('mod1.submod1'))
1908
self.assertTrue(id_list.is_module_name_used('mod1.submod2'))
1909
self.assertTrue(id_list.test_in('mod1.cl1.meth1'))
1910
self.assertTrue(id_list.test_in('mod1.submod1'))
1911
self.assertTrue(id_list.test_in('mod1.func1'))
1913
def test_bad_chars_in_params(self):
1914
id_list = self._create_id_list(['mod1.cl1.meth1(xx.yy)'])
1915
self.assertTrue(id_list.is_module_name_used('mod1'))
1916
self.assertTrue(id_list.test_in('mod1.cl1.meth1(xx.yy)'))
1918
def test_module_used(self):
1919
id_list = self._create_id_list(['mod.class.meth'])
1920
self.assertTrue(id_list.is_module_name_used('mod'))
1921
self.assertTrue(id_list.is_module_name_used('mod.class'))
1922
self.assertTrue(id_list.is_module_name_used('mod.class.meth'))
1924
def test_test_suite(self):
1925
# This test is slow, so we do a single test with one test in each
1929
'bzrlib.tests.test_selftest.TestTestIdList.test_test_suite',
1930
# transport implementations
1931
'bzrlib.tests.test_transport_implementations.TransportTests'
1932
'.test_abspath(LocalURLServer)',
1933
# packages_to_test()
1934
'bzrlib.tests.blackbox.test_branch.TestBranch.test_branch',
1935
# MODULES_TO_DOCTEST
1936
'bzrlib.timestamp.format_highres_date',
1937
# plugins can't be tested that way since selftest may be run with
1940
suite = tests.test_suite(test_list)
1941
self.assertEquals(test_list, self._test_ids(suite))
1944
class TestLoadTestIdList(tests.TestCaseInTempDir):
1946
def _create_test_list_file(self, file_name, content):
1947
fl = open(file_name, 'wt')
1951
def test_load_unknown(self):
1952
self.assertRaises(errors.NoSuchFile,
1953
tests.load_test_id_list, 'i_do_not_exist')
1955
def test_load_test_list(self):
1956
test_list_fname = 'test.list'
1957
self._create_test_list_file(test_list_fname,
1958
'mod1.cl1.meth1\nmod2.cl2.meth2\n')
1959
tlist = tests.load_test_id_list(test_list_fname)
1960
self.assertEquals(2, len(tlist))
1961
self.assertEquals('mod1.cl1.meth1', tlist[0])
1962
self.assertEquals('mod2.cl2.meth2', tlist[1])
1964
def test_load_dirty_file(self):
1965
test_list_fname = 'test.list'
1966
self._create_test_list_file(test_list_fname,
1967
' mod1.cl1.meth1\n\nmod2.cl2.meth2 \n'
1969
tlist = tests.load_test_id_list(test_list_fname)
1970
self.assertEquals(4, len(tlist))
1971
self.assertEquals('mod1.cl1.meth1', tlist[0])
1972
self.assertEquals('', tlist[1])
1973
self.assertEquals('mod2.cl2.meth2', tlist[2])
1974
self.assertEquals('bar baz', tlist[3])