84
84
'a test message\n')
87
class TestUnicodeFilename(tests.TestCase):
89
def test_probe_passes(self):
90
"""UnicodeFilename._probe passes."""
91
# We can't test much more than that because the behaviour depends
93
tests.UnicodeFilename._probe()
96
class TestTreeShape(tests.TestCaseInTempDir):
87
class TestTreeShape(TestCaseInTempDir):
98
89
def test_unicode_paths(self):
99
self.requireFeature(tests.UnicodeFilename)
101
90
filename = u'hell\u00d8'
102
self.build_tree_contents([(filename, 'contents of hello')])
92
self.build_tree_contents([(filename, 'contents of hello')])
93
except UnicodeEncodeError:
94
raise TestSkipped("can't build unicode working tree in "
95
"filesystem encoding %s" % sys.getfilesystemencoding())
103
96
self.failUnlessExists(filename)
106
class TestTransportScenarios(tests.TestCase):
99
class TestTransportProviderAdapter(TestCase):
107
100
"""A group of tests that test the transport implementation adaption core.
109
This is a meta test that the tests are applied to all available
102
This is a meta test that the tests are applied to all available
112
This will be generalised in the future which is why it is in this
105
This will be generalised in the future which is why it is in this
113
106
test file even though it is specific to transport tests at the moment.
116
109
def test_get_transport_permutations(self):
117
# this checks that get_test_permutations defined by the module is
118
# called by the get_transport_test_permutations function.
110
# this checks that we the module get_test_permutations call
111
# is made by the adapter get_transport_test_permitations method.
119
112
class MockModule(object):
120
113
def get_test_permutations(self):
121
114
return sample_permutation
122
115
sample_permutation = [(1,2), (3,4)]
123
from bzrlib.tests.per_transport import get_transport_test_permutations
116
from bzrlib.tests.test_transport_implementations \
117
import TransportTestProviderAdapter
118
adapter = TransportTestProviderAdapter()
124
119
self.assertEqual(sample_permutation,
125
get_transport_test_permutations(MockModule()))
120
adapter.get_transport_test_permutations(MockModule()))
127
def test_scenarios_invlude_all_modules(self):
128
# this checks that the scenario generator returns as many permutations
129
# as there are in all the registered transport modules - we assume if
130
# this matches its probably doing the right thing especially in
131
# combination with the tests for setting the right classes below.
132
from bzrlib.tests.per_transport import transport_test_permutations
122
def test_adapter_checks_all_modules(self):
123
# this checks that the adapter returns as many permurtations as
124
# there are in all the registered# transport modules for there
125
# - we assume if this matches its probably doing the right thing
126
# especially in combination with the tests for setting the right
128
from bzrlib.tests.test_transport_implementations \
129
import TransportTestProviderAdapter
133
130
from bzrlib.transport import _get_transport_modules
134
131
modules = _get_transport_modules()
135
132
permutation_count = 0
136
133
for module in modules:
138
permutation_count += len(reduce(getattr,
135
permutation_count += len(reduce(getattr,
139
136
(module + ".get_test_permutations").split('.')[1:],
140
137
__import__(module))())
141
138
except errors.DependencyNotPresent:
143
scenarios = transport_test_permutations()
144
self.assertEqual(permutation_count, len(scenarios))
140
input_test = TestTransportProviderAdapter(
141
"test_adapter_sets_transport_class")
142
adapter = TransportTestProviderAdapter()
143
self.assertEqual(permutation_count,
144
len(list(iter(adapter.adapt(input_test)))))
146
def test_scenarios_include_transport_class(self):
146
def test_adapter_sets_transport_class(self):
147
# Check that the test adapter inserts a transport and server into the
147
150
# This test used to know about all the possible transports and the
148
151
# order they were returned but that seems overly brittle (mbp
150
from bzrlib.tests.per_transport import transport_test_permutations
151
scenarios = transport_test_permutations()
153
from bzrlib.tests.test_transport_implementations \
154
import TransportTestProviderAdapter
155
scenarios = TransportTestProviderAdapter().scenarios
152
156
# there are at least that many builtin transports
153
157
self.assertTrue(len(scenarios) > 6)
154
158
one_scenario = scenarios[0]
206
213
'transport_readonly_server': 'b',
207
214
'transport_server': 'a',
208
215
'vfs_transport_factory': 'v'})],
212
class TestRepositoryScenarios(tests.TestCase):
219
class TestRepositoryProviderAdapter(TestCase):
220
"""A group of tests that test the repository implementation test adapter."""
222
def test_constructor(self):
223
# check that constructor parameters are passed through to the
225
from bzrlib.tests.repository_implementations import RepositoryTestProviderAdapter
228
formats = [("c", "C"), ("d", "D")]
229
adapter = RepositoryTestProviderAdapter(server1, server2, formats)
232
{'bzrdir_format': 'C',
233
'repository_format': 'c',
234
'transport_readonly_server': 'b',
235
'transport_server': 'a'}),
237
{'bzrdir_format': 'D',
238
'repository_format': 'd',
239
'transport_readonly_server': 'b',
240
'transport_server': 'a'})],
243
def test_setting_vfs_transport(self):
244
"""The vfs_transport_factory can be set optionally."""
245
from bzrlib.tests.repository_implementations import RepositoryTestProviderAdapter
246
formats = [("a", "b"), ("c", "d")]
247
adapter = RepositoryTestProviderAdapter(None, None, formats,
248
vfs_transport_factory="vfs")
251
{'bzrdir_format': 'b',
252
'repository_format': 'a',
253
'transport_readonly_server': None,
254
'transport_server': None,
255
'vfs_transport_factory': 'vfs'}),
257
{'bzrdir_format': 'd',
258
'repository_format': 'c',
259
'transport_readonly_server': None,
260
'transport_server': None,
261
'vfs_transport_factory': 'vfs'})],
214
264
def test_formats_to_scenarios(self):
215
from bzrlib.tests.per_repository import formats_to_scenarios
216
formats = [("(c)", remote.RemoteRepositoryFormat()),
217
("(d)", repository.format_registry.get(
218
'Bazaar pack repository format 1 (needs bzr 0.92)\n'))]
219
no_vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
221
vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
222
vfs_transport_factory="vfs")
223
# no_vfs generate scenarios without vfs_transport_factory
265
"""The adapter can generate all the scenarios needed."""
266
from bzrlib.tests.repository_implementations import RepositoryTestProviderAdapter
267
no_vfs_adapter = RepositoryTestProviderAdapter("server", "readonly",
269
vfs_adapter = RepositoryTestProviderAdapter("server", "readonly",
270
[], vfs_transport_factory="vfs")
271
# no_vfs generate scenarios without vfs_transport_factor
272
formats = [("c", "C"), (1, "D")]
224
273
self.assertEqual([
225
('RemoteRepositoryFormat(c)',
226
{'bzrdir_format': remote.RemoteBzrDirFormat(),
227
'repository_format': remote.RemoteRepositoryFormat(),
275
{'bzrdir_format': 'C',
276
'repository_format': 'c',
228
277
'transport_readonly_server': 'readonly',
229
278
'transport_server': 'server'}),
230
('RepositoryFormatKnitPack1(d)',
231
{'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
232
'repository_format': pack_repo.RepositoryFormatKnitPack1(),
280
{'bzrdir_format': 'D',
281
'repository_format': 1,
233
282
'transport_readonly_server': 'readonly',
234
283
'transport_server': 'server'})],
284
no_vfs_adapter.formats_to_scenarios(formats))
236
285
self.assertEqual([
237
('RemoteRepositoryFormat(c)',
238
{'bzrdir_format': remote.RemoteBzrDirFormat(),
239
'repository_format': remote.RemoteRepositoryFormat(),
287
{'bzrdir_format': 'C',
288
'repository_format': 'c',
240
289
'transport_readonly_server': 'readonly',
241
290
'transport_server': 'server',
242
291
'vfs_transport_factory': 'vfs'}),
243
('RepositoryFormatKnitPack1(d)',
244
{'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
245
'repository_format': pack_repo.RepositoryFormatKnitPack1(),
293
{'bzrdir_format': 'D',
294
'repository_format': 1,
246
295
'transport_readonly_server': 'readonly',
247
296
'transport_server': 'server',
248
297
'vfs_transport_factory': 'vfs'})],
252
class TestTestScenarioApplication(tests.TestCase):
298
vfs_adapter.formats_to_scenarios(formats))
301
class TestTestScenarioApplier(TestCase):
253
302
"""Tests for the test adaption facilities."""
255
def test_apply_scenario(self):
256
from bzrlib.tests import apply_scenario
257
input_test = TestTestScenarioApplication("test_apply_scenario")
304
def test_adapt_applies_scenarios(self):
305
from bzrlib.tests.repository_implementations import TestScenarioApplier
306
input_test = TestTestScenarioApplier("test_adapt_test_to_scenario")
307
adapter = TestScenarioApplier()
308
adapter.scenarios = [("1", "dict"), ("2", "settings")]
310
def capture_call(test, scenario):
311
calls.append((test, scenario))
313
adapter.adapt_test_to_scenario = capture_call
314
adapter.adapt(input_test)
315
self.assertEqual([(input_test, ("1", "dict")),
316
(input_test, ("2", "settings"))], calls)
318
def test_adapt_test_to_scenario(self):
319
from bzrlib.tests.repository_implementations import TestScenarioApplier
320
input_test = TestTestScenarioApplier("test_adapt_test_to_scenario")
321
adapter = TestScenarioApplier()
258
322
# setup two adapted tests
259
adapted_test1 = apply_scenario(input_test,
323
adapted_test1 = adapter.adapt_test_to_scenario(input_test,
261
325
{"bzrdir_format":"bzr_format",
262
326
"repository_format":"repo_fmt",
263
327
"transport_server":"transport_server",
264
328
"transport_readonly_server":"readonly-server"}))
265
adapted_test2 = apply_scenario(input_test,
329
adapted_test2 = adapter.adapt_test_to_scenario(input_test,
266
330
("new id 2", {"bzrdir_format":None}))
267
331
# input_test should have been altered.
268
332
self.assertRaises(AttributeError, getattr, input_test, "bzrdir_format")
269
# the new tests are mutually incompatible, ensuring it has
333
# the new tests are mutually incompatible, ensuring it has
270
334
# made new ones, and unspecified elements in the scenario
271
335
# should not have been altered.
272
336
self.assertEqual("bzr_format", adapted_test1.bzrdir_format)
275
339
self.assertEqual("readonly-server",
276
340
adapted_test1.transport_readonly_server)
277
341
self.assertEqual(
278
"bzrlib.tests.test_selftest.TestTestScenarioApplication."
279
"test_apply_scenario(new id)",
342
"bzrlib.tests.test_selftest.TestTestScenarioApplier."
343
"test_adapt_test_to_scenario(new id)",
280
344
adapted_test1.id())
281
345
self.assertEqual(None, adapted_test2.bzrdir_format)
282
346
self.assertEqual(
283
"bzrlib.tests.test_selftest.TestTestScenarioApplication."
284
"test_apply_scenario(new id 2)",
347
"bzrlib.tests.test_selftest.TestTestScenarioApplier."
348
"test_adapt_test_to_scenario(new id 2)",
285
349
adapted_test2.id())
288
class TestInterRepositoryScenarios(tests.TestCase):
352
class TestInterRepositoryProviderAdapter(TestCase):
353
"""A group of tests that test the InterRepository test adapter."""
290
def test_scenarios(self):
355
def test_adapted_tests(self):
291
356
# check that constructor parameters are passed through to the adapted
293
from bzrlib.tests.per_interrepository import make_scenarios
358
from bzrlib.tests.interrepository_implementations import \
359
InterRepositoryTestProviderAdapter
296
362
formats = [(str, "C1", "C2"), (int, "D1", "D2")]
297
scenarios = make_scenarios(server1, server2, formats)
363
adapter = InterRepositoryTestProviderAdapter(server1, server2, formats)
298
364
self.assertEqual([
300
366
{'interrepo_class': str,
301
367
'repository_format': 'C1',
302
368
'repository_format_to': 'C2',
303
369
'transport_readonly_server': 'b',
304
370
'transport_server': 'a'}),
306
372
{'interrepo_class': int,
307
373
'repository_format': 'D1',
308
374
'repository_format_to': 'D2',
309
375
'transport_readonly_server': 'b',
310
376
'transport_server': 'a'})],
314
class TestWorkingTreeScenarios(tests.TestCase):
316
def test_scenarios(self):
317
# check that constructor parameters are passed through to the adapted
319
from bzrlib.tests.per_workingtree import make_scenarios
322
formats = [workingtree.WorkingTreeFormat2(),
323
workingtree.WorkingTreeFormat3(),]
324
scenarios = make_scenarios(server1, server2, formats)
326
('WorkingTreeFormat2',
327
{'bzrdir_format': formats[0]._matchingbzrdir,
328
'transport_readonly_server': 'b',
329
'transport_server': 'a',
330
'workingtree_format': formats[0]}),
331
('WorkingTreeFormat3',
332
{'bzrdir_format': formats[1]._matchingbzrdir,
333
'transport_readonly_server': 'b',
334
'transport_server': 'a',
335
'workingtree_format': formats[1]})],
339
class TestTreeScenarios(tests.TestCase):
341
def test_scenarios(self):
342
# the tree implementation scenario generator is meant to setup one
343
# instance for each working tree format, and one additional instance
344
# that will use the default wt format, but create a revision tree for
345
# the tests. this means that the wt ones should have the
346
# workingtree_to_test_tree attribute set to 'return_parameter' and the
347
# revision one set to revision_tree_from_workingtree.
349
from bzrlib.tests.per_tree import (
350
_dirstate_tree_from_workingtree,
377
adapter.formats_to_scenarios(formats))
380
class TestInterVersionedFileProviderAdapter(TestCase):
381
"""A group of tests that test the InterVersionedFile test adapter."""
383
def test_scenarios(self):
384
# check that constructor parameters are passed through to the adapted
386
from bzrlib.tests.interversionedfile_implementations \
387
import InterVersionedFileTestProviderAdapter
390
formats = [(str, "C1", "C2"), (int, "D1", "D2")]
391
adapter = InterVersionedFileTestProviderAdapter(server1, server2, formats)
394
{'interversionedfile_class':str,
395
'transport_readonly_server': 'b',
396
'transport_server': 'a',
397
'versionedfile_factory': 'C1',
398
'versionedfile_factory_to': 'C2'}),
400
{'interversionedfile_class': int,
401
'transport_readonly_server': 'b',
402
'transport_server': 'a',
403
'versionedfile_factory': 'D1',
404
'versionedfile_factory_to': 'D2'})],
408
class TestRevisionStoreProviderAdapter(TestCase):
409
"""A group of tests that test the RevisionStore test adapter."""
411
def test_scenarios(self):
412
# check that constructor parameters are passed through to the adapted
414
from bzrlib.tests.revisionstore_implementations \
415
import RevisionStoreTestProviderAdapter
416
# revision stores need a store factory - i.e. RevisionKnit
417
#, a readonly and rw transport
421
store_factories = ["c", "d"]
422
adapter = RevisionStoreTestProviderAdapter(server1, server2, store_factories)
425
{'store_factory': 'c',
426
'transport_readonly_server': 'b',
427
'transport_server': 'a'}),
429
{'store_factory': 'd',
430
'transport_readonly_server': 'b',
431
'transport_server': 'a'})],
435
class TestWorkingTreeProviderAdapter(TestCase):
436
"""A group of tests that test the workingtree implementation test adapter."""
438
def test_scenarios(self):
439
# check that constructor parameters are passed through to the adapted
441
from bzrlib.tests.workingtree_implementations \
442
import WorkingTreeTestProviderAdapter
445
formats = [("c", "C"), ("d", "D")]
446
adapter = WorkingTreeTestProviderAdapter(server1, server2, formats)
449
{'bzrdir_format': 'C',
450
'transport_readonly_server': 'b',
451
'transport_server': 'a',
452
'workingtree_format': 'c'}),
454
{'bzrdir_format': 'D',
455
'transport_readonly_server': 'b',
456
'transport_server': 'a',
457
'workingtree_format': 'd'})],
461
class TestTreeProviderAdapter(TestCase):
462
"""Test the setup of tree_implementation tests."""
464
def test_adapted_tests(self):
465
# the tree implementation adapter is meant to setup one instance for
466
# each working tree format, and one additional instance that will
467
# use the default wt format, but create a revision tree for the tests.
468
# this means that the wt ones should have the workingtree_to_test_tree
469
# attribute set to 'return_parameter' and the revision one set to
470
# revision_tree_from_workingtree.
472
from bzrlib.tests.tree_implementations import (
473
TreeTestProviderAdapter,
354
474
return_parameter,
355
475
revision_tree_from_workingtree
477
from bzrlib.workingtree import WorkingTreeFormat, WorkingTreeFormat3
478
input_test = TestTreeProviderAdapter(
479
"test_adapted_tests")
359
formats = [workingtree.WorkingTreeFormat2(),
360
workingtree.WorkingTreeFormat3(),]
361
scenarios = make_scenarios(server1, server2, formats)
362
self.assertEqual(7, len(scenarios))
363
default_wt_format = workingtree.WorkingTreeFormat4._default_format
364
wt4_format = workingtree.WorkingTreeFormat4()
365
wt5_format = workingtree.WorkingTreeFormat5()
366
expected_scenarios = [
367
('WorkingTreeFormat2',
368
{'bzrdir_format': formats[0]._matchingbzrdir,
369
'transport_readonly_server': 'b',
370
'transport_server': 'a',
371
'workingtree_format': formats[0],
372
'_workingtree_to_test_tree': return_parameter,
374
('WorkingTreeFormat3',
375
{'bzrdir_format': formats[1]._matchingbzrdir,
376
'transport_readonly_server': 'b',
377
'transport_server': 'a',
378
'workingtree_format': formats[1],
379
'_workingtree_to_test_tree': return_parameter,
382
{'_workingtree_to_test_tree': revision_tree_from_workingtree,
383
'bzrdir_format': default_wt_format._matchingbzrdir,
384
'transport_readonly_server': 'b',
385
'transport_server': 'a',
386
'workingtree_format': default_wt_format,
388
('DirStateRevisionTree,WT4',
389
{'_workingtree_to_test_tree': _dirstate_tree_from_workingtree,
390
'bzrdir_format': wt4_format._matchingbzrdir,
391
'transport_readonly_server': 'b',
392
'transport_server': 'a',
393
'workingtree_format': wt4_format,
395
('DirStateRevisionTree,WT5',
396
{'_workingtree_to_test_tree': _dirstate_tree_from_workingtree,
397
'bzrdir_format': wt5_format._matchingbzrdir,
398
'transport_readonly_server': 'b',
399
'transport_server': 'a',
400
'workingtree_format': wt5_format,
403
{'_workingtree_to_test_tree': preview_tree_pre,
404
'bzrdir_format': default_wt_format._matchingbzrdir,
405
'transport_readonly_server': 'b',
406
'transport_server': 'a',
407
'workingtree_format': default_wt_format}),
409
{'_workingtree_to_test_tree': preview_tree_post,
410
'bzrdir_format': default_wt_format._matchingbzrdir,
411
'transport_readonly_server': 'b',
412
'transport_server': 'a',
413
'workingtree_format': default_wt_format}),
415
self.assertEqual(expected_scenarios, scenarios)
418
class TestInterTreeScenarios(tests.TestCase):
482
formats = [("c", "C"), ("d", "D")]
483
adapter = TreeTestProviderAdapter(server1, server2, formats)
484
suite = adapter.adapt(input_test)
485
tests = list(iter(suite))
486
self.assertEqual(4, len(tests))
487
# this must match the default format setp up in
488
# TreeTestProviderAdapter.adapt
489
default_format = WorkingTreeFormat3
490
self.assertEqual(tests[0].workingtree_format, formats[0][0])
491
self.assertEqual(tests[0].bzrdir_format, formats[0][1])
492
self.assertEqual(tests[0].transport_server, server1)
493
self.assertEqual(tests[0].transport_readonly_server, server2)
494
self.assertEqual(tests[0].workingtree_to_test_tree, return_parameter)
495
self.assertEqual(tests[1].workingtree_format, formats[1][0])
496
self.assertEqual(tests[1].bzrdir_format, formats[1][1])
497
self.assertEqual(tests[1].transport_server, server1)
498
self.assertEqual(tests[1].transport_readonly_server, server2)
499
self.assertEqual(tests[1].workingtree_to_test_tree, return_parameter)
500
self.assertIsInstance(tests[2].workingtree_format, default_format)
501
#self.assertEqual(tests[2].bzrdir_format,
502
# default_format._matchingbzrdir)
503
self.assertEqual(tests[2].transport_server, server1)
504
self.assertEqual(tests[2].transport_readonly_server, server2)
505
self.assertEqual(tests[2].workingtree_to_test_tree,
506
revision_tree_from_workingtree)
509
class TestInterTreeProviderAdapter(TestCase):
419
510
"""A group of tests that test the InterTreeTestAdapter."""
421
def test_scenarios(self):
512
def test_adapted_tests(self):
422
513
# check that constructor parameters are passed through to the adapted
424
515
# for InterTree tests we want the machinery to bring up two trees in
426
517
# because each optimiser can be direction specific, we need to test
427
518
# each optimiser in its chosen direction.
428
519
# unlike the TestProviderAdapter we dont want to automatically add a
429
# parameterized one for WorkingTree - the optimisers will tell us what
520
# parameterised one for WorkingTree - the optimisers will tell us what
431
from bzrlib.tests.per_tree import (
522
from bzrlib.tests.tree_implementations import (
432
523
return_parameter,
433
524
revision_tree_from_workingtree
435
from bzrlib.tests.per_intertree import (
526
from bzrlib.tests.intertree_implementations import (
527
InterTreeTestProviderAdapter,
438
529
from bzrlib.workingtree import WorkingTreeFormat2, WorkingTreeFormat3
439
input_test = TestInterTreeScenarios(
530
input_test = TestInterTreeProviderAdapter(
531
"test_adapted_tests")
443
534
format1 = WorkingTreeFormat2()
444
535
format2 = WorkingTreeFormat3()
445
formats = [("1", str, format1, format2, "converter1"),
446
("2", int, format2, format1, "converter2")]
447
scenarios = make_scenarios(server1, server2, formats)
448
self.assertEqual(2, len(scenarios))
449
expected_scenarios = [
451
"bzrdir_format": format1._matchingbzrdir,
452
"intertree_class": formats[0][1],
453
"workingtree_format": formats[0][2],
454
"workingtree_format_to": formats[0][3],
455
"mutable_trees_to_test_trees": formats[0][4],
456
"_workingtree_to_test_tree": return_parameter,
457
"transport_server": server1,
458
"transport_readonly_server": server2,
461
"bzrdir_format": format2._matchingbzrdir,
462
"intertree_class": formats[1][1],
463
"workingtree_format": formats[1][2],
464
"workingtree_format_to": formats[1][3],
465
"mutable_trees_to_test_trees": formats[1][4],
466
"_workingtree_to_test_tree": return_parameter,
467
"transport_server": server1,
468
"transport_readonly_server": server2,
471
self.assertEqual(scenarios, expected_scenarios)
474
class TestTestCaseInTempDir(tests.TestCaseInTempDir):
536
formats = [(str, format1, format2, "converter1"),
537
(int, format2, format1, "converter2")]
538
adapter = InterTreeTestProviderAdapter(server1, server2, formats)
539
suite = adapter.adapt(input_test)
540
tests = list(iter(suite))
541
self.assertEqual(2, len(tests))
542
self.assertEqual(tests[0].intertree_class, formats[0][0])
543
self.assertEqual(tests[0].workingtree_format, formats[0][1])
544
self.assertEqual(tests[0].workingtree_format_to, formats[0][2])
545
self.assertEqual(tests[0].mutable_trees_to_test_trees, formats[0][3])
546
self.assertEqual(tests[0].workingtree_to_test_tree, return_parameter)
547
self.assertEqual(tests[0].transport_server, server1)
548
self.assertEqual(tests[0].transport_readonly_server, server2)
549
self.assertEqual(tests[1].intertree_class, formats[1][0])
550
self.assertEqual(tests[1].workingtree_format, formats[1][1])
551
self.assertEqual(tests[1].workingtree_format_to, formats[1][2])
552
self.assertEqual(tests[1].mutable_trees_to_test_trees, formats[1][3])
553
self.assertEqual(tests[1].workingtree_to_test_tree, return_parameter)
554
self.assertEqual(tests[1].transport_server, server1)
555
self.assertEqual(tests[1].transport_readonly_server, server2)
558
class TestTestCaseInTempDir(TestCaseInTempDir):
476
560
def test_home_is_not_working(self):
477
561
self.assertNotEqual(self.test_dir, self.test_home_dir)
478
562
cwd = osutils.getcwd()
479
self.assertIsSameRealPath(self.test_dir, cwd)
480
self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
482
def test_assertEqualStat_equal(self):
483
from bzrlib.tests.test_dirstate import _FakeStat
484
self.build_tree(["foo"])
485
real = os.lstat("foo")
486
fake = _FakeStat(real.st_size, real.st_mtime, real.st_ctime,
487
real.st_dev, real.st_ino, real.st_mode)
488
self.assertEqualStat(real, fake)
490
def test_assertEqualStat_notequal(self):
491
self.build_tree(["foo", "bar"])
492
self.assertRaises(AssertionError, self.assertEqualStat,
493
os.lstat("foo"), os.lstat("bar"))
496
class TestTestCaseWithMemoryTransport(tests.TestCaseWithMemoryTransport):
563
self.assertEqual(self.test_dir, cwd)
564
self.assertEqual(self.test_home_dir, os.environ['HOME'])
567
class TestTestCaseWithMemoryTransport(TestCaseWithMemoryTransport):
498
569
def test_home_is_non_existant_dir_under_root(self):
499
570
"""The test_home_dir for TestCaseWithMemoryTransport is missing.
501
572
This is because TestCaseWithMemoryTransport is for tests that do not
502
need any disk resources: they should be hooked into bzrlib in such a
503
way that no global settings are being changed by the test (only a
573
need any disk resources: they should be hooked into bzrlib in such a
574
way that no global settings are being changed by the test (only a
504
575
few tests should need to do that), and having a missing dir as home is
505
576
an effective way to ensure that this is the case.
507
self.assertIsSameRealPath(
508
self.TEST_ROOT + "/MemoryTransportMissingHomeDir",
578
self.assertEqual(self.TEST_ROOT + "/MemoryTransportMissingHomeDir",
509
579
self.test_home_dir)
510
self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
580
self.assertEqual(self.test_home_dir, os.environ['HOME'])
512
582
def test_cwd_is_TEST_ROOT(self):
513
self.assertIsSameRealPath(self.test_dir, self.TEST_ROOT)
583
self.assertEqual(self.test_dir, self.TEST_ROOT)
514
584
cwd = osutils.getcwd()
515
self.assertIsSameRealPath(self.test_dir, cwd)
585
self.assertEqual(self.test_dir, cwd)
517
587
def test_make_branch_and_memory_tree(self):
518
588
"""In TestCaseWithMemoryTransport we should not make the branch on disk.
538
608
self.assertEqual(format.repository_format.__class__,
539
609
tree.branch.repository._format.__class__)
541
def test_make_branch_builder(self):
542
builder = self.make_branch_builder('dir')
543
self.assertIsInstance(builder, branchbuilder.BranchBuilder)
544
# Guard against regression into MemoryTransport leaking
545
# files to disk instead of keeping them in memory.
546
self.failIf(osutils.lexists('dir'))
548
def test_make_branch_builder_with_format(self):
549
# Use a repo layout that doesn't conform to a 'named' layout, to ensure
550
# that the format objects are used.
551
format = bzrdir.BzrDirMetaFormat1()
552
repo_format = weaverepo.RepositoryFormat7()
553
format.repository_format = repo_format
554
builder = self.make_branch_builder('dir', format=format)
555
the_branch = builder.get_branch()
556
# Guard against regression into MemoryTransport leaking
557
# files to disk instead of keeping them in memory.
558
self.failIf(osutils.lexists('dir'))
559
self.assertEqual(format.repository_format.__class__,
560
the_branch.repository._format.__class__)
561
self.assertEqual(repo_format.get_format_string(),
562
self.get_transport().get_bytes(
563
'dir/.bzr/repository/format'))
565
def test_make_branch_builder_with_format_name(self):
566
builder = self.make_branch_builder('dir', format='knit')
567
the_branch = builder.get_branch()
568
# Guard against regression into MemoryTransport leaking
569
# files to disk instead of keeping them in memory.
570
self.failIf(osutils.lexists('dir'))
571
dir_format = bzrdir.format_registry.make_bzrdir('knit')
572
self.assertEqual(dir_format.repository_format.__class__,
573
the_branch.repository._format.__class__)
574
self.assertEqual('Bazaar-NG Knit Repository Format 1',
575
self.get_transport().get_bytes(
576
'dir/.bzr/repository/format'))
578
def test_safety_net(self):
579
"""No test should modify the safety .bzr directory.
581
We just test that the _check_safety_net private method raises
582
AssertionError, it's easier than building a test suite with the same
585
# Oops, a commit in the current directory (i.e. without local .bzr
586
# directory) will crawl up the hierarchy to find a .bzr directory.
587
self.run_bzr(['commit', '-mfoo', '--unchanged'])
588
# But we have a safety net in place.
589
self.assertRaises(AssertionError, self._check_safety_net)
591
def test_dangling_locks_cause_failures(self):
592
class TestDanglingLock(tests.TestCaseWithMemoryTransport):
593
def test_function(self):
594
t = self.get_transport('.')
595
l = lockdir.LockDir(t, 'lock')
598
test = TestDanglingLock('test_function')
600
self.assertEqual(1, len(result.errors))
603
class TestTestCaseWithTransport(tests.TestCaseWithTransport):
612
class TestTestCaseWithTransport(TestCaseWithTransport):
604
613
"""Tests for the convenience functions TestCaseWithTransport introduces."""
606
615
def test_get_readonly_url_none(self):
681
678
self.assertEqual(url, t.clone('..').base)
684
class TestTestResult(tests.TestCase):
686
def check_timing(self, test_case, expected_re):
681
class MockProgress(_BaseProgressBar):
682
"""Progress-bar standin that records calls.
684
Useful for testing pb using code.
688
_BaseProgressBar.__init__(self)
692
self.calls.append(('tick',))
694
def update(self, msg=None, current=None, total=None):
695
self.calls.append(('update', msg, current, total))
698
self.calls.append(('clear',))
700
def note(self, msg, *args):
701
self.calls.append(('note', msg, args))
704
class TestTestResult(TestCase):
706
def test_elapsed_time_with_benchmarking(self):
687
707
result = bzrlib.tests.TextTestResult(self._log_file,
691
test_case.run(result)
692
timed_string = result._testTimeString(test_case)
693
self.assertContainsRe(timed_string, expected_re)
695
def test_test_reporting(self):
696
class ShortDelayTestCase(tests.TestCase):
697
def test_short_delay(self):
699
def test_short_benchmark(self):
700
self.time(time.sleep, 0.003)
701
self.check_timing(ShortDelayTestCase('test_short_delay'),
703
# if a benchmark time is given, we now show just that time followed by
705
self.check_timing(ShortDelayTestCase('test_short_benchmark'),
708
def test_unittest_reporting_unittest_class(self):
709
# getting the time from a non-bzrlib test works ok
710
class ShortDelayTestCase(unittest.TestCase):
711
def test_short_delay(self):
713
self.check_timing(ShortDelayTestCase('test_short_delay'),
711
result._recordTestStartTime()
713
result.extractBenchmarkTime(self)
714
timed_string = result._testTimeString()
715
# without explicit benchmarking, we should get a simple time.
716
self.assertContainsRe(timed_string, "^ +[0-9]+ms$")
717
# if a benchmark time is given, we want a x of y style result.
718
self.time(time.sleep, 0.001)
719
result.extractBenchmarkTime(self)
720
timed_string = result._testTimeString()
721
self.assertContainsRe(
722
timed_string, "^ +[0-9]+ms/ +[0-9]+ms$")
723
# extracting the time from a non-bzrlib testcase sets to None
724
result._recordTestStartTime()
725
result.extractBenchmarkTime(
726
unittest.FunctionTestCase(self.test_elapsed_time_with_benchmarking))
727
timed_string = result._testTimeString()
728
self.assertContainsRe(timed_string, "^ +[0-9]+ms$")
729
# cheat. Yes, wash thy mouth out with soap.
730
self._benchtime = None
716
732
def test_assigned_benchmark_file_stores_date(self):
717
733
output = StringIO()
1028
1059
# run a test that is skipped, and check the suite as a whole still
1030
1061
# skipping_test must be hidden in here so it's not run as a real test
1031
class SkippingTest(tests.TestCase):
1032
def skipping_test(self):
1033
raise tests.TestSkipped('test intentionally skipped')
1034
runner = tests.TextTestRunner(stream=self._log_file)
1035
test = SkippingTest("skipping_test")
1062
def skipping_test():
1063
raise TestSkipped('test intentionally skipped')
1065
runner = TextTestRunner(stream=self._log_file)
1066
test = unittest.FunctionTestCase(skipping_test)
1036
1067
result = self.run_test_runner(runner, test)
1037
1068
self.assertTrue(result.wasSuccessful())
1039
1070
def test_skipped_from_setup(self):
1041
class SkippedSetupTest(tests.TestCase):
1071
class SkippedSetupTest(TestCase):
1043
1073
def setUp(self):
1044
calls.append('setUp')
1045
1075
self.addCleanup(self.cleanup)
1046
raise tests.TestSkipped('skipped setup')
1076
raise TestSkipped('skipped setup')
1048
1078
def test_skip(self):
1049
1079
self.fail('test reached')
1051
1081
def cleanup(self):
1052
calls.append('cleanup')
1054
runner = tests.TextTestRunner(stream=self._log_file)
1084
runner = TextTestRunner(stream=self._log_file)
1055
1085
test = SkippedSetupTest('test_skip')
1056
1086
result = self.run_test_runner(runner, test)
1057
1087
self.assertTrue(result.wasSuccessful())
1058
1088
# Check if cleanup was called the right number of times.
1059
self.assertEqual(['setUp', 'cleanup'], calls)
1089
self.assertEqual(0, test.counter)
1061
1091
def test_skipped_from_test(self):
1063
class SkippedTest(tests.TestCase):
1092
class SkippedTest(TestCase):
1065
1094
def setUp(self):
1066
tests.TestCase.setUp(self)
1067
calls.append('setUp')
1068
1096
self.addCleanup(self.cleanup)
1070
1098
def test_skip(self):
1071
raise tests.TestSkipped('skipped test')
1099
raise TestSkipped('skipped test')
1073
1101
def cleanup(self):
1074
calls.append('cleanup')
1076
runner = tests.TextTestRunner(stream=self._log_file)
1104
runner = TextTestRunner(stream=self._log_file)
1077
1105
test = SkippedTest('test_skip')
1078
1106
result = self.run_test_runner(runner, test)
1079
1107
self.assertTrue(result.wasSuccessful())
1080
1108
# Check if cleanup was called the right number of times.
1081
self.assertEqual(['setUp', 'cleanup'], calls)
1083
def test_not_applicable(self):
1084
# run a test that is skipped because it's not applicable
1085
def not_applicable_test():
1086
raise tests.TestNotApplicable('this test never runs')
1088
runner = tests.TextTestRunner(stream=out, verbosity=2)
1089
test = unittest.FunctionTestCase(not_applicable_test)
1090
result = self.run_test_runner(runner, test)
1091
self._log_file.write(out.getvalue())
1092
self.assertTrue(result.wasSuccessful())
1093
self.assertTrue(result.wasStrictlySuccessful())
1094
self.assertContainsRe(out.getvalue(),
1095
r'(?m)not_applicable_test * N/A')
1096
self.assertContainsRe(out.getvalue(),
1097
r'(?m)^ this test never runs')
1099
def test_not_applicable_demo(self):
1100
# just so you can see it in the test output
1101
raise tests.TestNotApplicable('this test is just a demonstation')
1109
self.assertEqual(0, test.counter)
1103
1111
def test_unsupported_features_listed(self):
1104
1112
"""When unsupported features are encountered they are detailed."""
1105
class Feature1(tests.Feature):
1113
class Feature1(Feature):
1106
1114
def _probe(self): return False
1107
class Feature2(tests.Feature):
1115
class Feature2(Feature):
1108
1116
def _probe(self): return False
1109
1117
# create sample tests
1110
1118
test1 = SampleTestCase('_test_pass')
1141
1148
revision_id = workingtree.get_parent_ids()[0]
1142
1149
self.assertEndsWith(output_string.rstrip(), revision_id)
1144
def assertLogDeleted(self, test):
1145
log = test._get_log()
1146
self.assertEqual("DELETED log file to reduce memory footprint", log)
1147
self.assertEqual('', test._log_contents)
1148
self.assertIs(None, test._log_file_name)
1150
1151
def test_success_log_deleted(self):
1151
1152
"""Successful tests have their log deleted"""
1153
class LogTester(tests.TestCase):
1154
class LogTester(TestCase):
1155
1156
def test_success(self):
1156
1157
self.log('this will be removed\n')
1159
runner = tests.TextTestRunner(stream=sio)
1159
sio = cStringIO.StringIO()
1160
runner = TextTestRunner(stream=sio)
1160
1161
test = LogTester('test_success')
1161
1162
result = self.run_test_runner(runner, test)
1163
self.assertLogDeleted(test)
1165
def test_skipped_log_deleted(self):
1166
"""Skipped tests have their log deleted"""
1168
class LogTester(tests.TestCase):
1170
def test_skipped(self):
1171
self.log('this will be removed\n')
1172
raise tests.TestSkipped()
1175
runner = tests.TextTestRunner(stream=sio)
1176
test = LogTester('test_skipped')
1177
result = self.run_test_runner(runner, test)
1179
self.assertLogDeleted(test)
1181
def test_not_aplicable_log_deleted(self):
1182
"""Not applicable tests have their log deleted"""
1184
class LogTester(tests.TestCase):
1186
def test_not_applicable(self):
1187
self.log('this will be removed\n')
1188
raise tests.TestNotApplicable()
1191
runner = tests.TextTestRunner(stream=sio)
1192
test = LogTester('test_not_applicable')
1193
result = self.run_test_runner(runner, test)
1195
self.assertLogDeleted(test)
1197
def test_known_failure_log_deleted(self):
1198
"""Know failure tests have their log deleted"""
1200
class LogTester(tests.TestCase):
1202
def test_known_failure(self):
1203
self.log('this will be removed\n')
1204
raise tests.KnownFailure()
1207
runner = tests.TextTestRunner(stream=sio)
1208
test = LogTester('test_known_failure')
1209
result = self.run_test_runner(runner, test)
1211
self.assertLogDeleted(test)
1164
log = test._get_log()
1165
self.assertEqual("DELETED log file to reduce memory footprint", log)
1166
self.assertEqual('', test._log_contents)
1167
self.assertIs(None, test._log_file_name)
1213
1169
def test_fail_log_kept(self):
1214
1170
"""Failed tests have their log kept"""
1216
class LogTester(tests.TestCase):
1172
class LogTester(TestCase):
1218
1174
def test_fail(self):
1219
1175
self.log('this will be kept\n')
1220
1176
self.fail('this test fails')
1223
runner = tests.TextTestRunner(stream=sio)
1178
sio = cStringIO.StringIO()
1179
runner = TextTestRunner(stream=sio)
1224
1180
test = LogTester('test_fail')
1225
1181
result = self.run_test_runner(runner, test)
1255
1211
self.assertEqual(log, test._log_contents)
1258
class SampleTestCase(tests.TestCase):
1214
class SampleTestCase(TestCase):
1260
1216
def _test_pass(self):
1263
class _TestException(Exception):
1266
class TestTestCase(tests.TestCase):
1220
class TestTestCase(TestCase):
1267
1221
"""Tests that test the core bzrlib TestCase."""
1269
def test_assertLength_matches_empty(self):
1271
self.assertLength(0, a_list)
1273
def test_assertLength_matches_nonempty(self):
1275
self.assertLength(3, a_list)
1277
def test_assertLength_fails_different(self):
1279
self.assertRaises(AssertionError, self.assertLength, 1, a_list)
1281
def test_assertLength_shows_sequence_in_failure(self):
1283
exception = self.assertRaises(AssertionError, self.assertLength, 2,
1285
self.assertEqual('Incorrect length: wanted 2, got 3 for [1, 2, 3]',
1288
def test_base_setUp_not_called_causes_failure(self):
1289
class TestCaseWithBrokenSetUp(tests.TestCase):
1291
pass # does not call TestCase.setUp
1294
test = TestCaseWithBrokenSetUp('test_foo')
1295
result = unittest.TestResult()
1297
self.assertFalse(result.wasSuccessful())
1298
self.assertEqual(1, result.testsRun)
1300
def test_base_tearDown_not_called_causes_failure(self):
1301
class TestCaseWithBrokenTearDown(tests.TestCase):
1303
pass # does not call TestCase.tearDown
1306
test = TestCaseWithBrokenTearDown('test_foo')
1307
result = unittest.TestResult()
1309
self.assertFalse(result.wasSuccessful())
1310
self.assertEqual(1, result.testsRun)
1312
1223
def test_debug_flags_sanitised(self):
1313
1224
"""The bzrlib debug flags should be sanitised by setUp."""
1314
if 'allow_debug' in tests.selftest_debug_flags:
1315
raise tests.TestNotApplicable(
1316
'-Eallow_debug option prevents debug flag sanitisation')
1317
1225
# we could set something and run a test that will check
1318
1226
# it gets santised, but this is probably sufficient for now:
1319
1227
# if someone runs the test with -Dsomething it will error.
1320
1228
self.assertEqual(set(), bzrlib.debug.debug_flags)
1322
def change_selftest_debug_flags(self, new_flags):
1323
orig_selftest_flags = tests.selftest_debug_flags
1324
self.addCleanup(self._restore_selftest_debug_flags, orig_selftest_flags)
1325
tests.selftest_debug_flags = set(new_flags)
1327
def _restore_selftest_debug_flags(self, flags):
1328
tests.selftest_debug_flags = flags
1330
def test_allow_debug_flag(self):
1331
"""The -Eallow_debug flag prevents bzrlib.debug.debug_flags from being
1332
sanitised (i.e. cleared) before running a test.
1334
self.change_selftest_debug_flags(set(['allow_debug']))
1335
bzrlib.debug.debug_flags = set(['a-flag'])
1336
class TestThatRecordsFlags(tests.TestCase):
1337
def test_foo(nested_self):
1338
self.flags = set(bzrlib.debug.debug_flags)
1339
test = TestThatRecordsFlags('test_foo')
1340
test.run(self.make_test_result())
1341
self.assertEqual(set(['a-flag']), self.flags)
1343
def test_debug_flags_restored(self):
1344
"""The bzrlib debug flags should be restored to their original state
1345
after the test was run, even if allow_debug is set.
1347
self.change_selftest_debug_flags(set(['allow_debug']))
1348
# Now run a test that modifies debug.debug_flags.
1349
bzrlib.debug.debug_flags = set(['original-state'])
1350
class TestThatModifiesFlags(tests.TestCase):
1352
bzrlib.debug.debug_flags = set(['modified'])
1353
test = TestThatModifiesFlags('test_foo')
1354
test.run(self.make_test_result())
1355
self.assertEqual(set(['original-state']), bzrlib.debug.debug_flags)
1357
def make_test_result(self):
1358
return tests.TextTestResult(self._log_file, descriptions=0, verbosity=1)
1360
1230
def inner_test(self):
1361
1231
# the inner child test
1362
1232
note("inner_test")
1616
1422
def test_applyDeprecated_not_deprecated(self):
1617
1423
sample_object = ApplyDeprecatedHelper()
1618
1424
# calling an undeprecated callable raises an assertion
1619
self.assertRaises(AssertionError, self.applyDeprecated,
1620
deprecated_in((0, 11, 0)),
1425
self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
1621
1426
sample_object.sample_normal_method)
1622
self.assertRaises(AssertionError, self.applyDeprecated,
1623
deprecated_in((0, 11, 0)),
1427
self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
1624
1428
sample_undeprecated_function, "a param value")
1625
1429
# calling a deprecated callable (function or method) with the wrong
1626
1430
# expected deprecation fails.
1627
self.assertRaises(AssertionError, self.applyDeprecated,
1628
deprecated_in((0, 10, 0)),
1431
self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
1629
1432
sample_object.sample_deprecated_method, "a param value")
1630
self.assertRaises(AssertionError, self.applyDeprecated,
1631
deprecated_in((0, 10, 0)),
1433
self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
1632
1434
sample_deprecated_function)
1633
1435
# calling a deprecated callable (function or method) with the right
1634
1436
# expected deprecation returns the functions result.
1635
self.assertEqual("a param value",
1636
self.applyDeprecated(deprecated_in((0, 11, 0)),
1437
self.assertEqual("a param value", self.applyDeprecated(zero_eleven,
1637
1438
sample_object.sample_deprecated_method, "a param value"))
1638
self.assertEqual(2, self.applyDeprecated(deprecated_in((0, 11, 0)),
1439
self.assertEqual(2, self.applyDeprecated(zero_eleven,
1639
1440
sample_deprecated_function))
1640
1441
# calling a nested deprecation with the wrong deprecation version
1641
# fails even if a deeper nested function was deprecated with the
1442
# fails even if a deeper nested function was deprecated with the
1642
1443
# supplied version.
1643
1444
self.assertRaises(AssertionError, self.applyDeprecated,
1644
deprecated_in((0, 11, 0)), sample_object.sample_nested_deprecation)
1445
zero_eleven, sample_object.sample_nested_deprecation)
1645
1446
# calling a nested deprecation with the right deprecation value
1646
1447
# returns the calls result.
1647
self.assertEqual(2, self.applyDeprecated(deprecated_in((0, 10, 0)),
1448
self.assertEqual(2, self.applyDeprecated(zero_ten,
1648
1449
sample_object.sample_nested_deprecation))
1650
1451
def test_callDeprecated(self):
1651
1452
def testfunc(be_deprecated, result=None):
1652
1453
if be_deprecated is True:
1653
symbol_versioning.warn('i am deprecated', DeprecationWarning,
1454
symbol_versioning.warn('i am deprecated', DeprecationWarning,
1656
1457
result = self.callDeprecated(['i am deprecated'], testfunc, True)
1776
1561
def test_default_str(self):
1777
1562
"""Feature.__str__ should default to __class__.__name__."""
1778
class NamedFeature(tests.Feature):
1563
class NamedFeature(Feature):
1780
1565
feature = NamedFeature()
1781
1566
self.assertEqual('NamedFeature', str(feature))
1784
class TestUnavailableFeature(tests.TestCase):
1569
class TestUnavailableFeature(TestCase):
1786
1571
def test_access_feature(self):
1787
feature = tests.Feature()
1788
exception = tests.UnavailableFeature(feature)
1573
exception = UnavailableFeature(feature)
1789
1574
self.assertIs(feature, exception.args[0])
1792
class TestSelftestFiltering(tests.TestCase):
1577
class TestSelftestFiltering(TestCase):
1794
1579
def setUp(self):
1795
tests.TestCase.setUp(self)
1796
1580
self.suite = TestUtil.TestSuite()
1797
1581
self.loader = TestUtil.TestLoader()
1798
1582
self.suite.addTest(self.loader.loadTestsFromModuleNames([
1799
1583
'bzrlib.tests.test_selftest']))
1800
self.all_names = _test_ids(self.suite)
1802
def test_condition_id_re(self):
1803
test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1804
'test_condition_id_re')
1805
filtered_suite = tests.filter_suite_by_condition(
1806
self.suite, tests.condition_id_re('test_condition_id_re'))
1807
self.assertEqual([test_name], _test_ids(filtered_suite))
1809
def test_condition_id_in_list(self):
1810
test_names = ['bzrlib.tests.test_selftest.TestSelftestFiltering.'
1811
'test_condition_id_in_list']
1812
id_list = tests.TestIdList(test_names)
1813
filtered_suite = tests.filter_suite_by_condition(
1814
self.suite, tests.condition_id_in_list(id_list))
1815
my_pattern = 'TestSelftestFiltering.*test_condition_id_in_list'
1816
re_filtered = tests.filter_suite_by_re(self.suite, my_pattern)
1817
self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
1819
def test_condition_id_startswith(self):
1820
klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
1821
start1 = klass + 'test_condition_id_starts'
1822
start2 = klass + 'test_condition_id_in'
1823
test_names = [ klass + 'test_condition_id_in_list',
1824
klass + 'test_condition_id_startswith',
1826
filtered_suite = tests.filter_suite_by_condition(
1827
self.suite, tests.condition_id_startswith([start1, start2]))
1828
self.assertEqual(test_names, _test_ids(filtered_suite))
1830
def test_condition_isinstance(self):
1831
filtered_suite = tests.filter_suite_by_condition(
1832
self.suite, tests.condition_isinstance(self.__class__))
1833
class_pattern = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
1834
re_filtered = tests.filter_suite_by_re(self.suite, class_pattern)
1835
self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
1837
def test_exclude_tests_by_condition(self):
1838
excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1839
'test_exclude_tests_by_condition')
1840
filtered_suite = tests.exclude_tests_by_condition(self.suite,
1841
lambda x:x.id() == excluded_name)
1842
self.assertEqual(len(self.all_names) - 1,
1843
filtered_suite.countTestCases())
1844
self.assertFalse(excluded_name in _test_ids(filtered_suite))
1845
remaining_names = list(self.all_names)
1846
remaining_names.remove(excluded_name)
1847
self.assertEqual(remaining_names, _test_ids(filtered_suite))
1849
def test_exclude_tests_by_re(self):
1850
self.all_names = _test_ids(self.suite)
1851
filtered_suite = tests.exclude_tests_by_re(self.suite,
1852
'exclude_tests_by_re')
1853
excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1854
'test_exclude_tests_by_re')
1855
self.assertEqual(len(self.all_names) - 1,
1856
filtered_suite.countTestCases())
1857
self.assertFalse(excluded_name in _test_ids(filtered_suite))
1858
remaining_names = list(self.all_names)
1859
remaining_names.remove(excluded_name)
1860
self.assertEqual(remaining_names, _test_ids(filtered_suite))
1862
def test_filter_suite_by_condition(self):
1863
test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1864
'test_filter_suite_by_condition')
1865
filtered_suite = tests.filter_suite_by_condition(self.suite,
1866
lambda x:x.id() == test_name)
1867
self.assertEqual([test_name], _test_ids(filtered_suite))
1584
self.all_names = [t.id() for t in iter_suite_tests(self.suite)]
1869
1586
def test_filter_suite_by_re(self):
1870
filtered_suite = tests.filter_suite_by_re(self.suite,
1871
'test_filter_suite_by_r')
1872
filtered_names = _test_ids(filtered_suite)
1587
filtered_suite = filter_suite_by_re(self.suite, 'test_filter')
1588
filtered_names = [t.id() for t in iter_suite_tests(filtered_suite)]
1873
1589
self.assertEqual(filtered_names, ['bzrlib.tests.test_selftest.'
1874
1590
'TestSelftestFiltering.test_filter_suite_by_re'])
1876
def test_filter_suite_by_id_list(self):
1877
test_list = ['bzrlib.tests.test_selftest.'
1878
'TestSelftestFiltering.test_filter_suite_by_id_list']
1879
filtered_suite = tests.filter_suite_by_id_list(
1880
self.suite, tests.TestIdList(test_list))
1881
filtered_names = _test_ids(filtered_suite)
1884
['bzrlib.tests.test_selftest.'
1885
'TestSelftestFiltering.test_filter_suite_by_id_list'])
1887
def test_filter_suite_by_id_startswith(self):
1888
# By design this test may fail if another test is added whose name also
1889
# begins with one of the start value used.
1890
klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
1891
start1 = klass + 'test_filter_suite_by_id_starts'
1892
start2 = klass + 'test_filter_suite_by_id_li'
1893
test_list = [klass + 'test_filter_suite_by_id_list',
1894
klass + 'test_filter_suite_by_id_startswith',
1896
filtered_suite = tests.filter_suite_by_id_startswith(
1897
self.suite, [start1, start2])
1900
_test_ids(filtered_suite),
1903
def test_preserve_input(self):
1904
# NB: Surely this is something in the stdlib to do this?
1905
self.assertTrue(self.suite is tests.preserve_input(self.suite))
1906
self.assertTrue("@#$" is tests.preserve_input("@#$"))
1908
def test_randomize_suite(self):
1909
randomized_suite = tests.randomize_suite(self.suite)
1910
# randomizing should not add or remove test names.
1911
self.assertEqual(set(_test_ids(self.suite)),
1912
set(_test_ids(randomized_suite)))
1913
# Technically, this *can* fail, because random.shuffle(list) can be
1914
# equal to list. Trying multiple times just pushes the frequency back.
1915
# As its len(self.all_names)!:1, the failure frequency should be low
1916
# enough to ignore. RBC 20071021.
1917
# It should change the order.
1918
self.assertNotEqual(self.all_names, _test_ids(randomized_suite))
1919
# But not the length. (Possibly redundant with the set test, but not
1921
self.assertEqual(len(self.all_names), len(_test_ids(randomized_suite)))
1923
def test_split_suit_by_condition(self):
1924
self.all_names = _test_ids(self.suite)
1925
condition = tests.condition_id_re('test_filter_suite_by_r')
1926
split_suite = tests.split_suite_by_condition(self.suite, condition)
1927
filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1928
'test_filter_suite_by_re')
1929
self.assertEqual([filtered_name], _test_ids(split_suite[0]))
1930
self.assertFalse(filtered_name in _test_ids(split_suite[1]))
1931
remaining_names = list(self.all_names)
1932
remaining_names.remove(filtered_name)
1933
self.assertEqual(remaining_names, _test_ids(split_suite[1]))
1935
def test_split_suit_by_re(self):
1936
self.all_names = _test_ids(self.suite)
1937
split_suite = tests.split_suite_by_re(self.suite,
1938
'test_filter_suite_by_r')
1939
filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1940
'test_filter_suite_by_re')
1941
self.assertEqual([filtered_name], _test_ids(split_suite[0]))
1942
self.assertFalse(filtered_name in _test_ids(split_suite[1]))
1943
remaining_names = list(self.all_names)
1944
remaining_names.remove(filtered_name)
1945
self.assertEqual(remaining_names, _test_ids(split_suite[1]))
1948
class TestCheckInventoryShape(tests.TestCaseWithTransport):
1592
def test_sort_suite_by_re(self):
1593
sorted_suite = sort_suite_by_re(self.suite, 'test_filter')
1594
sorted_names = [t.id() for t in iter_suite_tests(sorted_suite)]
1595
self.assertEqual(sorted_names[0], 'bzrlib.tests.test_selftest.'
1596
'TestSelftestFiltering.test_filter_suite_by_re')
1597
self.assertEquals(sorted(self.all_names), sorted(sorted_names))
1600
class TestCheckInventoryShape(TestCaseWithTransport):
1950
1602
def test_check_inventory_shape(self):
1951
1603
files = ['a', 'b/', 'b/c']
1957
1609
self.check_inventory_shape(tree.inventory, files)
1962
class TestBlackboxSupport(tests.TestCase):
1963
"""Tests for testsuite blackbox features."""
1965
def test_run_bzr_failure_not_caught(self):
1966
# When we run bzr in blackbox mode, we want any unexpected errors to
1967
# propagate up to the test suite so that it can show the error in the
1968
# usual way, and we won't get a double traceback.
1969
e = self.assertRaises(
1971
self.run_bzr, ['assert-fail'])
1972
# make sure we got the real thing, not an error from somewhere else in
1973
# the test framework
1974
self.assertEquals('always fails', str(e))
1975
# check that there's no traceback in the test log
1976
self.assertNotContainsRe(self._get_log(keep_log_file=True),
1979
def test_run_bzr_user_error_caught(self):
1980
# Running bzr in blackbox mode, normal/expected/user errors should be
1981
# caught in the regular way and turned into an error message plus exit
1983
out, err = self.run_bzr(["log", "/nonexistantpath"], retcode=3)
1984
self.assertEqual(out, '')
1985
self.assertContainsRe(err,
1986
'bzr: ERROR: Not a branch: ".*nonexistantpath/".\n')
1989
class TestTestLoader(tests.TestCase):
1990
"""Tests for the test loader."""
1992
def _get_loader_and_module(self):
1993
"""Gets a TestLoader and a module with one test in it."""
1994
loader = TestUtil.TestLoader()
1996
class Stub(tests.TestCase):
1999
class MyModule(object):
2001
MyModule.a_class = Stub
2003
return loader, module
2005
def test_module_no_load_tests_attribute_loads_classes(self):
2006
loader, module = self._get_loader_and_module()
2007
self.assertEqual(1, loader.loadTestsFromModule(module).countTestCases())
2009
def test_module_load_tests_attribute_gets_called(self):
2010
loader, module = self._get_loader_and_module()
2011
# 'self' is here because we're faking the module with a class. Regular
2012
# load_tests do not need that :)
2013
def load_tests(self, standard_tests, module, loader):
2014
result = loader.suiteClass()
2015
for test in tests.iter_suite_tests(standard_tests):
2016
result.addTests([test, test])
2018
# add a load_tests() method which multiplies the tests from the module.
2019
module.__class__.load_tests = load_tests
2020
self.assertEqual(2, loader.loadTestsFromModule(module).countTestCases())
2022
def test_load_tests_from_module_name_smoke_test(self):
2023
loader = TestUtil.TestLoader()
2024
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2025
self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
2028
def test_load_tests_from_module_name_with_bogus_module_name(self):
2029
loader = TestUtil.TestLoader()
2030
self.assertRaises(ImportError, loader.loadTestsFromModuleName, 'bogus')
2033
class TestTestIdList(tests.TestCase):
2035
def _create_id_list(self, test_list):
2036
return tests.TestIdList(test_list)
2038
def _create_suite(self, test_id_list):
2040
class Stub(tests.TestCase):
2044
def _create_test_id(id):
2047
suite = TestUtil.TestSuite()
2048
for id in test_id_list:
2049
t = Stub('test_foo')
2050
t.id = _create_test_id(id)
2054
def _test_ids(self, test_suite):
2055
"""Get the ids for the tests in a test suite."""
2056
return [t.id() for t in tests.iter_suite_tests(test_suite)]
2058
def test_empty_list(self):
2059
id_list = self._create_id_list([])
2060
self.assertEquals({}, id_list.tests)
2061
self.assertEquals({}, id_list.modules)
2063
def test_valid_list(self):
2064
id_list = self._create_id_list(
2065
['mod1.cl1.meth1', 'mod1.cl1.meth2',
2066
'mod1.func1', 'mod1.cl2.meth2',
2068
'mod1.submod2.cl1.meth1', 'mod1.submod2.cl2.meth2',
2070
self.assertTrue(id_list.refers_to('mod1'))
2071
self.assertTrue(id_list.refers_to('mod1.submod1'))
2072
self.assertTrue(id_list.refers_to('mod1.submod2'))
2073
self.assertTrue(id_list.includes('mod1.cl1.meth1'))
2074
self.assertTrue(id_list.includes('mod1.submod1'))
2075
self.assertTrue(id_list.includes('mod1.func1'))
2077
def test_bad_chars_in_params(self):
2078
id_list = self._create_id_list(['mod1.cl1.meth1(xx.yy)'])
2079
self.assertTrue(id_list.refers_to('mod1'))
2080
self.assertTrue(id_list.includes('mod1.cl1.meth1(xx.yy)'))
2082
def test_module_used(self):
2083
id_list = self._create_id_list(['mod.class.meth'])
2084
self.assertTrue(id_list.refers_to('mod'))
2085
self.assertTrue(id_list.refers_to('mod.class'))
2086
self.assertTrue(id_list.refers_to('mod.class.meth'))
2088
def test_test_suite_matches_id_list_with_unknown(self):
2089
loader = TestUtil.TestLoader()
2090
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2091
test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',
2093
not_found, duplicates = tests.suite_matches_id_list(suite, test_list)
2094
self.assertEquals(['bogus'], not_found)
2095
self.assertEquals([], duplicates)
2097
def test_suite_matches_id_list_with_duplicates(self):
2098
loader = TestUtil.TestLoader()
2099
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2100
dupes = loader.suiteClass()
2101
for test in tests.iter_suite_tests(suite):
2103
dupes.addTest(test) # Add it again
2105
test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',]
2106
not_found, duplicates = tests.suite_matches_id_list(
2108
self.assertEquals([], not_found)
2109
self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
2113
class TestTestSuite(tests.TestCase):
2115
def test_test_suite(self):
2116
# This test is slow, so we do a single test with one test in each
2120
'bzrlib.tests.blackbox.test_branch.TestBranch.test_branch',
2121
('bzrlib.tests.per_transport.TransportTests'
2122
'.test_abspath(LocalURLServer)'),
2123
'bzrlib.tests.test_selftest.TestTestSuite.test_test_suite',
2124
# modules_to_doctest
2125
'bzrlib.timestamp.format_highres_date',
2126
# plugins can't be tested that way since selftest may be run with
2129
suite = tests.test_suite(test_list)
2130
self.assertEquals(test_list, _test_ids(suite))
2132
def test_test_suite_list_and_start(self):
2133
test_list = ['bzrlib.tests.test_selftest.TestTestSuite.test_test_suite']
2134
suite = tests.test_suite(test_list,
2135
['bzrlib.tests.test_selftest.TestTestSuite'])
2136
# test_test_suite_list_and_start is not included
2137
self.assertEquals(test_list, _test_ids(suite))
2140
class TestLoadTestIdList(tests.TestCaseInTempDir):
2142
def _create_test_list_file(self, file_name, content):
2143
fl = open(file_name, 'wt')
2147
def test_load_unknown(self):
2148
self.assertRaises(errors.NoSuchFile,
2149
tests.load_test_id_list, 'i_do_not_exist')
2151
def test_load_test_list(self):
2152
test_list_fname = 'test.list'
2153
self._create_test_list_file(test_list_fname,
2154
'mod1.cl1.meth1\nmod2.cl2.meth2\n')
2155
tlist = tests.load_test_id_list(test_list_fname)
2156
self.assertEquals(2, len(tlist))
2157
self.assertEquals('mod1.cl1.meth1', tlist[0])
2158
self.assertEquals('mod2.cl2.meth2', tlist[1])
2160
def test_load_dirty_file(self):
2161
test_list_fname = 'test.list'
2162
self._create_test_list_file(test_list_fname,
2163
' mod1.cl1.meth1\n\nmod2.cl2.meth2 \n'
2165
tlist = tests.load_test_id_list(test_list_fname)
2166
self.assertEquals(4, len(tlist))
2167
self.assertEquals('mod1.cl1.meth1', tlist[0])
2168
self.assertEquals('', tlist[1])
2169
self.assertEquals('mod2.cl2.meth2', tlist[2])
2170
self.assertEquals('bar baz', tlist[3])
2173
class TestFilteredByModuleTestLoader(tests.TestCase):
2175
def _create_loader(self, test_list):
2176
id_filter = tests.TestIdList(test_list)
2177
loader = TestUtil.FilteredByModuleTestLoader(id_filter.refers_to)
2180
def test_load_tests(self):
2181
test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
2182
loader = self._create_loader(test_list)
2184
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2185
self.assertEquals(test_list, _test_ids(suite))
2187
def test_exclude_tests(self):
2188
test_list = ['bogus']
2189
loader = self._create_loader(test_list)
2191
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2192
self.assertEquals([], _test_ids(suite))
2195
class TestFilteredByNameStartTestLoader(tests.TestCase):
2197
def _create_loader(self, name_start):
2198
def needs_module(name):
2199
return name.startswith(name_start) or name_start.startswith(name)
2200
loader = TestUtil.FilteredByModuleTestLoader(needs_module)
2203
def test_load_tests(self):
2204
test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
2205
loader = self._create_loader('bzrlib.tests.test_samp')
2207
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2208
self.assertEquals(test_list, _test_ids(suite))
2210
def test_load_tests_inside_module(self):
2211
test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
2212
loader = self._create_loader('bzrlib.tests.test_sampler.Demo')
2214
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2215
self.assertEquals(test_list, _test_ids(suite))
2217
def test_exclude_tests(self):
2218
test_list = ['bogus']
2219
loader = self._create_loader('bogus')
2221
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2222
self.assertEquals([], _test_ids(suite))
2225
class TestTestPrefixRegistry(tests.TestCase):
2227
def _get_registry(self):
2228
tp_registry = tests.TestPrefixAliasRegistry()
2231
def test_register_new_prefix(self):
2232
tpr = self._get_registry()
2233
tpr.register('foo', 'fff.ooo.ooo')
2234
self.assertEquals('fff.ooo.ooo', tpr.get('foo'))
2236
def test_register_existing_prefix(self):
2237
tpr = self._get_registry()
2238
tpr.register('bar', 'bbb.aaa.rrr')
2239
tpr.register('bar', 'bBB.aAA.rRR')
2240
self.assertEquals('bbb.aaa.rrr', tpr.get('bar'))
2241
self.assertContainsRe(self._get_log(keep_log_file=True),
2242
r'.*bar.*bbb.aaa.rrr.*bBB.aAA.rRR')
2244
def test_get_unknown_prefix(self):
2245
tpr = self._get_registry()
2246
self.assertRaises(KeyError, tpr.get, 'I am not a prefix')
2248
def test_resolve_prefix(self):
2249
tpr = self._get_registry()
2250
tpr.register('bar', 'bb.aa.rr')
2251
self.assertEquals('bb.aa.rr', tpr.resolve_alias('bar'))
2253
def test_resolve_unknown_alias(self):
2254
tpr = self._get_registry()
2255
self.assertRaises(errors.BzrCommandError,
2256
tpr.resolve_alias, 'I am not a prefix')
2258
def test_predefined_prefixes(self):
2259
tpr = tests.test_prefix_alias_registry
2260
self.assertEquals('bzrlib', tpr.resolve_alias('bzrlib'))
2261
self.assertEquals('bzrlib.doc', tpr.resolve_alias('bd'))
2262
self.assertEquals('bzrlib.utils', tpr.resolve_alias('bu'))
2263
self.assertEquals('bzrlib.tests', tpr.resolve_alias('bt'))
2264
self.assertEquals('bzrlib.tests.blackbox', tpr.resolve_alias('bb'))
2265
self.assertEquals('bzrlib.plugins', tpr.resolve_alias('bp'))
2268
class TestRunSuite(tests.TestCase):
2270
def test_runner_class(self):
2271
"""run_suite accepts and uses a runner_class keyword argument."""
2272
class Stub(tests.TestCase):
2275
suite = Stub("test_foo")
2277
class MyRunner(tests.TextTestRunner):
2278
def run(self, test):
2280
return tests.ExtendedTestResult(self.stream, self.descriptions,
2282
tests.run_suite(suite, runner_class=MyRunner, stream=StringIO())
2283
self.assertLength(1, calls)
2285
def test_done(self):
2286
"""run_suite should call result.done()"""
2288
def one_more_call(): self.calls += 1
2289
def test_function():
2291
test = unittest.FunctionTestCase(test_function)
2292
class InstrumentedTestResult(tests.ExtendedTestResult):
2293
def done(self): one_more_call()
2294
class MyRunner(tests.TextTestRunner):
2295
def run(self, test):
2296
return InstrumentedTestResult(self.stream, self.descriptions,
2298
tests.run_suite(test, runner_class=MyRunner, stream=StringIO())
2299
self.assertEquals(1, self.calls)