/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-08-13 01:33:15 UTC
  • mto: (4599.4.12 bug-398668)
  • mto: This revision was merged to the branch mainline in revision 4607.
  • Revision ID: robertc@robertcollins.net-20090813013315-xatr2leyof6122dj
Set tree root ID in tree transform tests that don't care about the root id.

Show diffs side-by-side

added added

removed removed

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