~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_selftest.py

  • Committer: Martin Pool
  • Date: 2009-07-19 01:05:42 UTC
  • mto: This revision was merged to the branch mainline in revision 4558.
  • Revision ID: mbp@sourcefrog.net-20090719010542-34bzx1i5ynfvs6zd
TextUIFactory should cope with EOF when in get_boolean

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 MockProgress(progress._BaseProgressBar):
 
685
    """Progress-bar standin that records calls.
 
686
 
 
687
    Useful for testing pb using code.
 
688
    """
 
689
 
 
690
    def __init__(self):
 
691
        progress._BaseProgressBar.__init__(self)
 
692
        self.calls = []
 
693
 
 
694
    def tick(self):
 
695
        self.calls.append(('tick',))
 
696
 
 
697
    def update(self, msg=None, current=None, total=None):
 
698
        self.calls.append(('update', msg, current, total))
 
699
 
 
700
    def clear(self):
 
701
        self.calls.append(('clear',))
 
702
 
 
703
    def note(self, msg, *args):
 
704
        self.calls.append(('note', msg, args))
 
705
 
 
706
 
 
707
class TestTestResult(tests.TestCase):
 
708
 
 
709
    def check_timing(self, test_case, expected_re):
 
710
        result = bzrlib.tests.TextTestResult(self._log_file,
 
711
                descriptions=0,
 
712
                verbosity=1,
 
713
                )
 
714
        test_case.run(result)
 
715
        timed_string = result._testTimeString(test_case)
 
716
        self.assertContainsRe(timed_string, expected_re)
 
717
 
 
718
    def test_test_reporting(self):
 
719
        class ShortDelayTestCase(tests.TestCase):
 
720
            def test_short_delay(self):
 
721
                time.sleep(0.003)
 
722
            def test_short_benchmark(self):
 
723
                self.time(time.sleep, 0.003)
 
724
        self.check_timing(ShortDelayTestCase('test_short_delay'),
 
725
                          r"^ +[0-9]+ms$")
 
726
        # if a benchmark time is given, we want a x of y style result.
 
727
        self.check_timing(ShortDelayTestCase('test_short_benchmark'),
 
728
                          r"^ +[0-9]+ms/ +[0-9]+ms$")
 
729
 
 
730
    def test_unittest_reporting_unittest_class(self):
 
731
        # getting the time from a non-bzrlib test works ok
 
732
        class ShortDelayTestCase(unittest.TestCase):
 
733
            def test_short_delay(self):
 
734
                time.sleep(0.003)
 
735
        self.check_timing(ShortDelayTestCase('test_short_delay'),
 
736
                          r"^ +[0-9]+ms$")
 
737
 
 
738
    def test_assigned_benchmark_file_stores_date(self):
 
739
        output = StringIO()
 
740
        result = bzrlib.tests.TextTestResult(self._log_file,
 
741
                                        descriptions=0,
 
742
                                        verbosity=1,
 
743
                                        bench_history=output
 
744
                                        )
 
745
        output_string = output.getvalue()
 
746
        # if you are wondering about the regexp please read the comment in
 
747
        # test_bench_history (bzrlib.tests.test_selftest.TestRunner)
 
748
        # XXX: what comment?  -- Andrew Bennetts
 
749
        self.assertContainsRe(output_string, "--date [0-9.]+")
 
750
 
 
751
    def test_benchhistory_records_test_times(self):
 
752
        result_stream = StringIO()
 
753
        result = bzrlib.tests.TextTestResult(
 
754
            self._log_file,
 
755
            descriptions=0,
 
756
            verbosity=1,
 
757
            bench_history=result_stream
 
758
            )
 
759
 
 
760
        # we want profile a call and check that its test duration is recorded
 
761
        # make a new test instance that when run will generate a benchmark
 
762
        example_test_case = TestTestResult("_time_hello_world_encoding")
 
763
        # execute the test, which should succeed and record times
 
764
        example_test_case.run(result)
 
765
        lines = result_stream.getvalue().splitlines()
 
766
        self.assertEqual(2, len(lines))
 
767
        self.assertContainsRe(lines[1],
 
768
            " *[0-9]+ms bzrlib.tests.test_selftest.TestTestResult"
 
769
            "._time_hello_world_encoding")
 
770
 
 
771
    def _time_hello_world_encoding(self):
 
772
        """Profile two sleep calls
 
773
 
 
774
        This is used to exercise the test framework.
 
775
        """
 
776
        self.time(unicode, 'hello', errors='replace')
 
777
        self.time(unicode, 'world', errors='replace')
 
778
 
 
779
    def test_lsprofiling(self):
 
780
        """Verbose test result prints lsprof statistics from test cases."""
 
781
        self.requireFeature(test_lsprof.LSProfFeature)
 
782
        result_stream = StringIO()
 
783
        result = bzrlib.tests.VerboseTestResult(
 
784
            unittest._WritelnDecorator(result_stream),
 
785
            descriptions=0,
 
786
            verbosity=2,
 
787
            )
 
788
        # we want profile a call of some sort and check it is output by
 
789
        # addSuccess. We dont care about addError or addFailure as they
 
790
        # are not that interesting for performance tuning.
 
791
        # make a new test instance that when run will generate a profile
 
792
        example_test_case = TestTestResult("_time_hello_world_encoding")
 
793
        example_test_case._gather_lsprof_in_benchmarks = True
 
794
        # execute the test, which should succeed and record profiles
 
795
        example_test_case.run(result)
 
796
        # lsprofile_something()
 
797
        # if this worked we want
 
798
        # LSProf output for <built in function unicode> (['hello'], {'errors': 'replace'})
 
799
        #    CallCount    Recursive    Total(ms)   Inline(ms) module:lineno(function)
 
800
        # (the lsprof header)
 
801
        # ... an arbitrary number of lines
 
802
        # and the function call which is time.sleep.
 
803
        #           1        0            ???         ???       ???(sleep)
 
804
        # and then repeated but with 'world', rather than 'hello'.
 
805
        # this should appear in the output stream of our test result.
 
806
        output = result_stream.getvalue()
 
807
        self.assertContainsRe(output,
 
808
            r"LSProf output for <type 'unicode'>\(\('hello',\), {'errors': 'replace'}\)")
 
809
        self.assertContainsRe(output,
 
810
            r" *CallCount *Recursive *Total\(ms\) *Inline\(ms\) *module:lineno\(function\)\n")
 
811
        self.assertContainsRe(output,
 
812
            r"( +1 +0 +0\.\d+ +0\.\d+ +<method 'disable' of '_lsprof\.Profiler' objects>\n)?")
 
813
        self.assertContainsRe(output,
 
814
            r"LSProf output for <type 'unicode'>\(\('world',\), {'errors': 'replace'}\)\n")
 
815
 
 
816
    def test_known_failure(self):
 
817
        """A KnownFailure being raised should trigger several result actions."""
 
818
        class InstrumentedTestResult(tests.ExtendedTestResult):
 
819
            def done(self): pass
 
820
            def startTests(self): pass
 
821
            def report_test_start(self, test): pass
 
822
            def report_known_failure(self, test, err):
 
823
                self._call = test, err
 
824
        result = InstrumentedTestResult(None, None, None, None)
 
825
        def test_function():
 
826
            raise tests.KnownFailure('failed!')
 
827
        test = unittest.FunctionTestCase(test_function)
 
828
        test.run(result)
 
829
        # it should invoke 'report_known_failure'.
 
830
        self.assertEqual(2, len(result._call))
 
831
        self.assertEqual(test, result._call[0])
 
832
        self.assertEqual(tests.KnownFailure, result._call[1][0])
 
833
        self.assertIsInstance(result._call[1][1], tests.KnownFailure)
 
834
        # we dont introspec the traceback, if the rest is ok, it would be
 
835
        # exceptional for it not to be.
 
836
        # it should update the known_failure_count on the object.
 
837
        self.assertEqual(1, result.known_failure_count)
 
838
        # the result should be successful.
 
839
        self.assertTrue(result.wasSuccessful())
 
840
 
 
841
    def test_verbose_report_known_failure(self):
 
842
        # verbose test output formatting
 
843
        result_stream = StringIO()
 
844
        result = bzrlib.tests.VerboseTestResult(
 
845
            unittest._WritelnDecorator(result_stream),
 
846
            descriptions=0,
 
847
            verbosity=2,
 
848
            )
 
849
        test = self.get_passing_test()
 
850
        result.startTest(test)
 
851
        prefix = len(result_stream.getvalue())
 
852
        # the err parameter has the shape:
 
853
        # (class, exception object, traceback)
 
854
        # KnownFailures dont get their tracebacks shown though, so we
 
855
        # can skip that.
 
856
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
 
857
        result.report_known_failure(test, err)
 
858
        output = result_stream.getvalue()[prefix:]
 
859
        lines = output.splitlines()
 
860
        self.assertContainsRe(lines[0], r'XFAIL *\d+ms$')
 
861
        self.assertEqual(lines[1], '    foo')
 
862
        self.assertEqual(2, len(lines))
 
863
 
 
864
    def test_text_report_known_failure(self):
 
865
        # text test output formatting
 
866
        pb = MockProgress()
 
867
        result = bzrlib.tests.TextTestResult(
 
868
            StringIO(),
 
869
            descriptions=0,
 
870
            verbosity=1,
 
871
            pb=pb,
 
872
            )
 
873
        test = self.get_passing_test()
 
874
        # this seeds the state to handle reporting the test.
 
875
        result.startTest(test)
 
876
        # the err parameter has the shape:
 
877
        # (class, exception object, traceback)
 
878
        # KnownFailures dont get their tracebacks shown though, so we
 
879
        # can skip that.
 
880
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
 
881
        result.report_known_failure(test, err)
 
882
        self.assertEqual(
 
883
            [
 
884
            ('update', '[1 in 0s] passing_test', None, None),
 
885
            ('note', 'XFAIL: %s\n%s\n', ('passing_test', err[1]))
 
886
            ],
 
887
            pb.calls)
 
888
        # known_failures should be printed in the summary, so if we run a test
 
889
        # after there are some known failures, the update prefix should match
 
890
        # this.
 
891
        result.known_failure_count = 3
 
892
        test.run(result)
 
893
        self.assertEqual(
 
894
            [
 
895
            ('update', '[2 in 0s] passing_test', None, None),
 
896
            ],
 
897
            pb.calls[2:])
 
898
 
 
899
    def get_passing_test(self):
 
900
        """Return a test object that can't be run usefully."""
 
901
        def passing_test():
 
902
            pass
 
903
        return unittest.FunctionTestCase(passing_test)
 
904
 
 
905
    def test_add_not_supported(self):
 
906
        """Test the behaviour of invoking addNotSupported."""
 
907
        class InstrumentedTestResult(tests.ExtendedTestResult):
 
908
            def done(self): pass
 
909
            def startTests(self): pass
 
910
            def report_test_start(self, test): pass
 
911
            def report_unsupported(self, test, feature):
 
912
                self._call = test, feature
 
913
        result = InstrumentedTestResult(None, None, None, None)
 
914
        test = SampleTestCase('_test_pass')
 
915
        feature = tests.Feature()
 
916
        result.startTest(test)
 
917
        result.addNotSupported(test, feature)
 
918
        # it should invoke 'report_unsupported'.
 
919
        self.assertEqual(2, len(result._call))
 
920
        self.assertEqual(test, result._call[0])
 
921
        self.assertEqual(feature, result._call[1])
 
922
        # the result should be successful.
 
923
        self.assertTrue(result.wasSuccessful())
 
924
        # it should record the test against a count of tests not run due to
 
925
        # this feature.
 
926
        self.assertEqual(1, result.unsupported['Feature'])
 
927
        # and invoking it again should increment that counter
 
928
        result.addNotSupported(test, feature)
 
929
        self.assertEqual(2, result.unsupported['Feature'])
 
930
 
 
931
    def test_verbose_report_unsupported(self):
 
932
        # verbose test output formatting
 
933
        result_stream = StringIO()
 
934
        result = bzrlib.tests.VerboseTestResult(
 
935
            unittest._WritelnDecorator(result_stream),
 
936
            descriptions=0,
 
937
            verbosity=2,
 
938
            )
 
939
        test = self.get_passing_test()
 
940
        feature = tests.Feature()
 
941
        result.startTest(test)
 
942
        prefix = len(result_stream.getvalue())
 
943
        result.report_unsupported(test, feature)
 
944
        output = result_stream.getvalue()[prefix:]
 
945
        lines = output.splitlines()
 
946
        self.assertEqual(lines, ['NODEP                   0ms',
 
947
                                 "    The feature 'Feature' is not available."])
 
948
 
 
949
    def test_text_report_unsupported(self):
 
950
        # text test output formatting
 
951
        pb = MockProgress()
 
952
        result = bzrlib.tests.TextTestResult(
 
953
            StringIO(),
 
954
            descriptions=0,
 
955
            verbosity=1,
 
956
            pb=pb,
 
957
            )
 
958
        test = self.get_passing_test()
 
959
        feature = tests.Feature()
 
960
        # this seeds the state to handle reporting the test.
 
961
        result.startTest(test)
 
962
        result.report_unsupported(test, feature)
 
963
        # no output on unsupported features
 
964
        self.assertEqual(
 
965
            [('update', '[1 in 0s] passing_test', None, None)
 
966
            ],
 
967
            pb.calls)
 
968
        # the number of missing features should be printed in the progress
 
969
        # summary, so check for that.
 
970
        result.unsupported = {'foo':0, 'bar':0}
 
971
        test.run(result)
 
972
        self.assertEqual(
 
973
            [
 
974
            ('update', '[2 in 0s, 2 missing] passing_test', None, None),
 
975
            ],
 
976
            pb.calls[1:])
 
977
 
 
978
    def test_unavailable_exception(self):
 
979
        """An UnavailableFeature being raised should invoke addNotSupported."""
 
980
        class InstrumentedTestResult(tests.ExtendedTestResult):
 
981
            def done(self): pass
 
982
            def startTests(self): pass
 
983
            def report_test_start(self, test): pass
 
984
            def addNotSupported(self, test, feature):
 
985
                self._call = test, feature
 
986
        result = InstrumentedTestResult(None, None, None, None)
 
987
        feature = tests.Feature()
 
988
        def test_function():
 
989
            raise tests.UnavailableFeature(feature)
 
990
        test = unittest.FunctionTestCase(test_function)
 
991
        test.run(result)
 
992
        # it should invoke 'addNotSupported'.
 
993
        self.assertEqual(2, len(result._call))
 
994
        self.assertEqual(test, result._call[0])
 
995
        self.assertEqual(feature, result._call[1])
 
996
        # and not count as an error
 
997
        self.assertEqual(0, result.error_count)
 
998
 
 
999
    def test_strict_with_unsupported_feature(self):
 
1000
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
 
1001
                                             verbosity=1)
 
1002
        test = self.get_passing_test()
 
1003
        feature = "Unsupported Feature"
 
1004
        result.addNotSupported(test, feature)
 
1005
        self.assertFalse(result.wasStrictlySuccessful())
 
1006
        self.assertEqual(None, result._extractBenchmarkTime(test))
 
1007
 
 
1008
    def test_strict_with_known_failure(self):
 
1009
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
 
1010
                                             verbosity=1)
 
1011
        test = self.get_passing_test()
 
1012
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
 
1013
        result._addKnownFailure(test, err)
 
1014
        self.assertFalse(result.wasStrictlySuccessful())
 
1015
        self.assertEqual(None, result._extractBenchmarkTime(test))
 
1016
 
 
1017
    def test_strict_with_success(self):
 
1018
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
 
1019
                                             verbosity=1)
 
1020
        test = self.get_passing_test()
 
1021
        result.addSuccess(test)
 
1022
        self.assertTrue(result.wasStrictlySuccessful())
 
1023
        self.assertEqual(None, result._extractBenchmarkTime(test))
 
1024
 
 
1025
    def test_startTests(self):
 
1026
        """Starting the first test should trigger startTests."""
 
1027
        class InstrumentedTestResult(tests.ExtendedTestResult):
 
1028
            calls = 0
 
1029
            def startTests(self): self.calls += 1
 
1030
            def report_test_start(self, test): pass
 
1031
        result = InstrumentedTestResult(None, None, None, None)
 
1032
        def test_function():
 
1033
            pass
 
1034
        test = unittest.FunctionTestCase(test_function)
 
1035
        test.run(result)
 
1036
        self.assertEquals(1, result.calls)
 
1037
 
 
1038
 
 
1039
class TestUnicodeFilenameFeature(tests.TestCase):
 
1040
 
 
1041
    def test_probe_passes(self):
 
1042
        """UnicodeFilenameFeature._probe passes."""
 
1043
        # We can't test much more than that because the behaviour depends
 
1044
        # on the platform.
 
1045
        tests.UnicodeFilenameFeature._probe()
 
1046
 
 
1047
 
 
1048
class TestRunner(tests.TestCase):
 
1049
 
 
1050
    def dummy_test(self):
 
1051
        pass
 
1052
 
 
1053
    def run_test_runner(self, testrunner, test):
 
1054
        """Run suite in testrunner, saving global state and restoring it.
 
1055
 
 
1056
        This current saves and restores:
 
1057
        TestCaseInTempDir.TEST_ROOT
 
1058
 
 
1059
        There should be no tests in this file that use
 
1060
        bzrlib.tests.TextTestRunner without using this convenience method,
 
1061
        because of our use of global state.
 
1062
        """
 
1063
        old_root = tests.TestCaseInTempDir.TEST_ROOT
 
1064
        try:
 
1065
            tests.TestCaseInTempDir.TEST_ROOT = None
 
1066
            return testrunner.run(test)
 
1067
        finally:
 
1068
            tests.TestCaseInTempDir.TEST_ROOT = old_root
 
1069
 
 
1070
    def test_known_failure_failed_run(self):
 
1071
        # run a test that generates a known failure which should be printed in
 
1072
        # the final output when real failures occur.
 
1073
        def known_failure_test():
 
1074
            raise tests.KnownFailure('failed')
 
1075
        test = unittest.TestSuite()
 
1076
        test.addTest(unittest.FunctionTestCase(known_failure_test))
 
1077
        def failing_test():
 
1078
            raise AssertionError('foo')
 
1079
        test.addTest(unittest.FunctionTestCase(failing_test))
 
1080
        stream = StringIO()
 
1081
        runner = tests.TextTestRunner(stream=stream)
 
1082
        result = self.run_test_runner(runner, test)
 
1083
        lines = stream.getvalue().splitlines()
 
1084
        self.assertEqual([
 
1085
            '',
 
1086
            '======================================================================',
 
1087
            'FAIL: unittest.FunctionTestCase (failing_test)',
 
1088
            '----------------------------------------------------------------------',
 
1089
            'Traceback (most recent call last):',
 
1090
            '    raise AssertionError(\'foo\')',
 
1091
            'AssertionError: foo',
 
1092
            '',
 
1093
            '----------------------------------------------------------------------',
 
1094
            '',
 
1095
            'FAILED (failures=1, known_failure_count=1)'],
 
1096
            lines[3:8] + lines[9:13] + lines[14:])
 
1097
 
 
1098
    def test_known_failure_ok_run(self):
 
1099
        # run a test that generates a known failure which should be printed in the final output.
 
1100
        def known_failure_test():
 
1101
            raise tests.KnownFailure('failed')
 
1102
        test = unittest.FunctionTestCase(known_failure_test)
 
1103
        stream = StringIO()
 
1104
        runner = tests.TextTestRunner(stream=stream)
 
1105
        result = self.run_test_runner(runner, test)
 
1106
        self.assertContainsRe(stream.getvalue(),
 
1107
            '\n'
 
1108
            '-*\n'
 
1109
            'Ran 1 test in .*\n'
 
1110
            '\n'
 
1111
            'OK \\(known_failures=1\\)\n')
 
1112
 
 
1113
    def test_skipped_test(self):
 
1114
        # run a test that is skipped, and check the suite as a whole still
 
1115
        # succeeds.
 
1116
        # skipping_test must be hidden in here so it's not run as a real test
 
1117
        class SkippingTest(tests.TestCase):
 
1118
            def skipping_test(self):
 
1119
                raise tests.TestSkipped('test intentionally skipped')
 
1120
        runner = tests.TextTestRunner(stream=self._log_file)
 
1121
        test = SkippingTest("skipping_test")
 
1122
        result = self.run_test_runner(runner, test)
 
1123
        self.assertTrue(result.wasSuccessful())
 
1124
 
 
1125
    def test_skipped_from_setup(self):
 
1126
        calls = []
 
1127
        class SkippedSetupTest(tests.TestCase):
 
1128
 
 
1129
            def setUp(self):
 
1130
                calls.append('setUp')
 
1131
                self.addCleanup(self.cleanup)
 
1132
                raise tests.TestSkipped('skipped setup')
 
1133
 
 
1134
            def test_skip(self):
 
1135
                self.fail('test reached')
 
1136
 
 
1137
            def cleanup(self):
 
1138
                calls.append('cleanup')
 
1139
 
 
1140
        runner = tests.TextTestRunner(stream=self._log_file)
 
1141
        test = SkippedSetupTest('test_skip')
 
1142
        result = self.run_test_runner(runner, test)
 
1143
        self.assertTrue(result.wasSuccessful())
 
1144
        # Check if cleanup was called the right number of times.
 
1145
        self.assertEqual(['setUp', 'cleanup'], calls)
 
1146
 
 
1147
    def test_skipped_from_test(self):
 
1148
        calls = []
 
1149
        class SkippedTest(tests.TestCase):
 
1150
 
 
1151
            def setUp(self):
 
1152
                tests.TestCase.setUp(self)
 
1153
                calls.append('setUp')
 
1154
                self.addCleanup(self.cleanup)
 
1155
 
 
1156
            def test_skip(self):
 
1157
                raise tests.TestSkipped('skipped test')
 
1158
 
 
1159
            def cleanup(self):
 
1160
                calls.append('cleanup')
 
1161
 
 
1162
        runner = tests.TextTestRunner(stream=self._log_file)
 
1163
        test = SkippedTest('test_skip')
 
1164
        result = self.run_test_runner(runner, test)
 
1165
        self.assertTrue(result.wasSuccessful())
 
1166
        # Check if cleanup was called the right number of times.
 
1167
        self.assertEqual(['setUp', 'cleanup'], calls)
 
1168
 
 
1169
    def test_not_applicable(self):
 
1170
        # run a test that is skipped because it's not applicable
 
1171
        def not_applicable_test():
 
1172
            raise tests.TestNotApplicable('this test never runs')
 
1173
        out = StringIO()
 
1174
        runner = tests.TextTestRunner(stream=out, verbosity=2)
 
1175
        test = unittest.FunctionTestCase(not_applicable_test)
 
1176
        result = self.run_test_runner(runner, test)
 
1177
        self._log_file.write(out.getvalue())
 
1178
        self.assertTrue(result.wasSuccessful())
 
1179
        self.assertTrue(result.wasStrictlySuccessful())
 
1180
        self.assertContainsRe(out.getvalue(),
 
1181
                r'(?m)not_applicable_test   * N/A')
 
1182
        self.assertContainsRe(out.getvalue(),
 
1183
                r'(?m)^    this test never runs')
 
1184
 
 
1185
    def test_not_applicable_demo(self):
 
1186
        # just so you can see it in the test output
 
1187
        raise tests.TestNotApplicable('this test is just a demonstation')
 
1188
 
 
1189
    def test_unsupported_features_listed(self):
 
1190
        """When unsupported features are encountered they are detailed."""
 
1191
        class Feature1(tests.Feature):
 
1192
            def _probe(self): return False
 
1193
        class Feature2(tests.Feature):
 
1194
            def _probe(self): return False
 
1195
        # create sample tests
 
1196
        test1 = SampleTestCase('_test_pass')
 
1197
        test1._test_needs_features = [Feature1()]
 
1198
        test2 = SampleTestCase('_test_pass')
 
1199
        test2._test_needs_features = [Feature2()]
 
1200
        test = unittest.TestSuite()
 
1201
        test.addTest(test1)
 
1202
        test.addTest(test2)
 
1203
        stream = StringIO()
 
1204
        runner = tests.TextTestRunner(stream=stream)
 
1205
        result = self.run_test_runner(runner, test)
 
1206
        lines = stream.getvalue().splitlines()
 
1207
        self.assertEqual([
 
1208
            'OK',
 
1209
            "Missing feature 'Feature1' skipped 1 tests.",
 
1210
            "Missing feature 'Feature2' skipped 1 tests.",
 
1211
            ],
 
1212
            lines[-3:])
 
1213
 
 
1214
    def test_bench_history(self):
 
1215
        # tests that the running the benchmark produces a history file
 
1216
        # containing a timestamp and the revision id of the bzrlib source which
 
1217
        # was tested.
 
1218
        workingtree = _get_bzr_source_tree()
 
1219
        test = TestRunner('dummy_test')
 
1220
        output = StringIO()
 
1221
        runner = tests.TextTestRunner(stream=self._log_file,
 
1222
                                      bench_history=output)
 
1223
        result = self.run_test_runner(runner, test)
 
1224
        output_string = output.getvalue()
 
1225
        self.assertContainsRe(output_string, "--date [0-9.]+")
 
1226
        if workingtree is not None:
 
1227
            revision_id = workingtree.get_parent_ids()[0]
 
1228
            self.assertEndsWith(output_string.rstrip(), revision_id)
 
1229
 
 
1230
    def assertLogDeleted(self, test):
 
1231
        log = test._get_log()
 
1232
        self.assertEqual("DELETED log file to reduce memory footprint", log)
 
1233
        self.assertEqual('', test._log_contents)
 
1234
        self.assertIs(None, test._log_file_name)
 
1235
 
 
1236
    def test_success_log_deleted(self):
 
1237
        """Successful tests have their log deleted"""
 
1238
 
 
1239
        class LogTester(tests.TestCase):
 
1240
 
 
1241
            def test_success(self):
 
1242
                self.log('this will be removed\n')
 
1243
 
 
1244
        sio = StringIO()
 
1245
        runner = tests.TextTestRunner(stream=sio)
 
1246
        test = LogTester('test_success')
 
1247
        result = self.run_test_runner(runner, test)
 
1248
 
 
1249
        self.assertLogDeleted(test)
 
1250
 
 
1251
    def test_skipped_log_deleted(self):
 
1252
        """Skipped tests have their log deleted"""
 
1253
 
 
1254
        class LogTester(tests.TestCase):
 
1255
 
 
1256
            def test_skipped(self):
 
1257
                self.log('this will be removed\n')
 
1258
                raise tests.TestSkipped()
 
1259
 
 
1260
        sio = StringIO()
 
1261
        runner = tests.TextTestRunner(stream=sio)
 
1262
        test = LogTester('test_skipped')
 
1263
        result = self.run_test_runner(runner, test)
 
1264
 
 
1265
        self.assertLogDeleted(test)
 
1266
 
 
1267
    def test_not_aplicable_log_deleted(self):
 
1268
        """Not applicable tests have their log deleted"""
 
1269
 
 
1270
        class LogTester(tests.TestCase):
 
1271
 
 
1272
            def test_not_applicable(self):
 
1273
                self.log('this will be removed\n')
 
1274
                raise tests.TestNotApplicable()
 
1275
 
 
1276
        sio = StringIO()
 
1277
        runner = tests.TextTestRunner(stream=sio)
 
1278
        test = LogTester('test_not_applicable')
 
1279
        result = self.run_test_runner(runner, test)
 
1280
 
 
1281
        self.assertLogDeleted(test)
 
1282
 
 
1283
    def test_known_failure_log_deleted(self):
 
1284
        """Know failure tests have their log deleted"""
 
1285
 
 
1286
        class LogTester(tests.TestCase):
 
1287
 
 
1288
            def test_known_failure(self):
 
1289
                self.log('this will be removed\n')
 
1290
                raise tests.KnownFailure()
 
1291
 
 
1292
        sio = StringIO()
 
1293
        runner = tests.TextTestRunner(stream=sio)
 
1294
        test = LogTester('test_known_failure')
 
1295
        result = self.run_test_runner(runner, test)
 
1296
 
 
1297
        self.assertLogDeleted(test)
 
1298
 
 
1299
    def test_fail_log_kept(self):
 
1300
        """Failed tests have their log kept"""
 
1301
 
 
1302
        class LogTester(tests.TestCase):
 
1303
 
 
1304
            def test_fail(self):
 
1305
                self.log('this will be kept\n')
 
1306
                self.fail('this test fails')
 
1307
 
 
1308
        sio = StringIO()
 
1309
        runner = tests.TextTestRunner(stream=sio)
 
1310
        test = LogTester('test_fail')
 
1311
        result = self.run_test_runner(runner, test)
 
1312
 
 
1313
        text = sio.getvalue()
 
1314
        self.assertContainsRe(text, 'this will be kept')
 
1315
        self.assertContainsRe(text, 'this test fails')
 
1316
 
 
1317
        log = test._get_log()
 
1318
        self.assertContainsRe(log, 'this will be kept')
 
1319
        self.assertEqual(log, test._log_contents)
 
1320
 
 
1321
    def test_error_log_kept(self):
 
1322
        """Tests with errors have their log kept"""
 
1323
 
 
1324
        class LogTester(tests.TestCase):
 
1325
 
 
1326
            def test_error(self):
 
1327
                self.log('this will be kept\n')
 
1328
                raise ValueError('random exception raised')
 
1329
 
 
1330
        sio = StringIO()
 
1331
        runner = tests.TextTestRunner(stream=sio)
 
1332
        test = LogTester('test_error')
 
1333
        result = self.run_test_runner(runner, test)
 
1334
 
 
1335
        text = sio.getvalue()
 
1336
        self.assertContainsRe(text, 'this will be kept')
 
1337
        self.assertContainsRe(text, 'random exception raised')
 
1338
 
 
1339
        log = test._get_log()
 
1340
        self.assertContainsRe(log, 'this will be kept')
 
1341
        self.assertEqual(log, test._log_contents)
 
1342
 
 
1343
 
 
1344
class SampleTestCase(tests.TestCase):
 
1345
 
 
1346
    def _test_pass(self):
 
1347
        pass
 
1348
 
 
1349
class _TestException(Exception):
 
1350
    pass
 
1351
 
 
1352
class TestTestCase(tests.TestCase):
 
1353
    """Tests that test the core bzrlib TestCase."""
 
1354
 
 
1355
    def test_assertLength_matches_empty(self):
 
1356
        a_list = []
 
1357
        self.assertLength(0, a_list)
 
1358
 
 
1359
    def test_assertLength_matches_nonempty(self):
 
1360
        a_list = [1, 2, 3]
 
1361
        self.assertLength(3, a_list)
 
1362
 
 
1363
    def test_assertLength_fails_different(self):
 
1364
        a_list = []
 
1365
        self.assertRaises(AssertionError, self.assertLength, 1, a_list)
 
1366
 
 
1367
    def test_assertLength_shows_sequence_in_failure(self):
 
1368
        a_list = [1, 2, 3]
 
1369
        exception = self.assertRaises(AssertionError, self.assertLength, 2,
 
1370
            a_list)
 
1371
        self.assertEqual('Incorrect length: wanted 2, got 3 for [1, 2, 3]',
 
1372
            exception.args[0])
 
1373
 
 
1374
    def test_base_setUp_not_called_causes_failure(self):
 
1375
        class TestCaseWithBrokenSetUp(tests.TestCase):
 
1376
            def setUp(self):
 
1377
                pass # does not call TestCase.setUp
 
1378
            def test_foo(self):
 
1379
                pass
 
1380
        test = TestCaseWithBrokenSetUp('test_foo')
 
1381
        result = unittest.TestResult()
 
1382
        test.run(result)
 
1383
        self.assertFalse(result.wasSuccessful())
 
1384
        self.assertEqual(1, result.testsRun)
 
1385
 
 
1386
    def test_base_tearDown_not_called_causes_failure(self):
 
1387
        class TestCaseWithBrokenTearDown(tests.TestCase):
 
1388
            def tearDown(self):
 
1389
                pass # does not call TestCase.tearDown
 
1390
            def test_foo(self):
 
1391
                pass
 
1392
        test = TestCaseWithBrokenTearDown('test_foo')
 
1393
        result = unittest.TestResult()
 
1394
        test.run(result)
 
1395
        self.assertFalse(result.wasSuccessful())
 
1396
        self.assertEqual(1, result.testsRun)
 
1397
 
 
1398
    def test_debug_flags_sanitised(self):
 
1399
        """The bzrlib debug flags should be sanitised by setUp."""
 
1400
        if 'allow_debug' in tests.selftest_debug_flags:
 
1401
            raise tests.TestNotApplicable(
 
1402
                '-Eallow_debug option prevents debug flag sanitisation')
 
1403
        # we could set something and run a test that will check
 
1404
        # it gets santised, but this is probably sufficient for now:
 
1405
        # if someone runs the test with -Dsomething it will error.
 
1406
        self.assertEqual(set(), bzrlib.debug.debug_flags)
 
1407
 
 
1408
    def change_selftest_debug_flags(self, new_flags):
 
1409
        orig_selftest_flags = tests.selftest_debug_flags
 
1410
        self.addCleanup(self._restore_selftest_debug_flags, orig_selftest_flags)
 
1411
        tests.selftest_debug_flags = set(new_flags)
 
1412
 
 
1413
    def _restore_selftest_debug_flags(self, flags):
 
1414
        tests.selftest_debug_flags = flags
 
1415
 
 
1416
    def test_allow_debug_flag(self):
 
1417
        """The -Eallow_debug flag prevents bzrlib.debug.debug_flags from being
 
1418
        sanitised (i.e. cleared) before running a test.
 
1419
        """
 
1420
        self.change_selftest_debug_flags(set(['allow_debug']))
 
1421
        bzrlib.debug.debug_flags = set(['a-flag'])
 
1422
        class TestThatRecordsFlags(tests.TestCase):
 
1423
            def test_foo(nested_self):
 
1424
                self.flags = set(bzrlib.debug.debug_flags)
 
1425
        test = TestThatRecordsFlags('test_foo')
 
1426
        test.run(self.make_test_result())
 
1427
        self.assertEqual(set(['a-flag']), self.flags)
 
1428
 
 
1429
    def test_debug_flags_restored(self):
 
1430
        """The bzrlib debug flags should be restored to their original state
 
1431
        after the test was run, even if allow_debug is set.
 
1432
        """
 
1433
        self.change_selftest_debug_flags(set(['allow_debug']))
 
1434
        # Now run a test that modifies debug.debug_flags.
 
1435
        bzrlib.debug.debug_flags = set(['original-state'])
 
1436
        class TestThatModifiesFlags(tests.TestCase):
 
1437
            def test_foo(self):
 
1438
                bzrlib.debug.debug_flags = set(['modified'])
 
1439
        test = TestThatModifiesFlags('test_foo')
 
1440
        test.run(self.make_test_result())
 
1441
        self.assertEqual(set(['original-state']), bzrlib.debug.debug_flags)
 
1442
 
 
1443
    def make_test_result(self):
 
1444
        return tests.TextTestResult(self._log_file, descriptions=0, verbosity=1)
 
1445
 
 
1446
    def inner_test(self):
 
1447
        # the inner child test
 
1448
        note("inner_test")
 
1449
 
 
1450
    def outer_child(self):
 
1451
        # the outer child test
 
1452
        note("outer_start")
 
1453
        self.inner_test = TestTestCase("inner_child")
 
1454
        result = self.make_test_result()
 
1455
        self.inner_test.run(result)
 
1456
        note("outer finish")
 
1457
 
 
1458
    def test_trace_nesting(self):
 
1459
        # this tests that each test case nests its trace facility correctly.
 
1460
        # we do this by running a test case manually. That test case (A)
 
1461
        # should setup a new log, log content to it, setup a child case (B),
 
1462
        # which should log independently, then case (A) should log a trailer
 
1463
        # and return.
 
1464
        # we do two nested children so that we can verify the state of the
 
1465
        # logs after the outer child finishes is correct, which a bad clean
 
1466
        # up routine in tearDown might trigger a fault in our test with only
 
1467
        # one child, we should instead see the bad result inside our test with
 
1468
        # the two children.
 
1469
        # the outer child test
 
1470
        original_trace = bzrlib.trace._trace_file
 
1471
        outer_test = TestTestCase("outer_child")
 
1472
        result = self.make_test_result()
 
1473
        outer_test.run(result)
 
1474
        self.assertEqual(original_trace, bzrlib.trace._trace_file)
 
1475
 
 
1476
    def method_that_times_a_bit_twice(self):
 
1477
        # call self.time twice to ensure it aggregates
 
1478
        self.time(time.sleep, 0.007)
 
1479
        self.time(time.sleep, 0.007)
 
1480
 
 
1481
    def test_time_creates_benchmark_in_result(self):
 
1482
        """Test that the TestCase.time() method accumulates a benchmark time."""
 
1483
        sample_test = TestTestCase("method_that_times_a_bit_twice")
 
1484
        output_stream = StringIO()
 
1485
        result = bzrlib.tests.VerboseTestResult(
 
1486
            unittest._WritelnDecorator(output_stream),
 
1487
            descriptions=0,
 
1488
            verbosity=2,
 
1489
            num_tests=sample_test.countTestCases())
 
1490
        sample_test.run(result)
 
1491
        self.assertContainsRe(
 
1492
            output_stream.getvalue(),
 
1493
            r"\d+ms/ +\d+ms\n$")
 
1494
 
 
1495
    def test_hooks_sanitised(self):
 
1496
        """The bzrlib hooks should be sanitised by setUp."""
 
1497
        # Note this test won't fail with hooks that the core library doesn't
 
1498
        # use - but it trigger with a plugin that adds hooks, so its still a
 
1499
        # useful warning in that case.
 
1500
        self.assertEqual(bzrlib.branch.BranchHooks(),
 
1501
            bzrlib.branch.Branch.hooks)
 
1502
        self.assertEqual(bzrlib.smart.server.SmartServerHooks(),
 
1503
            bzrlib.smart.server.SmartTCPServer.hooks)
 
1504
        self.assertEqual(bzrlib.commands.CommandHooks(),
 
1505
            bzrlib.commands.Command.hooks)
 
1506
 
 
1507
    def test__gather_lsprof_in_benchmarks(self):
 
1508
        """When _gather_lsprof_in_benchmarks is on, accumulate profile data.
 
1509
 
 
1510
        Each self.time() call is individually and separately profiled.
 
1511
        """
 
1512
        self.requireFeature(test_lsprof.LSProfFeature)
 
1513
        # overrides the class member with an instance member so no cleanup
 
1514
        # needed.
 
1515
        self._gather_lsprof_in_benchmarks = True
 
1516
        self.time(time.sleep, 0.000)
 
1517
        self.time(time.sleep, 0.003)
 
1518
        self.assertEqual(2, len(self._benchcalls))
 
1519
        self.assertEqual((time.sleep, (0.000,), {}), self._benchcalls[0][0])
 
1520
        self.assertEqual((time.sleep, (0.003,), {}), self._benchcalls[1][0])
 
1521
        self.assertIsInstance(self._benchcalls[0][1], bzrlib.lsprof.Stats)
 
1522
        self.assertIsInstance(self._benchcalls[1][1], bzrlib.lsprof.Stats)
 
1523
 
 
1524
    def test_knownFailure(self):
 
1525
        """Self.knownFailure() should raise a KnownFailure exception."""
 
1526
        self.assertRaises(tests.KnownFailure, self.knownFailure, "A Failure")
 
1527
 
 
1528
    def test_requireFeature_available(self):
 
1529
        """self.requireFeature(available) is a no-op."""
 
1530
        class Available(tests.Feature):
 
1531
            def _probe(self):return True
 
1532
        feature = Available()
 
1533
        self.requireFeature(feature)
 
1534
 
 
1535
    def test_requireFeature_unavailable(self):
 
1536
        """self.requireFeature(unavailable) raises UnavailableFeature."""
 
1537
        class Unavailable(tests.Feature):
 
1538
            def _probe(self):return False
 
1539
        feature = Unavailable()
 
1540
        self.assertRaises(tests.UnavailableFeature,
 
1541
                          self.requireFeature, feature)
 
1542
 
 
1543
    def test_run_no_parameters(self):
 
1544
        test = SampleTestCase('_test_pass')
 
1545
        test.run()
 
1546
 
 
1547
    def test_run_enabled_unittest_result(self):
 
1548
        """Test we revert to regular behaviour when the test is enabled."""
 
1549
        test = SampleTestCase('_test_pass')
 
1550
        class EnabledFeature(object):
 
1551
            def available(self):
 
1552
                return True
 
1553
        test._test_needs_features = [EnabledFeature()]
 
1554
        result = unittest.TestResult()
 
1555
        test.run(result)
 
1556
        self.assertEqual(1, result.testsRun)
 
1557
        self.assertEqual([], result.errors)
 
1558
        self.assertEqual([], result.failures)
 
1559
 
 
1560
    def test_run_disabled_unittest_result(self):
 
1561
        """Test our compatability for disabled tests with unittest results."""
 
1562
        test = SampleTestCase('_test_pass')
 
1563
        class DisabledFeature(object):
 
1564
            def available(self):
 
1565
                return False
 
1566
        test._test_needs_features = [DisabledFeature()]
 
1567
        result = unittest.TestResult()
 
1568
        test.run(result)
 
1569
        self.assertEqual(1, result.testsRun)
 
1570
        self.assertEqual([], result.errors)
 
1571
        self.assertEqual([], result.failures)
 
1572
 
 
1573
    def test_run_disabled_supporting_result(self):
 
1574
        """Test disabled tests behaviour with support aware results."""
 
1575
        test = SampleTestCase('_test_pass')
 
1576
        class DisabledFeature(object):
 
1577
            def available(self):
 
1578
                return False
 
1579
        the_feature = DisabledFeature()
 
1580
        test._test_needs_features = [the_feature]
 
1581
        class InstrumentedTestResult(unittest.TestResult):
 
1582
            def __init__(self):
 
1583
                unittest.TestResult.__init__(self)
 
1584
                self.calls = []
 
1585
            def startTest(self, test):
 
1586
                self.calls.append(('startTest', test))
 
1587
            def stopTest(self, test):
 
1588
                self.calls.append(('stopTest', test))
 
1589
            def addNotSupported(self, test, feature):
 
1590
                self.calls.append(('addNotSupported', test, feature))
 
1591
        result = InstrumentedTestResult()
 
1592
        test.run(result)
 
1593
        self.assertEqual([
 
1594
            ('startTest', test),
 
1595
            ('addNotSupported', test, the_feature),
 
1596
            ('stopTest', test),
 
1597
            ],
 
1598
            result.calls)
 
1599
 
 
1600
    def test_assert_list_raises_on_generator(self):
 
1601
        def generator_which_will_raise():
 
1602
            # This will not raise until after the first yield
 
1603
            yield 1
 
1604
            raise _TestException()
 
1605
 
 
1606
        e = self.assertListRaises(_TestException, generator_which_will_raise)
 
1607
        self.assertIsInstance(e, _TestException)
 
1608
 
 
1609
        e = self.assertListRaises(Exception, generator_which_will_raise)
 
1610
        self.assertIsInstance(e, _TestException)
 
1611
 
 
1612
    def test_assert_list_raises_on_plain(self):
 
1613
        def plain_exception():
 
1614
            raise _TestException()
 
1615
            return []
 
1616
 
 
1617
        e = self.assertListRaises(_TestException, plain_exception)
 
1618
        self.assertIsInstance(e, _TestException)
 
1619
 
 
1620
        e = self.assertListRaises(Exception, plain_exception)
 
1621
        self.assertIsInstance(e, _TestException)
 
1622
 
 
1623
    def test_assert_list_raises_assert_wrong_exception(self):
 
1624
        class _NotTestException(Exception):
 
1625
            pass
 
1626
 
 
1627
        def wrong_exception():
 
1628
            raise _NotTestException()
 
1629
 
 
1630
        def wrong_exception_generator():
 
1631
            yield 1
 
1632
            yield 2
 
1633
            raise _NotTestException()
 
1634
 
 
1635
        # Wrong exceptions are not intercepted
 
1636
        self.assertRaises(_NotTestException,
 
1637
            self.assertListRaises, _TestException, wrong_exception)
 
1638
        self.assertRaises(_NotTestException,
 
1639
            self.assertListRaises, _TestException, wrong_exception_generator)
 
1640
 
 
1641
    def test_assert_list_raises_no_exception(self):
 
1642
        def success():
 
1643
            return []
 
1644
 
 
1645
        def success_generator():
 
1646
            yield 1
 
1647
            yield 2
 
1648
 
 
1649
        self.assertRaises(AssertionError,
 
1650
            self.assertListRaises, _TestException, success)
 
1651
 
 
1652
        self.assertRaises(AssertionError,
 
1653
            self.assertListRaises, _TestException, success_generator)
 
1654
 
 
1655
 
 
1656
# NB: Don't delete this; it's not actually from 0.11!
 
1657
@deprecated_function(deprecated_in((0, 11, 0)))
 
1658
def sample_deprecated_function():
 
1659
    """A deprecated function to test applyDeprecated with."""
 
1660
    return 2
 
1661
 
 
1662
 
 
1663
def sample_undeprecated_function(a_param):
 
1664
    """A undeprecated function to test applyDeprecated with."""
 
1665
 
 
1666
 
 
1667
class ApplyDeprecatedHelper(object):
 
1668
    """A helper class for ApplyDeprecated tests."""
 
1669
 
 
1670
    @deprecated_method(deprecated_in((0, 11, 0)))
 
1671
    def sample_deprecated_method(self, param_one):
 
1672
        """A deprecated method for testing with."""
 
1673
        return param_one
 
1674
 
 
1675
    def sample_normal_method(self):
 
1676
        """A undeprecated method."""
 
1677
 
 
1678
    @deprecated_method(deprecated_in((0, 10, 0)))
 
1679
    def sample_nested_deprecation(self):
 
1680
        return sample_deprecated_function()
 
1681
 
 
1682
 
 
1683
class TestExtraAssertions(tests.TestCase):
 
1684
    """Tests for new test assertions in bzrlib test suite"""
 
1685
 
 
1686
    def test_assert_isinstance(self):
 
1687
        self.assertIsInstance(2, int)
 
1688
        self.assertIsInstance(u'', basestring)
 
1689
        self.assertRaises(AssertionError, self.assertIsInstance, None, int)
 
1690
        self.assertRaises(AssertionError, self.assertIsInstance, 23.3, int)
 
1691
 
 
1692
    def test_assertEndsWith(self):
 
1693
        self.assertEndsWith('foo', 'oo')
 
1694
        self.assertRaises(AssertionError, self.assertEndsWith, 'o', 'oo')
 
1695
 
 
1696
    def test_applyDeprecated_not_deprecated(self):
 
1697
        sample_object = ApplyDeprecatedHelper()
 
1698
        # calling an undeprecated callable raises an assertion
 
1699
        self.assertRaises(AssertionError, self.applyDeprecated,
 
1700
            deprecated_in((0, 11, 0)),
 
1701
            sample_object.sample_normal_method)
 
1702
        self.assertRaises(AssertionError, self.applyDeprecated,
 
1703
            deprecated_in((0, 11, 0)),
 
1704
            sample_undeprecated_function, "a param value")
 
1705
        # calling a deprecated callable (function or method) with the wrong
 
1706
        # expected deprecation fails.
 
1707
        self.assertRaises(AssertionError, self.applyDeprecated,
 
1708
            deprecated_in((0, 10, 0)),
 
1709
            sample_object.sample_deprecated_method, "a param value")
 
1710
        self.assertRaises(AssertionError, self.applyDeprecated,
 
1711
            deprecated_in((0, 10, 0)),
 
1712
            sample_deprecated_function)
 
1713
        # calling a deprecated callable (function or method) with the right
 
1714
        # expected deprecation returns the functions result.
 
1715
        self.assertEqual("a param value",
 
1716
            self.applyDeprecated(deprecated_in((0, 11, 0)),
 
1717
            sample_object.sample_deprecated_method, "a param value"))
 
1718
        self.assertEqual(2, self.applyDeprecated(deprecated_in((0, 11, 0)),
 
1719
            sample_deprecated_function))
 
1720
        # calling a nested deprecation with the wrong deprecation version
 
1721
        # fails even if a deeper nested function was deprecated with the
 
1722
        # supplied version.
 
1723
        self.assertRaises(AssertionError, self.applyDeprecated,
 
1724
            deprecated_in((0, 11, 0)), sample_object.sample_nested_deprecation)
 
1725
        # calling a nested deprecation with the right deprecation value
 
1726
        # returns the calls result.
 
1727
        self.assertEqual(2, self.applyDeprecated(deprecated_in((0, 10, 0)),
 
1728
            sample_object.sample_nested_deprecation))
 
1729
 
 
1730
    def test_callDeprecated(self):
 
1731
        def testfunc(be_deprecated, result=None):
 
1732
            if be_deprecated is True:
 
1733
                symbol_versioning.warn('i am deprecated', DeprecationWarning,
 
1734
                                       stacklevel=1)
 
1735
            return result
 
1736
        result = self.callDeprecated(['i am deprecated'], testfunc, True)
 
1737
        self.assertIs(None, result)
 
1738
        result = self.callDeprecated([], testfunc, False, 'result')
 
1739
        self.assertEqual('result', result)
 
1740
        self.callDeprecated(['i am deprecated'], testfunc, be_deprecated=True)
 
1741
        self.callDeprecated([], testfunc, be_deprecated=False)
 
1742
 
 
1743
 
 
1744
class TestWarningTests(tests.TestCase):
 
1745
    """Tests for calling methods that raise warnings."""
 
1746
 
 
1747
    def test_callCatchWarnings(self):
 
1748
        def meth(a, b):
 
1749
            warnings.warn("this is your last warning")
 
1750
            return a + b
 
1751
        wlist, result = self.callCatchWarnings(meth, 1, 2)
 
1752
        self.assertEquals(3, result)
 
1753
        # would like just to compare them, but UserWarning doesn't implement
 
1754
        # eq well
 
1755
        w0, = wlist
 
1756
        self.assertIsInstance(w0, UserWarning)
 
1757
        self.assertEquals("this is your last warning", str(w0))
 
1758
 
 
1759
 
 
1760
class TestConvenienceMakers(tests.TestCaseWithTransport):
 
1761
    """Test for the make_* convenience functions."""
 
1762
 
 
1763
    def test_make_branch_and_tree_with_format(self):
 
1764
        # we should be able to supply a format to make_branch_and_tree
 
1765
        self.make_branch_and_tree('a', format=bzrlib.bzrdir.BzrDirMetaFormat1())
 
1766
        self.make_branch_and_tree('b', format=bzrlib.bzrdir.BzrDirFormat6())
 
1767
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('a')._format,
 
1768
                              bzrlib.bzrdir.BzrDirMetaFormat1)
 
1769
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('b')._format,
 
1770
                              bzrlib.bzrdir.BzrDirFormat6)
 
1771
 
 
1772
    def test_make_branch_and_memory_tree(self):
 
1773
        # we should be able to get a new branch and a mutable tree from
 
1774
        # TestCaseWithTransport
 
1775
        tree = self.make_branch_and_memory_tree('a')
 
1776
        self.assertIsInstance(tree, bzrlib.memorytree.MemoryTree)
 
1777
 
 
1778
 
 
1779
class TestSFTPMakeBranchAndTree(test_sftp_transport.TestCaseWithSFTPServer):
 
1780
 
 
1781
    def test_make_tree_for_sftp_branch(self):
 
1782
        """Transports backed by local directories create local trees."""
 
1783
 
 
1784
        tree = self.make_branch_and_tree('t1')
 
1785
        base = tree.bzrdir.root_transport.base
 
1786
        self.failIf(base.startswith('sftp'),
 
1787
                'base %r is on sftp but should be local' % base)
 
1788
        self.assertEquals(tree.bzrdir.root_transport,
 
1789
                tree.branch.bzrdir.root_transport)
 
1790
        self.assertEquals(tree.bzrdir.root_transport,
 
1791
                tree.branch.repository.bzrdir.root_transport)
 
1792
 
 
1793
 
 
1794
class TestSelftest(tests.TestCase):
 
1795
    """Tests of bzrlib.tests.selftest."""
 
1796
 
 
1797
    def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
 
1798
        factory_called = []
 
1799
        def factory():
 
1800
            factory_called.append(True)
 
1801
            return TestUtil.TestSuite()
 
1802
        out = StringIO()
 
1803
        err = StringIO()
 
1804
        self.apply_redirected(out, err, None, bzrlib.tests.selftest,
 
1805
            test_suite_factory=factory)
 
1806
        self.assertEqual([True], factory_called)
 
1807
 
 
1808
 
 
1809
class TestKnownFailure(tests.TestCase):
 
1810
 
 
1811
    def test_known_failure(self):
 
1812
        """Check that KnownFailure is defined appropriately."""
 
1813
        # a KnownFailure is an assertion error for compatability with unaware
 
1814
        # runners.
 
1815
        self.assertIsInstance(tests.KnownFailure(""), AssertionError)
 
1816
 
 
1817
    def test_expect_failure(self):
 
1818
        try:
 
1819
            self.expectFailure("Doomed to failure", self.assertTrue, False)
 
1820
        except tests.KnownFailure, e:
 
1821
            self.assertEqual('Doomed to failure', e.args[0])
 
1822
        try:
 
1823
            self.expectFailure("Doomed to failure", self.assertTrue, True)
 
1824
        except AssertionError, e:
 
1825
            self.assertEqual('Unexpected success.  Should have failed:'
 
1826
                             ' Doomed to failure', e.args[0])
 
1827
        else:
 
1828
            self.fail('Assertion not raised')
 
1829
 
 
1830
 
 
1831
class TestFeature(tests.TestCase):
 
1832
 
 
1833
    def test_caching(self):
 
1834
        """Feature._probe is called by the feature at most once."""
 
1835
        class InstrumentedFeature(tests.Feature):
 
1836
            def __init__(self):
 
1837
                super(InstrumentedFeature, self).__init__()
 
1838
                self.calls = []
 
1839
            def _probe(self):
 
1840
                self.calls.append('_probe')
 
1841
                return False
 
1842
        feature = InstrumentedFeature()
 
1843
        feature.available()
 
1844
        self.assertEqual(['_probe'], feature.calls)
 
1845
        feature.available()
 
1846
        self.assertEqual(['_probe'], feature.calls)
 
1847
 
 
1848
    def test_named_str(self):
 
1849
        """Feature.__str__ should thunk to feature_name()."""
 
1850
        class NamedFeature(tests.Feature):
 
1851
            def feature_name(self):
 
1852
                return 'symlinks'
 
1853
        feature = NamedFeature()
 
1854
        self.assertEqual('symlinks', str(feature))
 
1855
 
 
1856
    def test_default_str(self):
 
1857
        """Feature.__str__ should default to __class__.__name__."""
 
1858
        class NamedFeature(tests.Feature):
 
1859
            pass
 
1860
        feature = NamedFeature()
 
1861
        self.assertEqual('NamedFeature', str(feature))
 
1862
 
 
1863
 
 
1864
class TestUnavailableFeature(tests.TestCase):
 
1865
 
 
1866
    def test_access_feature(self):
 
1867
        feature = tests.Feature()
 
1868
        exception = tests.UnavailableFeature(feature)
 
1869
        self.assertIs(feature, exception.args[0])
 
1870
 
 
1871
 
 
1872
class TestSelftestFiltering(tests.TestCase):
 
1873
 
 
1874
    def setUp(self):
 
1875
        tests.TestCase.setUp(self)
 
1876
        self.suite = TestUtil.TestSuite()
 
1877
        self.loader = TestUtil.TestLoader()
 
1878
        self.suite.addTest(self.loader.loadTestsFromModuleNames([
 
1879
            'bzrlib.tests.test_selftest']))
 
1880
        self.all_names = _test_ids(self.suite)
 
1881
 
 
1882
    def test_condition_id_re(self):
 
1883
        test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
1884
            'test_condition_id_re')
 
1885
        filtered_suite = tests.filter_suite_by_condition(
 
1886
            self.suite, tests.condition_id_re('test_condition_id_re'))
 
1887
        self.assertEqual([test_name], _test_ids(filtered_suite))
 
1888
 
 
1889
    def test_condition_id_in_list(self):
 
1890
        test_names = ['bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
1891
                      'test_condition_id_in_list']
 
1892
        id_list = tests.TestIdList(test_names)
 
1893
        filtered_suite = tests.filter_suite_by_condition(
 
1894
            self.suite, tests.condition_id_in_list(id_list))
 
1895
        my_pattern = 'TestSelftestFiltering.*test_condition_id_in_list'
 
1896
        re_filtered = tests.filter_suite_by_re(self.suite, my_pattern)
 
1897
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
 
1898
 
 
1899
    def test_condition_id_startswith(self):
 
1900
        klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
1901
        start1 = klass + 'test_condition_id_starts'
 
1902
        start2 = klass + 'test_condition_id_in'
 
1903
        test_names = [ klass + 'test_condition_id_in_list',
 
1904
                      klass + 'test_condition_id_startswith',
 
1905
                     ]
 
1906
        filtered_suite = tests.filter_suite_by_condition(
 
1907
            self.suite, tests.condition_id_startswith([start1, start2]))
 
1908
        self.assertEqual(test_names, _test_ids(filtered_suite))
 
1909
 
 
1910
    def test_condition_isinstance(self):
 
1911
        filtered_suite = tests.filter_suite_by_condition(
 
1912
            self.suite, tests.condition_isinstance(self.__class__))
 
1913
        class_pattern = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
1914
        re_filtered = tests.filter_suite_by_re(self.suite, class_pattern)
 
1915
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
 
1916
 
 
1917
    def test_exclude_tests_by_condition(self):
 
1918
        excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
1919
            'test_exclude_tests_by_condition')
 
1920
        filtered_suite = tests.exclude_tests_by_condition(self.suite,
 
1921
            lambda x:x.id() == excluded_name)
 
1922
        self.assertEqual(len(self.all_names) - 1,
 
1923
            filtered_suite.countTestCases())
 
1924
        self.assertFalse(excluded_name in _test_ids(filtered_suite))
 
1925
        remaining_names = list(self.all_names)
 
1926
        remaining_names.remove(excluded_name)
 
1927
        self.assertEqual(remaining_names, _test_ids(filtered_suite))
 
1928
 
 
1929
    def test_exclude_tests_by_re(self):
 
1930
        self.all_names = _test_ids(self.suite)
 
1931
        filtered_suite = tests.exclude_tests_by_re(self.suite,
 
1932
                                                   'exclude_tests_by_re')
 
1933
        excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
1934
            'test_exclude_tests_by_re')
 
1935
        self.assertEqual(len(self.all_names) - 1,
 
1936
            filtered_suite.countTestCases())
 
1937
        self.assertFalse(excluded_name in _test_ids(filtered_suite))
 
1938
        remaining_names = list(self.all_names)
 
1939
        remaining_names.remove(excluded_name)
 
1940
        self.assertEqual(remaining_names, _test_ids(filtered_suite))
 
1941
 
 
1942
    def test_filter_suite_by_condition(self):
 
1943
        test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
1944
            'test_filter_suite_by_condition')
 
1945
        filtered_suite = tests.filter_suite_by_condition(self.suite,
 
1946
            lambda x:x.id() == test_name)
 
1947
        self.assertEqual([test_name], _test_ids(filtered_suite))
 
1948
 
 
1949
    def test_filter_suite_by_re(self):
 
1950
        filtered_suite = tests.filter_suite_by_re(self.suite,
 
1951
                                                  'test_filter_suite_by_r')
 
1952
        filtered_names = _test_ids(filtered_suite)
 
1953
        self.assertEqual(filtered_names, ['bzrlib.tests.test_selftest.'
 
1954
            'TestSelftestFiltering.test_filter_suite_by_re'])
 
1955
 
 
1956
    def test_filter_suite_by_id_list(self):
 
1957
        test_list = ['bzrlib.tests.test_selftest.'
 
1958
                     'TestSelftestFiltering.test_filter_suite_by_id_list']
 
1959
        filtered_suite = tests.filter_suite_by_id_list(
 
1960
            self.suite, tests.TestIdList(test_list))
 
1961
        filtered_names = _test_ids(filtered_suite)
 
1962
        self.assertEqual(
 
1963
            filtered_names,
 
1964
            ['bzrlib.tests.test_selftest.'
 
1965
             'TestSelftestFiltering.test_filter_suite_by_id_list'])
 
1966
 
 
1967
    def test_filter_suite_by_id_startswith(self):
 
1968
        # By design this test may fail if another test is added whose name also
 
1969
        # begins with one of the start value used.
 
1970
        klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
1971
        start1 = klass + 'test_filter_suite_by_id_starts'
 
1972
        start2 = klass + 'test_filter_suite_by_id_li'
 
1973
        test_list = [klass + 'test_filter_suite_by_id_list',
 
1974
                     klass + 'test_filter_suite_by_id_startswith',
 
1975
                     ]
 
1976
        filtered_suite = tests.filter_suite_by_id_startswith(
 
1977
            self.suite, [start1, start2])
 
1978
        self.assertEqual(
 
1979
            test_list,
 
1980
            _test_ids(filtered_suite),
 
1981
            )
 
1982
 
 
1983
    def test_preserve_input(self):
 
1984
        # NB: Surely this is something in the stdlib to do this?
 
1985
        self.assertTrue(self.suite is tests.preserve_input(self.suite))
 
1986
        self.assertTrue("@#$" is tests.preserve_input("@#$"))
 
1987
 
 
1988
    def test_randomize_suite(self):
 
1989
        randomized_suite = tests.randomize_suite(self.suite)
 
1990
        # randomizing should not add or remove test names.
 
1991
        self.assertEqual(set(_test_ids(self.suite)),
 
1992
                         set(_test_ids(randomized_suite)))
 
1993
        # Technically, this *can* fail, because random.shuffle(list) can be
 
1994
        # equal to list. Trying multiple times just pushes the frequency back.
 
1995
        # As its len(self.all_names)!:1, the failure frequency should be low
 
1996
        # enough to ignore. RBC 20071021.
 
1997
        # It should change the order.
 
1998
        self.assertNotEqual(self.all_names, _test_ids(randomized_suite))
 
1999
        # But not the length. (Possibly redundant with the set test, but not
 
2000
        # necessarily.)
 
2001
        self.assertEqual(len(self.all_names), len(_test_ids(randomized_suite)))
 
2002
 
 
2003
    def test_split_suit_by_condition(self):
 
2004
        self.all_names = _test_ids(self.suite)
 
2005
        condition = tests.condition_id_re('test_filter_suite_by_r')
 
2006
        split_suite = tests.split_suite_by_condition(self.suite, condition)
 
2007
        filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2008
            'test_filter_suite_by_re')
 
2009
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
 
2010
        self.assertFalse(filtered_name in _test_ids(split_suite[1]))
 
2011
        remaining_names = list(self.all_names)
 
2012
        remaining_names.remove(filtered_name)
 
2013
        self.assertEqual(remaining_names, _test_ids(split_suite[1]))
 
2014
 
 
2015
    def test_split_suit_by_re(self):
 
2016
        self.all_names = _test_ids(self.suite)
 
2017
        split_suite = tests.split_suite_by_re(self.suite,
 
2018
                                              'test_filter_suite_by_r')
 
2019
        filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2020
            'test_filter_suite_by_re')
 
2021
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
 
2022
        self.assertFalse(filtered_name in _test_ids(split_suite[1]))
 
2023
        remaining_names = list(self.all_names)
 
2024
        remaining_names.remove(filtered_name)
 
2025
        self.assertEqual(remaining_names, _test_ids(split_suite[1]))
 
2026
 
 
2027
 
 
2028
class TestCheckInventoryShape(tests.TestCaseWithTransport):
 
2029
 
 
2030
    def test_check_inventory_shape(self):
 
2031
        files = ['a', 'b/', 'b/c']
 
2032
        tree = self.make_branch_and_tree('.')
 
2033
        self.build_tree(files)
 
2034
        tree.add(files)
 
2035
        tree.lock_read()
 
2036
        try:
 
2037
            self.check_inventory_shape(tree.inventory, files)
 
2038
        finally:
 
2039
            tree.unlock()
 
2040
 
 
2041
 
 
2042
class TestBlackboxSupport(tests.TestCase):
 
2043
    """Tests for testsuite blackbox features."""
 
2044
 
 
2045
    def test_run_bzr_failure_not_caught(self):
 
2046
        # When we run bzr in blackbox mode, we want any unexpected errors to
 
2047
        # propagate up to the test suite so that it can show the error in the
 
2048
        # usual way, and we won't get a double traceback.
 
2049
        e = self.assertRaises(
 
2050
            AssertionError,
 
2051
            self.run_bzr, ['assert-fail'])
 
2052
        # make sure we got the real thing, not an error from somewhere else in
 
2053
        # the test framework
 
2054
        self.assertEquals('always fails', str(e))
 
2055
        # check that there's no traceback in the test log
 
2056
        self.assertNotContainsRe(self._get_log(keep_log_file=True),
 
2057
            r'Traceback')
 
2058
 
 
2059
    def test_run_bzr_user_error_caught(self):
 
2060
        # Running bzr in blackbox mode, normal/expected/user errors should be
 
2061
        # caught in the regular way and turned into an error message plus exit
 
2062
        # code.
 
2063
        out, err = self.run_bzr(["log", "/nonexistantpath"], retcode=3)
 
2064
        self.assertEqual(out, '')
 
2065
        self.assertContainsRe(err,
 
2066
            'bzr: ERROR: Not a branch: ".*nonexistantpath/".\n')
 
2067
 
 
2068
 
 
2069
class TestTestLoader(tests.TestCase):
 
2070
    """Tests for the test loader."""
 
2071
 
 
2072
    def _get_loader_and_module(self):
 
2073
        """Gets a TestLoader and a module with one test in it."""
 
2074
        loader = TestUtil.TestLoader()
 
2075
        module = {}
 
2076
        class Stub(tests.TestCase):
 
2077
            def test_foo(self):
 
2078
                pass
 
2079
        class MyModule(object):
 
2080
            pass
 
2081
        MyModule.a_class = Stub
 
2082
        module = MyModule()
 
2083
        return loader, module
 
2084
 
 
2085
    def test_module_no_load_tests_attribute_loads_classes(self):
 
2086
        loader, module = self._get_loader_and_module()
 
2087
        self.assertEqual(1, loader.loadTestsFromModule(module).countTestCases())
 
2088
 
 
2089
    def test_module_load_tests_attribute_gets_called(self):
 
2090
        loader, module = self._get_loader_and_module()
 
2091
        # 'self' is here because we're faking the module with a class. Regular
 
2092
        # load_tests do not need that :)
 
2093
        def load_tests(self, standard_tests, module, loader):
 
2094
            result = loader.suiteClass()
 
2095
            for test in tests.iter_suite_tests(standard_tests):
 
2096
                result.addTests([test, test])
 
2097
            return result
 
2098
        # add a load_tests() method which multiplies the tests from the module.
 
2099
        module.__class__.load_tests = load_tests
 
2100
        self.assertEqual(2, loader.loadTestsFromModule(module).countTestCases())
 
2101
 
 
2102
    def test_load_tests_from_module_name_smoke_test(self):
 
2103
        loader = TestUtil.TestLoader()
 
2104
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2105
        self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
 
2106
                          _test_ids(suite))
 
2107
 
 
2108
    def test_load_tests_from_module_name_with_bogus_module_name(self):
 
2109
        loader = TestUtil.TestLoader()
 
2110
        self.assertRaises(ImportError, loader.loadTestsFromModuleName, 'bogus')
 
2111
 
 
2112
 
 
2113
class TestTestIdList(tests.TestCase):
 
2114
 
 
2115
    def _create_id_list(self, test_list):
 
2116
        return tests.TestIdList(test_list)
 
2117
 
 
2118
    def _create_suite(self, test_id_list):
 
2119
 
 
2120
        class Stub(tests.TestCase):
 
2121
            def test_foo(self):
 
2122
                pass
 
2123
 
 
2124
        def _create_test_id(id):
 
2125
            return lambda: id
 
2126
 
 
2127
        suite = TestUtil.TestSuite()
 
2128
        for id in test_id_list:
 
2129
            t  = Stub('test_foo')
 
2130
            t.id = _create_test_id(id)
 
2131
            suite.addTest(t)
 
2132
        return suite
 
2133
 
 
2134
    def _test_ids(self, test_suite):
 
2135
        """Get the ids for the tests in a test suite."""
 
2136
        return [t.id() for t in tests.iter_suite_tests(test_suite)]
 
2137
 
 
2138
    def test_empty_list(self):
 
2139
        id_list = self._create_id_list([])
 
2140
        self.assertEquals({}, id_list.tests)
 
2141
        self.assertEquals({}, id_list.modules)
 
2142
 
 
2143
    def test_valid_list(self):
 
2144
        id_list = self._create_id_list(
 
2145
            ['mod1.cl1.meth1', 'mod1.cl1.meth2',
 
2146
             'mod1.func1', 'mod1.cl2.meth2',
 
2147
             'mod1.submod1',
 
2148
             'mod1.submod2.cl1.meth1', 'mod1.submod2.cl2.meth2',
 
2149
             ])
 
2150
        self.assertTrue(id_list.refers_to('mod1'))
 
2151
        self.assertTrue(id_list.refers_to('mod1.submod1'))
 
2152
        self.assertTrue(id_list.refers_to('mod1.submod2'))
 
2153
        self.assertTrue(id_list.includes('mod1.cl1.meth1'))
 
2154
        self.assertTrue(id_list.includes('mod1.submod1'))
 
2155
        self.assertTrue(id_list.includes('mod1.func1'))
 
2156
 
 
2157
    def test_bad_chars_in_params(self):
 
2158
        id_list = self._create_id_list(['mod1.cl1.meth1(xx.yy)'])
 
2159
        self.assertTrue(id_list.refers_to('mod1'))
 
2160
        self.assertTrue(id_list.includes('mod1.cl1.meth1(xx.yy)'))
 
2161
 
 
2162
    def test_module_used(self):
 
2163
        id_list = self._create_id_list(['mod.class.meth'])
 
2164
        self.assertTrue(id_list.refers_to('mod'))
 
2165
        self.assertTrue(id_list.refers_to('mod.class'))
 
2166
        self.assertTrue(id_list.refers_to('mod.class.meth'))
 
2167
 
 
2168
    def test_test_suite_matches_id_list_with_unknown(self):
 
2169
        loader = TestUtil.TestLoader()
 
2170
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2171
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',
 
2172
                     'bogus']
 
2173
        not_found, duplicates = tests.suite_matches_id_list(suite, test_list)
 
2174
        self.assertEquals(['bogus'], not_found)
 
2175
        self.assertEquals([], duplicates)
 
2176
 
 
2177
    def test_suite_matches_id_list_with_duplicates(self):
 
2178
        loader = TestUtil.TestLoader()
 
2179
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2180
        dupes = loader.suiteClass()
 
2181
        for test in tests.iter_suite_tests(suite):
 
2182
            dupes.addTest(test)
 
2183
            dupes.addTest(test) # Add it again
 
2184
 
 
2185
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',]
 
2186
        not_found, duplicates = tests.suite_matches_id_list(
 
2187
            dupes, test_list)
 
2188
        self.assertEquals([], not_found)
 
2189
        self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
 
2190
                          duplicates)
 
2191
 
 
2192
 
 
2193
class TestTestSuite(tests.TestCase):
 
2194
 
 
2195
    def test_test_suite(self):
 
2196
        # This test is slow, so we do a single test with one test in each
 
2197
        # category
 
2198
        test_list = [
 
2199
            # testmod_names
 
2200
            'bzrlib.tests.blackbox.test_branch.TestBranch.test_branch',
 
2201
            ('bzrlib.tests.per_transport.TransportTests'
 
2202
             '.test_abspath(LocalURLServer)'),
 
2203
            'bzrlib.tests.test_selftest.TestTestSuite.test_test_suite',
 
2204
            # modules_to_doctest
 
2205
            'bzrlib.timestamp.format_highres_date',
 
2206
            # plugins can't be tested that way since selftest may be run with
 
2207
            # --no-plugins
 
2208
            ]
 
2209
        suite = tests.test_suite(test_list)
 
2210
        self.assertEquals(test_list, _test_ids(suite))
 
2211
 
 
2212
    def test_test_suite_list_and_start(self):
 
2213
        test_list = ['bzrlib.tests.test_selftest.TestTestSuite.test_test_suite']
 
2214
        suite = tests.test_suite(test_list,
 
2215
                                 ['bzrlib.tests.test_selftest.TestTestSuite'])
 
2216
        # test_test_suite_list_and_start is not included 
 
2217
        self.assertEquals(test_list, _test_ids(suite))
 
2218
 
 
2219
 
 
2220
class TestLoadTestIdList(tests.TestCaseInTempDir):
 
2221
 
 
2222
    def _create_test_list_file(self, file_name, content):
 
2223
        fl = open(file_name, 'wt')
 
2224
        fl.write(content)
 
2225
        fl.close()
 
2226
 
 
2227
    def test_load_unknown(self):
 
2228
        self.assertRaises(errors.NoSuchFile,
 
2229
                          tests.load_test_id_list, 'i_do_not_exist')
 
2230
 
 
2231
    def test_load_test_list(self):
 
2232
        test_list_fname = 'test.list'
 
2233
        self._create_test_list_file(test_list_fname,
 
2234
                                    'mod1.cl1.meth1\nmod2.cl2.meth2\n')
 
2235
        tlist = tests.load_test_id_list(test_list_fname)
 
2236
        self.assertEquals(2, len(tlist))
 
2237
        self.assertEquals('mod1.cl1.meth1', tlist[0])
 
2238
        self.assertEquals('mod2.cl2.meth2', tlist[1])
 
2239
 
 
2240
    def test_load_dirty_file(self):
 
2241
        test_list_fname = 'test.list'
 
2242
        self._create_test_list_file(test_list_fname,
 
2243
                                    '  mod1.cl1.meth1\n\nmod2.cl2.meth2  \n'
 
2244
                                    'bar baz\n')
 
2245
        tlist = tests.load_test_id_list(test_list_fname)
 
2246
        self.assertEquals(4, len(tlist))
 
2247
        self.assertEquals('mod1.cl1.meth1', tlist[0])
 
2248
        self.assertEquals('', tlist[1])
 
2249
        self.assertEquals('mod2.cl2.meth2', tlist[2])
 
2250
        self.assertEquals('bar baz', tlist[3])
 
2251
 
 
2252
 
 
2253
class TestFilteredByModuleTestLoader(tests.TestCase):
 
2254
 
 
2255
    def _create_loader(self, test_list):
 
2256
        id_filter = tests.TestIdList(test_list)
 
2257
        loader = TestUtil.FilteredByModuleTestLoader(id_filter.refers_to)
 
2258
        return loader
 
2259
 
 
2260
    def test_load_tests(self):
 
2261
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
 
2262
        loader = self._create_loader(test_list)
 
2263
 
 
2264
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2265
        self.assertEquals(test_list, _test_ids(suite))
 
2266
 
 
2267
    def test_exclude_tests(self):
 
2268
        test_list = ['bogus']
 
2269
        loader = self._create_loader(test_list)
 
2270
 
 
2271
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2272
        self.assertEquals([], _test_ids(suite))
 
2273
 
 
2274
 
 
2275
class TestFilteredByNameStartTestLoader(tests.TestCase):
 
2276
 
 
2277
    def _create_loader(self, name_start):
 
2278
        def needs_module(name):
 
2279
            return name.startswith(name_start) or name_start.startswith(name)
 
2280
        loader = TestUtil.FilteredByModuleTestLoader(needs_module)
 
2281
        return loader
 
2282
 
 
2283
    def test_load_tests(self):
 
2284
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
 
2285
        loader = self._create_loader('bzrlib.tests.test_samp')
 
2286
 
 
2287
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2288
        self.assertEquals(test_list, _test_ids(suite))
 
2289
 
 
2290
    def test_load_tests_inside_module(self):
 
2291
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
 
2292
        loader = self._create_loader('bzrlib.tests.test_sampler.Demo')
 
2293
 
 
2294
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2295
        self.assertEquals(test_list, _test_ids(suite))
 
2296
 
 
2297
    def test_exclude_tests(self):
 
2298
        test_list = ['bogus']
 
2299
        loader = self._create_loader('bogus')
 
2300
 
 
2301
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2302
        self.assertEquals([], _test_ids(suite))
 
2303
 
 
2304
 
 
2305
class TestTestPrefixRegistry(tests.TestCase):
 
2306
 
 
2307
    def _get_registry(self):
 
2308
        tp_registry = tests.TestPrefixAliasRegistry()
 
2309
        return tp_registry
 
2310
 
 
2311
    def test_register_new_prefix(self):
 
2312
        tpr = self._get_registry()
 
2313
        tpr.register('foo', 'fff.ooo.ooo')
 
2314
        self.assertEquals('fff.ooo.ooo', tpr.get('foo'))
 
2315
 
 
2316
    def test_register_existing_prefix(self):
 
2317
        tpr = self._get_registry()
 
2318
        tpr.register('bar', 'bbb.aaa.rrr')
 
2319
        tpr.register('bar', 'bBB.aAA.rRR')
 
2320
        self.assertEquals('bbb.aaa.rrr', tpr.get('bar'))
 
2321
        self.assertContainsRe(self._get_log(keep_log_file=True),
 
2322
                              r'.*bar.*bbb.aaa.rrr.*bBB.aAA.rRR')
 
2323
 
 
2324
    def test_get_unknown_prefix(self):
 
2325
        tpr = self._get_registry()
 
2326
        self.assertRaises(KeyError, tpr.get, 'I am not a prefix')
 
2327
 
 
2328
    def test_resolve_prefix(self):
 
2329
        tpr = self._get_registry()
 
2330
        tpr.register('bar', 'bb.aa.rr')
 
2331
        self.assertEquals('bb.aa.rr', tpr.resolve_alias('bar'))
 
2332
 
 
2333
    def test_resolve_unknown_alias(self):
 
2334
        tpr = self._get_registry()
 
2335
        self.assertRaises(errors.BzrCommandError,
 
2336
                          tpr.resolve_alias, 'I am not a prefix')
 
2337
 
 
2338
    def test_predefined_prefixes(self):
 
2339
        tpr = tests.test_prefix_alias_registry
 
2340
        self.assertEquals('bzrlib', tpr.resolve_alias('bzrlib'))
 
2341
        self.assertEquals('bzrlib.doc', tpr.resolve_alias('bd'))
 
2342
        self.assertEquals('bzrlib.utils', tpr.resolve_alias('bu'))
 
2343
        self.assertEquals('bzrlib.tests', tpr.resolve_alias('bt'))
 
2344
        self.assertEquals('bzrlib.tests.blackbox', tpr.resolve_alias('bb'))
 
2345
        self.assertEquals('bzrlib.plugins', tpr.resolve_alias('bp'))
 
2346
 
 
2347
 
 
2348
class TestRunSuite(tests.TestCase):
 
2349
 
 
2350
    def test_runner_class(self):
 
2351
        """run_suite accepts and uses a runner_class keyword argument."""
 
2352
        class Stub(tests.TestCase):
 
2353
            def test_foo(self):
 
2354
                pass
 
2355
        suite = Stub("test_foo")
 
2356
        calls = []
 
2357
        class MyRunner(tests.TextTestRunner):
 
2358
            def run(self, test):
 
2359
                calls.append(test)
 
2360
                return tests.ExtendedTestResult(self.stream, self.descriptions,
 
2361
                                                self.verbosity)
 
2362
        tests.run_suite(suite, runner_class=MyRunner, stream=StringIO())
 
2363
        self.assertEqual(calls, [suite])
 
2364
 
 
2365
    def test_done(self):
 
2366
        """run_suite should call result.done()"""
 
2367
        self.calls = 0
 
2368
        def one_more_call(): self.calls += 1
 
2369
        def test_function():
 
2370
            pass
 
2371
        test = unittest.FunctionTestCase(test_function)
 
2372
        class InstrumentedTestResult(tests.ExtendedTestResult):
 
2373
            def done(self): one_more_call()
 
2374
        class MyRunner(tests.TextTestRunner):
 
2375
            def run(self, test):
 
2376
                return InstrumentedTestResult(self.stream, self.descriptions,
 
2377
                                              self.verbosity)
 
2378
        tests.run_suite(test, runner_class=MyRunner, stream=StringIO())
 
2379
        self.assertEquals(1, self.calls)