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