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):
1124
class SkippedSetupTest(TestCase):
1127
calls.append('setUp')
1128
self.addCleanup(self.cleanup)
1129
raise TestSkipped('skipped setup')
1131
def test_skip(self):
1132
self.fail('test reached')
1135
calls.append('cleanup')
1137
runner = TextTestRunner(stream=self._log_file)
1138
test = SkippedSetupTest('test_skip')
1139
result = self.run_test_runner(runner, test)
1140
self.assertTrue(result.wasSuccessful())
1141
# Check if cleanup was called the right number of times.
1142
self.assertEqual(['setUp', 'cleanup'], calls)
1144
def test_skipped_from_test(self):
1146
class SkippedTest(TestCase):
1149
calls.append('setUp')
1150
self.addCleanup(self.cleanup)
1152
def test_skip(self):
1153
raise TestSkipped('skipped test')
1156
calls.append('cleanup')
1158
runner = TextTestRunner(stream=self._log_file)
1159
test = SkippedTest('test_skip')
1160
result = self.run_test_runner(runner, test)
1161
self.assertTrue(result.wasSuccessful())
1162
# Check if cleanup was called the right number of times.
1163
self.assertEqual(['setUp', 'cleanup'], calls)
1165
def test_not_applicable(self):
1166
# run a test that is skipped because it's not applicable
1167
def not_applicable_test():
1168
from bzrlib.tests import TestNotApplicable
1169
raise TestNotApplicable('this test never runs')
1171
runner = TextTestRunner(stream=out, verbosity=2)
1172
test = unittest.FunctionTestCase(not_applicable_test)
1173
result = self.run_test_runner(runner, test)
1174
self._log_file.write(out.getvalue())
1175
self.assertTrue(result.wasSuccessful())
1176
self.assertTrue(result.wasStrictlySuccessful())
1177
self.assertContainsRe(out.getvalue(),
1178
r'(?m)not_applicable_test * N/A')
1179
self.assertContainsRe(out.getvalue(),
1180
r'(?m)^ this test never runs')
1182
def test_not_applicable_demo(self):
1183
# just so you can see it in the test output
1184
raise TestNotApplicable('this test is just a demonstation')
1186
def test_unsupported_features_listed(self):
1187
"""When unsupported features are encountered they are detailed."""
1188
class Feature1(Feature):
1189
def _probe(self): return False
1190
class Feature2(Feature):
1191
def _probe(self): return False
1192
# create sample tests
1193
test1 = SampleTestCase('_test_pass')
1194
test1._test_needs_features = [Feature1()]
1195
test2 = SampleTestCase('_test_pass')
1196
test2._test_needs_features = [Feature2()]
1197
test = unittest.TestSuite()
1201
runner = TextTestRunner(stream=stream)
1202
result = self.run_test_runner(runner, test)
1203
lines = stream.getvalue().splitlines()
1206
"Missing feature 'Feature1' skipped 1 tests.",
1207
"Missing feature 'Feature2' skipped 1 tests.",
1211
def test_bench_history(self):
1212
# tests that the running the benchmark produces a history file
1213
# containing a timestamp and the revision id of the bzrlib source which
1215
workingtree = _get_bzr_source_tree()
1216
test = TestRunner('dummy_test')
1218
runner = TextTestRunner(stream=self._log_file, bench_history=output)
1219
result = self.run_test_runner(runner, test)
1220
output_string = output.getvalue()
1221
self.assertContainsRe(output_string, "--date [0-9.]+")
1222
if workingtree is not None:
1223
revision_id = workingtree.get_parent_ids()[0]
1224
self.assertEndsWith(output_string.rstrip(), revision_id)
1226
def assertLogDeleted(self, test):
1227
log = test._get_log()
1228
self.assertEqual("DELETED log file to reduce memory footprint", log)
1229
self.assertEqual('', test._log_contents)
1230
self.assertIs(None, test._log_file_name)
1232
def test_success_log_deleted(self):
1233
"""Successful tests have their log deleted"""
1235
class LogTester(TestCase):
1237
def test_success(self):
1238
self.log('this will be removed\n')
1240
sio = cStringIO.StringIO()
1241
runner = TextTestRunner(stream=sio)
1242
test = LogTester('test_success')
1243
result = self.run_test_runner(runner, test)
1245
self.assertLogDeleted(test)
1247
def test_skipped_log_deleted(self):
1248
"""Skipped tests have their log deleted"""
1250
class LogTester(TestCase):
1252
def test_skipped(self):
1253
self.log('this will be removed\n')
1254
raise tests.TestSkipped()
1256
sio = cStringIO.StringIO()
1257
runner = TextTestRunner(stream=sio)
1258
test = LogTester('test_skipped')
1259
result = self.run_test_runner(runner, test)
1261
self.assertLogDeleted(test)
1263
def test_not_aplicable_log_deleted(self):
1264
"""Not applicable tests have their log deleted"""
1266
class LogTester(TestCase):
1268
def test_not_applicable(self):
1269
self.log('this will be removed\n')
1270
raise tests.TestNotApplicable()
1272
sio = cStringIO.StringIO()
1273
runner = TextTestRunner(stream=sio)
1274
test = LogTester('test_not_applicable')
1275
result = self.run_test_runner(runner, test)
1277
self.assertLogDeleted(test)
1279
def test_known_failure_log_deleted(self):
1280
"""Know failure tests have their log deleted"""
1282
class LogTester(TestCase):
1284
def test_known_failure(self):
1285
self.log('this will be removed\n')
1286
raise tests.KnownFailure()
1288
sio = cStringIO.StringIO()
1289
runner = TextTestRunner(stream=sio)
1290
test = LogTester('test_known_failure')
1291
result = self.run_test_runner(runner, test)
1293
self.assertLogDeleted(test)
1295
def test_fail_log_kept(self):
1296
"""Failed tests have their log kept"""
1298
class LogTester(TestCase):
1300
def test_fail(self):
1301
self.log('this will be kept\n')
1302
self.fail('this test fails')
1304
sio = cStringIO.StringIO()
1305
runner = TextTestRunner(stream=sio)
1306
test = LogTester('test_fail')
1307
result = self.run_test_runner(runner, test)
1309
text = sio.getvalue()
1310
self.assertContainsRe(text, 'this will be kept')
1311
self.assertContainsRe(text, 'this test fails')
1313
log = test._get_log()
1314
self.assertContainsRe(log, 'this will be kept')
1315
self.assertEqual(log, test._log_contents)
1317
def test_error_log_kept(self):
1318
"""Tests with errors have their log kept"""
1320
class LogTester(TestCase):
1322
def test_error(self):
1323
self.log('this will be kept\n')
1324
raise ValueError('random exception raised')
1326
sio = cStringIO.StringIO()
1327
runner = TextTestRunner(stream=sio)
1328
test = LogTester('test_error')
1329
result = self.run_test_runner(runner, test)
1331
text = sio.getvalue()
1332
self.assertContainsRe(text, 'this will be kept')
1333
self.assertContainsRe(text, 'random exception raised')
1335
log = test._get_log()
1336
self.assertContainsRe(log, 'this will be kept')
1337
self.assertEqual(log, test._log_contents)
1340
class SampleTestCase(TestCase):
1342
def _test_pass(self):
1346
class TestTestCase(TestCase):
1347
"""Tests that test the core bzrlib TestCase."""
1349
def test_debug_flags_sanitised(self):
1350
"""The bzrlib debug flags should be sanitised by setUp."""
1351
# we could set something and run a test that will check
1352
# it gets santised, but this is probably sufficient for now:
1353
# if someone runs the test with -Dsomething it will error.
1354
self.assertEqual(set(), bzrlib.debug.debug_flags)
1356
def inner_test(self):
1357
# the inner child test
1360
def outer_child(self):
1361
# the outer child test
1363
self.inner_test = TestTestCase("inner_child")
1364
result = bzrlib.tests.TextTestResult(self._log_file,
1367
self.inner_test.run(result)
1368
note("outer finish")
1370
def test_trace_nesting(self):
1371
# this tests that each test case nests its trace facility correctly.
1372
# we do this by running a test case manually. That test case (A)
1373
# should setup a new log, log content to it, setup a child case (B),
1374
# which should log independently, then case (A) should log a trailer
1376
# we do two nested children so that we can verify the state of the
1377
# logs after the outer child finishes is correct, which a bad clean
1378
# up routine in tearDown might trigger a fault in our test with only
1379
# one child, we should instead see the bad result inside our test with
1381
# the outer child test
1382
original_trace = bzrlib.trace._trace_file
1383
outer_test = TestTestCase("outer_child")
1384
result = bzrlib.tests.TextTestResult(self._log_file,
1387
outer_test.run(result)
1388
self.assertEqual(original_trace, bzrlib.trace._trace_file)
1390
def method_that_times_a_bit_twice(self):
1391
# call self.time twice to ensure it aggregates
1392
self.time(time.sleep, 0.007)
1393
self.time(time.sleep, 0.007)
1395
def test_time_creates_benchmark_in_result(self):
1396
"""Test that the TestCase.time() method accumulates a benchmark time."""
1397
sample_test = TestTestCase("method_that_times_a_bit_twice")
1398
output_stream = StringIO()
1399
result = bzrlib.tests.VerboseTestResult(
1400
unittest._WritelnDecorator(output_stream),
1403
num_tests=sample_test.countTestCases())
1404
sample_test.run(result)
1405
self.assertContainsRe(
1406
output_stream.getvalue(),
1407
r"\d+ms/ +\d+ms\n$")
1409
def test_hooks_sanitised(self):
1410
"""The bzrlib hooks should be sanitised by setUp."""
1411
self.assertEqual(bzrlib.branch.BranchHooks(),
1412
bzrlib.branch.Branch.hooks)
1413
self.assertEqual(bzrlib.smart.server.SmartServerHooks(),
1414
bzrlib.smart.server.SmartTCPServer.hooks)
1416
def test__gather_lsprof_in_benchmarks(self):
1417
"""When _gather_lsprof_in_benchmarks is on, accumulate profile data.
1419
Each self.time() call is individually and separately profiled.
1421
self.requireFeature(test_lsprof.LSProfFeature)
1422
# overrides the class member with an instance member so no cleanup
1424
self._gather_lsprof_in_benchmarks = True
1425
self.time(time.sleep, 0.000)
1426
self.time(time.sleep, 0.003)
1427
self.assertEqual(2, len(self._benchcalls))
1428
self.assertEqual((time.sleep, (0.000,), {}), self._benchcalls[0][0])
1429
self.assertEqual((time.sleep, (0.003,), {}), self._benchcalls[1][0])
1430
self.assertIsInstance(self._benchcalls[0][1], bzrlib.lsprof.Stats)
1431
self.assertIsInstance(self._benchcalls[1][1], bzrlib.lsprof.Stats)
1433
def test_knownFailure(self):
1434
"""Self.knownFailure() should raise a KnownFailure exception."""
1435
self.assertRaises(KnownFailure, self.knownFailure, "A Failure")
1437
def test_requireFeature_available(self):
1438
"""self.requireFeature(available) is a no-op."""
1439
class Available(Feature):
1440
def _probe(self):return True
1441
feature = Available()
1442
self.requireFeature(feature)
1444
def test_requireFeature_unavailable(self):
1445
"""self.requireFeature(unavailable) raises UnavailableFeature."""
1446
class Unavailable(Feature):
1447
def _probe(self):return False
1448
feature = Unavailable()
1449
self.assertRaises(UnavailableFeature, self.requireFeature, feature)
1451
def test_run_no_parameters(self):
1452
test = SampleTestCase('_test_pass')
1455
def test_run_enabled_unittest_result(self):
1456
"""Test we revert to regular behaviour when the test is enabled."""
1457
test = SampleTestCase('_test_pass')
1458
class EnabledFeature(object):
1459
def available(self):
1461
test._test_needs_features = [EnabledFeature()]
1462
result = unittest.TestResult()
1464
self.assertEqual(1, result.testsRun)
1465
self.assertEqual([], result.errors)
1466
self.assertEqual([], result.failures)
1468
def test_run_disabled_unittest_result(self):
1469
"""Test our compatability for disabled tests with unittest results."""
1470
test = SampleTestCase('_test_pass')
1471
class DisabledFeature(object):
1472
def available(self):
1474
test._test_needs_features = [DisabledFeature()]
1475
result = unittest.TestResult()
1477
self.assertEqual(1, result.testsRun)
1478
self.assertEqual([], result.errors)
1479
self.assertEqual([], result.failures)
1481
def test_run_disabled_supporting_result(self):
1482
"""Test disabled tests behaviour with support aware results."""
1483
test = SampleTestCase('_test_pass')
1484
class DisabledFeature(object):
1485
def available(self):
1487
the_feature = DisabledFeature()
1488
test._test_needs_features = [the_feature]
1489
class InstrumentedTestResult(unittest.TestResult):
1491
unittest.TestResult.__init__(self)
1493
def startTest(self, test):
1494
self.calls.append(('startTest', test))
1495
def stopTest(self, test):
1496
self.calls.append(('stopTest', test))
1497
def addNotSupported(self, test, feature):
1498
self.calls.append(('addNotSupported', test, feature))
1499
result = InstrumentedTestResult()
1502
('startTest', test),
1503
('addNotSupported', test, the_feature),
1509
@symbol_versioning.deprecated_function(zero_eleven)
1510
def sample_deprecated_function():
1511
"""A deprecated function to test applyDeprecated with."""
1515
def sample_undeprecated_function(a_param):
1516
"""A undeprecated function to test applyDeprecated with."""
1519
class ApplyDeprecatedHelper(object):
1520
"""A helper class for ApplyDeprecated tests."""
1522
@symbol_versioning.deprecated_method(zero_eleven)
1523
def sample_deprecated_method(self, param_one):
1524
"""A deprecated method for testing with."""
1527
def sample_normal_method(self):
1528
"""A undeprecated method."""
1530
@symbol_versioning.deprecated_method(zero_ten)
1531
def sample_nested_deprecation(self):
1532
return sample_deprecated_function()
1535
class TestExtraAssertions(TestCase):
1536
"""Tests for new test assertions in bzrlib test suite"""
1538
def test_assert_isinstance(self):
1539
self.assertIsInstance(2, int)
1540
self.assertIsInstance(u'', basestring)
1541
self.assertRaises(AssertionError, self.assertIsInstance, None, int)
1542
self.assertRaises(AssertionError, self.assertIsInstance, 23.3, int)
1544
def test_assertEndsWith(self):
1545
self.assertEndsWith('foo', 'oo')
1546
self.assertRaises(AssertionError, self.assertEndsWith, 'o', 'oo')
1548
def test_applyDeprecated_not_deprecated(self):
1549
sample_object = ApplyDeprecatedHelper()
1550
# calling an undeprecated callable raises an assertion
1551
self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
1552
sample_object.sample_normal_method)
1553
self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
1554
sample_undeprecated_function, "a param value")
1555
# calling a deprecated callable (function or method) with the wrong
1556
# expected deprecation fails.
1557
self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
1558
sample_object.sample_deprecated_method, "a param value")
1559
self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
1560
sample_deprecated_function)
1561
# calling a deprecated callable (function or method) with the right
1562
# expected deprecation returns the functions result.
1563
self.assertEqual("a param value", self.applyDeprecated(zero_eleven,
1564
sample_object.sample_deprecated_method, "a param value"))
1565
self.assertEqual(2, self.applyDeprecated(zero_eleven,
1566
sample_deprecated_function))
1567
# calling a nested deprecation with the wrong deprecation version
1568
# fails even if a deeper nested function was deprecated with the
1570
self.assertRaises(AssertionError, self.applyDeprecated,
1571
zero_eleven, sample_object.sample_nested_deprecation)
1572
# calling a nested deprecation with the right deprecation value
1573
# returns the calls result.
1574
self.assertEqual(2, self.applyDeprecated(zero_ten,
1575
sample_object.sample_nested_deprecation))
1577
def test_callDeprecated(self):
1578
def testfunc(be_deprecated, result=None):
1579
if be_deprecated is True:
1580
symbol_versioning.warn('i am deprecated', DeprecationWarning,
1583
result = self.callDeprecated(['i am deprecated'], testfunc, True)
1584
self.assertIs(None, result)
1585
result = self.callDeprecated([], testfunc, False, 'result')
1586
self.assertEqual('result', result)
1587
self.callDeprecated(['i am deprecated'], testfunc, be_deprecated=True)
1588
self.callDeprecated([], testfunc, be_deprecated=False)
1591
class TestWarningTests(TestCase):
1592
"""Tests for calling methods that raise warnings."""
1594
def test_callCatchWarnings(self):
1596
warnings.warn("this is your last warning")
1598
wlist, result = self.callCatchWarnings(meth, 1, 2)
1599
self.assertEquals(3, result)
1600
# would like just to compare them, but UserWarning doesn't implement
1603
self.assertIsInstance(w0, UserWarning)
1604
self.assertEquals("this is your last warning", str(w0))
1607
class TestConvenienceMakers(TestCaseWithTransport):
1608
"""Test for the make_* convenience functions."""
1610
def test_make_branch_and_tree_with_format(self):
1611
# we should be able to supply a format to make_branch_and_tree
1612
self.make_branch_and_tree('a', format=bzrlib.bzrdir.BzrDirMetaFormat1())
1613
self.make_branch_and_tree('b', format=bzrlib.bzrdir.BzrDirFormat6())
1614
self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('a')._format,
1615
bzrlib.bzrdir.BzrDirMetaFormat1)
1616
self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('b')._format,
1617
bzrlib.bzrdir.BzrDirFormat6)
1619
def test_make_branch_and_memory_tree(self):
1620
# we should be able to get a new branch and a mutable tree from
1621
# TestCaseWithTransport
1622
tree = self.make_branch_and_memory_tree('a')
1623
self.assertIsInstance(tree, bzrlib.memorytree.MemoryTree)
1626
class TestSFTPMakeBranchAndTree(TestCaseWithSFTPServer):
1628
def test_make_tree_for_sftp_branch(self):
1629
"""Transports backed by local directories create local trees."""
1631
tree = self.make_branch_and_tree('t1')
1632
base = tree.bzrdir.root_transport.base
1633
self.failIf(base.startswith('sftp'),
1634
'base %r is on sftp but should be local' % base)
1635
self.assertEquals(tree.bzrdir.root_transport,
1636
tree.branch.bzrdir.root_transport)
1637
self.assertEquals(tree.bzrdir.root_transport,
1638
tree.branch.repository.bzrdir.root_transport)
1641
class TestSelftest(TestCase):
1642
"""Tests of bzrlib.tests.selftest."""
1644
def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
1647
factory_called.append(True)
1651
self.apply_redirected(out, err, None, bzrlib.tests.selftest,
1652
test_suite_factory=factory)
1653
self.assertEqual([True], factory_called)
1656
class TestKnownFailure(TestCase):
1658
def test_known_failure(self):
1659
"""Check that KnownFailure is defined appropriately."""
1660
# a KnownFailure is an assertion error for compatability with unaware
1662
self.assertIsInstance(KnownFailure(""), AssertionError)
1664
def test_expect_failure(self):
1666
self.expectFailure("Doomed to failure", self.assertTrue, False)
1667
except KnownFailure, e:
1668
self.assertEqual('Doomed to failure', e.args[0])
1670
self.expectFailure("Doomed to failure", self.assertTrue, True)
1671
except AssertionError, e:
1672
self.assertEqual('Unexpected success. Should have failed:'
1673
' Doomed to failure', e.args[0])
1675
self.fail('Assertion not raised')
1678
class TestFeature(TestCase):
1680
def test_caching(self):
1681
"""Feature._probe is called by the feature at most once."""
1682
class InstrumentedFeature(Feature):
1684
Feature.__init__(self)
1687
self.calls.append('_probe')
1689
feature = InstrumentedFeature()
1691
self.assertEqual(['_probe'], feature.calls)
1693
self.assertEqual(['_probe'], feature.calls)
1695
def test_named_str(self):
1696
"""Feature.__str__ should thunk to feature_name()."""
1697
class NamedFeature(Feature):
1698
def feature_name(self):
1700
feature = NamedFeature()
1701
self.assertEqual('symlinks', str(feature))
1703
def test_default_str(self):
1704
"""Feature.__str__ should default to __class__.__name__."""
1705
class NamedFeature(Feature):
1707
feature = NamedFeature()
1708
self.assertEqual('NamedFeature', str(feature))
1711
class TestUnavailableFeature(TestCase):
1713
def test_access_feature(self):
1715
exception = UnavailableFeature(feature)
1716
self.assertIs(feature, exception.args[0])
1719
class TestSelftestFiltering(TestCase):
1722
self.suite = TestUtil.TestSuite()
1723
self.loader = TestUtil.TestLoader()
1724
self.suite.addTest(self.loader.loadTestsFromModuleNames([
1725
'bzrlib.tests.test_selftest']))
1726
self.all_names = self._test_ids(self.suite)
1728
def _test_ids(self, test_suite):
1729
"""Get the ids for the tests in a test suite."""
1730
return [t.id() for t in iter_suite_tests(test_suite)]
1732
def test_condition_id_re(self):
1733
test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1734
'test_condition_id_re')
1735
filtered_suite = filter_suite_by_condition(self.suite,
1736
condition_id_re('test_condition_id_re'))
1737
self.assertEqual([test_name], self._test_ids(filtered_suite))
1739
def test_condition_id_in_list(self):
1740
test_names = ['bzrlib.tests.test_selftest.TestSelftestFiltering.'
1741
'test_condition_id_in_list']
1742
id_list = tests.TestIdList(test_names)
1743
filtered_suite = filter_suite_by_condition(
1744
self.suite, tests.condition_id_in_list(id_list))
1745
my_pattern = 'TestSelftestFiltering.*test_condition_id_in_list'
1746
re_filtered = filter_suite_by_re(self.suite, my_pattern)
1747
self.assertEqual(self._test_ids(re_filtered),
1748
self._test_ids(filtered_suite))
1750
def test_condition_isinstance(self):
1751
filtered_suite = filter_suite_by_condition(self.suite,
1752
condition_isinstance(self.__class__))
1753
class_pattern = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
1754
re_filtered = filter_suite_by_re(self.suite, class_pattern)
1755
self.assertEqual(self._test_ids(re_filtered),
1756
self._test_ids(filtered_suite))
1758
def test_exclude_tests_by_condition(self):
1759
excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1760
'test_exclude_tests_by_condition')
1761
filtered_suite = exclude_tests_by_condition(self.suite,
1762
lambda x:x.id() == excluded_name)
1763
self.assertEqual(len(self.all_names) - 1,
1764
filtered_suite.countTestCases())
1765
self.assertFalse(excluded_name in self._test_ids(filtered_suite))
1766
remaining_names = list(self.all_names)
1767
remaining_names.remove(excluded_name)
1768
self.assertEqual(remaining_names, self._test_ids(filtered_suite))
1770
def test_exclude_tests_by_re(self):
1771
self.all_names = self._test_ids(self.suite)
1772
filtered_suite = exclude_tests_by_re(self.suite, 'exclude_tests_by_re')
1773
excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1774
'test_exclude_tests_by_re')
1775
self.assertEqual(len(self.all_names) - 1,
1776
filtered_suite.countTestCases())
1777
self.assertFalse(excluded_name in self._test_ids(filtered_suite))
1778
remaining_names = list(self.all_names)
1779
remaining_names.remove(excluded_name)
1780
self.assertEqual(remaining_names, self._test_ids(filtered_suite))
1782
def test_filter_suite_by_condition(self):
1783
test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1784
'test_filter_suite_by_condition')
1785
filtered_suite = filter_suite_by_condition(self.suite,
1786
lambda x:x.id() == test_name)
1787
self.assertEqual([test_name], self._test_ids(filtered_suite))
1789
def test_filter_suite_by_re(self):
1790
filtered_suite = filter_suite_by_re(self.suite, 'test_filter_suite_by_r')
1791
filtered_names = self._test_ids(filtered_suite)
1792
self.assertEqual(filtered_names, ['bzrlib.tests.test_selftest.'
1793
'TestSelftestFiltering.test_filter_suite_by_re'])
1795
def test_filter_suite_by_id_list(self):
1796
test_list = ['bzrlib.tests.test_selftest.'
1797
'TestSelftestFiltering.test_filter_suite_by_id_list']
1798
filtered_suite = tests.filter_suite_by_id_list(
1799
self.suite, tests.TestIdList(test_list))
1800
filtered_names = self._test_ids(filtered_suite)
1803
['bzrlib.tests.test_selftest.'
1804
'TestSelftestFiltering.test_filter_suite_by_id_list'])
1806
def test_preserve_input(self):
1807
# NB: Surely this is something in the stdlib to do this?
1808
self.assertTrue(self.suite is preserve_input(self.suite))
1809
self.assertTrue("@#$" is preserve_input("@#$"))
1811
def test_randomize_suite(self):
1812
randomized_suite = randomize_suite(self.suite)
1813
# randomizing should not add or remove test names.
1814
self.assertEqual(set(self._test_ids(self.suite)),
1815
set(self._test_ids(randomized_suite)))
1816
# Technically, this *can* fail, because random.shuffle(list) can be
1817
# equal to list. Trying multiple times just pushes the frequency back.
1818
# As its len(self.all_names)!:1, the failure frequency should be low
1819
# enough to ignore. RBC 20071021.
1820
# It should change the order.
1821
self.assertNotEqual(self.all_names, self._test_ids(randomized_suite))
1822
# But not the length. (Possibly redundant with the set test, but not
1824
self.assertEqual(len(self.all_names),
1825
len(self._test_ids(randomized_suite)))
1827
def test_sort_suite_by_re(self):
1828
sorted_suite = self.applyDeprecated(one_zero,
1829
sort_suite_by_re, self.suite, 'test_filter_suite_by_r')
1830
sorted_names = self._test_ids(sorted_suite)
1831
self.assertEqual(sorted_names[0], 'bzrlib.tests.test_selftest.'
1832
'TestSelftestFiltering.test_filter_suite_by_re')
1833
self.assertEquals(sorted(self.all_names), sorted(sorted_names))
1835
def test_split_suit_by_re(self):
1836
self.all_names = self._test_ids(self.suite)
1837
split_suite = split_suite_by_re(self.suite, 'test_filter_suite_by_r')
1838
filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1839
'test_filter_suite_by_re')
1840
self.assertEqual([filtered_name], self._test_ids(split_suite[0]))
1841
self.assertFalse(filtered_name in self._test_ids(split_suite[1]))
1842
remaining_names = list(self.all_names)
1843
remaining_names.remove(filtered_name)
1844
self.assertEqual(remaining_names, self._test_ids(split_suite[1]))
1847
class TestCheckInventoryShape(TestCaseWithTransport):
1849
def test_check_inventory_shape(self):
1850
files = ['a', 'b/', 'b/c']
1851
tree = self.make_branch_and_tree('.')
1852
self.build_tree(files)
1856
self.check_inventory_shape(tree.inventory, files)
1861
class TestBlackboxSupport(TestCase):
1862
"""Tests for testsuite blackbox features."""
1864
def test_run_bzr_failure_not_caught(self):
1865
# When we run bzr in blackbox mode, we want any unexpected errors to
1866
# propagate up to the test suite so that it can show the error in the
1867
# usual way, and we won't get a double traceback.
1868
e = self.assertRaises(
1870
self.run_bzr, ['assert-fail'])
1871
# make sure we got the real thing, not an error from somewhere else in
1872
# the test framework
1873
self.assertEquals('always fails', str(e))
1874
# check that there's no traceback in the test log
1875
self.assertNotContainsRe(self._get_log(keep_log_file=True),
1878
def test_run_bzr_user_error_caught(self):
1879
# Running bzr in blackbox mode, normal/expected/user errors should be
1880
# caught in the regular way and turned into an error message plus exit
1882
out, err = self.run_bzr(["log", "/nonexistantpath"], retcode=3)
1883
self.assertEqual(out, '')
1884
self.assertContainsRe(err,
1885
'bzr: ERROR: Not a branch: ".*nonexistantpath/".\n')
1888
class TestTestLoader(TestCase):
1889
"""Tests for the test loader."""
1891
def _get_loader_and_module(self):
1892
"""Gets a TestLoader and a module with one test in it."""
1893
loader = TestUtil.TestLoader()
1895
class Stub(TestCase):
1898
class MyModule(object):
1900
MyModule.a_class = Stub
1902
return loader, module
1904
def test_module_no_load_tests_attribute_loads_classes(self):
1905
loader, module = self._get_loader_and_module()
1906
self.assertEqual(1, loader.loadTestsFromModule(module).countTestCases())
1908
def test_module_load_tests_attribute_gets_called(self):
1909
loader, module = self._get_loader_and_module()
1910
# 'self' is here because we're faking the module with a class. Regular
1911
# load_tests do not need that :)
1912
def load_tests(self, standard_tests, module, loader):
1913
result = loader.suiteClass()
1914
for test in iter_suite_tests(standard_tests):
1915
result.addTests([test, test])
1917
# add a load_tests() method which multiplies the tests from the module.
1918
module.__class__.load_tests = load_tests
1919
self.assertEqual(2, loader.loadTestsFromModule(module).countTestCases())
1922
class TestTestIdList(tests.TestCase):
1924
def _create_id_list(self, test_list):
1925
return tests.TestIdList(test_list)
1927
def _create_suite(self, test_id_list):
1929
class Stub(TestCase):
1933
def _create_test_id(id):
1936
suite = TestUtil.TestSuite()
1937
for id in test_id_list:
1938
t = Stub('test_foo')
1939
t.id = _create_test_id(id)
1943
def _test_ids(self, test_suite):
1944
"""Get the ids for the tests in a test suite."""
1945
return [t.id() for t in iter_suite_tests(test_suite)]
1947
def test_empty_list(self):
1948
id_list = self._create_id_list([])
1949
self.assertEquals({}, id_list.tests)
1950
self.assertEquals({}, id_list.modules)
1952
def test_valid_list(self):
1953
id_list = self._create_id_list(
1954
['mod1.cl1.meth1', 'mod1.cl1.meth2',
1955
'mod1.func1', 'mod1.cl2.meth2',
1957
'mod1.submod2.cl1.meth1', 'mod1.submod2.cl2.meth2',
1959
self.assertTrue(id_list.is_module_name_used('mod1'))
1960
self.assertTrue(id_list.is_module_name_used('mod1.submod1'))
1961
self.assertTrue(id_list.is_module_name_used('mod1.submod2'))
1962
self.assertTrue(id_list.test_in('mod1.cl1.meth1'))
1963
self.assertTrue(id_list.test_in('mod1.submod1'))
1964
self.assertTrue(id_list.test_in('mod1.func1'))
1966
def test_bad_chars_in_params(self):
1967
id_list = self._create_id_list(['mod1.cl1.meth1(xx.yy)'])
1968
self.assertTrue(id_list.is_module_name_used('mod1'))
1969
self.assertTrue(id_list.test_in('mod1.cl1.meth1(xx.yy)'))
1971
def test_module_used(self):
1972
id_list = self._create_id_list(['mod.class.meth'])
1973
self.assertTrue(id_list.is_module_name_used('mod'))
1974
self.assertTrue(id_list.is_module_name_used('mod.class'))
1975
self.assertTrue(id_list.is_module_name_used('mod.class.meth'))
1977
def test_test_suite(self):
1978
# This test is slow, so we do a single test with one test in each
1982
'bzrlib.tests.test_selftest.TestTestIdList.test_test_suite',
1983
# transport implementations
1984
'bzrlib.tests.test_transport_implementations.TransportTests'
1985
'.test_abspath(LocalURLServer)',
1986
# packages_to_test()
1987
'bzrlib.tests.blackbox.test_branch.TestBranch.test_branch',
1988
# MODULES_TO_DOCTEST
1989
'bzrlib.timestamp.format_highres_date',
1990
# plugins can't be tested that way since selftest may be run with
1993
suite = tests.test_suite(test_list)
1994
self.assertEquals(test_list, self._test_ids(suite))
1996
def test_test_suite_matches_id_list_with_unknown(self):
1997
loader = TestUtil.TestLoader()
1998
import bzrlib.tests.test_sampler
1999
suite = loader.loadTestsFromModule(bzrlib.tests.test_sampler)
2000
test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',
2002
not_found, duplicates = tests.suite_matches_id_list(suite, test_list)
2003
self.assertEquals(['bogus'], not_found)
2004
self.assertEquals([], duplicates)
2006
def test_suite_matches_id_list_with_duplicates(self):
2007
loader = TestUtil.TestLoader()
2008
import bzrlib.tests.test_sampler
2009
suite = loader.loadTestsFromModule(bzrlib.tests.test_sampler)
2010
dupes = loader.suiteClass()
2011
for test in iter_suite_tests(suite):
2013
dupes.addTest(test) # Add it again
2015
test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',]
2016
not_found, duplicates = tests.suite_matches_id_list(
2018
self.assertEquals([], not_found)
2019
self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
2023
class TestLoadTestIdList(tests.TestCaseInTempDir):
2025
def _create_test_list_file(self, file_name, content):
2026
fl = open(file_name, 'wt')
2030
def test_load_unknown(self):
2031
self.assertRaises(errors.NoSuchFile,
2032
tests.load_test_id_list, 'i_do_not_exist')
2034
def test_load_test_list(self):
2035
test_list_fname = 'test.list'
2036
self._create_test_list_file(test_list_fname,
2037
'mod1.cl1.meth1\nmod2.cl2.meth2\n')
2038
tlist = tests.load_test_id_list(test_list_fname)
2039
self.assertEquals(2, len(tlist))
2040
self.assertEquals('mod1.cl1.meth1', tlist[0])
2041
self.assertEquals('mod2.cl2.meth2', tlist[1])
2043
def test_load_dirty_file(self):
2044
test_list_fname = 'test.list'
2045
self._create_test_list_file(test_list_fname,
2046
' mod1.cl1.meth1\n\nmod2.cl2.meth2 \n'
2048
tlist = tests.load_test_id_list(test_list_fname)
2049
self.assertEquals(4, len(tlist))
2050
self.assertEquals('mod1.cl1.meth1', tlist[0])
2051
self.assertEquals('', tlist[1])
2052
self.assertEquals('mod2.cl2.meth2', tlist[2])
2053
self.assertEquals('bar baz', tlist[3])