13
13
# You should have received a copy of the GNU General Public License
14
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
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
17
"""Tests for the test framework."""
19
from cStringIO import StringIO
20
from doctest import ELLIPSIS
21
from StringIO import StringIO
28
from testtools import MultiTestResult
29
from testtools.content_type import ContentType
30
from testtools.matchers import (
34
import testtools.tests.helpers
28
37
from bzrlib import (
36
from bzrlib.progress import _BaseProgressBar
37
from bzrlib.repofmt import weaverepo
38
from bzrlib.symbol_versioning import zero_ten, zero_eleven
53
from bzrlib.repofmt import (
58
from bzrlib.symbol_versioning import (
39
63
from bzrlib.tests import (
46
TestCaseWithMemoryTransport,
47
TestCaseWithTransport,
53
clean_selftest_output,
60
from bzrlib.tests.test_sftp_transport import TestCaseWithSFTPServer
61
from bzrlib.tests.TestUtil import _load_module_by_name
62
70
from bzrlib.trace import note
63
from bzrlib.transport.memory import MemoryServer, MemoryTransport
71
from bzrlib.transport import memory
64
72
from bzrlib.version import _get_bzr_source_tree
67
class SelftestTests(TestCase):
75
def _test_ids(test_suite):
76
"""Get the ids for the tests in a test suite."""
77
return [t.id() for t in tests.iter_suite_tests(test_suite)]
80
class SelftestTests(tests.TestCase):
69
82
def test_import_tests(self):
70
mod = _load_module_by_name('bzrlib.tests.test_selftest')
83
mod = TestUtil._load_module_by_name('bzrlib.tests.test_selftest')
71
84
self.assertEqual(mod.SelftestTests, SelftestTests)
73
86
def test_import_test_failure(self):
74
87
self.assertRaises(ImportError,
88
TestUtil._load_module_by_name,
76
89
'bzrlib.no-name-yet')
78
class MetaTestLog(TestCase):
92
class MetaTestLog(tests.TestCase):
80
94
def test_logging(self):
81
95
"""Test logs are captured when a test fails."""
82
96
self.log('a test message')
83
self._log_file.flush()
84
self.assertContainsRe(self._get_log(keep_log_file=True),
88
class TestTreeShape(TestCaseInTempDir):
97
details = self.getDetails()
99
self.assertThat(log.content_type, Equals(ContentType(
100
"text", "plain", {"charset": "utf8"})))
101
self.assertThat(u"".join(log.iter_text()), Equals(self.get_log()))
102
self.assertThat(self.get_log(),
103
DocTestMatches(u"...a test message\n", ELLIPSIS))
106
class TestUnicodeFilename(tests.TestCase):
108
def test_probe_passes(self):
109
"""UnicodeFilename._probe passes."""
110
# We can't test much more than that because the behaviour depends
112
tests.UnicodeFilename._probe()
115
class TestTreeShape(tests.TestCaseInTempDir):
90
117
def test_unicode_paths(self):
118
self.requireFeature(tests.UnicodeFilename)
91
120
filename = u'hell\u00d8'
93
self.build_tree_contents([(filename, 'contents of hello')])
94
except UnicodeEncodeError:
95
raise TestSkipped("can't build unicode working tree in "
96
"filesystem encoding %s" % sys.getfilesystemencoding())
121
self.build_tree_contents([(filename, 'contents of hello')])
97
122
self.failUnlessExists(filename)
100
class TestTransportProviderAdapter(TestCase):
125
class TestTransportScenarios(tests.TestCase):
101
126
"""A group of tests that test the transport implementation adaption core.
103
This is a meta test that the tests are applied to all available
128
This is a meta test that the tests are applied to all available
106
This will be generalised in the future which is why it is in this
131
This will be generalised in the future which is why it is in this
107
132
test file even though it is specific to transport tests at the moment.
110
135
def test_get_transport_permutations(self):
111
# this checks that we the module get_test_permutations call
112
# is made by the adapter get_transport_test_permitations method.
136
# this checks that get_test_permutations defined by the module is
137
# called by the get_transport_test_permutations function.
113
138
class MockModule(object):
114
139
def get_test_permutations(self):
115
140
return sample_permutation
116
141
sample_permutation = [(1,2), (3,4)]
117
from bzrlib.tests.test_transport_implementations \
118
import TransportTestProviderAdapter
119
adapter = TransportTestProviderAdapter()
142
from bzrlib.tests.per_transport import get_transport_test_permutations
120
143
self.assertEqual(sample_permutation,
121
adapter.get_transport_test_permutations(MockModule()))
144
get_transport_test_permutations(MockModule()))
123
def test_adapter_checks_all_modules(self):
124
# this checks that the adapter returns as many permurtations as
125
# there are in all the registered# transport modules for there
126
# - we assume if this matches its probably doing the right thing
127
# especially in combination with the tests for setting the right
129
from bzrlib.tests.test_transport_implementations \
130
import TransportTestProviderAdapter
146
def test_scenarios_include_all_modules(self):
147
# this checks that the scenario generator returns as many permutations
148
# as there are in all the registered transport modules - we assume if
149
# this matches its probably doing the right thing especially in
150
# combination with the tests for setting the right classes below.
151
from bzrlib.tests.per_transport import transport_test_permutations
131
152
from bzrlib.transport import _get_transport_modules
132
153
modules = _get_transport_modules()
133
154
permutation_count = 0
134
155
for module in modules:
136
permutation_count += len(reduce(getattr,
157
permutation_count += len(reduce(getattr,
137
158
(module + ".get_test_permutations").split('.')[1:],
138
159
__import__(module))())
139
160
except errors.DependencyNotPresent:
141
input_test = TestTransportProviderAdapter(
142
"test_adapter_sets_transport_class")
143
adapter = TransportTestProviderAdapter()
144
self.assertEqual(permutation_count,
145
len(list(iter(adapter.adapt(input_test)))))
162
scenarios = transport_test_permutations()
163
self.assertEqual(permutation_count, len(scenarios))
147
def test_adapter_sets_transport_class(self):
148
# Check that the test adapter inserts a transport and server into the
165
def test_scenarios_include_transport_class(self):
151
166
# This test used to know about all the possible transports and the
152
167
# order they were returned but that seems overly brittle (mbp
154
from bzrlib.tests.test_transport_implementations \
155
import TransportTestProviderAdapter
156
scenarios = TransportTestProviderAdapter().scenarios
169
from bzrlib.tests.per_transport import transport_test_permutations
170
scenarios = transport_test_permutations()
157
171
# there are at least that many builtin transports
158
172
self.assertTrue(len(scenarios) > 6)
159
173
one_scenario = scenarios[0]
214
225
'transport_readonly_server': 'b',
215
226
'transport_server': 'a',
216
227
'vfs_transport_factory': 'v'})],
220
class TestRepositoryProviderAdapter(TestCase):
221
"""A group of tests that test the repository implementation test adapter."""
223
def test_constructor(self):
224
# check that constructor parameters are passed through to the
226
from bzrlib.tests.repository_implementations import RepositoryTestProviderAdapter
229
formats = [("c", "C"), ("d", "D")]
230
adapter = RepositoryTestProviderAdapter(server1, server2, formats)
233
{'bzrdir_format': 'C',
234
'repository_format': 'c',
235
'transport_readonly_server': 'b',
236
'transport_server': 'a'}),
238
{'bzrdir_format': 'D',
239
'repository_format': 'd',
240
'transport_readonly_server': 'b',
241
'transport_server': 'a'})],
244
def test_setting_vfs_transport(self):
245
"""The vfs_transport_factory can be set optionally."""
246
from bzrlib.tests.repository_implementations import RepositoryTestProviderAdapter
247
formats = [("a", "b"), ("c", "d")]
248
adapter = RepositoryTestProviderAdapter(None, None, formats,
231
class TestRepositoryScenarios(tests.TestCase):
233
def test_formats_to_scenarios(self):
234
from bzrlib.tests.per_repository import formats_to_scenarios
235
formats = [("(c)", remote.RemoteRepositoryFormat()),
236
("(d)", repository.format_registry.get(
237
'Bazaar repository format 2a (needs bzr 1.16 or later)\n'))]
238
no_vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
240
vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
249
241
vfs_transport_factory="vfs")
252
{'bzrdir_format': 'b',
253
'repository_format': 'a',
254
'transport_readonly_server': None,
255
'transport_server': None,
256
'vfs_transport_factory': 'vfs'}),
258
{'bzrdir_format': 'd',
259
'repository_format': 'c',
260
'transport_readonly_server': None,
261
'transport_server': None,
262
'vfs_transport_factory': 'vfs'})],
265
def test_formats_to_scenarios(self):
266
"""The adapter can generate all the scenarios needed."""
267
from bzrlib.tests.repository_implementations import RepositoryTestProviderAdapter
268
no_vfs_adapter = RepositoryTestProviderAdapter("server", "readonly",
270
vfs_adapter = RepositoryTestProviderAdapter("server", "readonly",
271
[], vfs_transport_factory="vfs")
272
# no_vfs generate scenarios without vfs_transport_factor
273
formats = [("c", "C"), (1, "D")]
276
{'bzrdir_format': 'C',
277
'repository_format': 'c',
242
# no_vfs generate scenarios without vfs_transport_factory
244
('RemoteRepositoryFormat(c)',
245
{'bzrdir_format': remote.RemoteBzrDirFormat(),
246
'repository_format': remote.RemoteRepositoryFormat(),
278
247
'transport_readonly_server': 'readonly',
279
248
'transport_server': 'server'}),
281
{'bzrdir_format': 'D',
282
'repository_format': 1,
249
('RepositoryFormat2a(d)',
250
{'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
251
'repository_format': groupcompress_repo.RepositoryFormat2a(),
283
252
'transport_readonly_server': 'readonly',
284
'transport_server': 'server'})],
285
no_vfs_adapter.formats_to_scenarios(formats))
253
'transport_server': 'server'})]
254
self.assertEqual(expected, no_vfs_scenarios)
286
255
self.assertEqual([
288
{'bzrdir_format': 'C',
289
'repository_format': 'c',
256
('RemoteRepositoryFormat(c)',
257
{'bzrdir_format': remote.RemoteBzrDirFormat(),
258
'repository_format': remote.RemoteRepositoryFormat(),
290
259
'transport_readonly_server': 'readonly',
291
260
'transport_server': 'server',
292
261
'vfs_transport_factory': 'vfs'}),
294
{'bzrdir_format': 'D',
295
'repository_format': 1,
262
('RepositoryFormat2a(d)',
263
{'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
264
'repository_format': groupcompress_repo.RepositoryFormat2a(),
296
265
'transport_readonly_server': 'readonly',
297
266
'transport_server': 'server',
298
267
'vfs_transport_factory': 'vfs'})],
299
vfs_adapter.formats_to_scenarios(formats))
302
class TestTestScenarioApplier(TestCase):
271
class TestTestScenarioApplication(tests.TestCase):
303
272
"""Tests for the test adaption facilities."""
305
def test_adapt_applies_scenarios(self):
306
from bzrlib.tests.repository_implementations import TestScenarioApplier
307
input_test = TestTestScenarioApplier("test_adapt_test_to_scenario")
308
adapter = TestScenarioApplier()
309
adapter.scenarios = [("1", "dict"), ("2", "settings")]
311
def capture_call(test, scenario):
312
calls.append((test, scenario))
314
adapter.adapt_test_to_scenario = capture_call
315
adapter.adapt(input_test)
316
self.assertEqual([(input_test, ("1", "dict")),
317
(input_test, ("2", "settings"))], calls)
319
def test_adapt_test_to_scenario(self):
320
from bzrlib.tests.repository_implementations import TestScenarioApplier
321
input_test = TestTestScenarioApplier("test_adapt_test_to_scenario")
322
adapter = TestScenarioApplier()
274
def test_apply_scenario(self):
275
from bzrlib.tests import apply_scenario
276
input_test = TestTestScenarioApplication("test_apply_scenario")
323
277
# setup two adapted tests
324
adapted_test1 = adapter.adapt_test_to_scenario(input_test,
278
adapted_test1 = apply_scenario(input_test,
326
280
{"bzrdir_format":"bzr_format",
327
281
"repository_format":"repo_fmt",
328
282
"transport_server":"transport_server",
329
283
"transport_readonly_server":"readonly-server"}))
330
adapted_test2 = adapter.adapt_test_to_scenario(input_test,
284
adapted_test2 = apply_scenario(input_test,
331
285
("new id 2", {"bzrdir_format":None}))
332
286
# input_test should have been altered.
333
287
self.assertRaises(AttributeError, getattr, input_test, "bzrdir_format")
334
# the new tests are mutually incompatible, ensuring it has
288
# the new tests are mutually incompatible, ensuring it has
335
289
# made new ones, and unspecified elements in the scenario
336
290
# should not have been altered.
337
291
self.assertEqual("bzr_format", adapted_test1.bzrdir_format)
340
294
self.assertEqual("readonly-server",
341
295
adapted_test1.transport_readonly_server)
342
296
self.assertEqual(
343
"bzrlib.tests.test_selftest.TestTestScenarioApplier."
344
"test_adapt_test_to_scenario(new id)",
297
"bzrlib.tests.test_selftest.TestTestScenarioApplication."
298
"test_apply_scenario(new id)",
345
299
adapted_test1.id())
346
300
self.assertEqual(None, adapted_test2.bzrdir_format)
347
301
self.assertEqual(
348
"bzrlib.tests.test_selftest.TestTestScenarioApplier."
349
"test_adapt_test_to_scenario(new id 2)",
302
"bzrlib.tests.test_selftest.TestTestScenarioApplication."
303
"test_apply_scenario(new id 2)",
350
304
adapted_test2.id())
353
class TestInterRepositoryProviderAdapter(TestCase):
354
"""A group of tests that test the InterRepository test adapter."""
307
class TestInterRepositoryScenarios(tests.TestCase):
356
def test_adapted_tests(self):
309
def test_scenarios(self):
357
310
# check that constructor parameters are passed through to the adapted
359
from bzrlib.tests.interrepository_implementations import \
360
InterRepositoryTestProviderAdapter
312
from bzrlib.tests.per_interrepository import make_scenarios
363
formats = [(str, "C1", "C2"), (int, "D1", "D2")]
364
adapter = InterRepositoryTestProviderAdapter(server1, server2, formats)
315
formats = [("C0", "C1", "C2"), ("D0", "D1", "D2")]
316
scenarios = make_scenarios(server1, server2, formats)
365
317
self.assertEqual([
367
{'interrepo_class': str,
368
'repository_format': 'C1',
319
{'repository_format': 'C1',
369
320
'repository_format_to': 'C2',
370
321
'transport_readonly_server': 'b',
371
322
'transport_server': 'a'}),
373
{'interrepo_class': int,
374
'repository_format': 'D1',
324
{'repository_format': 'D1',
375
325
'repository_format_to': 'D2',
376
326
'transport_readonly_server': 'b',
377
327
'transport_server': 'a'})],
378
adapter.formats_to_scenarios(formats))
381
class TestInterVersionedFileProviderAdapter(TestCase):
382
"""A group of tests that test the InterVersionedFile test adapter."""
384
def test_scenarios(self):
385
# check that constructor parameters are passed through to the adapted
387
from bzrlib.tests.interversionedfile_implementations \
388
import InterVersionedFileTestProviderAdapter
391
formats = [(str, "C1", "C2"), (int, "D1", "D2")]
392
adapter = InterVersionedFileTestProviderAdapter(server1, server2, formats)
395
{'interversionedfile_class':str,
396
'transport_readonly_server': 'b',
397
'transport_server': 'a',
398
'versionedfile_factory': 'C1',
399
'versionedfile_factory_to': 'C2'}),
401
{'interversionedfile_class': int,
402
'transport_readonly_server': 'b',
403
'transport_server': 'a',
404
'versionedfile_factory': 'D1',
405
'versionedfile_factory_to': 'D2'})],
409
class TestRevisionStoreProviderAdapter(TestCase):
410
"""A group of tests that test the RevisionStore test adapter."""
412
def test_scenarios(self):
413
# check that constructor parameters are passed through to the adapted
415
from bzrlib.tests.revisionstore_implementations \
416
import RevisionStoreTestProviderAdapter
417
# revision stores need a store factory - i.e. RevisionKnit
418
#, a readonly and rw transport
422
store_factories = ["c", "d"]
423
adapter = RevisionStoreTestProviderAdapter(server1, server2, store_factories)
426
{'store_factory': 'c',
427
'transport_readonly_server': 'b',
428
'transport_server': 'a'}),
430
{'store_factory': 'd',
431
'transport_readonly_server': 'b',
432
'transport_server': 'a'})],
436
class TestWorkingTreeProviderAdapter(TestCase):
437
"""A group of tests that test the workingtree implementation test adapter."""
439
def test_scenarios(self):
440
# check that constructor parameters are passed through to the adapted
442
from bzrlib.tests.workingtree_implementations \
443
import WorkingTreeTestProviderAdapter
446
formats = [("c", "C"), ("d", "D")]
447
adapter = WorkingTreeTestProviderAdapter(server1, server2, formats)
450
{'bzrdir_format': 'C',
451
'transport_readonly_server': 'b',
452
'transport_server': 'a',
453
'workingtree_format': 'c'}),
455
{'bzrdir_format': 'D',
456
'transport_readonly_server': 'b',
457
'transport_server': 'a',
458
'workingtree_format': 'd'})],
462
class TestTreeProviderAdapter(TestCase):
463
"""Test the setup of tree_implementation tests."""
465
def test_adapted_tests(self):
466
# the tree implementation adapter is meant to setup one instance for
467
# each working tree format, and one additional instance that will
468
# use the default wt format, but create a revision tree for the tests.
469
# this means that the wt ones should have the workingtree_to_test_tree
470
# attribute set to 'return_parameter' and the revision one set to
471
# revision_tree_from_workingtree.
473
from bzrlib.tests.tree_implementations import (
474
TreeTestProviderAdapter,
331
class TestWorkingTreeScenarios(tests.TestCase):
333
def test_scenarios(self):
334
# check that constructor parameters are passed through to the adapted
336
from bzrlib.tests.per_workingtree import make_scenarios
339
formats = [workingtree.WorkingTreeFormat2(),
340
workingtree.WorkingTreeFormat3(),]
341
scenarios = make_scenarios(server1, server2, formats)
343
('WorkingTreeFormat2',
344
{'bzrdir_format': formats[0]._matchingbzrdir,
345
'transport_readonly_server': 'b',
346
'transport_server': 'a',
347
'workingtree_format': formats[0]}),
348
('WorkingTreeFormat3',
349
{'bzrdir_format': formats[1]._matchingbzrdir,
350
'transport_readonly_server': 'b',
351
'transport_server': 'a',
352
'workingtree_format': formats[1]})],
356
class TestTreeScenarios(tests.TestCase):
358
def test_scenarios(self):
359
# the tree implementation scenario generator is meant to setup one
360
# instance for each working tree format, and one additional instance
361
# that will use the default wt format, but create a revision tree for
362
# the tests. this means that the wt ones should have the
363
# workingtree_to_test_tree attribute set to 'return_parameter' and the
364
# revision one set to revision_tree_from_workingtree.
366
from bzrlib.tests.per_tree import (
367
_dirstate_tree_from_workingtree,
475
371
return_parameter,
476
372
revision_tree_from_workingtree
478
from bzrlib.workingtree import WorkingTreeFormat, WorkingTreeFormat3
479
input_test = TestTreeProviderAdapter(
480
"test_adapted_tests")
483
formats = [("c", "C"), ("d", "D")]
484
adapter = TreeTestProviderAdapter(server1, server2, formats)
485
suite = adapter.adapt(input_test)
486
tests = list(iter(suite))
487
self.assertEqual(4, len(tests))
488
# this must match the default format setp up in
489
# TreeTestProviderAdapter.adapt
490
default_format = WorkingTreeFormat3
491
self.assertEqual(tests[0].workingtree_format, formats[0][0])
492
self.assertEqual(tests[0].bzrdir_format, formats[0][1])
493
self.assertEqual(tests[0].transport_server, server1)
494
self.assertEqual(tests[0].transport_readonly_server, server2)
495
self.assertEqual(tests[0].workingtree_to_test_tree, return_parameter)
496
self.assertEqual(tests[1].workingtree_format, formats[1][0])
497
self.assertEqual(tests[1].bzrdir_format, formats[1][1])
498
self.assertEqual(tests[1].transport_server, server1)
499
self.assertEqual(tests[1].transport_readonly_server, server2)
500
self.assertEqual(tests[1].workingtree_to_test_tree, return_parameter)
501
self.assertIsInstance(tests[2].workingtree_format, default_format)
502
#self.assertEqual(tests[2].bzrdir_format,
503
# default_format._matchingbzrdir)
504
self.assertEqual(tests[2].transport_server, server1)
505
self.assertEqual(tests[2].transport_readonly_server, server2)
506
self.assertEqual(tests[2].workingtree_to_test_tree,
507
revision_tree_from_workingtree)
510
class TestInterTreeProviderAdapter(TestCase):
376
formats = [workingtree.WorkingTreeFormat2(),
377
workingtree.WorkingTreeFormat3(),]
378
scenarios = make_scenarios(server1, server2, formats)
379
self.assertEqual(7, len(scenarios))
380
default_wt_format = workingtree.WorkingTreeFormat4._default_format
381
wt4_format = workingtree.WorkingTreeFormat4()
382
wt5_format = workingtree.WorkingTreeFormat5()
383
expected_scenarios = [
384
('WorkingTreeFormat2',
385
{'bzrdir_format': formats[0]._matchingbzrdir,
386
'transport_readonly_server': 'b',
387
'transport_server': 'a',
388
'workingtree_format': formats[0],
389
'_workingtree_to_test_tree': return_parameter,
391
('WorkingTreeFormat3',
392
{'bzrdir_format': formats[1]._matchingbzrdir,
393
'transport_readonly_server': 'b',
394
'transport_server': 'a',
395
'workingtree_format': formats[1],
396
'_workingtree_to_test_tree': return_parameter,
399
{'_workingtree_to_test_tree': revision_tree_from_workingtree,
400
'bzrdir_format': default_wt_format._matchingbzrdir,
401
'transport_readonly_server': 'b',
402
'transport_server': 'a',
403
'workingtree_format': default_wt_format,
405
('DirStateRevisionTree,WT4',
406
{'_workingtree_to_test_tree': _dirstate_tree_from_workingtree,
407
'bzrdir_format': wt4_format._matchingbzrdir,
408
'transport_readonly_server': 'b',
409
'transport_server': 'a',
410
'workingtree_format': wt4_format,
412
('DirStateRevisionTree,WT5',
413
{'_workingtree_to_test_tree': _dirstate_tree_from_workingtree,
414
'bzrdir_format': wt5_format._matchingbzrdir,
415
'transport_readonly_server': 'b',
416
'transport_server': 'a',
417
'workingtree_format': wt5_format,
420
{'_workingtree_to_test_tree': preview_tree_pre,
421
'bzrdir_format': default_wt_format._matchingbzrdir,
422
'transport_readonly_server': 'b',
423
'transport_server': 'a',
424
'workingtree_format': default_wt_format}),
426
{'_workingtree_to_test_tree': preview_tree_post,
427
'bzrdir_format': default_wt_format._matchingbzrdir,
428
'transport_readonly_server': 'b',
429
'transport_server': 'a',
430
'workingtree_format': default_wt_format}),
432
self.assertEqual(expected_scenarios, scenarios)
435
class TestInterTreeScenarios(tests.TestCase):
511
436
"""A group of tests that test the InterTreeTestAdapter."""
513
def test_adapted_tests(self):
438
def test_scenarios(self):
514
439
# check that constructor parameters are passed through to the adapted
516
441
# for InterTree tests we want the machinery to bring up two trees in
518
443
# because each optimiser can be direction specific, we need to test
519
444
# each optimiser in its chosen direction.
520
445
# unlike the TestProviderAdapter we dont want to automatically add a
521
# parameterised one for WorkingTree - the optimisers will tell us what
446
# parameterized one for WorkingTree - the optimisers will tell us what
523
from bzrlib.tests.tree_implementations import (
448
from bzrlib.tests.per_tree import (
524
449
return_parameter,
525
450
revision_tree_from_workingtree
527
from bzrlib.tests.intertree_implementations import (
528
InterTreeTestProviderAdapter,
452
from bzrlib.tests.per_intertree import (
530
455
from bzrlib.workingtree import WorkingTreeFormat2, WorkingTreeFormat3
531
input_test = TestInterTreeProviderAdapter(
532
"test_adapted_tests")
456
input_test = TestInterTreeScenarios(
535
460
format1 = WorkingTreeFormat2()
536
461
format2 = WorkingTreeFormat3()
537
formats = [(str, format1, format2, "converter1"),
538
(int, format2, format1, "converter2")]
539
adapter = InterTreeTestProviderAdapter(server1, server2, formats)
540
suite = adapter.adapt(input_test)
541
tests = list(iter(suite))
542
self.assertEqual(2, len(tests))
543
self.assertEqual(tests[0].intertree_class, formats[0][0])
544
self.assertEqual(tests[0].workingtree_format, formats[0][1])
545
self.assertEqual(tests[0].workingtree_format_to, formats[0][2])
546
self.assertEqual(tests[0].mutable_trees_to_test_trees, formats[0][3])
547
self.assertEqual(tests[0].workingtree_to_test_tree, return_parameter)
548
self.assertEqual(tests[0].transport_server, server1)
549
self.assertEqual(tests[0].transport_readonly_server, server2)
550
self.assertEqual(tests[1].intertree_class, formats[1][0])
551
self.assertEqual(tests[1].workingtree_format, formats[1][1])
552
self.assertEqual(tests[1].workingtree_format_to, formats[1][2])
553
self.assertEqual(tests[1].mutable_trees_to_test_trees, formats[1][3])
554
self.assertEqual(tests[1].workingtree_to_test_tree, return_parameter)
555
self.assertEqual(tests[1].transport_server, server1)
556
self.assertEqual(tests[1].transport_readonly_server, server2)
559
class TestTestCaseInTempDir(TestCaseInTempDir):
462
formats = [("1", str, format1, format2, "converter1"),
463
("2", int, format2, format1, "converter2")]
464
scenarios = make_scenarios(server1, server2, formats)
465
self.assertEqual(2, len(scenarios))
466
expected_scenarios = [
468
"bzrdir_format": format1._matchingbzrdir,
469
"intertree_class": formats[0][1],
470
"workingtree_format": formats[0][2],
471
"workingtree_format_to": formats[0][3],
472
"mutable_trees_to_test_trees": formats[0][4],
473
"_workingtree_to_test_tree": return_parameter,
474
"transport_server": server1,
475
"transport_readonly_server": server2,
478
"bzrdir_format": format2._matchingbzrdir,
479
"intertree_class": formats[1][1],
480
"workingtree_format": formats[1][2],
481
"workingtree_format_to": formats[1][3],
482
"mutable_trees_to_test_trees": formats[1][4],
483
"_workingtree_to_test_tree": return_parameter,
484
"transport_server": server1,
485
"transport_readonly_server": server2,
488
self.assertEqual(scenarios, expected_scenarios)
491
class TestTestCaseInTempDir(tests.TestCaseInTempDir):
561
493
def test_home_is_not_working(self):
562
494
self.assertNotEqual(self.test_dir, self.test_home_dir)
563
495
cwd = osutils.getcwd()
564
self.assertEqual(self.test_dir, cwd)
565
self.assertEqual(self.test_home_dir, os.environ['HOME'])
568
class TestTestCaseWithMemoryTransport(TestCaseWithMemoryTransport):
496
self.assertIsSameRealPath(self.test_dir, cwd)
497
self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
499
def test_assertEqualStat_equal(self):
500
from bzrlib.tests.test_dirstate import _FakeStat
501
self.build_tree(["foo"])
502
real = os.lstat("foo")
503
fake = _FakeStat(real.st_size, real.st_mtime, real.st_ctime,
504
real.st_dev, real.st_ino, real.st_mode)
505
self.assertEqualStat(real, fake)
507
def test_assertEqualStat_notequal(self):
508
self.build_tree(["foo", "longname"])
509
self.assertRaises(AssertionError, self.assertEqualStat,
510
os.lstat("foo"), os.lstat("longname"))
513
class TestTestCaseWithMemoryTransport(tests.TestCaseWithMemoryTransport):
570
515
def test_home_is_non_existant_dir_under_root(self):
571
516
"""The test_home_dir for TestCaseWithMemoryTransport is missing.
573
518
This is because TestCaseWithMemoryTransport is for tests that do not
574
need any disk resources: they should be hooked into bzrlib in such a
575
way that no global settings are being changed by the test (only a
519
need any disk resources: they should be hooked into bzrlib in such a
520
way that no global settings are being changed by the test (only a
576
521
few tests should need to do that), and having a missing dir as home is
577
522
an effective way to ensure that this is the case.
579
self.assertEqual(self.TEST_ROOT + "/MemoryTransportMissingHomeDir",
524
self.assertIsSameRealPath(
525
self.TEST_ROOT + "/MemoryTransportMissingHomeDir",
580
526
self.test_home_dir)
581
self.assertEqual(self.test_home_dir, os.environ['HOME'])
527
self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
583
529
def test_cwd_is_TEST_ROOT(self):
584
self.assertEqual(self.test_dir, self.TEST_ROOT)
530
self.assertIsSameRealPath(self.test_dir, self.TEST_ROOT)
585
531
cwd = osutils.getcwd()
586
self.assertEqual(self.test_dir, cwd)
532
self.assertIsSameRealPath(self.test_dir, cwd)
534
def test_BZR_HOME_and_HOME_are_bytestrings(self):
535
"""The $BZR_HOME and $HOME environment variables should not be unicode.
537
See https://bugs.launchpad.net/bzr/+bug/464174
539
self.assertIsInstance(os.environ['BZR_HOME'], str)
540
self.assertIsInstance(os.environ['HOME'], str)
588
542
def test_make_branch_and_memory_tree(self):
589
543
"""In TestCaseWithMemoryTransport we should not make the branch on disk.
654
658
self.assertRaises(AssertionError, self.assertIsDirectory, 'a_file', t)
655
659
self.assertRaises(AssertionError, self.assertIsDirectory, 'not_here', t)
658
class TestTestCaseTransports(TestCaseWithTransport):
661
def test_make_branch_builder(self):
662
builder = self.make_branch_builder('dir')
663
rev_id = builder.build_commit()
664
self.failUnlessExists('dir')
665
a_dir = bzrdir.BzrDir.open('dir')
666
self.assertRaises(errors.NoWorkingTree, a_dir.open_workingtree)
667
a_branch = a_dir.open_branch()
668
builder_branch = builder.get_branch()
669
self.assertEqual(a_branch.base, builder_branch.base)
670
self.assertEqual((1, rev_id), builder_branch.last_revision_info())
671
self.assertEqual((1, rev_id), a_branch.last_revision_info())
674
class TestTestCaseTransports(tests.TestCaseWithTransport):
661
677
super(TestTestCaseTransports, self).setUp()
662
self.vfs_transport_factory = MemoryServer
678
self.vfs_transport_factory = memory.MemoryServer
664
680
def test_make_bzrdir_preserves_transport(self):
665
681
t = self.get_transport()
666
682
result_bzrdir = self.make_bzrdir('subdir')
667
self.assertIsInstance(result_bzrdir.transport,
683
self.assertIsInstance(result_bzrdir.transport,
684
memory.MemoryTransport)
669
685
# should not be on disk, should only be in memory
670
686
self.failIfExists('subdir')
673
class TestChrootedTest(ChrootedTestCase):
689
class TestChrootedTest(tests.ChrootedTestCase):
675
691
def test_root_is_root(self):
676
from bzrlib.transport import get_transport
677
t = get_transport(self.get_readonly_url())
692
t = transport.get_transport(self.get_readonly_url())
679
694
self.assertEqual(url, t.clone('..').base)
682
class MockProgress(_BaseProgressBar):
683
"""Progress-bar standin that records calls.
685
Useful for testing pb using code.
689
_BaseProgressBar.__init__(self)
693
self.calls.append(('tick',))
695
def update(self, msg=None, current=None, total=None):
696
self.calls.append(('update', msg, current, total))
699
self.calls.append(('clear',))
701
def note(self, msg, *args):
702
self.calls.append(('note', msg, args))
705
class TestTestResult(TestCase):
707
def test_elapsed_time_with_benchmarking(self):
697
class TestProfileResult(tests.TestCase):
699
def test_profiles_tests(self):
700
self.requireFeature(test_lsprof.LSProfFeature)
701
terminal = testtools.tests.helpers.ExtendedTestResult()
702
result = tests.ProfileResult(terminal)
703
class Sample(tests.TestCase):
705
self.sample_function()
706
def sample_function(self):
710
case = terminal._events[0][1]
711
self.assertLength(1, case._benchcalls)
712
# We must be able to unpack it as the test reporting code wants
713
(_, _, _), stats = case._benchcalls[0]
714
self.assertTrue(callable(stats.pprint))
717
class TestTestResult(tests.TestCase):
719
def check_timing(self, test_case, expected_re):
708
720
result = bzrlib.tests.TextTestResult(self._log_file,
712
result._recordTestStartTime()
714
result.extractBenchmarkTime(self)
715
timed_string = result._testTimeString()
716
# without explicit benchmarking, we should get a simple time.
717
self.assertContainsRe(timed_string, "^ +[0-9]+ms$")
718
# if a benchmark time is given, we want a x of y style result.
719
self.time(time.sleep, 0.001)
720
result.extractBenchmarkTime(self)
721
timed_string = result._testTimeString()
722
self.assertContainsRe(
723
timed_string, "^ +[0-9]+ms/ +[0-9]+ms$")
724
# extracting the time from a non-bzrlib testcase sets to None
725
result._recordTestStartTime()
726
result.extractBenchmarkTime(
727
unittest.FunctionTestCase(self.test_elapsed_time_with_benchmarking))
728
timed_string = result._testTimeString()
729
self.assertContainsRe(timed_string, "^ +[0-9]+ms$")
730
# cheat. Yes, wash thy mouth out with soap.
731
self._benchtime = None
724
capture = testtools.tests.helpers.ExtendedTestResult()
725
test_case.run(MultiTestResult(result, capture))
726
run_case = capture._events[0][1]
727
timed_string = result._testTimeString(run_case)
728
self.assertContainsRe(timed_string, expected_re)
730
def test_test_reporting(self):
731
class ShortDelayTestCase(tests.TestCase):
732
def test_short_delay(self):
734
def test_short_benchmark(self):
735
self.time(time.sleep, 0.003)
736
self.check_timing(ShortDelayTestCase('test_short_delay'),
738
# if a benchmark time is given, we now show just that time followed by
740
self.check_timing(ShortDelayTestCase('test_short_benchmark'),
743
def test_unittest_reporting_unittest_class(self):
744
# getting the time from a non-bzrlib test works ok
745
class ShortDelayTestCase(unittest.TestCase):
746
def test_short_delay(self):
748
self.check_timing(ShortDelayTestCase('test_short_delay'),
751
def _patch_get_bzr_source_tree(self):
752
# Reading from the actual source tree breaks isolation, but we don't
753
# want to assume that thats *all* that would happen.
754
self.overrideAttr(bzrlib.version, '_get_bzr_source_tree', lambda: None)
733
756
def test_assigned_benchmark_file_stores_date(self):
757
self._patch_get_bzr_source_tree()
734
758
output = StringIO()
735
759
result = bzrlib.tests.TextTestResult(self._log_file,
1191
def _patch_get_bzr_source_tree(self):
1192
# Reading from the actual source tree breaks isolation, but we don't
1193
# want to assume that thats *all* that would happen.
1194
self._get_source_tree_calls = []
1196
self._get_source_tree_calls.append("called")
1198
self.overrideAttr(bzrlib.version, '_get_bzr_source_tree', new_get)
1137
1200
def test_bench_history(self):
1138
# tests that the running the benchmark produces a history file
1139
# containing a timestamp and the revision id of the bzrlib source which
1141
workingtree = _get_bzr_source_tree()
1201
# tests that the running the benchmark passes bench_history into
1202
# the test result object. We can tell that happens if
1203
# _get_bzr_source_tree is called.
1204
self._patch_get_bzr_source_tree()
1142
1205
test = TestRunner('dummy_test')
1143
1206
output = StringIO()
1144
runner = TextTestRunner(stream=self._log_file, bench_history=output)
1207
runner = tests.TextTestRunner(stream=self._log_file,
1208
bench_history=output)
1145
1209
result = self.run_test_runner(runner, test)
1146
1210
output_string = output.getvalue()
1147
1211
self.assertContainsRe(output_string, "--date [0-9.]+")
1148
if workingtree is not None:
1149
revision_id = workingtree.get_parent_ids()[0]
1150
self.assertEndsWith(output_string.rstrip(), revision_id)
1152
def test_success_log_deleted(self):
1153
"""Successful tests have their log deleted"""
1155
class LogTester(TestCase):
1157
def test_success(self):
1158
self.log('this will be removed\n')
1160
sio = cStringIO.StringIO()
1161
runner = TextTestRunner(stream=sio)
1162
test = LogTester('test_success')
1163
result = self.run_test_runner(runner, test)
1165
log = test._get_log()
1166
self.assertEqual("DELETED log file to reduce memory footprint", log)
1167
self.assertEqual('', test._log_contents)
1168
self.assertIs(None, test._log_file_name)
1170
def test_fail_log_kept(self):
1171
"""Failed tests have their log kept"""
1173
class LogTester(TestCase):
1175
def test_fail(self):
1176
self.log('this will be kept\n')
1177
self.fail('this test fails')
1179
sio = cStringIO.StringIO()
1180
runner = TextTestRunner(stream=sio)
1181
test = LogTester('test_fail')
1182
result = self.run_test_runner(runner, test)
1184
text = sio.getvalue()
1185
self.assertContainsRe(text, 'this will be kept')
1186
self.assertContainsRe(text, 'this test fails')
1188
log = test._get_log()
1189
self.assertContainsRe(log, 'this will be kept')
1190
self.assertEqual(log, test._log_contents)
1192
def test_error_log_kept(self):
1193
"""Tests with errors have their log kept"""
1195
class LogTester(TestCase):
1197
def test_error(self):
1198
self.log('this will be kept\n')
1199
raise ValueError('random exception raised')
1201
sio = cStringIO.StringIO()
1202
runner = TextTestRunner(stream=sio)
1203
test = LogTester('test_error')
1204
result = self.run_test_runner(runner, test)
1206
text = sio.getvalue()
1207
self.assertContainsRe(text, 'this will be kept')
1208
self.assertContainsRe(text, 'random exception raised')
1210
log = test._get_log()
1211
self.assertContainsRe(log, 'this will be kept')
1212
self.assertEqual(log, test._log_contents)
1215
class SampleTestCase(TestCase):
1212
self.assertLength(1, self._get_source_tree_calls)
1214
def test_startTestRun(self):
1215
"""run should call result.startTestRun()"""
1217
class LoggingDecorator(tests.ForwardingResult):
1218
def startTestRun(self):
1219
tests.ForwardingResult.startTestRun(self)
1220
calls.append('startTestRun')
1221
test = unittest.FunctionTestCase(lambda:None)
1223
runner = tests.TextTestRunner(stream=stream,
1224
result_decorators=[LoggingDecorator])
1225
result = self.run_test_runner(runner, test)
1226
self.assertLength(1, calls)
1228
def test_stopTestRun(self):
1229
"""run should call result.stopTestRun()"""
1231
class LoggingDecorator(tests.ForwardingResult):
1232
def stopTestRun(self):
1233
tests.ForwardingResult.stopTestRun(self)
1234
calls.append('stopTestRun')
1235
test = unittest.FunctionTestCase(lambda:None)
1237
runner = tests.TextTestRunner(stream=stream,
1238
result_decorators=[LoggingDecorator])
1239
result = self.run_test_runner(runner, test)
1240
self.assertLength(1, calls)
1243
class SampleTestCase(tests.TestCase):
1217
1245
def _test_pass(self):
1221
class TestTestCase(TestCase):
1248
class _TestException(Exception):
1252
class TestTestCase(tests.TestCase):
1222
1253
"""Tests that test the core bzrlib TestCase."""
1255
def test_assertLength_matches_empty(self):
1257
self.assertLength(0, a_list)
1259
def test_assertLength_matches_nonempty(self):
1261
self.assertLength(3, a_list)
1263
def test_assertLength_fails_different(self):
1265
self.assertRaises(AssertionError, self.assertLength, 1, a_list)
1267
def test_assertLength_shows_sequence_in_failure(self):
1269
exception = self.assertRaises(AssertionError, self.assertLength, 2,
1271
self.assertEqual('Incorrect length: wanted 2, got 3 for [1, 2, 3]',
1274
def test_base_setUp_not_called_causes_failure(self):
1275
class TestCaseWithBrokenSetUp(tests.TestCase):
1277
pass # does not call TestCase.setUp
1280
test = TestCaseWithBrokenSetUp('test_foo')
1281
result = unittest.TestResult()
1283
self.assertFalse(result.wasSuccessful())
1284
self.assertEqual(1, result.testsRun)
1286
def test_base_tearDown_not_called_causes_failure(self):
1287
class TestCaseWithBrokenTearDown(tests.TestCase):
1289
pass # does not call TestCase.tearDown
1292
test = TestCaseWithBrokenTearDown('test_foo')
1293
result = unittest.TestResult()
1295
self.assertFalse(result.wasSuccessful())
1296
self.assertEqual(1, result.testsRun)
1224
1298
def test_debug_flags_sanitised(self):
1225
1299
"""The bzrlib debug flags should be sanitised by setUp."""
1300
if 'allow_debug' in tests.selftest_debug_flags:
1301
raise tests.TestNotApplicable(
1302
'-Eallow_debug option prevents debug flag sanitisation')
1226
1303
# we could set something and run a test that will check
1227
1304
# it gets santised, but this is probably sufficient for now:
1228
1305
# if someone runs the test with -Dsomething it will error.
1229
self.assertEqual(set(), bzrlib.debug.debug_flags)
1307
if self._lock_check_thorough:
1308
flags.add('strict_locks')
1309
self.assertEqual(flags, bzrlib.debug.debug_flags)
1311
def change_selftest_debug_flags(self, new_flags):
1312
self.overrideAttr(tests, 'selftest_debug_flags', set(new_flags))
1314
def test_allow_debug_flag(self):
1315
"""The -Eallow_debug flag prevents bzrlib.debug.debug_flags from being
1316
sanitised (i.e. cleared) before running a test.
1318
self.change_selftest_debug_flags(set(['allow_debug']))
1319
bzrlib.debug.debug_flags = set(['a-flag'])
1320
class TestThatRecordsFlags(tests.TestCase):
1321
def test_foo(nested_self):
1322
self.flags = set(bzrlib.debug.debug_flags)
1323
test = TestThatRecordsFlags('test_foo')
1324
test.run(self.make_test_result())
1325
flags = set(['a-flag'])
1326
if 'disable_lock_checks' not in tests.selftest_debug_flags:
1327
flags.add('strict_locks')
1328
self.assertEqual(flags, self.flags)
1330
def test_disable_lock_checks(self):
1331
"""The -Edisable_lock_checks flag disables thorough checks."""
1332
class TestThatRecordsFlags(tests.TestCase):
1333
def test_foo(nested_self):
1334
self.flags = set(bzrlib.debug.debug_flags)
1335
self.test_lock_check_thorough = nested_self._lock_check_thorough
1336
self.change_selftest_debug_flags(set())
1337
test = TestThatRecordsFlags('test_foo')
1338
test.run(self.make_test_result())
1339
# By default we do strict lock checking and thorough lock/unlock
1341
self.assertTrue(self.test_lock_check_thorough)
1342
self.assertEqual(set(['strict_locks']), self.flags)
1343
# Now set the disable_lock_checks flag, and show that this changed.
1344
self.change_selftest_debug_flags(set(['disable_lock_checks']))
1345
test = TestThatRecordsFlags('test_foo')
1346
test.run(self.make_test_result())
1347
self.assertFalse(self.test_lock_check_thorough)
1348
self.assertEqual(set(), self.flags)
1350
def test_this_fails_strict_lock_check(self):
1351
class TestThatRecordsFlags(tests.TestCase):
1352
def test_foo(nested_self):
1353
self.flags1 = set(bzrlib.debug.debug_flags)
1354
self.thisFailsStrictLockCheck()
1355
self.flags2 = set(bzrlib.debug.debug_flags)
1356
# Make sure lock checking is active
1357
self.change_selftest_debug_flags(set())
1358
test = TestThatRecordsFlags('test_foo')
1359
test.run(self.make_test_result())
1360
self.assertEqual(set(['strict_locks']), self.flags1)
1361
self.assertEqual(set(), self.flags2)
1363
def test_debug_flags_restored(self):
1364
"""The bzrlib debug flags should be restored to their original state
1365
after the test was run, even if allow_debug is set.
1367
self.change_selftest_debug_flags(set(['allow_debug']))
1368
# Now run a test that modifies debug.debug_flags.
1369
bzrlib.debug.debug_flags = set(['original-state'])
1370
class TestThatModifiesFlags(tests.TestCase):
1372
bzrlib.debug.debug_flags = set(['modified'])
1373
test = TestThatModifiesFlags('test_foo')
1374
test.run(self.make_test_result())
1375
self.assertEqual(set(['original-state']), bzrlib.debug.debug_flags)
1377
def make_test_result(self):
1378
"""Get a test result that writes to the test log file."""
1379
return tests.TextTestResult(self._log_file, descriptions=0, verbosity=1)
1231
1381
def inner_test(self):
1232
1382
# the inner child test
1402
1675
def sample_normal_method(self):
1403
1676
"""A undeprecated method."""
1405
@symbol_versioning.deprecated_method(zero_ten)
1678
@deprecated_method(deprecated_in((0, 10, 0)))
1406
1679
def sample_nested_deprecation(self):
1407
1680
return sample_deprecated_function()
1410
class TestExtraAssertions(TestCase):
1683
class TestExtraAssertions(tests.TestCase):
1411
1684
"""Tests for new test assertions in bzrlib test suite"""
1413
1686
def test_assert_isinstance(self):
1414
1687
self.assertIsInstance(2, int)
1415
1688
self.assertIsInstance(u'', basestring)
1416
self.assertRaises(AssertionError, self.assertIsInstance, None, int)
1689
e = self.assertRaises(AssertionError, self.assertIsInstance, None, int)
1690
self.assertEquals(str(e),
1691
"None is an instance of <type 'NoneType'> rather than <type 'int'>")
1417
1692
self.assertRaises(AssertionError, self.assertIsInstance, 23.3, int)
1693
e = self.assertRaises(AssertionError,
1694
self.assertIsInstance, None, int, "it's just not")
1695
self.assertEquals(str(e),
1696
"None is an instance of <type 'NoneType'> rather than <type 'int'>"
1419
1699
def test_assertEndsWith(self):
1420
1700
self.assertEndsWith('foo', 'oo')
1421
1701
self.assertRaises(AssertionError, self.assertEndsWith, 'o', 'oo')
1703
def test_assertEqualDiff(self):
1704
e = self.assertRaises(AssertionError,
1705
self.assertEqualDiff, '', '\n')
1706
self.assertEquals(str(e),
1707
# Don't blink ! The '+' applies to the second string
1708
'first string is missing a final newline.\n+ \n')
1709
e = self.assertRaises(AssertionError,
1710
self.assertEqualDiff, '\n', '')
1711
self.assertEquals(str(e),
1712
# Don't blink ! The '-' applies to the second string
1713
'second string is missing a final newline.\n- \n')
1716
class TestDeprecations(tests.TestCase):
1423
1718
def test_applyDeprecated_not_deprecated(self):
1424
1719
sample_object = ApplyDeprecatedHelper()
1425
1720
# calling an undeprecated callable raises an assertion
1426
self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
1721
self.assertRaises(AssertionError, self.applyDeprecated,
1722
deprecated_in((0, 11, 0)),
1427
1723
sample_object.sample_normal_method)
1428
self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
1724
self.assertRaises(AssertionError, self.applyDeprecated,
1725
deprecated_in((0, 11, 0)),
1429
1726
sample_undeprecated_function, "a param value")
1430
1727
# calling a deprecated callable (function or method) with the wrong
1431
1728
# expected deprecation fails.
1432
self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
1729
self.assertRaises(AssertionError, self.applyDeprecated,
1730
deprecated_in((0, 10, 0)),
1433
1731
sample_object.sample_deprecated_method, "a param value")
1434
self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
1732
self.assertRaises(AssertionError, self.applyDeprecated,
1733
deprecated_in((0, 10, 0)),
1435
1734
sample_deprecated_function)
1436
1735
# calling a deprecated callable (function or method) with the right
1437
1736
# expected deprecation returns the functions result.
1438
self.assertEqual("a param value", self.applyDeprecated(zero_eleven,
1737
self.assertEqual("a param value",
1738
self.applyDeprecated(deprecated_in((0, 11, 0)),
1439
1739
sample_object.sample_deprecated_method, "a param value"))
1440
self.assertEqual(2, self.applyDeprecated(zero_eleven,
1740
self.assertEqual(2, self.applyDeprecated(deprecated_in((0, 11, 0)),
1441
1741
sample_deprecated_function))
1442
1742
# calling a nested deprecation with the wrong deprecation version
1443
# fails even if a deeper nested function was deprecated with the
1743
# fails even if a deeper nested function was deprecated with the
1444
1744
# supplied version.
1445
1745
self.assertRaises(AssertionError, self.applyDeprecated,
1446
zero_eleven, sample_object.sample_nested_deprecation)
1746
deprecated_in((0, 11, 0)), sample_object.sample_nested_deprecation)
1447
1747
# calling a nested deprecation with the right deprecation value
1448
1748
# returns the calls result.
1449
self.assertEqual(2, self.applyDeprecated(zero_ten,
1749
self.assertEqual(2, self.applyDeprecated(deprecated_in((0, 10, 0)),
1450
1750
sample_object.sample_nested_deprecation))
1452
1752
def test_callDeprecated(self):
1453
1753
def testfunc(be_deprecated, result=None):
1454
1754
if be_deprecated is True:
1455
symbol_versioning.warn('i am deprecated', DeprecationWarning,
1755
symbol_versioning.warn('i am deprecated', DeprecationWarning,
1458
1758
result = self.callDeprecated(['i am deprecated'], testfunc, True)
1481
1797
tree = self.make_branch_and_memory_tree('a')
1482
1798
self.assertIsInstance(tree, bzrlib.memorytree.MemoryTree)
1485
class TestSFTPMakeBranchAndTree(TestCaseWithSFTPServer):
1487
def test_make_tree_for_sftp_branch(self):
1488
"""Transports backed by local directories create local trees."""
1800
def test_make_tree_for_local_vfs_backed_transport(self):
1801
# make_branch_and_tree has to use local branch and repositories
1802
# when the vfs transport and local disk are colocated, even if
1803
# a different transport is in use for url generation.
1804
self.transport_server = test_server.FakeVFATServer
1805
self.assertFalse(self.get_url('t1').startswith('file://'))
1490
1806
tree = self.make_branch_and_tree('t1')
1491
1807
base = tree.bzrdir.root_transport.base
1492
self.failIf(base.startswith('sftp'),
1493
'base %r is on sftp but should be local' % base)
1808
self.assertStartsWith(base, 'file://')
1494
1809
self.assertEquals(tree.bzrdir.root_transport,
1495
1810
tree.branch.bzrdir.root_transport)
1496
1811
self.assertEquals(tree.bzrdir.root_transport,
1497
1812
tree.branch.repository.bzrdir.root_transport)
1500
class TestSelftest(TestCase):
1815
class SelfTestHelper:
1817
def run_selftest(self, **kwargs):
1818
"""Run selftest returning its output."""
1820
old_transport = bzrlib.tests.default_transport
1821
old_root = tests.TestCaseWithMemoryTransport.TEST_ROOT
1822
tests.TestCaseWithMemoryTransport.TEST_ROOT = None
1824
self.assertEqual(True, tests.selftest(stream=output, **kwargs))
1826
bzrlib.tests.default_transport = old_transport
1827
tests.TestCaseWithMemoryTransport.TEST_ROOT = old_root
1832
class TestSelftest(tests.TestCase, SelfTestHelper):
1501
1833
"""Tests of bzrlib.tests.selftest."""
1503
1835
def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
1504
1836
factory_called = []
1506
1838
factory_called.append(True)
1839
return TestUtil.TestSuite()
1508
1840
out = StringIO()
1509
1841
err = StringIO()
1510
self.apply_redirected(out, err, None, bzrlib.tests.selftest,
1842
self.apply_redirected(out, err, None, bzrlib.tests.selftest,
1511
1843
test_suite_factory=factory)
1512
1844
self.assertEqual([True], factory_called)
1515
class TestSelftestCleanOutput(TestCaseInTempDir):
1517
def test_clean_output(self):
1518
# test functionality of clean_selftest_output()
1519
self.build_tree(['test0000.tmp/', 'test0001.tmp/',
1520
'bzrlib/', 'tests/',
1521
'bzr', 'setup.py', 'test9999.tmp'])
1524
before = os.listdir(root)
1526
self.assertEquals(['bzr','bzrlib','setup.py',
1527
'test0000.tmp','test0001.tmp',
1528
'test9999.tmp','tests'],
1530
clean_selftest_output(root, quiet=True)
1531
after = os.listdir(root)
1533
self.assertEquals(['bzr','bzrlib','setup.py',
1534
'test9999.tmp','tests'],
1537
def test_clean_readonly(self):
1538
# test for delete read-only files
1539
self.build_tree(['test0000.tmp/', 'test0000.tmp/foo'])
1540
osutils.make_readonly('test0000.tmp/foo')
1542
before = os.listdir(root); before.sort()
1543
self.assertEquals(['test0000.tmp'], before)
1544
clean_selftest_output(root, quiet=True)
1545
after = os.listdir(root); after.sort()
1546
self.assertEquals([], after)
1549
class TestKnownFailure(TestCase):
1551
def test_known_failure(self):
1552
"""Check that KnownFailure is defined appropriately."""
1553
# a KnownFailure is an assertion error for compatability with unaware
1555
self.assertIsInstance(KnownFailure(""), AssertionError)
1557
def test_expect_failure(self):
1559
self.expectFailure("Doomed to failure", self.assertTrue, False)
1560
except KnownFailure, e:
1561
self.assertEqual('Doomed to failure', e.args[0])
1563
self.expectFailure("Doomed to failure", self.assertTrue, True)
1564
except AssertionError, e:
1565
self.assertEqual('Unexpected success. Should have failed:'
1566
' Doomed to failure', e.args[0])
1847
"""A test suite factory."""
1848
class Test(tests.TestCase):
1855
return TestUtil.TestSuite([Test("a"), Test("b"), Test("c")])
1857
def test_list_only(self):
1858
output = self.run_selftest(test_suite_factory=self.factory,
1860
self.assertEqual(3, len(output.readlines()))
1862
def test_list_only_filtered(self):
1863
output = self.run_selftest(test_suite_factory=self.factory,
1864
list_only=True, pattern="Test.b")
1865
self.assertEndsWith(output.getvalue(), "Test.b\n")
1866
self.assertLength(1, output.readlines())
1868
def test_list_only_excludes(self):
1869
output = self.run_selftest(test_suite_factory=self.factory,
1870
list_only=True, exclude_pattern="Test.b")
1871
self.assertNotContainsRe("Test.b", output.getvalue())
1872
self.assertLength(2, output.readlines())
1874
def test_lsprof_tests(self):
1875
self.requireFeature(test_lsprof.LSProfFeature)
1878
def __call__(test, result):
1880
def run(test, result):
1881
self.assertIsInstance(result, tests.ForwardingResult)
1882
calls.append("called")
1883
def countTestCases(self):
1885
self.run_selftest(test_suite_factory=Test, lsprof_tests=True)
1886
self.assertLength(1, calls)
1888
def test_random(self):
1889
# test randomising by listing a number of tests.
1890
output_123 = self.run_selftest(test_suite_factory=self.factory,
1891
list_only=True, random_seed="123")
1892
output_234 = self.run_selftest(test_suite_factory=self.factory,
1893
list_only=True, random_seed="234")
1894
self.assertNotEqual(output_123, output_234)
1895
# "Randominzing test order..\n\n
1896
self.assertLength(5, output_123.readlines())
1897
self.assertLength(5, output_234.readlines())
1899
def test_random_reuse_is_same_order(self):
1900
# test randomising by listing a number of tests.
1901
expected = self.run_selftest(test_suite_factory=self.factory,
1902
list_only=True, random_seed="123")
1903
repeated = self.run_selftest(test_suite_factory=self.factory,
1904
list_only=True, random_seed="123")
1905
self.assertEqual(expected.getvalue(), repeated.getvalue())
1907
def test_runner_class(self):
1908
self.requireFeature(features.subunit)
1909
from subunit import ProtocolTestCase
1910
stream = self.run_selftest(runner_class=tests.SubUnitBzrRunner,
1911
test_suite_factory=self.factory)
1912
test = ProtocolTestCase(stream)
1913
result = unittest.TestResult()
1915
self.assertEqual(3, result.testsRun)
1917
def test_starting_with_single_argument(self):
1918
output = self.run_selftest(test_suite_factory=self.factory,
1919
starting_with=['bzrlib.tests.test_selftest.Test.a'],
1921
self.assertEqual('bzrlib.tests.test_selftest.Test.a\n',
1924
def test_starting_with_multiple_argument(self):
1925
output = self.run_selftest(test_suite_factory=self.factory,
1926
starting_with=['bzrlib.tests.test_selftest.Test.a',
1927
'bzrlib.tests.test_selftest.Test.b'],
1929
self.assertEqual('bzrlib.tests.test_selftest.Test.a\n'
1930
'bzrlib.tests.test_selftest.Test.b\n',
1933
def check_transport_set(self, transport_server):
1934
captured_transport = []
1935
def seen_transport(a_transport):
1936
captured_transport.append(a_transport)
1937
class Capture(tests.TestCase):
1939
seen_transport(bzrlib.tests.default_transport)
1941
return TestUtil.TestSuite([Capture("a")])
1942
self.run_selftest(transport=transport_server, test_suite_factory=factory)
1943
self.assertEqual(transport_server, captured_transport[0])
1945
def test_transport_sftp(self):
1946
self.requireFeature(features.paramiko)
1947
from bzrlib.tests import stub_sftp
1948
self.check_transport_set(stub_sftp.SFTPAbsoluteServer)
1950
def test_transport_memory(self):
1951
self.check_transport_set(memory.MemoryServer)
1954
class TestSelftestWithIdList(tests.TestCaseInTempDir, SelfTestHelper):
1955
# Does IO: reads test.list
1957
def test_load_list(self):
1958
# Provide a list with one test - this test.
1959
test_id_line = '%s\n' % self.id()
1960
self.build_tree_contents([('test.list', test_id_line)])
1961
# And generate a list of the tests in the suite.
1962
stream = self.run_selftest(load_list='test.list', list_only=True)
1963
self.assertEqual(test_id_line, stream.getvalue())
1965
def test_load_unknown(self):
1966
# Provide a list with one test - this test.
1967
# And generate a list of the tests in the suite.
1968
err = self.assertRaises(errors.NoSuchFile, self.run_selftest,
1969
load_list='missing file name', list_only=True)
1972
class TestRunBzr(tests.TestCase):
1977
def _run_bzr_core(self, argv, retcode=0, encoding=None, stdin=None,
1979
"""Override _run_bzr_core to test how it is invoked by run_bzr.
1981
Attempts to run bzr from inside this class don't actually run it.
1983
We test how run_bzr actually invokes bzr in another location. Here we
1984
only need to test that it passes the right parameters to run_bzr.
1986
self.argv = list(argv)
1987
self.retcode = retcode
1988
self.encoding = encoding
1990
self.working_dir = working_dir
1991
return self.retcode, self.out, self.err
1993
def test_run_bzr_error(self):
1994
self.out = "It sure does!\n"
1995
out, err = self.run_bzr_error(['^$'], ['rocks'], retcode=34)
1996
self.assertEqual(['rocks'], self.argv)
1997
self.assertEqual(34, self.retcode)
1998
self.assertEqual('It sure does!\n', out)
1999
self.assertEquals(out, self.out)
2000
self.assertEqual('', err)
2001
self.assertEquals(err, self.err)
2003
def test_run_bzr_error_regexes(self):
2005
self.err = "bzr: ERROR: foobarbaz is not versioned"
2006
out, err = self.run_bzr_error(
2007
["bzr: ERROR: foobarbaz is not versioned"],
2008
['file-id', 'foobarbaz'])
2010
def test_encoding(self):
2011
"""Test that run_bzr passes encoding to _run_bzr_core"""
2012
self.run_bzr('foo bar')
2013
self.assertEqual(None, self.encoding)
2014
self.assertEqual(['foo', 'bar'], self.argv)
2016
self.run_bzr('foo bar', encoding='baz')
2017
self.assertEqual('baz', self.encoding)
2018
self.assertEqual(['foo', 'bar'], self.argv)
2020
def test_retcode(self):
2021
"""Test that run_bzr passes retcode to _run_bzr_core"""
2022
# Default is retcode == 0
2023
self.run_bzr('foo bar')
2024
self.assertEqual(0, self.retcode)
2025
self.assertEqual(['foo', 'bar'], self.argv)
2027
self.run_bzr('foo bar', retcode=1)
2028
self.assertEqual(1, self.retcode)
2029
self.assertEqual(['foo', 'bar'], self.argv)
2031
self.run_bzr('foo bar', retcode=None)
2032
self.assertEqual(None, self.retcode)
2033
self.assertEqual(['foo', 'bar'], self.argv)
2035
self.run_bzr(['foo', 'bar'], retcode=3)
2036
self.assertEqual(3, self.retcode)
2037
self.assertEqual(['foo', 'bar'], self.argv)
2039
def test_stdin(self):
2040
# test that the stdin keyword to run_bzr is passed through to
2041
# _run_bzr_core as-is. We do this by overriding
2042
# _run_bzr_core in this class, and then calling run_bzr,
2043
# which is a convenience function for _run_bzr_core, so
2045
self.run_bzr('foo bar', stdin='gam')
2046
self.assertEqual('gam', self.stdin)
2047
self.assertEqual(['foo', 'bar'], self.argv)
2049
self.run_bzr('foo bar', stdin='zippy')
2050
self.assertEqual('zippy', self.stdin)
2051
self.assertEqual(['foo', 'bar'], self.argv)
2053
def test_working_dir(self):
2054
"""Test that run_bzr passes working_dir to _run_bzr_core"""
2055
self.run_bzr('foo bar')
2056
self.assertEqual(None, self.working_dir)
2057
self.assertEqual(['foo', 'bar'], self.argv)
2059
self.run_bzr('foo bar', working_dir='baz')
2060
self.assertEqual('baz', self.working_dir)
2061
self.assertEqual(['foo', 'bar'], self.argv)
2063
def test_reject_extra_keyword_arguments(self):
2064
self.assertRaises(TypeError, self.run_bzr, "foo bar",
2065
error_regex=['error message'])
2068
class TestRunBzrCaptured(tests.TestCaseWithTransport):
2069
# Does IO when testing the working_dir parameter.
2071
def apply_redirected(self, stdin=None, stdout=None, stderr=None,
2072
a_callable=None, *args, **kwargs):
2074
self.factory_stdin = getattr(bzrlib.ui.ui_factory, "stdin", None)
2075
self.factory = bzrlib.ui.ui_factory
2076
self.working_dir = osutils.getcwd()
2077
stdout.write('foo\n')
2078
stderr.write('bar\n')
2081
def test_stdin(self):
2082
# test that the stdin keyword to _run_bzr_core is passed through to
2083
# apply_redirected as a StringIO. We do this by overriding
2084
# apply_redirected in this class, and then calling _run_bzr_core,
2085
# which calls apply_redirected.
2086
self.run_bzr(['foo', 'bar'], stdin='gam')
2087
self.assertEqual('gam', self.stdin.read())
2088
self.assertTrue(self.stdin is self.factory_stdin)
2089
self.run_bzr(['foo', 'bar'], stdin='zippy')
2090
self.assertEqual('zippy', self.stdin.read())
2091
self.assertTrue(self.stdin is self.factory_stdin)
2093
def test_ui_factory(self):
2094
# each invocation of self.run_bzr should get its
2095
# own UI factory, which is an instance of TestUIFactory,
2096
# with stdin, stdout and stderr attached to the stdin,
2097
# stdout and stderr of the invoked run_bzr
2098
current_factory = bzrlib.ui.ui_factory
2099
self.run_bzr(['foo'])
2100
self.failIf(current_factory is self.factory)
2101
self.assertNotEqual(sys.stdout, self.factory.stdout)
2102
self.assertNotEqual(sys.stderr, self.factory.stderr)
2103
self.assertEqual('foo\n', self.factory.stdout.getvalue())
2104
self.assertEqual('bar\n', self.factory.stderr.getvalue())
2105
self.assertIsInstance(self.factory, tests.TestUIFactory)
2107
def test_working_dir(self):
2108
self.build_tree(['one/', 'two/'])
2109
cwd = osutils.getcwd()
2111
# Default is to work in the current directory
2112
self.run_bzr(['foo', 'bar'])
2113
self.assertEqual(cwd, self.working_dir)
2115
self.run_bzr(['foo', 'bar'], working_dir=None)
2116
self.assertEqual(cwd, self.working_dir)
2118
# The function should be run in the alternative directory
2119
# but afterwards the current working dir shouldn't be changed
2120
self.run_bzr(['foo', 'bar'], working_dir='one')
2121
self.assertNotEqual(cwd, self.working_dir)
2122
self.assertEndsWith(self.working_dir, 'one')
2123
self.assertEqual(cwd, osutils.getcwd())
2125
self.run_bzr(['foo', 'bar'], working_dir='two')
2126
self.assertNotEqual(cwd, self.working_dir)
2127
self.assertEndsWith(self.working_dir, 'two')
2128
self.assertEqual(cwd, osutils.getcwd())
2131
class StubProcess(object):
2132
"""A stub process for testing run_bzr_subprocess."""
2134
def __init__(self, out="", err="", retcode=0):
2137
self.returncode = retcode
2139
def communicate(self):
2140
return self.out, self.err
2143
class TestWithFakedStartBzrSubprocess(tests.TestCaseWithTransport):
2144
"""Base class for tests testing how we might run bzr."""
2147
tests.TestCaseWithTransport.setUp(self)
2148
self.subprocess_calls = []
2150
def start_bzr_subprocess(self, process_args, env_changes=None,
2151
skip_if_plan_to_signal=False,
2153
allow_plugins=False):
2154
"""capture what run_bzr_subprocess tries to do."""
2155
self.subprocess_calls.append({'process_args':process_args,
2156
'env_changes':env_changes,
2157
'skip_if_plan_to_signal':skip_if_plan_to_signal,
2158
'working_dir':working_dir, 'allow_plugins':allow_plugins})
2159
return self.next_subprocess
2162
class TestRunBzrSubprocess(TestWithFakedStartBzrSubprocess):
2164
def assertRunBzrSubprocess(self, expected_args, process, *args, **kwargs):
2165
"""Run run_bzr_subprocess with args and kwargs using a stubbed process.
2167
Inside TestRunBzrSubprocessCommands we use a stub start_bzr_subprocess
2168
that will return static results. This assertion method populates those
2169
results and also checks the arguments run_bzr_subprocess generates.
2171
self.next_subprocess = process
2173
result = self.run_bzr_subprocess(*args, **kwargs)
2175
self.next_subprocess = None
2176
for key, expected in expected_args.iteritems():
2177
self.assertEqual(expected, self.subprocess_calls[-1][key])
1568
self.fail('Assertion not raised')
1571
class TestFeature(TestCase):
2180
self.next_subprocess = None
2181
for key, expected in expected_args.iteritems():
2182
self.assertEqual(expected, self.subprocess_calls[-1][key])
2185
def test_run_bzr_subprocess(self):
2186
"""The run_bzr_helper_external command behaves nicely."""
2187
self.assertRunBzrSubprocess({'process_args':['--version']},
2188
StubProcess(), '--version')
2189
self.assertRunBzrSubprocess({'process_args':['--version']},
2190
StubProcess(), ['--version'])
2191
# retcode=None disables retcode checking
2192
result = self.assertRunBzrSubprocess({},
2193
StubProcess(retcode=3), '--version', retcode=None)
2194
result = self.assertRunBzrSubprocess({},
2195
StubProcess(out="is free software"), '--version')
2196
self.assertContainsRe(result[0], 'is free software')
2197
# Running a subcommand that is missing errors
2198
self.assertRaises(AssertionError, self.assertRunBzrSubprocess,
2199
{'process_args':['--versionn']}, StubProcess(retcode=3),
2201
# Unless it is told to expect the error from the subprocess
2202
result = self.assertRunBzrSubprocess({},
2203
StubProcess(retcode=3), '--versionn', retcode=3)
2204
# Or to ignore retcode checking
2205
result = self.assertRunBzrSubprocess({},
2206
StubProcess(err="unknown command", retcode=3), '--versionn',
2208
self.assertContainsRe(result[1], 'unknown command')
2210
def test_env_change_passes_through(self):
2211
self.assertRunBzrSubprocess(
2212
{'env_changes':{'new':'value', 'changed':'newvalue', 'deleted':None}},
2214
env_changes={'new':'value', 'changed':'newvalue', 'deleted':None})
2216
def test_no_working_dir_passed_as_None(self):
2217
self.assertRunBzrSubprocess({'working_dir': None}, StubProcess(), '')
2219
def test_no_working_dir_passed_through(self):
2220
self.assertRunBzrSubprocess({'working_dir': 'dir'}, StubProcess(), '',
2223
def test_run_bzr_subprocess_no_plugins(self):
2224
self.assertRunBzrSubprocess({'allow_plugins': False},
2227
def test_allow_plugins(self):
2228
self.assertRunBzrSubprocess({'allow_plugins': True},
2229
StubProcess(), '', allow_plugins=True)
2232
class TestFinishBzrSubprocess(TestWithFakedStartBzrSubprocess):
2234
def test_finish_bzr_subprocess_with_error(self):
2235
"""finish_bzr_subprocess allows specification of the desired exit code.
2237
process = StubProcess(err="unknown command", retcode=3)
2238
result = self.finish_bzr_subprocess(process, retcode=3)
2239
self.assertEqual('', result[0])
2240
self.assertContainsRe(result[1], 'unknown command')
2242
def test_finish_bzr_subprocess_ignoring_retcode(self):
2243
"""finish_bzr_subprocess allows the exit code to be ignored."""
2244
process = StubProcess(err="unknown command", retcode=3)
2245
result = self.finish_bzr_subprocess(process, retcode=None)
2246
self.assertEqual('', result[0])
2247
self.assertContainsRe(result[1], 'unknown command')
2249
def test_finish_subprocess_with_unexpected_retcode(self):
2250
"""finish_bzr_subprocess raises self.failureException if the retcode is
2251
not the expected one.
2253
process = StubProcess(err="unknown command", retcode=3)
2254
self.assertRaises(self.failureException, self.finish_bzr_subprocess,
2258
class _DontSpawnProcess(Exception):
2259
"""A simple exception which just allows us to skip unnecessary steps"""
2262
class TestStartBzrSubProcess(tests.TestCase):
2264
def check_popen_state(self):
2265
"""Replace to make assertions when popen is called."""
2267
def _popen(self, *args, **kwargs):
2268
"""Record the command that is run, so that we can ensure it is correct"""
2269
self.check_popen_state()
2270
self._popen_args = args
2271
self._popen_kwargs = kwargs
2272
raise _DontSpawnProcess()
2274
def test_run_bzr_subprocess_no_plugins(self):
2275
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [])
2276
command = self._popen_args[0]
2277
self.assertEqual(sys.executable, command[0])
2278
self.assertEqual(self.get_bzr_path(), command[1])
2279
self.assertEqual(['--no-plugins'], command[2:])
2281
def test_allow_plugins(self):
2282
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2284
command = self._popen_args[0]
2285
self.assertEqual([], command[2:])
2287
def test_set_env(self):
2288
self.failIf('EXISTANT_ENV_VAR' in os.environ)
2290
def check_environment():
2291
self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2292
self.check_popen_state = check_environment
2293
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2294
env_changes={'EXISTANT_ENV_VAR':'set variable'})
2295
# not set in theparent
2296
self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2298
def test_run_bzr_subprocess_env_del(self):
2299
"""run_bzr_subprocess can remove environment variables too."""
2300
self.failIf('EXISTANT_ENV_VAR' in os.environ)
2301
def check_environment():
2302
self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2303
os.environ['EXISTANT_ENV_VAR'] = 'set variable'
2304
self.check_popen_state = check_environment
2305
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2306
env_changes={'EXISTANT_ENV_VAR':None})
2307
# Still set in parent
2308
self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2309
del os.environ['EXISTANT_ENV_VAR']
2311
def test_env_del_missing(self):
2312
self.failIf('NON_EXISTANT_ENV_VAR' in os.environ)
2313
def check_environment():
2314
self.assertFalse('NON_EXISTANT_ENV_VAR' in os.environ)
2315
self.check_popen_state = check_environment
2316
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2317
env_changes={'NON_EXISTANT_ENV_VAR':None})
2319
def test_working_dir(self):
2320
"""Test that we can specify the working dir for the child"""
2321
orig_getcwd = osutils.getcwd
2322
orig_chdir = os.chdir
2330
osutils.getcwd = getcwd
2332
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2335
osutils.getcwd = orig_getcwd
2337
os.chdir = orig_chdir
2338
self.assertEqual(['foo', 'current'], chdirs)
2341
class TestActuallyStartBzrSubprocess(tests.TestCaseWithTransport):
2342
"""Tests that really need to do things with an external bzr."""
2344
def test_start_and_stop_bzr_subprocess_send_signal(self):
2345
"""finish_bzr_subprocess raises self.failureException if the retcode is
2346
not the expected one.
2348
self.disable_missing_extensions_warning()
2349
process = self.start_bzr_subprocess(['wait-until-signalled'],
2350
skip_if_plan_to_signal=True)
2351
self.assertEqual('running\n', process.stdout.readline())
2352
result = self.finish_bzr_subprocess(process, send_signal=signal.SIGINT,
2354
self.assertEqual('', result[0])
2355
self.assertEqual('bzr: interrupted\n', result[1])
2358
class TestFeature(tests.TestCase):
1573
2360
def test_caching(self):
1574
2361
"""Feature._probe is called by the feature at most once."""
1575
class InstrumentedFeature(Feature):
2362
class InstrumentedFeature(tests.Feature):
1576
2363
def __init__(self):
1577
Feature.__init__(self)
2364
super(InstrumentedFeature, self).__init__()
1578
2365
self.calls = []
1579
2366
def _probe(self):
1580
2367
self.calls.append('_probe')
1596
2383
def test_default_str(self):
1597
2384
"""Feature.__str__ should default to __class__.__name__."""
1598
class NamedFeature(Feature):
2385
class NamedFeature(tests.Feature):
1600
2387
feature = NamedFeature()
1601
2388
self.assertEqual('NamedFeature', str(feature))
1604
class TestUnavailableFeature(TestCase):
2391
class TestUnavailableFeature(tests.TestCase):
1606
2393
def test_access_feature(self):
1608
exception = UnavailableFeature(feature)
2394
feature = tests.Feature()
2395
exception = tests.UnavailableFeature(feature)
1609
2396
self.assertIs(feature, exception.args[0])
1612
class TestSelftestFiltering(TestCase):
2399
simple_thunk_feature = tests._CompatabilityThunkFeature(
2400
deprecated_in((2, 1, 0)),
2401
'bzrlib.tests.test_selftest',
2402
'simple_thunk_feature','UnicodeFilename',
2403
replacement_module='bzrlib.tests'
2406
class Test_CompatibilityFeature(tests.TestCase):
2408
def test_does_thunk(self):
2409
res = self.callDeprecated(
2410
['bzrlib.tests.test_selftest.simple_thunk_feature was deprecated'
2411
' in version 2.1.0. Use bzrlib.tests.UnicodeFilename instead.'],
2412
simple_thunk_feature.available)
2413
self.assertEqual(tests.UnicodeFilename.available(), res)
2416
class TestModuleAvailableFeature(tests.TestCase):
2418
def test_available_module(self):
2419
feature = tests.ModuleAvailableFeature('bzrlib.tests')
2420
self.assertEqual('bzrlib.tests', feature.module_name)
2421
self.assertEqual('bzrlib.tests', str(feature))
2422
self.assertTrue(feature.available())
2423
self.assertIs(tests, feature.module)
2425
def test_unavailable_module(self):
2426
feature = tests.ModuleAvailableFeature('bzrlib.no_such_module_exists')
2427
self.assertEqual('bzrlib.no_such_module_exists', str(feature))
2428
self.assertFalse(feature.available())
2429
self.assertIs(None, feature.module)
2432
class TestSelftestFiltering(tests.TestCase):
1614
2434
def setUp(self):
2435
tests.TestCase.setUp(self)
1615
2436
self.suite = TestUtil.TestSuite()
1616
2437
self.loader = TestUtil.TestLoader()
1617
self.suite.addTest(self.loader.loadTestsFromModuleNames([
1618
'bzrlib.tests.test_selftest']))
1619
self.all_names = [t.id() for t in iter_suite_tests(self.suite)]
2438
self.suite.addTest(self.loader.loadTestsFromModule(
2439
sys.modules['bzrlib.tests.test_selftest']))
2440
self.all_names = _test_ids(self.suite)
2442
def test_condition_id_re(self):
2443
test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2444
'test_condition_id_re')
2445
filtered_suite = tests.filter_suite_by_condition(
2446
self.suite, tests.condition_id_re('test_condition_id_re'))
2447
self.assertEqual([test_name], _test_ids(filtered_suite))
2449
def test_condition_id_in_list(self):
2450
test_names = ['bzrlib.tests.test_selftest.TestSelftestFiltering.'
2451
'test_condition_id_in_list']
2452
id_list = tests.TestIdList(test_names)
2453
filtered_suite = tests.filter_suite_by_condition(
2454
self.suite, tests.condition_id_in_list(id_list))
2455
my_pattern = 'TestSelftestFiltering.*test_condition_id_in_list'
2456
re_filtered = tests.filter_suite_by_re(self.suite, my_pattern)
2457
self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
2459
def test_condition_id_startswith(self):
2460
klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
2461
start1 = klass + 'test_condition_id_starts'
2462
start2 = klass + 'test_condition_id_in'
2463
test_names = [ klass + 'test_condition_id_in_list',
2464
klass + 'test_condition_id_startswith',
2466
filtered_suite = tests.filter_suite_by_condition(
2467
self.suite, tests.condition_id_startswith([start1, start2]))
2468
self.assertEqual(test_names, _test_ids(filtered_suite))
2470
def test_condition_isinstance(self):
2471
filtered_suite = tests.filter_suite_by_condition(
2472
self.suite, tests.condition_isinstance(self.__class__))
2473
class_pattern = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
2474
re_filtered = tests.filter_suite_by_re(self.suite, class_pattern)
2475
self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
2477
def test_exclude_tests_by_condition(self):
2478
excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2479
'test_exclude_tests_by_condition')
2480
filtered_suite = tests.exclude_tests_by_condition(self.suite,
2481
lambda x:x.id() == excluded_name)
2482
self.assertEqual(len(self.all_names) - 1,
2483
filtered_suite.countTestCases())
2484
self.assertFalse(excluded_name in _test_ids(filtered_suite))
2485
remaining_names = list(self.all_names)
2486
remaining_names.remove(excluded_name)
2487
self.assertEqual(remaining_names, _test_ids(filtered_suite))
2489
def test_exclude_tests_by_re(self):
2490
self.all_names = _test_ids(self.suite)
2491
filtered_suite = tests.exclude_tests_by_re(self.suite,
2492
'exclude_tests_by_re')
2493
excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2494
'test_exclude_tests_by_re')
2495
self.assertEqual(len(self.all_names) - 1,
2496
filtered_suite.countTestCases())
2497
self.assertFalse(excluded_name in _test_ids(filtered_suite))
2498
remaining_names = list(self.all_names)
2499
remaining_names.remove(excluded_name)
2500
self.assertEqual(remaining_names, _test_ids(filtered_suite))
2502
def test_filter_suite_by_condition(self):
2503
test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2504
'test_filter_suite_by_condition')
2505
filtered_suite = tests.filter_suite_by_condition(self.suite,
2506
lambda x:x.id() == test_name)
2507
self.assertEqual([test_name], _test_ids(filtered_suite))
1621
2509
def test_filter_suite_by_re(self):
1622
filtered_suite = filter_suite_by_re(self.suite, 'test_filter')
1623
filtered_names = [t.id() for t in iter_suite_tests(filtered_suite)]
2510
filtered_suite = tests.filter_suite_by_re(self.suite,
2511
'test_filter_suite_by_r')
2512
filtered_names = _test_ids(filtered_suite)
1624
2513
self.assertEqual(filtered_names, ['bzrlib.tests.test_selftest.'
1625
2514
'TestSelftestFiltering.test_filter_suite_by_re'])
1627
def test_sort_suite_by_re(self):
1628
sorted_suite = sort_suite_by_re(self.suite, 'test_filter')
1629
sorted_names = [t.id() for t in iter_suite_tests(sorted_suite)]
1630
self.assertEqual(sorted_names[0], 'bzrlib.tests.test_selftest.'
1631
'TestSelftestFiltering.test_filter_suite_by_re')
1632
self.assertEquals(sorted(self.all_names), sorted(sorted_names))
1635
class TestCheckInventoryShape(TestCaseWithTransport):
2516
def test_filter_suite_by_id_list(self):
2517
test_list = ['bzrlib.tests.test_selftest.'
2518
'TestSelftestFiltering.test_filter_suite_by_id_list']
2519
filtered_suite = tests.filter_suite_by_id_list(
2520
self.suite, tests.TestIdList(test_list))
2521
filtered_names = _test_ids(filtered_suite)
2524
['bzrlib.tests.test_selftest.'
2525
'TestSelftestFiltering.test_filter_suite_by_id_list'])
2527
def test_filter_suite_by_id_startswith(self):
2528
# By design this test may fail if another test is added whose name also
2529
# begins with one of the start value used.
2530
klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
2531
start1 = klass + 'test_filter_suite_by_id_starts'
2532
start2 = klass + 'test_filter_suite_by_id_li'
2533
test_list = [klass + 'test_filter_suite_by_id_list',
2534
klass + 'test_filter_suite_by_id_startswith',
2536
filtered_suite = tests.filter_suite_by_id_startswith(
2537
self.suite, [start1, start2])
2540
_test_ids(filtered_suite),
2543
def test_preserve_input(self):
2544
# NB: Surely this is something in the stdlib to do this?
2545
self.assertTrue(self.suite is tests.preserve_input(self.suite))
2546
self.assertTrue("@#$" is tests.preserve_input("@#$"))
2548
def test_randomize_suite(self):
2549
randomized_suite = tests.randomize_suite(self.suite)
2550
# randomizing should not add or remove test names.
2551
self.assertEqual(set(_test_ids(self.suite)),
2552
set(_test_ids(randomized_suite)))
2553
# Technically, this *can* fail, because random.shuffle(list) can be
2554
# equal to list. Trying multiple times just pushes the frequency back.
2555
# As its len(self.all_names)!:1, the failure frequency should be low
2556
# enough to ignore. RBC 20071021.
2557
# It should change the order.
2558
self.assertNotEqual(self.all_names, _test_ids(randomized_suite))
2559
# But not the length. (Possibly redundant with the set test, but not
2561
self.assertEqual(len(self.all_names), len(_test_ids(randomized_suite)))
2563
def test_split_suit_by_condition(self):
2564
self.all_names = _test_ids(self.suite)
2565
condition = tests.condition_id_re('test_filter_suite_by_r')
2566
split_suite = tests.split_suite_by_condition(self.suite, condition)
2567
filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2568
'test_filter_suite_by_re')
2569
self.assertEqual([filtered_name], _test_ids(split_suite[0]))
2570
self.assertFalse(filtered_name in _test_ids(split_suite[1]))
2571
remaining_names = list(self.all_names)
2572
remaining_names.remove(filtered_name)
2573
self.assertEqual(remaining_names, _test_ids(split_suite[1]))
2575
def test_split_suit_by_re(self):
2576
self.all_names = _test_ids(self.suite)
2577
split_suite = tests.split_suite_by_re(self.suite,
2578
'test_filter_suite_by_r')
2579
filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2580
'test_filter_suite_by_re')
2581
self.assertEqual([filtered_name], _test_ids(split_suite[0]))
2582
self.assertFalse(filtered_name in _test_ids(split_suite[1]))
2583
remaining_names = list(self.all_names)
2584
remaining_names.remove(filtered_name)
2585
self.assertEqual(remaining_names, _test_ids(split_suite[1]))
2588
class TestCheckInventoryShape(tests.TestCaseWithTransport):
1637
2590
def test_check_inventory_shape(self):
1638
2591
files = ['a', 'b/', 'b/c']
1644
2597
self.check_inventory_shape(tree.inventory, files)
2602
class TestBlackboxSupport(tests.TestCase):
2603
"""Tests for testsuite blackbox features."""
2605
def test_run_bzr_failure_not_caught(self):
2606
# When we run bzr in blackbox mode, we want any unexpected errors to
2607
# propagate up to the test suite so that it can show the error in the
2608
# usual way, and we won't get a double traceback.
2609
e = self.assertRaises(
2611
self.run_bzr, ['assert-fail'])
2612
# make sure we got the real thing, not an error from somewhere else in
2613
# the test framework
2614
self.assertEquals('always fails', str(e))
2615
# check that there's no traceback in the test log
2616
self.assertNotContainsRe(self.get_log(), r'Traceback')
2618
def test_run_bzr_user_error_caught(self):
2619
# Running bzr in blackbox mode, normal/expected/user errors should be
2620
# caught in the regular way and turned into an error message plus exit
2622
transport_server = memory.MemoryServer()
2623
transport_server.start_server()
2624
self.addCleanup(transport_server.stop_server)
2625
url = transport_server.get_url()
2626
self.permit_url(url)
2627
out, err = self.run_bzr(["log", "%s/nonexistantpath" % url], retcode=3)
2628
self.assertEqual(out, '')
2629
self.assertContainsRe(err,
2630
'bzr: ERROR: Not a branch: ".*nonexistantpath/".\n')
2633
class TestTestLoader(tests.TestCase):
2634
"""Tests for the test loader."""
2636
def _get_loader_and_module(self):
2637
"""Gets a TestLoader and a module with one test in it."""
2638
loader = TestUtil.TestLoader()
2640
class Stub(tests.TestCase):
2643
class MyModule(object):
2645
MyModule.a_class = Stub
2647
return loader, module
2649
def test_module_no_load_tests_attribute_loads_classes(self):
2650
loader, module = self._get_loader_and_module()
2651
self.assertEqual(1, loader.loadTestsFromModule(module).countTestCases())
2653
def test_module_load_tests_attribute_gets_called(self):
2654
loader, module = self._get_loader_and_module()
2655
# 'self' is here because we're faking the module with a class. Regular
2656
# load_tests do not need that :)
2657
def load_tests(self, standard_tests, module, loader):
2658
result = loader.suiteClass()
2659
for test in tests.iter_suite_tests(standard_tests):
2660
result.addTests([test, test])
2662
# add a load_tests() method which multiplies the tests from the module.
2663
module.__class__.load_tests = load_tests
2664
self.assertEqual(2, loader.loadTestsFromModule(module).countTestCases())
2666
def test_load_tests_from_module_name_smoke_test(self):
2667
loader = TestUtil.TestLoader()
2668
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2669
self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
2672
def test_load_tests_from_module_name_with_bogus_module_name(self):
2673
loader = TestUtil.TestLoader()
2674
self.assertRaises(ImportError, loader.loadTestsFromModuleName, 'bogus')
2677
class TestTestIdList(tests.TestCase):
2679
def _create_id_list(self, test_list):
2680
return tests.TestIdList(test_list)
2682
def _create_suite(self, test_id_list):
2684
class Stub(tests.TestCase):
2688
def _create_test_id(id):
2691
suite = TestUtil.TestSuite()
2692
for id in test_id_list:
2693
t = Stub('test_foo')
2694
t.id = _create_test_id(id)
2698
def _test_ids(self, test_suite):
2699
"""Get the ids for the tests in a test suite."""
2700
return [t.id() for t in tests.iter_suite_tests(test_suite)]
2702
def test_empty_list(self):
2703
id_list = self._create_id_list([])
2704
self.assertEquals({}, id_list.tests)
2705
self.assertEquals({}, id_list.modules)
2707
def test_valid_list(self):
2708
id_list = self._create_id_list(
2709
['mod1.cl1.meth1', 'mod1.cl1.meth2',
2710
'mod1.func1', 'mod1.cl2.meth2',
2712
'mod1.submod2.cl1.meth1', 'mod1.submod2.cl2.meth2',
2714
self.assertTrue(id_list.refers_to('mod1'))
2715
self.assertTrue(id_list.refers_to('mod1.submod1'))
2716
self.assertTrue(id_list.refers_to('mod1.submod2'))
2717
self.assertTrue(id_list.includes('mod1.cl1.meth1'))
2718
self.assertTrue(id_list.includes('mod1.submod1'))
2719
self.assertTrue(id_list.includes('mod1.func1'))
2721
def test_bad_chars_in_params(self):
2722
id_list = self._create_id_list(['mod1.cl1.meth1(xx.yy)'])
2723
self.assertTrue(id_list.refers_to('mod1'))
2724
self.assertTrue(id_list.includes('mod1.cl1.meth1(xx.yy)'))
2726
def test_module_used(self):
2727
id_list = self._create_id_list(['mod.class.meth'])
2728
self.assertTrue(id_list.refers_to('mod'))
2729
self.assertTrue(id_list.refers_to('mod.class'))
2730
self.assertTrue(id_list.refers_to('mod.class.meth'))
2732
def test_test_suite_matches_id_list_with_unknown(self):
2733
loader = TestUtil.TestLoader()
2734
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2735
test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',
2737
not_found, duplicates = tests.suite_matches_id_list(suite, test_list)
2738
self.assertEquals(['bogus'], not_found)
2739
self.assertEquals([], duplicates)
2741
def test_suite_matches_id_list_with_duplicates(self):
2742
loader = TestUtil.TestLoader()
2743
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2744
dupes = loader.suiteClass()
2745
for test in tests.iter_suite_tests(suite):
2747
dupes.addTest(test) # Add it again
2749
test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',]
2750
not_found, duplicates = tests.suite_matches_id_list(
2752
self.assertEquals([], not_found)
2753
self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
2757
class TestTestSuite(tests.TestCase):
2759
def test__test_suite_testmod_names(self):
2760
# Test that a plausible list of test module names are returned
2761
# by _test_suite_testmod_names.
2762
test_list = tests._test_suite_testmod_names()
2764
'bzrlib.tests.blackbox',
2765
'bzrlib.tests.per_transport',
2766
'bzrlib.tests.test_selftest',
2770
def test__test_suite_modules_to_doctest(self):
2771
# Test that a plausible list of modules to doctest is returned
2772
# by _test_suite_modules_to_doctest.
2773
test_list = tests._test_suite_modules_to_doctest()
2775
# When docstrings are stripped, there are no modules to doctest
2776
self.assertEqual([], test_list)
2783
def test_test_suite(self):
2784
# test_suite() loads the entire test suite to operate. To avoid this
2785
# overhead, and yet still be confident that things are happening,
2786
# we temporarily replace two functions used by test_suite with
2787
# test doubles that supply a few sample tests to load, and check they
2790
def testmod_names():
2791
calls.append("testmod_names")
2793
'bzrlib.tests.blackbox.test_branch',
2794
'bzrlib.tests.per_transport',
2795
'bzrlib.tests.test_selftest',
2797
self.overrideAttr(tests, '_test_suite_testmod_names', testmod_names)
2799
calls.append("modules_to_doctest")
2802
return ['bzrlib.timestamp']
2803
self.overrideAttr(tests, '_test_suite_modules_to_doctest', doctests)
2804
expected_test_list = [
2806
'bzrlib.tests.blackbox.test_branch.TestBranch.test_branch',
2807
('bzrlib.tests.per_transport.TransportTests'
2808
'.test_abspath(LocalTransport,LocalURLServer)'),
2809
'bzrlib.tests.test_selftest.TestTestSuite.test_test_suite',
2810
# plugins can't be tested that way since selftest may be run with
2813
if __doc__ is not None:
2814
expected_test_list.extend([
2815
# modules_to_doctest
2816
'bzrlib.timestamp.format_highres_date',
2818
suite = tests.test_suite()
2819
self.assertEqual(set(["testmod_names", "modules_to_doctest"]),
2821
self.assertSubset(expected_test_list, _test_ids(suite))
2823
def test_test_suite_list_and_start(self):
2824
# We cannot test this at the same time as the main load, because we want
2825
# to know that starting_with == None works. So a second load is
2826
# incurred - note that the starting_with parameter causes a partial load
2827
# rather than a full load so this test should be pretty quick.
2828
test_list = ['bzrlib.tests.test_selftest.TestTestSuite.test_test_suite']
2829
suite = tests.test_suite(test_list,
2830
['bzrlib.tests.test_selftest.TestTestSuite'])
2831
# test_test_suite_list_and_start is not included
2832
self.assertEquals(test_list, _test_ids(suite))
2835
class TestLoadTestIdList(tests.TestCaseInTempDir):
2837
def _create_test_list_file(self, file_name, content):
2838
fl = open(file_name, 'wt')
2842
def test_load_unknown(self):
2843
self.assertRaises(errors.NoSuchFile,
2844
tests.load_test_id_list, 'i_do_not_exist')
2846
def test_load_test_list(self):
2847
test_list_fname = 'test.list'
2848
self._create_test_list_file(test_list_fname,
2849
'mod1.cl1.meth1\nmod2.cl2.meth2\n')
2850
tlist = tests.load_test_id_list(test_list_fname)
2851
self.assertEquals(2, len(tlist))
2852
self.assertEquals('mod1.cl1.meth1', tlist[0])
2853
self.assertEquals('mod2.cl2.meth2', tlist[1])
2855
def test_load_dirty_file(self):
2856
test_list_fname = 'test.list'
2857
self._create_test_list_file(test_list_fname,
2858
' mod1.cl1.meth1\n\nmod2.cl2.meth2 \n'
2860
tlist = tests.load_test_id_list(test_list_fname)
2861
self.assertEquals(4, len(tlist))
2862
self.assertEquals('mod1.cl1.meth1', tlist[0])
2863
self.assertEquals('', tlist[1])
2864
self.assertEquals('mod2.cl2.meth2', tlist[2])
2865
self.assertEquals('bar baz', tlist[3])
2868
class TestFilteredByModuleTestLoader(tests.TestCase):
2870
def _create_loader(self, test_list):
2871
id_filter = tests.TestIdList(test_list)
2872
loader = TestUtil.FilteredByModuleTestLoader(id_filter.refers_to)
2875
def test_load_tests(self):
2876
test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
2877
loader = self._create_loader(test_list)
2878
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2879
self.assertEquals(test_list, _test_ids(suite))
2881
def test_exclude_tests(self):
2882
test_list = ['bogus']
2883
loader = self._create_loader(test_list)
2884
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2885
self.assertEquals([], _test_ids(suite))
2888
class TestFilteredByNameStartTestLoader(tests.TestCase):
2890
def _create_loader(self, name_start):
2891
def needs_module(name):
2892
return name.startswith(name_start) or name_start.startswith(name)
2893
loader = TestUtil.FilteredByModuleTestLoader(needs_module)
2896
def test_load_tests(self):
2897
test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
2898
loader = self._create_loader('bzrlib.tests.test_samp')
2900
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2901
self.assertEquals(test_list, _test_ids(suite))
2903
def test_load_tests_inside_module(self):
2904
test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
2905
loader = self._create_loader('bzrlib.tests.test_sampler.Demo')
2907
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2908
self.assertEquals(test_list, _test_ids(suite))
2910
def test_exclude_tests(self):
2911
test_list = ['bogus']
2912
loader = self._create_loader('bogus')
2914
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2915
self.assertEquals([], _test_ids(suite))
2918
class TestTestPrefixRegistry(tests.TestCase):
2920
def _get_registry(self):
2921
tp_registry = tests.TestPrefixAliasRegistry()
2924
def test_register_new_prefix(self):
2925
tpr = self._get_registry()
2926
tpr.register('foo', 'fff.ooo.ooo')
2927
self.assertEquals('fff.ooo.ooo', tpr.get('foo'))
2929
def test_register_existing_prefix(self):
2930
tpr = self._get_registry()
2931
tpr.register('bar', 'bbb.aaa.rrr')
2932
tpr.register('bar', 'bBB.aAA.rRR')
2933
self.assertEquals('bbb.aaa.rrr', tpr.get('bar'))
2934
self.assertThat(self.get_log(),
2935
DocTestMatches("...bar...bbb.aaa.rrr...BB.aAA.rRR", ELLIPSIS))
2937
def test_get_unknown_prefix(self):
2938
tpr = self._get_registry()
2939
self.assertRaises(KeyError, tpr.get, 'I am not a prefix')
2941
def test_resolve_prefix(self):
2942
tpr = self._get_registry()
2943
tpr.register('bar', 'bb.aa.rr')
2944
self.assertEquals('bb.aa.rr', tpr.resolve_alias('bar'))
2946
def test_resolve_unknown_alias(self):
2947
tpr = self._get_registry()
2948
self.assertRaises(errors.BzrCommandError,
2949
tpr.resolve_alias, 'I am not a prefix')
2951
def test_predefined_prefixes(self):
2952
tpr = tests.test_prefix_alias_registry
2953
self.assertEquals('bzrlib', tpr.resolve_alias('bzrlib'))
2954
self.assertEquals('bzrlib.doc', tpr.resolve_alias('bd'))
2955
self.assertEquals('bzrlib.utils', tpr.resolve_alias('bu'))
2956
self.assertEquals('bzrlib.tests', tpr.resolve_alias('bt'))
2957
self.assertEquals('bzrlib.tests.blackbox', tpr.resolve_alias('bb'))
2958
self.assertEquals('bzrlib.plugins', tpr.resolve_alias('bp'))
2961
class TestRunSuite(tests.TestCase):
2963
def test_runner_class(self):
2964
"""run_suite accepts and uses a runner_class keyword argument."""
2965
class Stub(tests.TestCase):
2968
suite = Stub("test_foo")
2970
class MyRunner(tests.TextTestRunner):
2971
def run(self, test):
2973
return tests.ExtendedTestResult(self.stream, self.descriptions,
2975
tests.run_suite(suite, runner_class=MyRunner, stream=StringIO())
2976
self.assertLength(1, calls)