/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_selftest.py

  • Committer: Robert Collins
  • Date: 2009-03-16 05:05:52 UTC
  • mto: This revision was merged to the branch mainline in revision 4149.
  • Revision ID: robertc@robertcollins.net-20090316050552-hqcgx49ugew0facc
Add a refresh_data method on Repository allowing cleaner handling of insertions into RemoteRepository objects with _real_repository instances.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006, 2007, 2008 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
"""Tests for the test framework."""
 
18
 
 
19
import cStringIO
 
20
import os
 
21
from StringIO import StringIO
 
22
import sys
 
23
import time
 
24
import unittest
 
25
import warnings
 
26
 
 
27
import bzrlib
 
28
from bzrlib import (
 
29
    branchbuilder,
 
30
    bzrdir,
 
31
    errors,
 
32
    memorytree,
 
33
    osutils,
 
34
    remote,
 
35
    repository,
 
36
    symbol_versioning,
 
37
    tests,
 
38
    workingtree,
 
39
    )
 
40
from bzrlib.progress import _BaseProgressBar
 
41
from bzrlib.repofmt import (
 
42
    pack_repo,
 
43
    weaverepo,
 
44
    )
 
45
from bzrlib.symbol_versioning import (
 
46
    one_zero,
 
47
    zero_eleven,
 
48
    zero_ten,
 
49
    )
 
50
from bzrlib.tests import (
 
51
                          ChrootedTestCase,
 
52
                          ExtendedTestResult,
 
53
                          Feature,
 
54
                          KnownFailure,
 
55
                          TestCase,
 
56
                          TestCaseInTempDir,
 
57
                          TestCaseWithMemoryTransport,
 
58
                          TestCaseWithTransport,
 
59
                          TestNotApplicable,
 
60
                          TestSkipped,
 
61
                          TestSuite,
 
62
                          TestUtil,
 
63
                          TextTestRunner,
 
64
                          UnavailableFeature,
 
65
                          condition_id_re,
 
66
                          condition_isinstance,
 
67
                          exclude_tests_by_condition,
 
68
                          exclude_tests_by_re,
 
69
                          filter_suite_by_condition,
 
70
                          filter_suite_by_re,
 
71
                          iter_suite_tests,
 
72
                          preserve_input,
 
73
                          randomize_suite,
 
74
                          run_suite,
 
75
                          split_suite_by_condition,
 
76
                          split_suite_by_re,
 
77
                          test_lsprof,
 
78
                          test_suite,
 
79
                          )
 
80
from bzrlib.tests.test_sftp_transport import TestCaseWithSFTPServer
 
81
from bzrlib.tests.TestUtil import _load_module_by_name
 
82
from bzrlib.trace import note
 
83
from bzrlib.transport.memory import MemoryServer, MemoryTransport
 
84
from bzrlib.version import _get_bzr_source_tree
 
85
 
 
86
 
 
87
def _test_ids(test_suite):
 
88
    """Get the ids for the tests in a test suite."""
 
89
    return [t.id() for t in iter_suite_tests(test_suite)]
 
90
 
 
91
 
 
92
class SelftestTests(TestCase):
 
93
 
 
94
    def test_import_tests(self):
 
95
        mod = _load_module_by_name('bzrlib.tests.test_selftest')
 
96
        self.assertEqual(mod.SelftestTests, SelftestTests)
 
97
 
 
98
    def test_import_test_failure(self):
 
99
        self.assertRaises(ImportError,
 
100
                          _load_module_by_name,
 
101
                          'bzrlib.no-name-yet')
 
102
 
 
103
class MetaTestLog(TestCase):
 
104
 
 
105
    def test_logging(self):
 
106
        """Test logs are captured when a test fails."""
 
107
        self.log('a test message')
 
108
        self._log_file.flush()
 
109
        self.assertContainsRe(self._get_log(keep_log_file=True),
 
110
                              'a test message\n')
 
111
 
 
112
 
 
113
class TestUnicodeFilename(TestCase):
 
114
 
 
115
    def test_probe_passes(self):
 
116
        """UnicodeFilename._probe passes."""
 
117
        # We can't test much more than that because the behaviour depends
 
118
        # on the platform.
 
119
        tests.UnicodeFilename._probe()
 
120
 
 
121
 
 
122
class TestTreeShape(TestCaseInTempDir):
 
123
 
 
124
    def test_unicode_paths(self):
 
125
        self.requireFeature(tests.UnicodeFilename)
 
126
 
 
127
        filename = u'hell\u00d8'
 
128
        self.build_tree_contents([(filename, 'contents of hello')])
 
129
        self.failUnlessExists(filename)
 
130
 
 
131
 
 
132
class TestTransportScenarios(TestCase):
 
133
    """A group of tests that test the transport implementation adaption core.
 
134
 
 
135
    This is a meta test that the tests are applied to all available
 
136
    transports.
 
137
 
 
138
    This will be generalised in the future which is why it is in this
 
139
    test file even though it is specific to transport tests at the moment.
 
140
    """
 
141
 
 
142
    def test_get_transport_permutations(self):
 
143
        # this checks that get_test_permutations defined by the module is
 
144
        # called by the get_transport_test_permutations function.
 
145
        class MockModule(object):
 
146
            def get_test_permutations(self):
 
147
                return sample_permutation
 
148
        sample_permutation = [(1,2), (3,4)]
 
149
        from bzrlib.tests.test_transport_implementations \
 
150
            import get_transport_test_permutations
 
151
        self.assertEqual(sample_permutation,
 
152
                         get_transport_test_permutations(MockModule()))
 
153
 
 
154
    def test_scenarios_invlude_all_modules(self):
 
155
        # this checks that the scenario generator returns as many permutations
 
156
        # as there are in all the registered transport modules - we assume if
 
157
        # this matches its probably doing the right thing especially in
 
158
        # combination with the tests for setting the right classes below.
 
159
        from bzrlib.tests.test_transport_implementations \
 
160
            import transport_test_permutations
 
161
        from bzrlib.transport import _get_transport_modules
 
162
        modules = _get_transport_modules()
 
163
        permutation_count = 0
 
164
        for module in modules:
 
165
            try:
 
166
                permutation_count += len(reduce(getattr,
 
167
                    (module + ".get_test_permutations").split('.')[1:],
 
168
                     __import__(module))())
 
169
            except errors.DependencyNotPresent:
 
170
                pass
 
171
        scenarios = transport_test_permutations()
 
172
        self.assertEqual(permutation_count, len(scenarios))
 
173
 
 
174
    def test_scenarios_include_transport_class(self):
 
175
        # This test used to know about all the possible transports and the
 
176
        # order they were returned but that seems overly brittle (mbp
 
177
        # 20060307)
 
178
        from bzrlib.tests.test_transport_implementations \
 
179
            import transport_test_permutations
 
180
        scenarios = transport_test_permutations()
 
181
        # there are at least that many builtin transports
 
182
        self.assertTrue(len(scenarios) > 6)
 
183
        one_scenario = scenarios[0]
 
184
        self.assertIsInstance(one_scenario[0], str)
 
185
        self.assertTrue(issubclass(one_scenario[1]["transport_class"],
 
186
                                   bzrlib.transport.Transport))
 
187
        self.assertTrue(issubclass(one_scenario[1]["transport_server"],
 
188
                                   bzrlib.transport.Server))
 
189
 
 
190
 
 
191
class TestBranchScenarios(TestCase):
 
192
 
 
193
    def test_scenarios(self):
 
194
        # check that constructor parameters are passed through to the adapted
 
195
        # test.
 
196
        from bzrlib.tests.branch_implementations import make_scenarios
 
197
        server1 = "a"
 
198
        server2 = "b"
 
199
        formats = [("c", "C"), ("d", "D")]
 
200
        scenarios = make_scenarios(server1, server2, formats)
 
201
        self.assertEqual(2, len(scenarios))
 
202
        self.assertEqual([
 
203
            ('str',
 
204
             {'branch_format': 'c',
 
205
              'bzrdir_format': 'C',
 
206
              'transport_readonly_server': 'b',
 
207
              'transport_server': 'a'}),
 
208
            ('str',
 
209
             {'branch_format': 'd',
 
210
              'bzrdir_format': 'D',
 
211
              'transport_readonly_server': 'b',
 
212
              'transport_server': 'a'})],
 
213
            scenarios)
 
214
 
 
215
 
 
216
class TestBzrDirScenarios(TestCase):
 
217
 
 
218
    def test_scenarios(self):
 
219
        # check that constructor parameters are passed through to the adapted
 
220
        # test.
 
221
        from bzrlib.tests.bzrdir_implementations import make_scenarios
 
222
        vfs_factory = "v"
 
223
        server1 = "a"
 
224
        server2 = "b"
 
225
        formats = ["c", "d"]
 
226
        scenarios = make_scenarios(vfs_factory, server1, server2, formats)
 
227
        self.assertEqual([
 
228
            ('str',
 
229
             {'bzrdir_format': 'c',
 
230
              'transport_readonly_server': 'b',
 
231
              'transport_server': 'a',
 
232
              'vfs_transport_factory': 'v'}),
 
233
            ('str',
 
234
             {'bzrdir_format': 'd',
 
235
              'transport_readonly_server': 'b',
 
236
              'transport_server': 'a',
 
237
              'vfs_transport_factory': 'v'})],
 
238
            scenarios)
 
239
 
 
240
 
 
241
class TestRepositoryScenarios(TestCase):
 
242
 
 
243
    def test_formats_to_scenarios(self):
 
244
        from bzrlib.tests.per_repository import formats_to_scenarios
 
245
        formats = [("(c)", remote.RemoteRepositoryFormat()),
 
246
                   ("(d)", repository.format_registry.get(
 
247
                        'Bazaar pack repository format 1 (needs bzr 0.92)\n'))]
 
248
        no_vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
 
249
            None)
 
250
        vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
 
251
            vfs_transport_factory="vfs")
 
252
        # no_vfs generate scenarios without vfs_transport_factory
 
253
        self.assertEqual([
 
254
            ('RemoteRepositoryFormat(c)',
 
255
             {'bzrdir_format': remote.RemoteBzrDirFormat(),
 
256
              'repository_format': remote.RemoteRepositoryFormat(),
 
257
              'transport_readonly_server': 'readonly',
 
258
              'transport_server': 'server'}),
 
259
            ('RepositoryFormatKnitPack1(d)',
 
260
             {'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
 
261
              'repository_format': pack_repo.RepositoryFormatKnitPack1(),
 
262
              'transport_readonly_server': 'readonly',
 
263
              'transport_server': 'server'})],
 
264
            no_vfs_scenarios)
 
265
        self.assertEqual([
 
266
            ('RemoteRepositoryFormat(c)',
 
267
             {'bzrdir_format': remote.RemoteBzrDirFormat(),
 
268
              'repository_format': remote.RemoteRepositoryFormat(),
 
269
              'transport_readonly_server': 'readonly',
 
270
              'transport_server': 'server',
 
271
              'vfs_transport_factory': 'vfs'}),
 
272
            ('RepositoryFormatKnitPack1(d)',
 
273
             {'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
 
274
              'repository_format': pack_repo.RepositoryFormatKnitPack1(),
 
275
              'transport_readonly_server': 'readonly',
 
276
              'transport_server': 'server',
 
277
              'vfs_transport_factory': 'vfs'})],
 
278
            vfs_scenarios)
 
279
 
 
280
 
 
281
class TestTestScenarioApplication(TestCase):
 
282
    """Tests for the test adaption facilities."""
 
283
 
 
284
    def test_apply_scenario(self):
 
285
        from bzrlib.tests import apply_scenario
 
286
        input_test = TestTestScenarioApplication("test_apply_scenario")
 
287
        # setup two adapted tests
 
288
        adapted_test1 = apply_scenario(input_test,
 
289
            ("new id",
 
290
            {"bzrdir_format":"bzr_format",
 
291
             "repository_format":"repo_fmt",
 
292
             "transport_server":"transport_server",
 
293
             "transport_readonly_server":"readonly-server"}))
 
294
        adapted_test2 = apply_scenario(input_test,
 
295
            ("new id 2", {"bzrdir_format":None}))
 
296
        # input_test should have been altered.
 
297
        self.assertRaises(AttributeError, getattr, input_test, "bzrdir_format")
 
298
        # the new tests are mutually incompatible, ensuring it has
 
299
        # made new ones, and unspecified elements in the scenario
 
300
        # should not have been altered.
 
301
        self.assertEqual("bzr_format", adapted_test1.bzrdir_format)
 
302
        self.assertEqual("repo_fmt", adapted_test1.repository_format)
 
303
        self.assertEqual("transport_server", adapted_test1.transport_server)
 
304
        self.assertEqual("readonly-server",
 
305
            adapted_test1.transport_readonly_server)
 
306
        self.assertEqual(
 
307
            "bzrlib.tests.test_selftest.TestTestScenarioApplication."
 
308
            "test_apply_scenario(new id)",
 
309
            adapted_test1.id())
 
310
        self.assertEqual(None, adapted_test2.bzrdir_format)
 
311
        self.assertEqual(
 
312
            "bzrlib.tests.test_selftest.TestTestScenarioApplication."
 
313
            "test_apply_scenario(new id 2)",
 
314
            adapted_test2.id())
 
315
 
 
316
 
 
317
class TestInterRepositoryScenarios(TestCase):
 
318
 
 
319
    def test_scenarios(self):
 
320
        # check that constructor parameters are passed through to the adapted
 
321
        # test.
 
322
        from bzrlib.tests.interrepository_implementations import \
 
323
            make_scenarios
 
324
        server1 = "a"
 
325
        server2 = "b"
 
326
        formats = [(str, "C1", "C2"), (int, "D1", "D2")]
 
327
        scenarios = make_scenarios(server1, server2, formats)
 
328
        self.assertEqual([
 
329
            ('str,str,str',
 
330
             {'interrepo_class': str,
 
331
              'repository_format': 'C1',
 
332
              'repository_format_to': 'C2',
 
333
              'transport_readonly_server': 'b',
 
334
              'transport_server': 'a'}),
 
335
            ('int,str,str',
 
336
             {'interrepo_class': int,
 
337
              'repository_format': 'D1',
 
338
              'repository_format_to': 'D2',
 
339
              'transport_readonly_server': 'b',
 
340
              'transport_server': 'a'})],
 
341
            scenarios)
 
342
 
 
343
 
 
344
class TestWorkingTreeScenarios(TestCase):
 
345
 
 
346
    def test_scenarios(self):
 
347
        # check that constructor parameters are passed through to the adapted
 
348
        # test.
 
349
        from bzrlib.tests.workingtree_implementations \
 
350
            import make_scenarios
 
351
        server1 = "a"
 
352
        server2 = "b"
 
353
        formats = [workingtree.WorkingTreeFormat2(),
 
354
                   workingtree.WorkingTreeFormat3(),]
 
355
        scenarios = make_scenarios(server1, server2, formats)
 
356
        self.assertEqual([
 
357
            ('WorkingTreeFormat2',
 
358
             {'bzrdir_format': formats[0]._matchingbzrdir,
 
359
              'transport_readonly_server': 'b',
 
360
              'transport_server': 'a',
 
361
              'workingtree_format': formats[0]}),
 
362
            ('WorkingTreeFormat3',
 
363
             {'bzrdir_format': formats[1]._matchingbzrdir,
 
364
              'transport_readonly_server': 'b',
 
365
              'transport_server': 'a',
 
366
              'workingtree_format': formats[1]})],
 
367
            scenarios)
 
368
 
 
369
 
 
370
class TestTreeScenarios(TestCase):
 
371
 
 
372
    def test_scenarios(self):
 
373
        # the tree implementation scenario generator is meant to setup one
 
374
        # instance for each working tree format, and one additional instance
 
375
        # that will use the default wt format, but create a revision tree for
 
376
        # the tests.  this means that the wt ones should have the
 
377
        # workingtree_to_test_tree attribute set to 'return_parameter' and the
 
378
        # revision one set to revision_tree_from_workingtree.
 
379
 
 
380
        from bzrlib.tests.tree_implementations import (
 
381
            _dirstate_tree_from_workingtree,
 
382
            make_scenarios,
 
383
            preview_tree_pre,
 
384
            preview_tree_post,
 
385
            return_parameter,
 
386
            revision_tree_from_workingtree
 
387
            )
 
388
        server1 = "a"
 
389
        server2 = "b"
 
390
        formats = [workingtree.WorkingTreeFormat2(),
 
391
                   workingtree.WorkingTreeFormat3(),]
 
392
        scenarios = make_scenarios(server1, server2, formats)
 
393
        self.assertEqual(7, len(scenarios))
 
394
        default_wt_format = workingtree.WorkingTreeFormat4._default_format
 
395
        wt4_format = workingtree.WorkingTreeFormat4()
 
396
        wt5_format = workingtree.WorkingTreeFormat5()
 
397
        expected_scenarios = [
 
398
            ('WorkingTreeFormat2',
 
399
             {'bzrdir_format': formats[0]._matchingbzrdir,
 
400
              'transport_readonly_server': 'b',
 
401
              'transport_server': 'a',
 
402
              'workingtree_format': formats[0],
 
403
              '_workingtree_to_test_tree': return_parameter,
 
404
              }),
 
405
            ('WorkingTreeFormat3',
 
406
             {'bzrdir_format': formats[1]._matchingbzrdir,
 
407
              'transport_readonly_server': 'b',
 
408
              'transport_server': 'a',
 
409
              'workingtree_format': formats[1],
 
410
              '_workingtree_to_test_tree': return_parameter,
 
411
             }),
 
412
            ('RevisionTree',
 
413
             {'_workingtree_to_test_tree': revision_tree_from_workingtree,
 
414
              'bzrdir_format': default_wt_format._matchingbzrdir,
 
415
              'transport_readonly_server': 'b',
 
416
              'transport_server': 'a',
 
417
              'workingtree_format': default_wt_format,
 
418
             }),
 
419
            ('DirStateRevisionTree,WT4',
 
420
             {'_workingtree_to_test_tree': _dirstate_tree_from_workingtree,
 
421
              'bzrdir_format': wt4_format._matchingbzrdir,
 
422
              'transport_readonly_server': 'b',
 
423
              'transport_server': 'a',
 
424
              'workingtree_format': wt4_format,
 
425
             }),
 
426
            ('DirStateRevisionTree,WT5',
 
427
             {'_workingtree_to_test_tree': _dirstate_tree_from_workingtree,
 
428
              'bzrdir_format': wt5_format._matchingbzrdir,
 
429
              'transport_readonly_server': 'b',
 
430
              'transport_server': 'a',
 
431
              'workingtree_format': wt5_format,
 
432
             }),
 
433
            ('PreviewTree',
 
434
             {'_workingtree_to_test_tree': preview_tree_pre,
 
435
              'bzrdir_format': default_wt_format._matchingbzrdir,
 
436
              'transport_readonly_server': 'b',
 
437
              'transport_server': 'a',
 
438
              'workingtree_format': default_wt_format}),
 
439
            ('PreviewTreePost',
 
440
             {'_workingtree_to_test_tree': preview_tree_post,
 
441
              'bzrdir_format': default_wt_format._matchingbzrdir,
 
442
              'transport_readonly_server': 'b',
 
443
              'transport_server': 'a',
 
444
              'workingtree_format': default_wt_format}),
 
445
             ]
 
446
        self.assertEqual(expected_scenarios, scenarios)
 
447
 
 
448
 
 
449
class TestInterTreeScenarios(TestCase):
 
450
    """A group of tests that test the InterTreeTestAdapter."""
 
451
 
 
452
    def test_scenarios(self):
 
453
        # check that constructor parameters are passed through to the adapted
 
454
        # test.
 
455
        # for InterTree tests we want the machinery to bring up two trees in
 
456
        # each instance: the base one, and the one we are interacting with.
 
457
        # because each optimiser can be direction specific, we need to test
 
458
        # each optimiser in its chosen direction.
 
459
        # unlike the TestProviderAdapter we dont want to automatically add a
 
460
        # parameterized one for WorkingTree - the optimisers will tell us what
 
461
        # ones to add.
 
462
        from bzrlib.tests.tree_implementations import (
 
463
            return_parameter,
 
464
            revision_tree_from_workingtree
 
465
            )
 
466
        from bzrlib.tests.intertree_implementations import (
 
467
            make_scenarios,
 
468
            )
 
469
        from bzrlib.workingtree import WorkingTreeFormat2, WorkingTreeFormat3
 
470
        input_test = TestInterTreeScenarios(
 
471
            "test_scenarios")
 
472
        server1 = "a"
 
473
        server2 = "b"
 
474
        format1 = WorkingTreeFormat2()
 
475
        format2 = WorkingTreeFormat3()
 
476
        formats = [("1", str, format1, format2, "converter1"),
 
477
            ("2", int, format2, format1, "converter2")]
 
478
        scenarios = make_scenarios(server1, server2, formats)
 
479
        self.assertEqual(2, len(scenarios))
 
480
        expected_scenarios = [
 
481
            ("1", {
 
482
                "bzrdir_format": format1._matchingbzrdir,
 
483
                "intertree_class": formats[0][1],
 
484
                "workingtree_format": formats[0][2],
 
485
                "workingtree_format_to": formats[0][3],
 
486
                "mutable_trees_to_test_trees": formats[0][4],
 
487
                "_workingtree_to_test_tree": return_parameter,
 
488
                "transport_server": server1,
 
489
                "transport_readonly_server": server2,
 
490
                }),
 
491
            ("2", {
 
492
                "bzrdir_format": format2._matchingbzrdir,
 
493
                "intertree_class": formats[1][1],
 
494
                "workingtree_format": formats[1][2],
 
495
                "workingtree_format_to": formats[1][3],
 
496
                "mutable_trees_to_test_trees": formats[1][4],
 
497
                "_workingtree_to_test_tree": return_parameter,
 
498
                "transport_server": server1,
 
499
                "transport_readonly_server": server2,
 
500
                }),
 
501
            ]
 
502
        self.assertEqual(scenarios, expected_scenarios)
 
503
 
 
504
 
 
505
class TestTestCaseInTempDir(TestCaseInTempDir):
 
506
 
 
507
    def test_home_is_not_working(self):
 
508
        self.assertNotEqual(self.test_dir, self.test_home_dir)
 
509
        cwd = osutils.getcwd()
 
510
        self.assertIsSameRealPath(self.test_dir, cwd)
 
511
        self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
 
512
 
 
513
    def test_assertEqualStat_equal(self):
 
514
        from bzrlib.tests.test_dirstate import _FakeStat
 
515
        self.build_tree(["foo"])
 
516
        real = os.lstat("foo")
 
517
        fake = _FakeStat(real.st_size, real.st_mtime, real.st_ctime,
 
518
            real.st_dev, real.st_ino, real.st_mode)
 
519
        self.assertEqualStat(real, fake)
 
520
 
 
521
    def test_assertEqualStat_notequal(self):
 
522
        self.build_tree(["foo", "bar"])
 
523
        self.assertRaises(AssertionError, self.assertEqualStat,
 
524
            os.lstat("foo"), os.lstat("bar"))
 
525
 
 
526
 
 
527
class TestTestCaseWithMemoryTransport(TestCaseWithMemoryTransport):
 
528
 
 
529
    def test_home_is_non_existant_dir_under_root(self):
 
530
        """The test_home_dir for TestCaseWithMemoryTransport is missing.
 
531
 
 
532
        This is because TestCaseWithMemoryTransport is for tests that do not
 
533
        need any disk resources: they should be hooked into bzrlib in such a
 
534
        way that no global settings are being changed by the test (only a
 
535
        few tests should need to do that), and having a missing dir as home is
 
536
        an effective way to ensure that this is the case.
 
537
        """
 
538
        self.assertIsSameRealPath(
 
539
            self.TEST_ROOT + "/MemoryTransportMissingHomeDir",
 
540
            self.test_home_dir)
 
541
        self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
 
542
 
 
543
    def test_cwd_is_TEST_ROOT(self):
 
544
        self.assertIsSameRealPath(self.test_dir, self.TEST_ROOT)
 
545
        cwd = osutils.getcwd()
 
546
        self.assertIsSameRealPath(self.test_dir, cwd)
 
547
 
 
548
    def test_make_branch_and_memory_tree(self):
 
549
        """In TestCaseWithMemoryTransport we should not make the branch on disk.
 
550
 
 
551
        This is hard to comprehensively robustly test, so we settle for making
 
552
        a branch and checking no directory was created at its relpath.
 
553
        """
 
554
        tree = self.make_branch_and_memory_tree('dir')
 
555
        # Guard against regression into MemoryTransport leaking
 
556
        # files to disk instead of keeping them in memory.
 
557
        self.failIf(osutils.lexists('dir'))
 
558
        self.assertIsInstance(tree, memorytree.MemoryTree)
 
559
 
 
560
    def test_make_branch_and_memory_tree_with_format(self):
 
561
        """make_branch_and_memory_tree should accept a format option."""
 
562
        format = bzrdir.BzrDirMetaFormat1()
 
563
        format.repository_format = weaverepo.RepositoryFormat7()
 
564
        tree = self.make_branch_and_memory_tree('dir', format=format)
 
565
        # Guard against regression into MemoryTransport leaking
 
566
        # files to disk instead of keeping them in memory.
 
567
        self.failIf(osutils.lexists('dir'))
 
568
        self.assertIsInstance(tree, memorytree.MemoryTree)
 
569
        self.assertEqual(format.repository_format.__class__,
 
570
            tree.branch.repository._format.__class__)
 
571
 
 
572
    def test_make_branch_builder(self):
 
573
        builder = self.make_branch_builder('dir')
 
574
        self.assertIsInstance(builder, branchbuilder.BranchBuilder)
 
575
        # Guard against regression into MemoryTransport leaking
 
576
        # files to disk instead of keeping them in memory.
 
577
        self.failIf(osutils.lexists('dir'))
 
578
 
 
579
    def test_make_branch_builder_with_format(self):
 
580
        # Use a repo layout that doesn't conform to a 'named' layout, to ensure
 
581
        # that the format objects are used.
 
582
        format = bzrdir.BzrDirMetaFormat1()
 
583
        repo_format = weaverepo.RepositoryFormat7()
 
584
        format.repository_format = repo_format
 
585
        builder = self.make_branch_builder('dir', format=format)
 
586
        the_branch = builder.get_branch()
 
587
        # Guard against regression into MemoryTransport leaking
 
588
        # files to disk instead of keeping them in memory.
 
589
        self.failIf(osutils.lexists('dir'))
 
590
        self.assertEqual(format.repository_format.__class__,
 
591
                         the_branch.repository._format.__class__)
 
592
        self.assertEqual(repo_format.get_format_string(),
 
593
                         self.get_transport().get_bytes(
 
594
                            'dir/.bzr/repository/format'))
 
595
 
 
596
    def test_make_branch_builder_with_format_name(self):
 
597
        builder = self.make_branch_builder('dir', format='knit')
 
598
        the_branch = builder.get_branch()
 
599
        # Guard against regression into MemoryTransport leaking
 
600
        # files to disk instead of keeping them in memory.
 
601
        self.failIf(osutils.lexists('dir'))
 
602
        dir_format = bzrdir.format_registry.make_bzrdir('knit')
 
603
        self.assertEqual(dir_format.repository_format.__class__,
 
604
                         the_branch.repository._format.__class__)
 
605
        self.assertEqual('Bazaar-NG Knit Repository Format 1',
 
606
                         self.get_transport().get_bytes(
 
607
                            'dir/.bzr/repository/format'))
 
608
 
 
609
    def test_safety_net(self):
 
610
        """No test should modify the safety .bzr directory.
 
611
 
 
612
        We just test that the _check_safety_net private method raises
 
613
        AssertionError, it's easier than building a test suite with the same
 
614
        test.
 
615
        """
 
616
        # Oops, a commit in the current directory (i.e. without local .bzr
 
617
        # directory) will crawl up the hierarchy to find a .bzr directory.
 
618
        self.run_bzr(['commit', '-mfoo', '--unchanged'])
 
619
        # But we have a safety net in place.
 
620
        self.assertRaises(AssertionError, self._check_safety_net)
 
621
 
 
622
 
 
623
class TestTestCaseWithTransport(TestCaseWithTransport):
 
624
    """Tests for the convenience functions TestCaseWithTransport introduces."""
 
625
 
 
626
    def test_get_readonly_url_none(self):
 
627
        from bzrlib.transport import get_transport
 
628
        from bzrlib.transport.memory import MemoryServer
 
629
        from bzrlib.transport.readonly import ReadonlyTransportDecorator
 
630
        self.vfs_transport_factory = MemoryServer
 
631
        self.transport_readonly_server = None
 
632
        # calling get_readonly_transport() constructs a decorator on the url
 
633
        # for the server
 
634
        url = self.get_readonly_url()
 
635
        url2 = self.get_readonly_url('foo/bar')
 
636
        t = get_transport(url)
 
637
        t2 = get_transport(url2)
 
638
        self.failUnless(isinstance(t, ReadonlyTransportDecorator))
 
639
        self.failUnless(isinstance(t2, ReadonlyTransportDecorator))
 
640
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
 
641
 
 
642
    def test_get_readonly_url_http(self):
 
643
        from bzrlib.tests.http_server import HttpServer
 
644
        from bzrlib.transport import get_transport
 
645
        from bzrlib.transport.local import LocalURLServer
 
646
        from bzrlib.transport.http import HttpTransportBase
 
647
        self.transport_server = LocalURLServer
 
648
        self.transport_readonly_server = HttpServer
 
649
        # calling get_readonly_transport() gives us a HTTP server instance.
 
650
        url = self.get_readonly_url()
 
651
        url2 = self.get_readonly_url('foo/bar')
 
652
        # the transport returned may be any HttpTransportBase subclass
 
653
        t = get_transport(url)
 
654
        t2 = get_transport(url2)
 
655
        self.failUnless(isinstance(t, HttpTransportBase))
 
656
        self.failUnless(isinstance(t2, HttpTransportBase))
 
657
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
 
658
 
 
659
    def test_is_directory(self):
 
660
        """Test assertIsDirectory assertion"""
 
661
        t = self.get_transport()
 
662
        self.build_tree(['a_dir/', 'a_file'], transport=t)
 
663
        self.assertIsDirectory('a_dir', t)
 
664
        self.assertRaises(AssertionError, self.assertIsDirectory, 'a_file', t)
 
665
        self.assertRaises(AssertionError, self.assertIsDirectory, 'not_here', t)
 
666
 
 
667
    def test_make_branch_builder(self):
 
668
        builder = self.make_branch_builder('dir')
 
669
        rev_id = builder.build_commit()
 
670
        self.failUnlessExists('dir')
 
671
        a_dir = bzrdir.BzrDir.open('dir')
 
672
        self.assertRaises(errors.NoWorkingTree, a_dir.open_workingtree)
 
673
        a_branch = a_dir.open_branch()
 
674
        builder_branch = builder.get_branch()
 
675
        self.assertEqual(a_branch.base, builder_branch.base)
 
676
        self.assertEqual((1, rev_id), builder_branch.last_revision_info())
 
677
        self.assertEqual((1, rev_id), a_branch.last_revision_info())
 
678
 
 
679
 
 
680
class TestTestCaseTransports(TestCaseWithTransport):
 
681
 
 
682
    def setUp(self):
 
683
        super(TestTestCaseTransports, self).setUp()
 
684
        self.vfs_transport_factory = MemoryServer
 
685
 
 
686
    def test_make_bzrdir_preserves_transport(self):
 
687
        t = self.get_transport()
 
688
        result_bzrdir = self.make_bzrdir('subdir')
 
689
        self.assertIsInstance(result_bzrdir.transport,
 
690
                              MemoryTransport)
 
691
        # should not be on disk, should only be in memory
 
692
        self.failIfExists('subdir')
 
693
 
 
694
 
 
695
class TestChrootedTest(ChrootedTestCase):
 
696
 
 
697
    def test_root_is_root(self):
 
698
        from bzrlib.transport import get_transport
 
699
        t = get_transport(self.get_readonly_url())
 
700
        url = t.base
 
701
        self.assertEqual(url, t.clone('..').base)
 
702
 
 
703
 
 
704
class MockProgress(_BaseProgressBar):
 
705
    """Progress-bar standin that records calls.
 
706
 
 
707
    Useful for testing pb using code.
 
708
    """
 
709
 
 
710
    def __init__(self):
 
711
        _BaseProgressBar.__init__(self)
 
712
        self.calls = []
 
713
 
 
714
    def tick(self):
 
715
        self.calls.append(('tick',))
 
716
 
 
717
    def update(self, msg=None, current=None, total=None):
 
718
        self.calls.append(('update', msg, current, total))
 
719
 
 
720
    def clear(self):
 
721
        self.calls.append(('clear',))
 
722
 
 
723
    def note(self, msg, *args):
 
724
        self.calls.append(('note', msg, args))
 
725
 
 
726
 
 
727
class TestTestResult(TestCase):
 
728
 
 
729
    def check_timing(self, test_case, expected_re):
 
730
        result = bzrlib.tests.TextTestResult(self._log_file,
 
731
                descriptions=0,
 
732
                verbosity=1,
 
733
                )
 
734
        test_case.run(result)
 
735
        timed_string = result._testTimeString(test_case)
 
736
        self.assertContainsRe(timed_string, expected_re)
 
737
 
 
738
    def test_test_reporting(self):
 
739
        class ShortDelayTestCase(TestCase):
 
740
            def test_short_delay(self):
 
741
                time.sleep(0.003)
 
742
            def test_short_benchmark(self):
 
743
                self.time(time.sleep, 0.003)
 
744
        self.check_timing(ShortDelayTestCase('test_short_delay'),
 
745
                          r"^ +[0-9]+ms$")
 
746
        # if a benchmark time is given, we want a x of y style result.
 
747
        self.check_timing(ShortDelayTestCase('test_short_benchmark'),
 
748
                          r"^ +[0-9]+ms/ +[0-9]+ms$")
 
749
 
 
750
    def test_unittest_reporting_unittest_class(self):
 
751
        # getting the time from a non-bzrlib test works ok
 
752
        class ShortDelayTestCase(unittest.TestCase):
 
753
            def test_short_delay(self):
 
754
                time.sleep(0.003)
 
755
        self.check_timing(ShortDelayTestCase('test_short_delay'),
 
756
                          r"^ +[0-9]+ms$")
 
757
 
 
758
    def test_assigned_benchmark_file_stores_date(self):
 
759
        output = StringIO()
 
760
        result = bzrlib.tests.TextTestResult(self._log_file,
 
761
                                        descriptions=0,
 
762
                                        verbosity=1,
 
763
                                        bench_history=output
 
764
                                        )
 
765
        output_string = output.getvalue()
 
766
        # if you are wondering about the regexp please read the comment in
 
767
        # test_bench_history (bzrlib.tests.test_selftest.TestRunner)
 
768
        # XXX: what comment?  -- Andrew Bennetts
 
769
        self.assertContainsRe(output_string, "--date [0-9.]+")
 
770
 
 
771
    def test_benchhistory_records_test_times(self):
 
772
        result_stream = StringIO()
 
773
        result = bzrlib.tests.TextTestResult(
 
774
            self._log_file,
 
775
            descriptions=0,
 
776
            verbosity=1,
 
777
            bench_history=result_stream
 
778
            )
 
779
 
 
780
        # we want profile a call and check that its test duration is recorded
 
781
        # make a new test instance that when run will generate a benchmark
 
782
        example_test_case = TestTestResult("_time_hello_world_encoding")
 
783
        # execute the test, which should succeed and record times
 
784
        example_test_case.run(result)
 
785
        lines = result_stream.getvalue().splitlines()
 
786
        self.assertEqual(2, len(lines))
 
787
        self.assertContainsRe(lines[1],
 
788
            " *[0-9]+ms bzrlib.tests.test_selftest.TestTestResult"
 
789
            "._time_hello_world_encoding")
 
790
 
 
791
    def _time_hello_world_encoding(self):
 
792
        """Profile two sleep calls
 
793
 
 
794
        This is used to exercise the test framework.
 
795
        """
 
796
        self.time(unicode, 'hello', errors='replace')
 
797
        self.time(unicode, 'world', errors='replace')
 
798
 
 
799
    def test_lsprofiling(self):
 
800
        """Verbose test result prints lsprof statistics from test cases."""
 
801
        self.requireFeature(test_lsprof.LSProfFeature)
 
802
        result_stream = StringIO()
 
803
        result = bzrlib.tests.VerboseTestResult(
 
804
            unittest._WritelnDecorator(result_stream),
 
805
            descriptions=0,
 
806
            verbosity=2,
 
807
            )
 
808
        # we want profile a call of some sort and check it is output by
 
809
        # addSuccess. We dont care about addError or addFailure as they
 
810
        # are not that interesting for performance tuning.
 
811
        # make a new test instance that when run will generate a profile
 
812
        example_test_case = TestTestResult("_time_hello_world_encoding")
 
813
        example_test_case._gather_lsprof_in_benchmarks = True
 
814
        # execute the test, which should succeed and record profiles
 
815
        example_test_case.run(result)
 
816
        # lsprofile_something()
 
817
        # if this worked we want
 
818
        # LSProf output for <built in function unicode> (['hello'], {'errors': 'replace'})
 
819
        #    CallCount    Recursive    Total(ms)   Inline(ms) module:lineno(function)
 
820
        # (the lsprof header)
 
821
        # ... an arbitrary number of lines
 
822
        # and the function call which is time.sleep.
 
823
        #           1        0            ???         ???       ???(sleep)
 
824
        # and then repeated but with 'world', rather than 'hello'.
 
825
        # this should appear in the output stream of our test result.
 
826
        output = result_stream.getvalue()
 
827
        self.assertContainsRe(output,
 
828
            r"LSProf output for <type 'unicode'>\(\('hello',\), {'errors': 'replace'}\)")
 
829
        self.assertContainsRe(output,
 
830
            r" *CallCount *Recursive *Total\(ms\) *Inline\(ms\) *module:lineno\(function\)\n")
 
831
        self.assertContainsRe(output,
 
832
            r"( +1 +0 +0\.\d+ +0\.\d+ +<method 'disable' of '_lsprof\.Profiler' objects>\n)?")
 
833
        self.assertContainsRe(output,
 
834
            r"LSProf output for <type 'unicode'>\(\('world',\), {'errors': 'replace'}\)\n")
 
835
 
 
836
    def test_known_failure(self):
 
837
        """A KnownFailure being raised should trigger several result actions."""
 
838
        class InstrumentedTestResult(ExtendedTestResult):
 
839
 
 
840
            def report_test_start(self, test): pass
 
841
            def report_known_failure(self, test, err):
 
842
                self._call = test, err
 
843
        result = InstrumentedTestResult(None, None, None, None)
 
844
        def test_function():
 
845
            raise KnownFailure('failed!')
 
846
        test = unittest.FunctionTestCase(test_function)
 
847
        test.run(result)
 
848
        # it should invoke 'report_known_failure'.
 
849
        self.assertEqual(2, len(result._call))
 
850
        self.assertEqual(test, result._call[0])
 
851
        self.assertEqual(KnownFailure, result._call[1][0])
 
852
        self.assertIsInstance(result._call[1][1], KnownFailure)
 
853
        # we dont introspec the traceback, if the rest is ok, it would be
 
854
        # exceptional for it not to be.
 
855
        # it should update the known_failure_count on the object.
 
856
        self.assertEqual(1, result.known_failure_count)
 
857
        # the result should be successful.
 
858
        self.assertTrue(result.wasSuccessful())
 
859
 
 
860
    def test_verbose_report_known_failure(self):
 
861
        # verbose test output formatting
 
862
        result_stream = StringIO()
 
863
        result = bzrlib.tests.VerboseTestResult(
 
864
            unittest._WritelnDecorator(result_stream),
 
865
            descriptions=0,
 
866
            verbosity=2,
 
867
            )
 
868
        test = self.get_passing_test()
 
869
        result.startTest(test)
 
870
        prefix = len(result_stream.getvalue())
 
871
        # the err parameter has the shape:
 
872
        # (class, exception object, traceback)
 
873
        # KnownFailures dont get their tracebacks shown though, so we
 
874
        # can skip that.
 
875
        err = (KnownFailure, KnownFailure('foo'), None)
 
876
        result.report_known_failure(test, err)
 
877
        output = result_stream.getvalue()[prefix:]
 
878
        lines = output.splitlines()
 
879
        self.assertContainsRe(lines[0], r'XFAIL *\d+ms$')
 
880
        self.assertEqual(lines[1], '    foo')
 
881
        self.assertEqual(2, len(lines))
 
882
 
 
883
    def test_text_report_known_failure(self):
 
884
        # text test output formatting
 
885
        pb = MockProgress()
 
886
        result = bzrlib.tests.TextTestResult(
 
887
            None,
 
888
            descriptions=0,
 
889
            verbosity=1,
 
890
            pb=pb,
 
891
            )
 
892
        test = self.get_passing_test()
 
893
        # this seeds the state to handle reporting the test.
 
894
        result.startTest(test)
 
895
        # the err parameter has the shape:
 
896
        # (class, exception object, traceback)
 
897
        # KnownFailures dont get their tracebacks shown though, so we
 
898
        # can skip that.
 
899
        err = (KnownFailure, KnownFailure('foo'), None)
 
900
        result.report_known_failure(test, err)
 
901
        self.assertEqual(
 
902
            [
 
903
            ('update', '[1 in 0s] passing_test', None, None),
 
904
            ('note', 'XFAIL: %s\n%s\n', ('passing_test', err[1]))
 
905
            ],
 
906
            pb.calls)
 
907
        # known_failures should be printed in the summary, so if we run a test
 
908
        # after there are some known failures, the update prefix should match
 
909
        # this.
 
910
        result.known_failure_count = 3
 
911
        test.run(result)
 
912
        self.assertEqual(
 
913
            [
 
914
            ('update', '[2 in 0s] passing_test', None, None),
 
915
            ],
 
916
            pb.calls[2:])
 
917
 
 
918
    def get_passing_test(self):
 
919
        """Return a test object that can't be run usefully."""
 
920
        def passing_test():
 
921
            pass
 
922
        return unittest.FunctionTestCase(passing_test)
 
923
 
 
924
    def test_add_not_supported(self):
 
925
        """Test the behaviour of invoking addNotSupported."""
 
926
        class InstrumentedTestResult(ExtendedTestResult):
 
927
            def report_test_start(self, test): pass
 
928
            def report_unsupported(self, test, feature):
 
929
                self._call = test, feature
 
930
        result = InstrumentedTestResult(None, None, None, None)
 
931
        test = SampleTestCase('_test_pass')
 
932
        feature = Feature()
 
933
        result.startTest(test)
 
934
        result.addNotSupported(test, feature)
 
935
        # it should invoke 'report_unsupported'.
 
936
        self.assertEqual(2, len(result._call))
 
937
        self.assertEqual(test, result._call[0])
 
938
        self.assertEqual(feature, result._call[1])
 
939
        # the result should be successful.
 
940
        self.assertTrue(result.wasSuccessful())
 
941
        # it should record the test against a count of tests not run due to
 
942
        # this feature.
 
943
        self.assertEqual(1, result.unsupported['Feature'])
 
944
        # and invoking it again should increment that counter
 
945
        result.addNotSupported(test, feature)
 
946
        self.assertEqual(2, result.unsupported['Feature'])
 
947
 
 
948
    def test_verbose_report_unsupported(self):
 
949
        # verbose test output formatting
 
950
        result_stream = StringIO()
 
951
        result = bzrlib.tests.VerboseTestResult(
 
952
            unittest._WritelnDecorator(result_stream),
 
953
            descriptions=0,
 
954
            verbosity=2,
 
955
            )
 
956
        test = self.get_passing_test()
 
957
        feature = Feature()
 
958
        result.startTest(test)
 
959
        prefix = len(result_stream.getvalue())
 
960
        result.report_unsupported(test, feature)
 
961
        output = result_stream.getvalue()[prefix:]
 
962
        lines = output.splitlines()
 
963
        self.assertEqual(lines, ['NODEP                   0ms', "    The feature 'Feature' is not available."])
 
964
 
 
965
    def test_text_report_unsupported(self):
 
966
        # text test output formatting
 
967
        pb = MockProgress()
 
968
        result = bzrlib.tests.TextTestResult(
 
969
            None,
 
970
            descriptions=0,
 
971
            verbosity=1,
 
972
            pb=pb,
 
973
            )
 
974
        test = self.get_passing_test()
 
975
        feature = Feature()
 
976
        # this seeds the state to handle reporting the test.
 
977
        result.startTest(test)
 
978
        result.report_unsupported(test, feature)
 
979
        # no output on unsupported features
 
980
        self.assertEqual(
 
981
            [('update', '[1 in 0s] passing_test', None, None)
 
982
            ],
 
983
            pb.calls)
 
984
        # the number of missing features should be printed in the progress
 
985
        # summary, so check for that.
 
986
        result.unsupported = {'foo':0, 'bar':0}
 
987
        test.run(result)
 
988
        self.assertEqual(
 
989
            [
 
990
            ('update', '[2 in 0s, 2 missing] passing_test', None, None),
 
991
            ],
 
992
            pb.calls[1:])
 
993
 
 
994
    def test_unavailable_exception(self):
 
995
        """An UnavailableFeature being raised should invoke addNotSupported."""
 
996
        class InstrumentedTestResult(ExtendedTestResult):
 
997
 
 
998
            def report_test_start(self, test): pass
 
999
            def addNotSupported(self, test, feature):
 
1000
                self._call = test, feature
 
1001
        result = InstrumentedTestResult(None, None, None, None)
 
1002
        feature = Feature()
 
1003
        def test_function():
 
1004
            raise UnavailableFeature(feature)
 
1005
        test = unittest.FunctionTestCase(test_function)
 
1006
        test.run(result)
 
1007
        # it should invoke 'addNotSupported'.
 
1008
        self.assertEqual(2, len(result._call))
 
1009
        self.assertEqual(test, result._call[0])
 
1010
        self.assertEqual(feature, result._call[1])
 
1011
        # and not count as an error
 
1012
        self.assertEqual(0, result.error_count)
 
1013
 
 
1014
    def test_strict_with_unsupported_feature(self):
 
1015
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
 
1016
                                             verbosity=1)
 
1017
        test = self.get_passing_test()
 
1018
        feature = "Unsupported Feature"
 
1019
        result.addNotSupported(test, feature)
 
1020
        self.assertFalse(result.wasStrictlySuccessful())
 
1021
        self.assertEqual(None, result._extractBenchmarkTime(test))
 
1022
 
 
1023
    def test_strict_with_known_failure(self):
 
1024
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
 
1025
                                             verbosity=1)
 
1026
        test = self.get_passing_test()
 
1027
        err = (KnownFailure, KnownFailure('foo'), None)
 
1028
        result._addKnownFailure(test, err)
 
1029
        self.assertFalse(result.wasStrictlySuccessful())
 
1030
        self.assertEqual(None, result._extractBenchmarkTime(test))
 
1031
 
 
1032
    def test_strict_with_success(self):
 
1033
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
 
1034
                                             verbosity=1)
 
1035
        test = self.get_passing_test()
 
1036
        result.addSuccess(test)
 
1037
        self.assertTrue(result.wasStrictlySuccessful())
 
1038
        self.assertEqual(None, result._extractBenchmarkTime(test))
 
1039
 
 
1040
 
 
1041
class TestUnicodeFilenameFeature(TestCase):
 
1042
 
 
1043
    def test_probe_passes(self):
 
1044
        """UnicodeFilenameFeature._probe passes."""
 
1045
        # We can't test much more than that because the behaviour depends
 
1046
        # on the platform.
 
1047
        tests.UnicodeFilenameFeature._probe()
 
1048
 
 
1049
 
 
1050
class TestRunner(TestCase):
 
1051
 
 
1052
    def dummy_test(self):
 
1053
        pass
 
1054
 
 
1055
    def run_test_runner(self, testrunner, test):
 
1056
        """Run suite in testrunner, saving global state and restoring it.
 
1057
 
 
1058
        This current saves and restores:
 
1059
        TestCaseInTempDir.TEST_ROOT
 
1060
 
 
1061
        There should be no tests in this file that use bzrlib.tests.TextTestRunner
 
1062
        without using this convenience method, because of our use of global state.
 
1063
        """
 
1064
        old_root = TestCaseInTempDir.TEST_ROOT
 
1065
        try:
 
1066
            TestCaseInTempDir.TEST_ROOT = None
 
1067
            return testrunner.run(test)
 
1068
        finally:
 
1069
            TestCaseInTempDir.TEST_ROOT = old_root
 
1070
 
 
1071
    def test_known_failure_failed_run(self):
 
1072
        # run a test that generates a known failure which should be printed in
 
1073
        # the final output when real failures occur.
 
1074
        def known_failure_test():
 
1075
            raise KnownFailure('failed')
 
1076
        test = unittest.TestSuite()
 
1077
        test.addTest(unittest.FunctionTestCase(known_failure_test))
 
1078
        def failing_test():
 
1079
            raise AssertionError('foo')
 
1080
        test.addTest(unittest.FunctionTestCase(failing_test))
 
1081
        stream = StringIO()
 
1082
        runner = TextTestRunner(stream=stream)
 
1083
        result = self.run_test_runner(runner, test)
 
1084
        lines = stream.getvalue().splitlines()
 
1085
        self.assertEqual([
 
1086
            '',
 
1087
            '======================================================================',
 
1088
            'FAIL: unittest.FunctionTestCase (failing_test)',
 
1089
            '----------------------------------------------------------------------',
 
1090
            'Traceback (most recent call last):',
 
1091
            '    raise AssertionError(\'foo\')',
 
1092
            'AssertionError: foo',
 
1093
            '',
 
1094
            '----------------------------------------------------------------------',
 
1095
            '',
 
1096
            'FAILED (failures=1, known_failure_count=1)'],
 
1097
            lines[0:5] + lines[6:10] + lines[11:])
 
1098
 
 
1099
    def test_known_failure_ok_run(self):
 
1100
        # run a test that generates a known failure which should be printed in the final output.
 
1101
        def known_failure_test():
 
1102
            raise KnownFailure('failed')
 
1103
        test = unittest.FunctionTestCase(known_failure_test)
 
1104
        stream = StringIO()
 
1105
        runner = TextTestRunner(stream=stream)
 
1106
        result = self.run_test_runner(runner, test)
 
1107
        self.assertContainsRe(stream.getvalue(),
 
1108
            '\n'
 
1109
            '-*\n'
 
1110
            'Ran 1 test in .*\n'
 
1111
            '\n'
 
1112
            'OK \\(known_failures=1\\)\n')
 
1113
 
 
1114
    def test_skipped_test(self):
 
1115
        # run a test that is skipped, and check the suite as a whole still
 
1116
        # succeeds.
 
1117
        # skipping_test must be hidden in here so it's not run as a real test
 
1118
        class SkippingTest(TestCase):
 
1119
            def skipping_test(self):
 
1120
                raise TestSkipped('test intentionally skipped')
 
1121
        runner = TextTestRunner(stream=self._log_file)
 
1122
        test = SkippingTest("skipping_test")
 
1123
        result = self.run_test_runner(runner, test)
 
1124
        self.assertTrue(result.wasSuccessful())
 
1125
 
 
1126
    def test_skipped_from_setup(self):
 
1127
        calls = []
 
1128
        class SkippedSetupTest(TestCase):
 
1129
 
 
1130
            def setUp(self):
 
1131
                calls.append('setUp')
 
1132
                self.addCleanup(self.cleanup)
 
1133
                raise TestSkipped('skipped setup')
 
1134
 
 
1135
            def test_skip(self):
 
1136
                self.fail('test reached')
 
1137
 
 
1138
            def cleanup(self):
 
1139
                calls.append('cleanup')
 
1140
 
 
1141
        runner = TextTestRunner(stream=self._log_file)
 
1142
        test = SkippedSetupTest('test_skip')
 
1143
        result = self.run_test_runner(runner, test)
 
1144
        self.assertTrue(result.wasSuccessful())
 
1145
        # Check if cleanup was called the right number of times.
 
1146
        self.assertEqual(['setUp', 'cleanup'], calls)
 
1147
 
 
1148
    def test_skipped_from_test(self):
 
1149
        calls = []
 
1150
        class SkippedTest(TestCase):
 
1151
 
 
1152
            def setUp(self):
 
1153
                calls.append('setUp')
 
1154
                self.addCleanup(self.cleanup)
 
1155
 
 
1156
            def test_skip(self):
 
1157
                raise TestSkipped('skipped test')
 
1158
 
 
1159
            def cleanup(self):
 
1160
                calls.append('cleanup')
 
1161
 
 
1162
        runner = TextTestRunner(stream=self._log_file)
 
1163
        test = SkippedTest('test_skip')
 
1164
        result = self.run_test_runner(runner, test)
 
1165
        self.assertTrue(result.wasSuccessful())
 
1166
        # Check if cleanup was called the right number of times.
 
1167
        self.assertEqual(['setUp', 'cleanup'], calls)
 
1168
 
 
1169
    def test_not_applicable(self):
 
1170
        # run a test that is skipped because it's not applicable
 
1171
        def not_applicable_test():
 
1172
            from bzrlib.tests import TestNotApplicable
 
1173
            raise TestNotApplicable('this test never runs')
 
1174
        out = StringIO()
 
1175
        runner = TextTestRunner(stream=out, verbosity=2)
 
1176
        test = unittest.FunctionTestCase(not_applicable_test)
 
1177
        result = self.run_test_runner(runner, test)
 
1178
        self._log_file.write(out.getvalue())
 
1179
        self.assertTrue(result.wasSuccessful())
 
1180
        self.assertTrue(result.wasStrictlySuccessful())
 
1181
        self.assertContainsRe(out.getvalue(),
 
1182
                r'(?m)not_applicable_test   * N/A')
 
1183
        self.assertContainsRe(out.getvalue(),
 
1184
                r'(?m)^    this test never runs')
 
1185
 
 
1186
    def test_not_applicable_demo(self):
 
1187
        # just so you can see it in the test output
 
1188
        raise TestNotApplicable('this test is just a demonstation')
 
1189
 
 
1190
    def test_unsupported_features_listed(self):
 
1191
        """When unsupported features are encountered they are detailed."""
 
1192
        class Feature1(Feature):
 
1193
            def _probe(self): return False
 
1194
        class Feature2(Feature):
 
1195
            def _probe(self): return False
 
1196
        # create sample tests
 
1197
        test1 = SampleTestCase('_test_pass')
 
1198
        test1._test_needs_features = [Feature1()]
 
1199
        test2 = SampleTestCase('_test_pass')
 
1200
        test2._test_needs_features = [Feature2()]
 
1201
        test = unittest.TestSuite()
 
1202
        test.addTest(test1)
 
1203
        test.addTest(test2)
 
1204
        stream = StringIO()
 
1205
        runner = TextTestRunner(stream=stream)
 
1206
        result = self.run_test_runner(runner, test)
 
1207
        lines = stream.getvalue().splitlines()
 
1208
        self.assertEqual([
 
1209
            'OK',
 
1210
            "Missing feature 'Feature1' skipped 1 tests.",
 
1211
            "Missing feature 'Feature2' skipped 1 tests.",
 
1212
            ],
 
1213
            lines[-3:])
 
1214
 
 
1215
    def test_bench_history(self):
 
1216
        # tests that the running the benchmark produces a history file
 
1217
        # containing a timestamp and the revision id of the bzrlib source which
 
1218
        # was tested.
 
1219
        workingtree = _get_bzr_source_tree()
 
1220
        test = TestRunner('dummy_test')
 
1221
        output = StringIO()
 
1222
        runner = TextTestRunner(stream=self._log_file, bench_history=output)
 
1223
        result = self.run_test_runner(runner, test)
 
1224
        output_string = output.getvalue()
 
1225
        self.assertContainsRe(output_string, "--date [0-9.]+")
 
1226
        if workingtree is not None:
 
1227
            revision_id = workingtree.get_parent_ids()[0]
 
1228
            self.assertEndsWith(output_string.rstrip(), revision_id)
 
1229
 
 
1230
    def assertLogDeleted(self, test):
 
1231
        log = test._get_log()
 
1232
        self.assertEqual("DELETED log file to reduce memory footprint", log)
 
1233
        self.assertEqual('', test._log_contents)
 
1234
        self.assertIs(None, test._log_file_name)
 
1235
 
 
1236
    def test_success_log_deleted(self):
 
1237
        """Successful tests have their log deleted"""
 
1238
 
 
1239
        class LogTester(TestCase):
 
1240
 
 
1241
            def test_success(self):
 
1242
                self.log('this will be removed\n')
 
1243
 
 
1244
        sio = cStringIO.StringIO()
 
1245
        runner = TextTestRunner(stream=sio)
 
1246
        test = LogTester('test_success')
 
1247
        result = self.run_test_runner(runner, test)
 
1248
 
 
1249
        self.assertLogDeleted(test)
 
1250
 
 
1251
    def test_skipped_log_deleted(self):
 
1252
        """Skipped tests have their log deleted"""
 
1253
 
 
1254
        class LogTester(TestCase):
 
1255
 
 
1256
            def test_skipped(self):
 
1257
                self.log('this will be removed\n')
 
1258
                raise tests.TestSkipped()
 
1259
 
 
1260
        sio = cStringIO.StringIO()
 
1261
        runner = TextTestRunner(stream=sio)
 
1262
        test = LogTester('test_skipped')
 
1263
        result = self.run_test_runner(runner, test)
 
1264
 
 
1265
        self.assertLogDeleted(test)
 
1266
 
 
1267
    def test_not_aplicable_log_deleted(self):
 
1268
        """Not applicable tests have their log deleted"""
 
1269
 
 
1270
        class LogTester(TestCase):
 
1271
 
 
1272
            def test_not_applicable(self):
 
1273
                self.log('this will be removed\n')
 
1274
                raise tests.TestNotApplicable()
 
1275
 
 
1276
        sio = cStringIO.StringIO()
 
1277
        runner = TextTestRunner(stream=sio)
 
1278
        test = LogTester('test_not_applicable')
 
1279
        result = self.run_test_runner(runner, test)
 
1280
 
 
1281
        self.assertLogDeleted(test)
 
1282
 
 
1283
    def test_known_failure_log_deleted(self):
 
1284
        """Know failure tests have their log deleted"""
 
1285
 
 
1286
        class LogTester(TestCase):
 
1287
 
 
1288
            def test_known_failure(self):
 
1289
                self.log('this will be removed\n')
 
1290
                raise tests.KnownFailure()
 
1291
 
 
1292
        sio = cStringIO.StringIO()
 
1293
        runner = TextTestRunner(stream=sio)
 
1294
        test = LogTester('test_known_failure')
 
1295
        result = self.run_test_runner(runner, test)
 
1296
 
 
1297
        self.assertLogDeleted(test)
 
1298
 
 
1299
    def test_fail_log_kept(self):
 
1300
        """Failed tests have their log kept"""
 
1301
 
 
1302
        class LogTester(TestCase):
 
1303
 
 
1304
            def test_fail(self):
 
1305
                self.log('this will be kept\n')
 
1306
                self.fail('this test fails')
 
1307
 
 
1308
        sio = cStringIO.StringIO()
 
1309
        runner = TextTestRunner(stream=sio)
 
1310
        test = LogTester('test_fail')
 
1311
        result = self.run_test_runner(runner, test)
 
1312
 
 
1313
        text = sio.getvalue()
 
1314
        self.assertContainsRe(text, 'this will be kept')
 
1315
        self.assertContainsRe(text, 'this test fails')
 
1316
 
 
1317
        log = test._get_log()
 
1318
        self.assertContainsRe(log, 'this will be kept')
 
1319
        self.assertEqual(log, test._log_contents)
 
1320
 
 
1321
    def test_error_log_kept(self):
 
1322
        """Tests with errors have their log kept"""
 
1323
 
 
1324
        class LogTester(TestCase):
 
1325
 
 
1326
            def test_error(self):
 
1327
                self.log('this will be kept\n')
 
1328
                raise ValueError('random exception raised')
 
1329
 
 
1330
        sio = cStringIO.StringIO()
 
1331
        runner = TextTestRunner(stream=sio)
 
1332
        test = LogTester('test_error')
 
1333
        result = self.run_test_runner(runner, test)
 
1334
 
 
1335
        text = sio.getvalue()
 
1336
        self.assertContainsRe(text, 'this will be kept')
 
1337
        self.assertContainsRe(text, 'random exception raised')
 
1338
 
 
1339
        log = test._get_log()
 
1340
        self.assertContainsRe(log, 'this will be kept')
 
1341
        self.assertEqual(log, test._log_contents)
 
1342
 
 
1343
 
 
1344
class SampleTestCase(TestCase):
 
1345
 
 
1346
    def _test_pass(self):
 
1347
        pass
 
1348
 
 
1349
class _TestException(Exception):
 
1350
    pass
 
1351
 
 
1352
class TestTestCase(TestCase):
 
1353
    """Tests that test the core bzrlib TestCase."""
 
1354
 
 
1355
    def test_assertLength_matches_empty(self):
 
1356
        a_list = []
 
1357
        self.assertLength(0, a_list)
 
1358
 
 
1359
    def test_assertLength_matches_nonempty(self):
 
1360
        a_list = [1, 2, 3]
 
1361
        self.assertLength(3, a_list)
 
1362
 
 
1363
    def test_assertLength_fails_different(self):
 
1364
        a_list = []
 
1365
        self.assertRaises(AssertionError, self.assertLength, 1, a_list)
 
1366
 
 
1367
    def test_assertLength_shows_sequence_in_failure(self):
 
1368
        a_list = [1, 2, 3]
 
1369
        exception = self.assertRaises(AssertionError, self.assertLength, 2,
 
1370
            a_list)
 
1371
        self.assertEqual('Incorrect length: wanted 2, got 3 for [1, 2, 3]',
 
1372
            exception.args[0])
 
1373
 
 
1374
    def test_debug_flags_sanitised(self):
 
1375
        """The bzrlib debug flags should be sanitised by setUp."""
 
1376
        if 'allow_debug' in tests.selftest_debug_flags:
 
1377
            raise TestNotApplicable(
 
1378
                '-Eallow_debug option prevents debug flag sanitisation')
 
1379
        # we could set something and run a test that will check
 
1380
        # it gets santised, but this is probably sufficient for now:
 
1381
        # if someone runs the test with -Dsomething it will error.
 
1382
        self.assertEqual(set(), bzrlib.debug.debug_flags)
 
1383
 
 
1384
    def change_selftest_debug_flags(self, new_flags):
 
1385
        orig_selftest_flags = tests.selftest_debug_flags
 
1386
        self.addCleanup(self._restore_selftest_debug_flags, orig_selftest_flags)
 
1387
        tests.selftest_debug_flags = set(new_flags)
 
1388
 
 
1389
    def _restore_selftest_debug_flags(self, flags):
 
1390
        tests.selftest_debug_flags = flags
 
1391
 
 
1392
    def test_allow_debug_flag(self):
 
1393
        """The -Eallow_debug flag prevents bzrlib.debug.debug_flags from being
 
1394
        sanitised (i.e. cleared) before running a test.
 
1395
        """
 
1396
        self.change_selftest_debug_flags(set(['allow_debug']))
 
1397
        bzrlib.debug.debug_flags = set(['a-flag'])
 
1398
        class TestThatRecordsFlags(TestCase):
 
1399
            def test_foo(nested_self):
 
1400
                self.flags = set(bzrlib.debug.debug_flags)
 
1401
        test = TestThatRecordsFlags('test_foo')
 
1402
        test.run(self.make_test_result())
 
1403
        self.assertEqual(set(['a-flag']), self.flags)
 
1404
 
 
1405
    def test_debug_flags_restored(self):
 
1406
        """The bzrlib debug flags should be restored to their original state
 
1407
        after the test was run, even if allow_debug is set.
 
1408
        """
 
1409
        self.change_selftest_debug_flags(set(['allow_debug']))
 
1410
        # Now run a test that modifies debug.debug_flags.
 
1411
        bzrlib.debug.debug_flags = set(['original-state'])
 
1412
        class TestThatModifiesFlags(TestCase):
 
1413
            def test_foo(self):
 
1414
                bzrlib.debug.debug_flags = set(['modified'])
 
1415
        test = TestThatModifiesFlags('test_foo')
 
1416
        test.run(self.make_test_result())
 
1417
        self.assertEqual(set(['original-state']), bzrlib.debug.debug_flags)
 
1418
 
 
1419
    def make_test_result(self):
 
1420
        return bzrlib.tests.TextTestResult(
 
1421
            self._log_file, descriptions=0, verbosity=1)
 
1422
 
 
1423
    def inner_test(self):
 
1424
        # the inner child test
 
1425
        note("inner_test")
 
1426
 
 
1427
    def outer_child(self):
 
1428
        # the outer child test
 
1429
        note("outer_start")
 
1430
        self.inner_test = TestTestCase("inner_child")
 
1431
        result = self.make_test_result()
 
1432
        self.inner_test.run(result)
 
1433
        note("outer finish")
 
1434
 
 
1435
    def test_trace_nesting(self):
 
1436
        # this tests that each test case nests its trace facility correctly.
 
1437
        # we do this by running a test case manually. That test case (A)
 
1438
        # should setup a new log, log content to it, setup a child case (B),
 
1439
        # which should log independently, then case (A) should log a trailer
 
1440
        # and return.
 
1441
        # we do two nested children so that we can verify the state of the
 
1442
        # logs after the outer child finishes is correct, which a bad clean
 
1443
        # up routine in tearDown might trigger a fault in our test with only
 
1444
        # one child, we should instead see the bad result inside our test with
 
1445
        # the two children.
 
1446
        # the outer child test
 
1447
        original_trace = bzrlib.trace._trace_file
 
1448
        outer_test = TestTestCase("outer_child")
 
1449
        result = self.make_test_result()
 
1450
        outer_test.run(result)
 
1451
        self.assertEqual(original_trace, bzrlib.trace._trace_file)
 
1452
 
 
1453
    def method_that_times_a_bit_twice(self):
 
1454
        # call self.time twice to ensure it aggregates
 
1455
        self.time(time.sleep, 0.007)
 
1456
        self.time(time.sleep, 0.007)
 
1457
 
 
1458
    def test_time_creates_benchmark_in_result(self):
 
1459
        """Test that the TestCase.time() method accumulates a benchmark time."""
 
1460
        sample_test = TestTestCase("method_that_times_a_bit_twice")
 
1461
        output_stream = StringIO()
 
1462
        result = bzrlib.tests.VerboseTestResult(
 
1463
            unittest._WritelnDecorator(output_stream),
 
1464
            descriptions=0,
 
1465
            verbosity=2,
 
1466
            num_tests=sample_test.countTestCases())
 
1467
        sample_test.run(result)
 
1468
        self.assertContainsRe(
 
1469
            output_stream.getvalue(),
 
1470
            r"\d+ms/ +\d+ms\n$")
 
1471
 
 
1472
    def test_hooks_sanitised(self):
 
1473
        """The bzrlib hooks should be sanitised by setUp."""
 
1474
        # Note this test won't fail with hooks that the core library doesn't
 
1475
        # use - but it trigger with a plugin that adds hooks, so its still a
 
1476
        # useful warning in that case.
 
1477
        self.assertEqual(bzrlib.branch.BranchHooks(),
 
1478
            bzrlib.branch.Branch.hooks)
 
1479
        self.assertEqual(bzrlib.smart.server.SmartServerHooks(),
 
1480
            bzrlib.smart.server.SmartTCPServer.hooks)
 
1481
        self.assertEqual(bzrlib.commands.CommandHooks(),
 
1482
            bzrlib.commands.Command.hooks)
 
1483
 
 
1484
    def test__gather_lsprof_in_benchmarks(self):
 
1485
        """When _gather_lsprof_in_benchmarks is on, accumulate profile data.
 
1486
 
 
1487
        Each self.time() call is individually and separately profiled.
 
1488
        """
 
1489
        self.requireFeature(test_lsprof.LSProfFeature)
 
1490
        # overrides the class member with an instance member so no cleanup
 
1491
        # needed.
 
1492
        self._gather_lsprof_in_benchmarks = True
 
1493
        self.time(time.sleep, 0.000)
 
1494
        self.time(time.sleep, 0.003)
 
1495
        self.assertEqual(2, len(self._benchcalls))
 
1496
        self.assertEqual((time.sleep, (0.000,), {}), self._benchcalls[0][0])
 
1497
        self.assertEqual((time.sleep, (0.003,), {}), self._benchcalls[1][0])
 
1498
        self.assertIsInstance(self._benchcalls[0][1], bzrlib.lsprof.Stats)
 
1499
        self.assertIsInstance(self._benchcalls[1][1], bzrlib.lsprof.Stats)
 
1500
 
 
1501
    def test_knownFailure(self):
 
1502
        """Self.knownFailure() should raise a KnownFailure exception."""
 
1503
        self.assertRaises(KnownFailure, self.knownFailure, "A Failure")
 
1504
 
 
1505
    def test_requireFeature_available(self):
 
1506
        """self.requireFeature(available) is a no-op."""
 
1507
        class Available(Feature):
 
1508
            def _probe(self):return True
 
1509
        feature = Available()
 
1510
        self.requireFeature(feature)
 
1511
 
 
1512
    def test_requireFeature_unavailable(self):
 
1513
        """self.requireFeature(unavailable) raises UnavailableFeature."""
 
1514
        class Unavailable(Feature):
 
1515
            def _probe(self):return False
 
1516
        feature = Unavailable()
 
1517
        self.assertRaises(UnavailableFeature, self.requireFeature, feature)
 
1518
 
 
1519
    def test_run_no_parameters(self):
 
1520
        test = SampleTestCase('_test_pass')
 
1521
        test.run()
 
1522
 
 
1523
    def test_run_enabled_unittest_result(self):
 
1524
        """Test we revert to regular behaviour when the test is enabled."""
 
1525
        test = SampleTestCase('_test_pass')
 
1526
        class EnabledFeature(object):
 
1527
            def available(self):
 
1528
                return True
 
1529
        test._test_needs_features = [EnabledFeature()]
 
1530
        result = unittest.TestResult()
 
1531
        test.run(result)
 
1532
        self.assertEqual(1, result.testsRun)
 
1533
        self.assertEqual([], result.errors)
 
1534
        self.assertEqual([], result.failures)
 
1535
 
 
1536
    def test_run_disabled_unittest_result(self):
 
1537
        """Test our compatability for disabled tests with unittest results."""
 
1538
        test = SampleTestCase('_test_pass')
 
1539
        class DisabledFeature(object):
 
1540
            def available(self):
 
1541
                return False
 
1542
        test._test_needs_features = [DisabledFeature()]
 
1543
        result = unittest.TestResult()
 
1544
        test.run(result)
 
1545
        self.assertEqual(1, result.testsRun)
 
1546
        self.assertEqual([], result.errors)
 
1547
        self.assertEqual([], result.failures)
 
1548
 
 
1549
    def test_run_disabled_supporting_result(self):
 
1550
        """Test disabled tests behaviour with support aware results."""
 
1551
        test = SampleTestCase('_test_pass')
 
1552
        class DisabledFeature(object):
 
1553
            def available(self):
 
1554
                return False
 
1555
        the_feature = DisabledFeature()
 
1556
        test._test_needs_features = [the_feature]
 
1557
        class InstrumentedTestResult(unittest.TestResult):
 
1558
            def __init__(self):
 
1559
                unittest.TestResult.__init__(self)
 
1560
                self.calls = []
 
1561
            def startTest(self, test):
 
1562
                self.calls.append(('startTest', test))
 
1563
            def stopTest(self, test):
 
1564
                self.calls.append(('stopTest', test))
 
1565
            def addNotSupported(self, test, feature):
 
1566
                self.calls.append(('addNotSupported', test, feature))
 
1567
        result = InstrumentedTestResult()
 
1568
        test.run(result)
 
1569
        self.assertEqual([
 
1570
            ('startTest', test),
 
1571
            ('addNotSupported', test, the_feature),
 
1572
            ('stopTest', test),
 
1573
            ],
 
1574
            result.calls)
 
1575
 
 
1576
    def test_assert_list_raises_on_generator(self):
 
1577
        def generator_which_will_raise():
 
1578
            # This will not raise until after the first yield
 
1579
            yield 1
 
1580
            raise _TestException()
 
1581
 
 
1582
        e = self.assertListRaises(_TestException, generator_which_will_raise)
 
1583
        self.assertIsInstance(e, _TestException)
 
1584
 
 
1585
        e = self.assertListRaises(Exception, generator_which_will_raise)
 
1586
        self.assertIsInstance(e, _TestException)
 
1587
 
 
1588
    def test_assert_list_raises_on_plain(self):
 
1589
        def plain_exception():
 
1590
            raise _TestException()
 
1591
            return []
 
1592
 
 
1593
        e = self.assertListRaises(_TestException, plain_exception)
 
1594
        self.assertIsInstance(e, _TestException)
 
1595
 
 
1596
        e = self.assertListRaises(Exception, plain_exception)
 
1597
        self.assertIsInstance(e, _TestException)
 
1598
 
 
1599
    def test_assert_list_raises_assert_wrong_exception(self):
 
1600
        class _NotTestException(Exception):
 
1601
            pass
 
1602
 
 
1603
        def wrong_exception():
 
1604
            raise _NotTestException()
 
1605
 
 
1606
        def wrong_exception_generator():
 
1607
            yield 1
 
1608
            yield 2
 
1609
            raise _NotTestException()
 
1610
 
 
1611
        # Wrong exceptions are not intercepted
 
1612
        self.assertRaises(_NotTestException,
 
1613
            self.assertListRaises, _TestException, wrong_exception)
 
1614
        self.assertRaises(_NotTestException,
 
1615
            self.assertListRaises, _TestException, wrong_exception_generator)
 
1616
 
 
1617
    def test_assert_list_raises_no_exception(self):
 
1618
        def success():
 
1619
            return []
 
1620
 
 
1621
        def success_generator():
 
1622
            yield 1
 
1623
            yield 2
 
1624
 
 
1625
        self.assertRaises(AssertionError,
 
1626
            self.assertListRaises, _TestException, success)
 
1627
 
 
1628
        self.assertRaises(AssertionError,
 
1629
            self.assertListRaises, _TestException, success_generator)
 
1630
 
 
1631
 
 
1632
@symbol_versioning.deprecated_function(zero_eleven)
 
1633
def sample_deprecated_function():
 
1634
    """A deprecated function to test applyDeprecated with."""
 
1635
    return 2
 
1636
 
 
1637
 
 
1638
def sample_undeprecated_function(a_param):
 
1639
    """A undeprecated function to test applyDeprecated with."""
 
1640
 
 
1641
 
 
1642
class ApplyDeprecatedHelper(object):
 
1643
    """A helper class for ApplyDeprecated tests."""
 
1644
 
 
1645
    @symbol_versioning.deprecated_method(zero_eleven)
 
1646
    def sample_deprecated_method(self, param_one):
 
1647
        """A deprecated method for testing with."""
 
1648
        return param_one
 
1649
 
 
1650
    def sample_normal_method(self):
 
1651
        """A undeprecated method."""
 
1652
 
 
1653
    @symbol_versioning.deprecated_method(zero_ten)
 
1654
    def sample_nested_deprecation(self):
 
1655
        return sample_deprecated_function()
 
1656
 
 
1657
 
 
1658
class TestExtraAssertions(TestCase):
 
1659
    """Tests for new test assertions in bzrlib test suite"""
 
1660
 
 
1661
    def test_assert_isinstance(self):
 
1662
        self.assertIsInstance(2, int)
 
1663
        self.assertIsInstance(u'', basestring)
 
1664
        self.assertRaises(AssertionError, self.assertIsInstance, None, int)
 
1665
        self.assertRaises(AssertionError, self.assertIsInstance, 23.3, int)
 
1666
 
 
1667
    def test_assertEndsWith(self):
 
1668
        self.assertEndsWith('foo', 'oo')
 
1669
        self.assertRaises(AssertionError, self.assertEndsWith, 'o', 'oo')
 
1670
 
 
1671
    def test_applyDeprecated_not_deprecated(self):
 
1672
        sample_object = ApplyDeprecatedHelper()
 
1673
        # calling an undeprecated callable raises an assertion
 
1674
        self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
 
1675
            sample_object.sample_normal_method)
 
1676
        self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
 
1677
            sample_undeprecated_function, "a param value")
 
1678
        # calling a deprecated callable (function or method) with the wrong
 
1679
        # expected deprecation fails.
 
1680
        self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
 
1681
            sample_object.sample_deprecated_method, "a param value")
 
1682
        self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
 
1683
            sample_deprecated_function)
 
1684
        # calling a deprecated callable (function or method) with the right
 
1685
        # expected deprecation returns the functions result.
 
1686
        self.assertEqual("a param value", self.applyDeprecated(zero_eleven,
 
1687
            sample_object.sample_deprecated_method, "a param value"))
 
1688
        self.assertEqual(2, self.applyDeprecated(zero_eleven,
 
1689
            sample_deprecated_function))
 
1690
        # calling a nested deprecation with the wrong deprecation version
 
1691
        # fails even if a deeper nested function was deprecated with the
 
1692
        # supplied version.
 
1693
        self.assertRaises(AssertionError, self.applyDeprecated,
 
1694
            zero_eleven, sample_object.sample_nested_deprecation)
 
1695
        # calling a nested deprecation with the right deprecation value
 
1696
        # returns the calls result.
 
1697
        self.assertEqual(2, self.applyDeprecated(zero_ten,
 
1698
            sample_object.sample_nested_deprecation))
 
1699
 
 
1700
    def test_callDeprecated(self):
 
1701
        def testfunc(be_deprecated, result=None):
 
1702
            if be_deprecated is True:
 
1703
                symbol_versioning.warn('i am deprecated', DeprecationWarning,
 
1704
                                       stacklevel=1)
 
1705
            return result
 
1706
        result = self.callDeprecated(['i am deprecated'], testfunc, True)
 
1707
        self.assertIs(None, result)
 
1708
        result = self.callDeprecated([], testfunc, False, 'result')
 
1709
        self.assertEqual('result', result)
 
1710
        self.callDeprecated(['i am deprecated'], testfunc, be_deprecated=True)
 
1711
        self.callDeprecated([], testfunc, be_deprecated=False)
 
1712
 
 
1713
 
 
1714
class TestWarningTests(TestCase):
 
1715
    """Tests for calling methods that raise warnings."""
 
1716
 
 
1717
    def test_callCatchWarnings(self):
 
1718
        def meth(a, b):
 
1719
            warnings.warn("this is your last warning")
 
1720
            return a + b
 
1721
        wlist, result = self.callCatchWarnings(meth, 1, 2)
 
1722
        self.assertEquals(3, result)
 
1723
        # would like just to compare them, but UserWarning doesn't implement
 
1724
        # eq well
 
1725
        w0, = wlist
 
1726
        self.assertIsInstance(w0, UserWarning)
 
1727
        self.assertEquals("this is your last warning", str(w0))
 
1728
 
 
1729
 
 
1730
class TestConvenienceMakers(TestCaseWithTransport):
 
1731
    """Test for the make_* convenience functions."""
 
1732
 
 
1733
    def test_make_branch_and_tree_with_format(self):
 
1734
        # we should be able to supply a format to make_branch_and_tree
 
1735
        self.make_branch_and_tree('a', format=bzrlib.bzrdir.BzrDirMetaFormat1())
 
1736
        self.make_branch_and_tree('b', format=bzrlib.bzrdir.BzrDirFormat6())
 
1737
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('a')._format,
 
1738
                              bzrlib.bzrdir.BzrDirMetaFormat1)
 
1739
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('b')._format,
 
1740
                              bzrlib.bzrdir.BzrDirFormat6)
 
1741
 
 
1742
    def test_make_branch_and_memory_tree(self):
 
1743
        # we should be able to get a new branch and a mutable tree from
 
1744
        # TestCaseWithTransport
 
1745
        tree = self.make_branch_and_memory_tree('a')
 
1746
        self.assertIsInstance(tree, bzrlib.memorytree.MemoryTree)
 
1747
 
 
1748
 
 
1749
class TestSFTPMakeBranchAndTree(TestCaseWithSFTPServer):
 
1750
 
 
1751
    def test_make_tree_for_sftp_branch(self):
 
1752
        """Transports backed by local directories create local trees."""
 
1753
 
 
1754
        tree = self.make_branch_and_tree('t1')
 
1755
        base = tree.bzrdir.root_transport.base
 
1756
        self.failIf(base.startswith('sftp'),
 
1757
                'base %r is on sftp but should be local' % base)
 
1758
        self.assertEquals(tree.bzrdir.root_transport,
 
1759
                tree.branch.bzrdir.root_transport)
 
1760
        self.assertEquals(tree.bzrdir.root_transport,
 
1761
                tree.branch.repository.bzrdir.root_transport)
 
1762
 
 
1763
 
 
1764
class TestSelftest(TestCase):
 
1765
    """Tests of bzrlib.tests.selftest."""
 
1766
 
 
1767
    def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
 
1768
        factory_called = []
 
1769
        def factory():
 
1770
            factory_called.append(True)
 
1771
            return TestSuite()
 
1772
        out = StringIO()
 
1773
        err = StringIO()
 
1774
        self.apply_redirected(out, err, None, bzrlib.tests.selftest,
 
1775
            test_suite_factory=factory)
 
1776
        self.assertEqual([True], factory_called)
 
1777
 
 
1778
 
 
1779
class TestKnownFailure(TestCase):
 
1780
 
 
1781
    def test_known_failure(self):
 
1782
        """Check that KnownFailure is defined appropriately."""
 
1783
        # a KnownFailure is an assertion error for compatability with unaware
 
1784
        # runners.
 
1785
        self.assertIsInstance(KnownFailure(""), AssertionError)
 
1786
 
 
1787
    def test_expect_failure(self):
 
1788
        try:
 
1789
            self.expectFailure("Doomed to failure", self.assertTrue, False)
 
1790
        except KnownFailure, e:
 
1791
            self.assertEqual('Doomed to failure', e.args[0])
 
1792
        try:
 
1793
            self.expectFailure("Doomed to failure", self.assertTrue, True)
 
1794
        except AssertionError, e:
 
1795
            self.assertEqual('Unexpected success.  Should have failed:'
 
1796
                             ' Doomed to failure', e.args[0])
 
1797
        else:
 
1798
            self.fail('Assertion not raised')
 
1799
 
 
1800
 
 
1801
class TestFeature(TestCase):
 
1802
 
 
1803
    def test_caching(self):
 
1804
        """Feature._probe is called by the feature at most once."""
 
1805
        class InstrumentedFeature(Feature):
 
1806
            def __init__(self):
 
1807
                Feature.__init__(self)
 
1808
                self.calls = []
 
1809
            def _probe(self):
 
1810
                self.calls.append('_probe')
 
1811
                return False
 
1812
        feature = InstrumentedFeature()
 
1813
        feature.available()
 
1814
        self.assertEqual(['_probe'], feature.calls)
 
1815
        feature.available()
 
1816
        self.assertEqual(['_probe'], feature.calls)
 
1817
 
 
1818
    def test_named_str(self):
 
1819
        """Feature.__str__ should thunk to feature_name()."""
 
1820
        class NamedFeature(Feature):
 
1821
            def feature_name(self):
 
1822
                return 'symlinks'
 
1823
        feature = NamedFeature()
 
1824
        self.assertEqual('symlinks', str(feature))
 
1825
 
 
1826
    def test_default_str(self):
 
1827
        """Feature.__str__ should default to __class__.__name__."""
 
1828
        class NamedFeature(Feature):
 
1829
            pass
 
1830
        feature = NamedFeature()
 
1831
        self.assertEqual('NamedFeature', str(feature))
 
1832
 
 
1833
 
 
1834
class TestUnavailableFeature(TestCase):
 
1835
 
 
1836
    def test_access_feature(self):
 
1837
        feature = Feature()
 
1838
        exception = UnavailableFeature(feature)
 
1839
        self.assertIs(feature, exception.args[0])
 
1840
 
 
1841
 
 
1842
class TestSelftestFiltering(TestCase):
 
1843
 
 
1844
    def setUp(self):
 
1845
        self.suite = TestUtil.TestSuite()
 
1846
        self.loader = TestUtil.TestLoader()
 
1847
        self.suite.addTest(self.loader.loadTestsFromModuleNames([
 
1848
            'bzrlib.tests.test_selftest']))
 
1849
        self.all_names = _test_ids(self.suite)
 
1850
 
 
1851
    def test_condition_id_re(self):
 
1852
        test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
1853
            'test_condition_id_re')
 
1854
        filtered_suite = filter_suite_by_condition(self.suite,
 
1855
            condition_id_re('test_condition_id_re'))
 
1856
        self.assertEqual([test_name], _test_ids(filtered_suite))
 
1857
 
 
1858
    def test_condition_id_in_list(self):
 
1859
        test_names = ['bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
1860
                      'test_condition_id_in_list']
 
1861
        id_list = tests.TestIdList(test_names)
 
1862
        filtered_suite = filter_suite_by_condition(
 
1863
            self.suite, tests.condition_id_in_list(id_list))
 
1864
        my_pattern = 'TestSelftestFiltering.*test_condition_id_in_list'
 
1865
        re_filtered = filter_suite_by_re(self.suite, my_pattern)
 
1866
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
 
1867
 
 
1868
    def test_condition_id_startswith(self):
 
1869
        klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
1870
        start1 = klass + 'test_condition_id_starts'
 
1871
        start2 = klass + 'test_condition_id_in'
 
1872
        test_names = [ klass + 'test_condition_id_in_list',
 
1873
                      klass + 'test_condition_id_startswith',
 
1874
                     ]
 
1875
        filtered_suite = filter_suite_by_condition(
 
1876
            self.suite, tests.condition_id_startswith([start1, start2]))
 
1877
        self.assertEqual(test_names, _test_ids(filtered_suite))
 
1878
 
 
1879
    def test_condition_isinstance(self):
 
1880
        filtered_suite = filter_suite_by_condition(self.suite,
 
1881
            condition_isinstance(self.__class__))
 
1882
        class_pattern = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
1883
        re_filtered = filter_suite_by_re(self.suite, class_pattern)
 
1884
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
 
1885
 
 
1886
    def test_exclude_tests_by_condition(self):
 
1887
        excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
1888
            'test_exclude_tests_by_condition')
 
1889
        filtered_suite = exclude_tests_by_condition(self.suite,
 
1890
            lambda x:x.id() == excluded_name)
 
1891
        self.assertEqual(len(self.all_names) - 1,
 
1892
            filtered_suite.countTestCases())
 
1893
        self.assertFalse(excluded_name in _test_ids(filtered_suite))
 
1894
        remaining_names = list(self.all_names)
 
1895
        remaining_names.remove(excluded_name)
 
1896
        self.assertEqual(remaining_names, _test_ids(filtered_suite))
 
1897
 
 
1898
    def test_exclude_tests_by_re(self):
 
1899
        self.all_names = _test_ids(self.suite)
 
1900
        filtered_suite = exclude_tests_by_re(self.suite, 'exclude_tests_by_re')
 
1901
        excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
1902
            'test_exclude_tests_by_re')
 
1903
        self.assertEqual(len(self.all_names) - 1,
 
1904
            filtered_suite.countTestCases())
 
1905
        self.assertFalse(excluded_name in _test_ids(filtered_suite))
 
1906
        remaining_names = list(self.all_names)
 
1907
        remaining_names.remove(excluded_name)
 
1908
        self.assertEqual(remaining_names, _test_ids(filtered_suite))
 
1909
 
 
1910
    def test_filter_suite_by_condition(self):
 
1911
        test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
1912
            'test_filter_suite_by_condition')
 
1913
        filtered_suite = filter_suite_by_condition(self.suite,
 
1914
            lambda x:x.id() == test_name)
 
1915
        self.assertEqual([test_name], _test_ids(filtered_suite))
 
1916
 
 
1917
    def test_filter_suite_by_re(self):
 
1918
        filtered_suite = filter_suite_by_re(self.suite, 'test_filter_suite_by_r')
 
1919
        filtered_names = _test_ids(filtered_suite)
 
1920
        self.assertEqual(filtered_names, ['bzrlib.tests.test_selftest.'
 
1921
            'TestSelftestFiltering.test_filter_suite_by_re'])
 
1922
 
 
1923
    def test_filter_suite_by_id_list(self):
 
1924
        test_list = ['bzrlib.tests.test_selftest.'
 
1925
                     'TestSelftestFiltering.test_filter_suite_by_id_list']
 
1926
        filtered_suite = tests.filter_suite_by_id_list(
 
1927
            self.suite, tests.TestIdList(test_list))
 
1928
        filtered_names = _test_ids(filtered_suite)
 
1929
        self.assertEqual(
 
1930
            filtered_names,
 
1931
            ['bzrlib.tests.test_selftest.'
 
1932
             'TestSelftestFiltering.test_filter_suite_by_id_list'])
 
1933
 
 
1934
    def test_filter_suite_by_id_startswith(self):
 
1935
        # By design this test may fail if another test is added whose name also
 
1936
        # begins with one of the start value used.
 
1937
        klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
1938
        start1 = klass + 'test_filter_suite_by_id_starts'
 
1939
        start2 = klass + 'test_filter_suite_by_id_li'
 
1940
        test_list = [klass + 'test_filter_suite_by_id_list',
 
1941
                     klass + 'test_filter_suite_by_id_startswith',
 
1942
                     ]
 
1943
        filtered_suite = tests.filter_suite_by_id_startswith(
 
1944
            self.suite, [start1, start2])
 
1945
        self.assertEqual(
 
1946
            test_list,
 
1947
            _test_ids(filtered_suite),
 
1948
            )
 
1949
 
 
1950
    def test_preserve_input(self):
 
1951
        # NB: Surely this is something in the stdlib to do this?
 
1952
        self.assertTrue(self.suite is preserve_input(self.suite))
 
1953
        self.assertTrue("@#$" is preserve_input("@#$"))
 
1954
 
 
1955
    def test_randomize_suite(self):
 
1956
        randomized_suite = randomize_suite(self.suite)
 
1957
        # randomizing should not add or remove test names.
 
1958
        self.assertEqual(set(_test_ids(self.suite)),
 
1959
                         set(_test_ids(randomized_suite)))
 
1960
        # Technically, this *can* fail, because random.shuffle(list) can be
 
1961
        # equal to list. Trying multiple times just pushes the frequency back.
 
1962
        # As its len(self.all_names)!:1, the failure frequency should be low
 
1963
        # enough to ignore. RBC 20071021.
 
1964
        # It should change the order.
 
1965
        self.assertNotEqual(self.all_names, _test_ids(randomized_suite))
 
1966
        # But not the length. (Possibly redundant with the set test, but not
 
1967
        # necessarily.)
 
1968
        self.assertEqual(len(self.all_names), len(_test_ids(randomized_suite)))
 
1969
 
 
1970
    def test_split_suit_by_condition(self):
 
1971
        self.all_names = _test_ids(self.suite)
 
1972
        condition = condition_id_re('test_filter_suite_by_r')
 
1973
        split_suite = split_suite_by_condition(self.suite, condition)
 
1974
        filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
1975
            'test_filter_suite_by_re')
 
1976
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
 
1977
        self.assertFalse(filtered_name in _test_ids(split_suite[1]))
 
1978
        remaining_names = list(self.all_names)
 
1979
        remaining_names.remove(filtered_name)
 
1980
        self.assertEqual(remaining_names, _test_ids(split_suite[1]))
 
1981
 
 
1982
    def test_split_suit_by_re(self):
 
1983
        self.all_names = _test_ids(self.suite)
 
1984
        split_suite = split_suite_by_re(self.suite, 'test_filter_suite_by_r')
 
1985
        filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
1986
            'test_filter_suite_by_re')
 
1987
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
 
1988
        self.assertFalse(filtered_name in _test_ids(split_suite[1]))
 
1989
        remaining_names = list(self.all_names)
 
1990
        remaining_names.remove(filtered_name)
 
1991
        self.assertEqual(remaining_names, _test_ids(split_suite[1]))
 
1992
 
 
1993
 
 
1994
class TestCheckInventoryShape(TestCaseWithTransport):
 
1995
 
 
1996
    def test_check_inventory_shape(self):
 
1997
        files = ['a', 'b/', 'b/c']
 
1998
        tree = self.make_branch_and_tree('.')
 
1999
        self.build_tree(files)
 
2000
        tree.add(files)
 
2001
        tree.lock_read()
 
2002
        try:
 
2003
            self.check_inventory_shape(tree.inventory, files)
 
2004
        finally:
 
2005
            tree.unlock()
 
2006
 
 
2007
 
 
2008
class TestBlackboxSupport(TestCase):
 
2009
    """Tests for testsuite blackbox features."""
 
2010
 
 
2011
    def test_run_bzr_failure_not_caught(self):
 
2012
        # When we run bzr in blackbox mode, we want any unexpected errors to
 
2013
        # propagate up to the test suite so that it can show the error in the
 
2014
        # usual way, and we won't get a double traceback.
 
2015
        e = self.assertRaises(
 
2016
            AssertionError,
 
2017
            self.run_bzr, ['assert-fail'])
 
2018
        # make sure we got the real thing, not an error from somewhere else in
 
2019
        # the test framework
 
2020
        self.assertEquals('always fails', str(e))
 
2021
        # check that there's no traceback in the test log
 
2022
        self.assertNotContainsRe(self._get_log(keep_log_file=True),
 
2023
            r'Traceback')
 
2024
 
 
2025
    def test_run_bzr_user_error_caught(self):
 
2026
        # Running bzr in blackbox mode, normal/expected/user errors should be
 
2027
        # caught in the regular way and turned into an error message plus exit
 
2028
        # code.
 
2029
        out, err = self.run_bzr(["log", "/nonexistantpath"], retcode=3)
 
2030
        self.assertEqual(out, '')
 
2031
        self.assertContainsRe(err,
 
2032
            'bzr: ERROR: Not a branch: ".*nonexistantpath/".\n')
 
2033
 
 
2034
 
 
2035
class TestTestLoader(TestCase):
 
2036
    """Tests for the test loader."""
 
2037
 
 
2038
    def _get_loader_and_module(self):
 
2039
        """Gets a TestLoader and a module with one test in it."""
 
2040
        loader = TestUtil.TestLoader()
 
2041
        module = {}
 
2042
        class Stub(TestCase):
 
2043
            def test_foo(self):
 
2044
                pass
 
2045
        class MyModule(object):
 
2046
            pass
 
2047
        MyModule.a_class = Stub
 
2048
        module = MyModule()
 
2049
        return loader, module
 
2050
 
 
2051
    def test_module_no_load_tests_attribute_loads_classes(self):
 
2052
        loader, module = self._get_loader_and_module()
 
2053
        self.assertEqual(1, loader.loadTestsFromModule(module).countTestCases())
 
2054
 
 
2055
    def test_module_load_tests_attribute_gets_called(self):
 
2056
        loader, module = self._get_loader_and_module()
 
2057
        # 'self' is here because we're faking the module with a class. Regular
 
2058
        # load_tests do not need that :)
 
2059
        def load_tests(self, standard_tests, module, loader):
 
2060
            result = loader.suiteClass()
 
2061
            for test in iter_suite_tests(standard_tests):
 
2062
                result.addTests([test, test])
 
2063
            return result
 
2064
        # add a load_tests() method which multiplies the tests from the module.
 
2065
        module.__class__.load_tests = load_tests
 
2066
        self.assertEqual(2, loader.loadTestsFromModule(module).countTestCases())
 
2067
 
 
2068
    def test_load_tests_from_module_name_smoke_test(self):
 
2069
        loader = TestUtil.TestLoader()
 
2070
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2071
        self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
 
2072
                          _test_ids(suite))
 
2073
 
 
2074
    def test_load_tests_from_module_name_with_bogus_module_name(self):
 
2075
        loader = TestUtil.TestLoader()
 
2076
        self.assertRaises(ImportError, loader.loadTestsFromModuleName, 'bogus')
 
2077
 
 
2078
 
 
2079
class TestTestIdList(tests.TestCase):
 
2080
 
 
2081
    def _create_id_list(self, test_list):
 
2082
        return tests.TestIdList(test_list)
 
2083
 
 
2084
    def _create_suite(self, test_id_list):
 
2085
 
 
2086
        class Stub(TestCase):
 
2087
            def test_foo(self):
 
2088
                pass
 
2089
 
 
2090
        def _create_test_id(id):
 
2091
            return lambda: id
 
2092
 
 
2093
        suite = TestUtil.TestSuite()
 
2094
        for id in test_id_list:
 
2095
            t  = Stub('test_foo')
 
2096
            t.id = _create_test_id(id)
 
2097
            suite.addTest(t)
 
2098
        return suite
 
2099
 
 
2100
    def _test_ids(self, test_suite):
 
2101
        """Get the ids for the tests in a test suite."""
 
2102
        return [t.id() for t in iter_suite_tests(test_suite)]
 
2103
 
 
2104
    def test_empty_list(self):
 
2105
        id_list = self._create_id_list([])
 
2106
        self.assertEquals({}, id_list.tests)
 
2107
        self.assertEquals({}, id_list.modules)
 
2108
 
 
2109
    def test_valid_list(self):
 
2110
        id_list = self._create_id_list(
 
2111
            ['mod1.cl1.meth1', 'mod1.cl1.meth2',
 
2112
             'mod1.func1', 'mod1.cl2.meth2',
 
2113
             'mod1.submod1',
 
2114
             'mod1.submod2.cl1.meth1', 'mod1.submod2.cl2.meth2',
 
2115
             ])
 
2116
        self.assertTrue(id_list.refers_to('mod1'))
 
2117
        self.assertTrue(id_list.refers_to('mod1.submod1'))
 
2118
        self.assertTrue(id_list.refers_to('mod1.submod2'))
 
2119
        self.assertTrue(id_list.includes('mod1.cl1.meth1'))
 
2120
        self.assertTrue(id_list.includes('mod1.submod1'))
 
2121
        self.assertTrue(id_list.includes('mod1.func1'))
 
2122
 
 
2123
    def test_bad_chars_in_params(self):
 
2124
        id_list = self._create_id_list(['mod1.cl1.meth1(xx.yy)'])
 
2125
        self.assertTrue(id_list.refers_to('mod1'))
 
2126
        self.assertTrue(id_list.includes('mod1.cl1.meth1(xx.yy)'))
 
2127
 
 
2128
    def test_module_used(self):
 
2129
        id_list = self._create_id_list(['mod.class.meth'])
 
2130
        self.assertTrue(id_list.refers_to('mod'))
 
2131
        self.assertTrue(id_list.refers_to('mod.class'))
 
2132
        self.assertTrue(id_list.refers_to('mod.class.meth'))
 
2133
 
 
2134
    def test_test_suite(self):
 
2135
        # This test is slow, so we do a single test with one test in each
 
2136
        # category
 
2137
        test_list = [
 
2138
            # testmod_names
 
2139
            'bzrlib.tests.blackbox.test_branch.TestBranch.test_branch',
 
2140
            'bzrlib.tests.test_selftest.TestTestIdList.test_test_suite',
 
2141
            # transport implementations
 
2142
            'bzrlib.tests.test_transport_implementations.TransportTests'
 
2143
            '.test_abspath(LocalURLServer)',
 
2144
            # modules_to_doctest
 
2145
            'bzrlib.timestamp.format_highres_date',
 
2146
            # plugins can't be tested that way since selftest may be run with
 
2147
            # --no-plugins
 
2148
            ]
 
2149
        suite = tests.test_suite(test_list)
 
2150
        self.assertEquals(test_list, _test_ids(suite))
 
2151
 
 
2152
    def test_test_suite_matches_id_list_with_unknown(self):
 
2153
        loader = TestUtil.TestLoader()
 
2154
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2155
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',
 
2156
                     'bogus']
 
2157
        not_found, duplicates = tests.suite_matches_id_list(suite, test_list)
 
2158
        self.assertEquals(['bogus'], not_found)
 
2159
        self.assertEquals([], duplicates)
 
2160
 
 
2161
    def test_suite_matches_id_list_with_duplicates(self):
 
2162
        loader = TestUtil.TestLoader()
 
2163
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2164
        dupes = loader.suiteClass()
 
2165
        for test in iter_suite_tests(suite):
 
2166
            dupes.addTest(test)
 
2167
            dupes.addTest(test) # Add it again
 
2168
 
 
2169
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',]
 
2170
        not_found, duplicates = tests.suite_matches_id_list(
 
2171
            dupes, test_list)
 
2172
        self.assertEquals([], not_found)
 
2173
        self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
 
2174
                          duplicates)
 
2175
 
 
2176
 
 
2177
class TestLoadTestIdList(tests.TestCaseInTempDir):
 
2178
 
 
2179
    def _create_test_list_file(self, file_name, content):
 
2180
        fl = open(file_name, 'wt')
 
2181
        fl.write(content)
 
2182
        fl.close()
 
2183
 
 
2184
    def test_load_unknown(self):
 
2185
        self.assertRaises(errors.NoSuchFile,
 
2186
                          tests.load_test_id_list, 'i_do_not_exist')
 
2187
 
 
2188
    def test_load_test_list(self):
 
2189
        test_list_fname = 'test.list'
 
2190
        self._create_test_list_file(test_list_fname,
 
2191
                                    'mod1.cl1.meth1\nmod2.cl2.meth2\n')
 
2192
        tlist = tests.load_test_id_list(test_list_fname)
 
2193
        self.assertEquals(2, len(tlist))
 
2194
        self.assertEquals('mod1.cl1.meth1', tlist[0])
 
2195
        self.assertEquals('mod2.cl2.meth2', tlist[1])
 
2196
 
 
2197
    def test_load_dirty_file(self):
 
2198
        test_list_fname = 'test.list'
 
2199
        self._create_test_list_file(test_list_fname,
 
2200
                                    '  mod1.cl1.meth1\n\nmod2.cl2.meth2  \n'
 
2201
                                    'bar baz\n')
 
2202
        tlist = tests.load_test_id_list(test_list_fname)
 
2203
        self.assertEquals(4, len(tlist))
 
2204
        self.assertEquals('mod1.cl1.meth1', tlist[0])
 
2205
        self.assertEquals('', tlist[1])
 
2206
        self.assertEquals('mod2.cl2.meth2', tlist[2])
 
2207
        self.assertEquals('bar baz', tlist[3])
 
2208
 
 
2209
 
 
2210
class TestFilteredByModuleTestLoader(tests.TestCase):
 
2211
 
 
2212
    def _create_loader(self, test_list):
 
2213
        id_filter = tests.TestIdList(test_list)
 
2214
        loader = TestUtil.FilteredByModuleTestLoader(id_filter.refers_to)
 
2215
        return loader
 
2216
 
 
2217
    def test_load_tests(self):
 
2218
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
 
2219
        loader = self._create_loader(test_list)
 
2220
 
 
2221
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2222
        self.assertEquals(test_list, _test_ids(suite))
 
2223
 
 
2224
    def test_exclude_tests(self):
 
2225
        test_list = ['bogus']
 
2226
        loader = self._create_loader(test_list)
 
2227
 
 
2228
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2229
        self.assertEquals([], _test_ids(suite))
 
2230
 
 
2231
 
 
2232
class TestFilteredByNameStartTestLoader(tests.TestCase):
 
2233
 
 
2234
    def _create_loader(self, name_start):
 
2235
        def needs_module(name):
 
2236
            return name.startswith(name_start) or name_start.startswith(name)
 
2237
        loader = TestUtil.FilteredByModuleTestLoader(needs_module)
 
2238
        return loader
 
2239
 
 
2240
    def test_load_tests(self):
 
2241
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
 
2242
        loader = self._create_loader('bzrlib.tests.test_samp')
 
2243
 
 
2244
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2245
        self.assertEquals(test_list, _test_ids(suite))
 
2246
 
 
2247
    def test_load_tests_inside_module(self):
 
2248
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
 
2249
        loader = self._create_loader('bzrlib.tests.test_sampler.Demo')
 
2250
 
 
2251
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2252
        self.assertEquals(test_list, _test_ids(suite))
 
2253
 
 
2254
    def test_exclude_tests(self):
 
2255
        test_list = ['bogus']
 
2256
        loader = self._create_loader('bogus')
 
2257
 
 
2258
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2259
        self.assertEquals([], _test_ids(suite))
 
2260
 
 
2261
 
 
2262
class TestTestPrefixRegistry(tests.TestCase):
 
2263
 
 
2264
    def _get_registry(self):
 
2265
        tp_registry = tests.TestPrefixAliasRegistry()
 
2266
        return tp_registry
 
2267
 
 
2268
    def test_register_new_prefix(self):
 
2269
        tpr = self._get_registry()
 
2270
        tpr.register('foo', 'fff.ooo.ooo')
 
2271
        self.assertEquals('fff.ooo.ooo', tpr.get('foo'))
 
2272
 
 
2273
    def test_register_existing_prefix(self):
 
2274
        tpr = self._get_registry()
 
2275
        tpr.register('bar', 'bbb.aaa.rrr')
 
2276
        tpr.register('bar', 'bBB.aAA.rRR')
 
2277
        self.assertEquals('bbb.aaa.rrr', tpr.get('bar'))
 
2278
        self.assertContainsRe(self._get_log(keep_log_file=True),
 
2279
                              r'.*bar.*bbb.aaa.rrr.*bBB.aAA.rRR')
 
2280
 
 
2281
    def test_get_unknown_prefix(self):
 
2282
        tpr = self._get_registry()
 
2283
        self.assertRaises(KeyError, tpr.get, 'I am not a prefix')
 
2284
 
 
2285
    def test_resolve_prefix(self):
 
2286
        tpr = self._get_registry()
 
2287
        tpr.register('bar', 'bb.aa.rr')
 
2288
        self.assertEquals('bb.aa.rr', tpr.resolve_alias('bar'))
 
2289
 
 
2290
    def test_resolve_unknown_alias(self):
 
2291
        tpr = self._get_registry()
 
2292
        self.assertRaises(errors.BzrCommandError,
 
2293
                          tpr.resolve_alias, 'I am not a prefix')
 
2294
 
 
2295
    def test_predefined_prefixes(self):
 
2296
        tpr = tests.test_prefix_alias_registry
 
2297
        self.assertEquals('bzrlib', tpr.resolve_alias('bzrlib'))
 
2298
        self.assertEquals('bzrlib.doc', tpr.resolve_alias('bd'))
 
2299
        self.assertEquals('bzrlib.utils', tpr.resolve_alias('bu'))
 
2300
        self.assertEquals('bzrlib.tests', tpr.resolve_alias('bt'))
 
2301
        self.assertEquals('bzrlib.tests.blackbox', tpr.resolve_alias('bb'))
 
2302
        self.assertEquals('bzrlib.plugins', tpr.resolve_alias('bp'))
 
2303
 
 
2304
 
 
2305
class TestRunSuite(TestCase):
 
2306
 
 
2307
    def test_runner_class(self):
 
2308
        """run_suite accepts and uses a runner_class keyword argument."""
 
2309
        class Stub(TestCase):
 
2310
            def test_foo(self):
 
2311
                pass
 
2312
        suite = Stub("test_foo")
 
2313
        calls = []
 
2314
        class MyRunner(TextTestRunner):
 
2315
            def run(self, test):
 
2316
                calls.append(test)
 
2317
                return ExtendedTestResult(self.stream, self.descriptions,
 
2318
                    self.verbosity)
 
2319
        run_suite(suite, runner_class=MyRunner)
 
2320
        self.assertEqual(calls, [suite])