/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_selftest.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2009-08-27 00:53:27 UTC
  • mfrom: (4436.2.1 386180-check)
  • Revision ID: pqm@pqm.ubuntu.com-20090827005327-iky1i2fzwi75h4ie
(mbp) make check no longer repeats the test run in LANG=C

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 signal
 
22
import sys
 
23
import time
 
24
import unittest
 
25
import warnings
 
26
 
 
27
import bzrlib
 
28
from bzrlib import (
 
29
    branchbuilder,
 
30
    bzrdir,
 
31
    debug,
 
32
    errors,
 
33
    lockdir,
 
34
    memorytree,
 
35
    osutils,
 
36
    progress,
 
37
    remote,
 
38
    repository,
 
39
    symbol_versioning,
 
40
    tests,
 
41
    workingtree,
 
42
    )
 
43
from bzrlib.repofmt import (
 
44
    groupcompress_repo,
 
45
    pack_repo,
 
46
    weaverepo,
 
47
    )
 
48
from bzrlib.symbol_versioning import (
 
49
    deprecated_function,
 
50
    deprecated_in,
 
51
    deprecated_method,
 
52
    )
 
53
from bzrlib.tests import (
 
54
    SubUnitFeature,
 
55
    test_lsprof,
 
56
    test_sftp_transport,
 
57
    TestUtil,
 
58
    )
 
59
from bzrlib.trace import note
 
60
from bzrlib.transport.memory import MemoryServer, MemoryTransport
 
61
from bzrlib.version import _get_bzr_source_tree
 
62
 
 
63
 
 
64
def _test_ids(test_suite):
 
65
    """Get the ids for the tests in a test suite."""
 
66
    return [t.id() for t in tests.iter_suite_tests(test_suite)]
 
67
 
 
68
 
 
69
class SelftestTests(tests.TestCase):
 
70
 
 
71
    def test_import_tests(self):
 
72
        mod = TestUtil._load_module_by_name('bzrlib.tests.test_selftest')
 
73
        self.assertEqual(mod.SelftestTests, SelftestTests)
 
74
 
 
75
    def test_import_test_failure(self):
 
76
        self.assertRaises(ImportError,
 
77
                          TestUtil._load_module_by_name,
 
78
                          'bzrlib.no-name-yet')
 
79
 
 
80
class MetaTestLog(tests.TestCase):
 
81
 
 
82
    def test_logging(self):
 
83
        """Test logs are captured when a test fails."""
 
84
        self.log('a test message')
 
85
        self._log_file.flush()
 
86
        self.assertContainsRe(self._get_log(keep_log_file=True),
 
87
                              'a test message\n')
 
88
 
 
89
 
 
90
class TestUnicodeFilename(tests.TestCase):
 
91
 
 
92
    def test_probe_passes(self):
 
93
        """UnicodeFilename._probe passes."""
 
94
        # We can't test much more than that because the behaviour depends
 
95
        # on the platform.
 
96
        tests.UnicodeFilename._probe()
 
97
 
 
98
 
 
99
class TestTreeShape(tests.TestCaseInTempDir):
 
100
 
 
101
    def test_unicode_paths(self):
 
102
        self.requireFeature(tests.UnicodeFilename)
 
103
 
 
104
        filename = u'hell\u00d8'
 
105
        self.build_tree_contents([(filename, 'contents of hello')])
 
106
        self.failUnlessExists(filename)
 
107
 
 
108
 
 
109
class TestTransportScenarios(tests.TestCase):
 
110
    """A group of tests that test the transport implementation adaption core.
 
111
 
 
112
    This is a meta test that the tests are applied to all available
 
113
    transports.
 
114
 
 
115
    This will be generalised in the future which is why it is in this
 
116
    test file even though it is specific to transport tests at the moment.
 
117
    """
 
118
 
 
119
    def test_get_transport_permutations(self):
 
120
        # this checks that get_test_permutations defined by the module is
 
121
        # called by the get_transport_test_permutations function.
 
122
        class MockModule(object):
 
123
            def get_test_permutations(self):
 
124
                return sample_permutation
 
125
        sample_permutation = [(1,2), (3,4)]
 
126
        from bzrlib.tests.per_transport import get_transport_test_permutations
 
127
        self.assertEqual(sample_permutation,
 
128
                         get_transport_test_permutations(MockModule()))
 
129
 
 
130
    def test_scenarios_include_all_modules(self):
 
131
        # this checks that the scenario generator returns as many permutations
 
132
        # as there are in all the registered transport modules - we assume if
 
133
        # this matches its probably doing the right thing especially in
 
134
        # combination with the tests for setting the right classes below.
 
135
        from bzrlib.tests.per_transport import transport_test_permutations
 
136
        from bzrlib.transport import _get_transport_modules
 
137
        modules = _get_transport_modules()
 
138
        permutation_count = 0
 
139
        for module in modules:
 
140
            try:
 
141
                permutation_count += len(reduce(getattr,
 
142
                    (module + ".get_test_permutations").split('.')[1:],
 
143
                     __import__(module))())
 
144
            except errors.DependencyNotPresent:
 
145
                pass
 
146
        scenarios = transport_test_permutations()
 
147
        self.assertEqual(permutation_count, len(scenarios))
 
148
 
 
149
    def test_scenarios_include_transport_class(self):
 
150
        # This test used to know about all the possible transports and the
 
151
        # order they were returned but that seems overly brittle (mbp
 
152
        # 20060307)
 
153
        from bzrlib.tests.per_transport import transport_test_permutations
 
154
        scenarios = transport_test_permutations()
 
155
        # there are at least that many builtin transports
 
156
        self.assertTrue(len(scenarios) > 6)
 
157
        one_scenario = scenarios[0]
 
158
        self.assertIsInstance(one_scenario[0], str)
 
159
        self.assertTrue(issubclass(one_scenario[1]["transport_class"],
 
160
                                   bzrlib.transport.Transport))
 
161
        self.assertTrue(issubclass(one_scenario[1]["transport_server"],
 
162
                                   bzrlib.transport.Server))
 
163
 
 
164
 
 
165
class TestBranchScenarios(tests.TestCase):
 
166
 
 
167
    def test_scenarios(self):
 
168
        # check that constructor parameters are passed through to the adapted
 
169
        # test.
 
170
        from bzrlib.tests.per_branch import make_scenarios
 
171
        server1 = "a"
 
172
        server2 = "b"
 
173
        formats = [("c", "C"), ("d", "D")]
 
174
        scenarios = make_scenarios(server1, server2, formats)
 
175
        self.assertEqual(2, len(scenarios))
 
176
        self.assertEqual([
 
177
            ('str',
 
178
             {'branch_format': 'c',
 
179
              'bzrdir_format': 'C',
 
180
              'transport_readonly_server': 'b',
 
181
              'transport_server': 'a'}),
 
182
            ('str',
 
183
             {'branch_format': 'd',
 
184
              'bzrdir_format': 'D',
 
185
              'transport_readonly_server': 'b',
 
186
              'transport_server': 'a'})],
 
187
            scenarios)
 
188
 
 
189
 
 
190
class TestBzrDirScenarios(tests.TestCase):
 
191
 
 
192
    def test_scenarios(self):
 
193
        # check that constructor parameters are passed through to the adapted
 
194
        # test.
 
195
        from bzrlib.tests.per_bzrdir import make_scenarios
 
196
        vfs_factory = "v"
 
197
        server1 = "a"
 
198
        server2 = "b"
 
199
        formats = ["c", "d"]
 
200
        scenarios = make_scenarios(vfs_factory, server1, server2, formats)
 
201
        self.assertEqual([
 
202
            ('str',
 
203
             {'bzrdir_format': 'c',
 
204
              'transport_readonly_server': 'b',
 
205
              'transport_server': 'a',
 
206
              'vfs_transport_factory': 'v'}),
 
207
            ('str',
 
208
             {'bzrdir_format': 'd',
 
209
              'transport_readonly_server': 'b',
 
210
              'transport_server': 'a',
 
211
              'vfs_transport_factory': 'v'})],
 
212
            scenarios)
 
213
 
 
214
 
 
215
class TestRepositoryScenarios(tests.TestCase):
 
216
 
 
217
    def test_formats_to_scenarios(self):
 
218
        from bzrlib.tests.per_repository import formats_to_scenarios
 
219
        formats = [("(c)", remote.RemoteRepositoryFormat()),
 
220
                   ("(d)", repository.format_registry.get(
 
221
                    'Bazaar repository format 2a (needs bzr 1.16 or later)\n'))]
 
222
        no_vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
 
223
            None)
 
224
        vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
 
225
            vfs_transport_factory="vfs")
 
226
        # no_vfs generate scenarios without vfs_transport_factory
 
227
        expected = [
 
228
            ('RemoteRepositoryFormat(c)',
 
229
             {'bzrdir_format': remote.RemoteBzrDirFormat(),
 
230
              'repository_format': remote.RemoteRepositoryFormat(),
 
231
              'transport_readonly_server': 'readonly',
 
232
              'transport_server': 'server'}),
 
233
            ('RepositoryFormat2a(d)',
 
234
             {'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
 
235
              'repository_format': groupcompress_repo.RepositoryFormat2a(),
 
236
              'transport_readonly_server': 'readonly',
 
237
              'transport_server': 'server'})]
 
238
        self.assertEqual(expected, no_vfs_scenarios)
 
239
        self.assertEqual([
 
240
            ('RemoteRepositoryFormat(c)',
 
241
             {'bzrdir_format': remote.RemoteBzrDirFormat(),
 
242
              'repository_format': remote.RemoteRepositoryFormat(),
 
243
              'transport_readonly_server': 'readonly',
 
244
              'transport_server': 'server',
 
245
              'vfs_transport_factory': 'vfs'}),
 
246
            ('RepositoryFormat2a(d)',
 
247
             {'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
 
248
              'repository_format': groupcompress_repo.RepositoryFormat2a(),
 
249
              'transport_readonly_server': 'readonly',
 
250
              'transport_server': 'server',
 
251
              'vfs_transport_factory': 'vfs'})],
 
252
            vfs_scenarios)
 
253
 
 
254
 
 
255
class TestTestScenarioApplication(tests.TestCase):
 
256
    """Tests for the test adaption facilities."""
 
257
 
 
258
    def test_apply_scenario(self):
 
259
        from bzrlib.tests import apply_scenario
 
260
        input_test = TestTestScenarioApplication("test_apply_scenario")
 
261
        # setup two adapted tests
 
262
        adapted_test1 = apply_scenario(input_test,
 
263
            ("new id",
 
264
            {"bzrdir_format":"bzr_format",
 
265
             "repository_format":"repo_fmt",
 
266
             "transport_server":"transport_server",
 
267
             "transport_readonly_server":"readonly-server"}))
 
268
        adapted_test2 = apply_scenario(input_test,
 
269
            ("new id 2", {"bzrdir_format":None}))
 
270
        # input_test should have been altered.
 
271
        self.assertRaises(AttributeError, getattr, input_test, "bzrdir_format")
 
272
        # the new tests are mutually incompatible, ensuring it has
 
273
        # made new ones, and unspecified elements in the scenario
 
274
        # should not have been altered.
 
275
        self.assertEqual("bzr_format", adapted_test1.bzrdir_format)
 
276
        self.assertEqual("repo_fmt", adapted_test1.repository_format)
 
277
        self.assertEqual("transport_server", adapted_test1.transport_server)
 
278
        self.assertEqual("readonly-server",
 
279
            adapted_test1.transport_readonly_server)
 
280
        self.assertEqual(
 
281
            "bzrlib.tests.test_selftest.TestTestScenarioApplication."
 
282
            "test_apply_scenario(new id)",
 
283
            adapted_test1.id())
 
284
        self.assertEqual(None, adapted_test2.bzrdir_format)
 
285
        self.assertEqual(
 
286
            "bzrlib.tests.test_selftest.TestTestScenarioApplication."
 
287
            "test_apply_scenario(new id 2)",
 
288
            adapted_test2.id())
 
289
 
 
290
 
 
291
class TestInterRepositoryScenarios(tests.TestCase):
 
292
 
 
293
    def test_scenarios(self):
 
294
        # check that constructor parameters are passed through to the adapted
 
295
        # test.
 
296
        from bzrlib.tests.per_interrepository import make_scenarios
 
297
        server1 = "a"
 
298
        server2 = "b"
 
299
        formats = [("C0", "C1", "C2"), ("D0", "D1", "D2")]
 
300
        scenarios = make_scenarios(server1, server2, formats)
 
301
        self.assertEqual([
 
302
            ('C0,str,str',
 
303
             {'repository_format': 'C1',
 
304
              'repository_format_to': 'C2',
 
305
              'transport_readonly_server': 'b',
 
306
              'transport_server': 'a'}),
 
307
            ('D0,str,str',
 
308
             {'repository_format': 'D1',
 
309
              'repository_format_to': 'D2',
 
310
              'transport_readonly_server': 'b',
 
311
              'transport_server': 'a'})],
 
312
            scenarios)
 
313
 
 
314
 
 
315
class TestWorkingTreeScenarios(tests.TestCase):
 
316
 
 
317
    def test_scenarios(self):
 
318
        # check that constructor parameters are passed through to the adapted
 
319
        # test.
 
320
        from bzrlib.tests.per_workingtree import make_scenarios
 
321
        server1 = "a"
 
322
        server2 = "b"
 
323
        formats = [workingtree.WorkingTreeFormat2(),
 
324
                   workingtree.WorkingTreeFormat3(),]
 
325
        scenarios = make_scenarios(server1, server2, formats)
 
326
        self.assertEqual([
 
327
            ('WorkingTreeFormat2',
 
328
             {'bzrdir_format': formats[0]._matchingbzrdir,
 
329
              'transport_readonly_server': 'b',
 
330
              'transport_server': 'a',
 
331
              'workingtree_format': formats[0]}),
 
332
            ('WorkingTreeFormat3',
 
333
             {'bzrdir_format': formats[1]._matchingbzrdir,
 
334
              'transport_readonly_server': 'b',
 
335
              'transport_server': 'a',
 
336
              'workingtree_format': formats[1]})],
 
337
            scenarios)
 
338
 
 
339
 
 
340
class TestTreeScenarios(tests.TestCase):
 
341
 
 
342
    def test_scenarios(self):
 
343
        # the tree implementation scenario generator is meant to setup one
 
344
        # instance for each working tree format, and one additional instance
 
345
        # that will use the default wt format, but create a revision tree for
 
346
        # the tests.  this means that the wt ones should have the
 
347
        # workingtree_to_test_tree attribute set to 'return_parameter' and the
 
348
        # revision one set to revision_tree_from_workingtree.
 
349
 
 
350
        from bzrlib.tests.per_tree import (
 
351
            _dirstate_tree_from_workingtree,
 
352
            make_scenarios,
 
353
            preview_tree_pre,
 
354
            preview_tree_post,
 
355
            return_parameter,
 
356
            revision_tree_from_workingtree
 
357
            )
 
358
        server1 = "a"
 
359
        server2 = "b"
 
360
        formats = [workingtree.WorkingTreeFormat2(),
 
361
                   workingtree.WorkingTreeFormat3(),]
 
362
        scenarios = make_scenarios(server1, server2, formats)
 
363
        self.assertEqual(7, len(scenarios))
 
364
        default_wt_format = workingtree.WorkingTreeFormat4._default_format
 
365
        wt4_format = workingtree.WorkingTreeFormat4()
 
366
        wt5_format = workingtree.WorkingTreeFormat5()
 
367
        expected_scenarios = [
 
368
            ('WorkingTreeFormat2',
 
369
             {'bzrdir_format': formats[0]._matchingbzrdir,
 
370
              'transport_readonly_server': 'b',
 
371
              'transport_server': 'a',
 
372
              'workingtree_format': formats[0],
 
373
              '_workingtree_to_test_tree': return_parameter,
 
374
              }),
 
375
            ('WorkingTreeFormat3',
 
376
             {'bzrdir_format': formats[1]._matchingbzrdir,
 
377
              'transport_readonly_server': 'b',
 
378
              'transport_server': 'a',
 
379
              'workingtree_format': formats[1],
 
380
              '_workingtree_to_test_tree': return_parameter,
 
381
             }),
 
382
            ('RevisionTree',
 
383
             {'_workingtree_to_test_tree': revision_tree_from_workingtree,
 
384
              'bzrdir_format': default_wt_format._matchingbzrdir,
 
385
              'transport_readonly_server': 'b',
 
386
              'transport_server': 'a',
 
387
              'workingtree_format': default_wt_format,
 
388
             }),
 
389
            ('DirStateRevisionTree,WT4',
 
390
             {'_workingtree_to_test_tree': _dirstate_tree_from_workingtree,
 
391
              'bzrdir_format': wt4_format._matchingbzrdir,
 
392
              'transport_readonly_server': 'b',
 
393
              'transport_server': 'a',
 
394
              'workingtree_format': wt4_format,
 
395
             }),
 
396
            ('DirStateRevisionTree,WT5',
 
397
             {'_workingtree_to_test_tree': _dirstate_tree_from_workingtree,
 
398
              'bzrdir_format': wt5_format._matchingbzrdir,
 
399
              'transport_readonly_server': 'b',
 
400
              'transport_server': 'a',
 
401
              'workingtree_format': wt5_format,
 
402
             }),
 
403
            ('PreviewTree',
 
404
             {'_workingtree_to_test_tree': preview_tree_pre,
 
405
              'bzrdir_format': default_wt_format._matchingbzrdir,
 
406
              'transport_readonly_server': 'b',
 
407
              'transport_server': 'a',
 
408
              'workingtree_format': default_wt_format}),
 
409
            ('PreviewTreePost',
 
410
             {'_workingtree_to_test_tree': preview_tree_post,
 
411
              'bzrdir_format': default_wt_format._matchingbzrdir,
 
412
              'transport_readonly_server': 'b',
 
413
              'transport_server': 'a',
 
414
              'workingtree_format': default_wt_format}),
 
415
             ]
 
416
        self.assertEqual(expected_scenarios, scenarios)
 
417
 
 
418
 
 
419
class TestInterTreeScenarios(tests.TestCase):
 
420
    """A group of tests that test the InterTreeTestAdapter."""
 
421
 
 
422
    def test_scenarios(self):
 
423
        # check that constructor parameters are passed through to the adapted
 
424
        # test.
 
425
        # for InterTree tests we want the machinery to bring up two trees in
 
426
        # each instance: the base one, and the one we are interacting with.
 
427
        # because each optimiser can be direction specific, we need to test
 
428
        # each optimiser in its chosen direction.
 
429
        # unlike the TestProviderAdapter we dont want to automatically add a
 
430
        # parameterized one for WorkingTree - the optimisers will tell us what
 
431
        # ones to add.
 
432
        from bzrlib.tests.per_tree import (
 
433
            return_parameter,
 
434
            revision_tree_from_workingtree
 
435
            )
 
436
        from bzrlib.tests.per_intertree import (
 
437
            make_scenarios,
 
438
            )
 
439
        from bzrlib.workingtree import WorkingTreeFormat2, WorkingTreeFormat3
 
440
        input_test = TestInterTreeScenarios(
 
441
            "test_scenarios")
 
442
        server1 = "a"
 
443
        server2 = "b"
 
444
        format1 = WorkingTreeFormat2()
 
445
        format2 = WorkingTreeFormat3()
 
446
        formats = [("1", str, format1, format2, "converter1"),
 
447
            ("2", int, format2, format1, "converter2")]
 
448
        scenarios = make_scenarios(server1, server2, formats)
 
449
        self.assertEqual(2, len(scenarios))
 
450
        expected_scenarios = [
 
451
            ("1", {
 
452
                "bzrdir_format": format1._matchingbzrdir,
 
453
                "intertree_class": formats[0][1],
 
454
                "workingtree_format": formats[0][2],
 
455
                "workingtree_format_to": formats[0][3],
 
456
                "mutable_trees_to_test_trees": formats[0][4],
 
457
                "_workingtree_to_test_tree": return_parameter,
 
458
                "transport_server": server1,
 
459
                "transport_readonly_server": server2,
 
460
                }),
 
461
            ("2", {
 
462
                "bzrdir_format": format2._matchingbzrdir,
 
463
                "intertree_class": formats[1][1],
 
464
                "workingtree_format": formats[1][2],
 
465
                "workingtree_format_to": formats[1][3],
 
466
                "mutable_trees_to_test_trees": formats[1][4],
 
467
                "_workingtree_to_test_tree": return_parameter,
 
468
                "transport_server": server1,
 
469
                "transport_readonly_server": server2,
 
470
                }),
 
471
            ]
 
472
        self.assertEqual(scenarios, expected_scenarios)
 
473
 
 
474
 
 
475
class TestTestCaseInTempDir(tests.TestCaseInTempDir):
 
476
 
 
477
    def test_home_is_not_working(self):
 
478
        self.assertNotEqual(self.test_dir, self.test_home_dir)
 
479
        cwd = osutils.getcwd()
 
480
        self.assertIsSameRealPath(self.test_dir, cwd)
 
481
        self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
 
482
 
 
483
    def test_assertEqualStat_equal(self):
 
484
        from bzrlib.tests.test_dirstate import _FakeStat
 
485
        self.build_tree(["foo"])
 
486
        real = os.lstat("foo")
 
487
        fake = _FakeStat(real.st_size, real.st_mtime, real.st_ctime,
 
488
            real.st_dev, real.st_ino, real.st_mode)
 
489
        self.assertEqualStat(real, fake)
 
490
 
 
491
    def test_assertEqualStat_notequal(self):
 
492
        self.build_tree(["foo", "bar"])
 
493
        self.assertRaises(AssertionError, self.assertEqualStat,
 
494
            os.lstat("foo"), os.lstat("bar"))
 
495
 
 
496
 
 
497
class TestTestCaseWithMemoryTransport(tests.TestCaseWithMemoryTransport):
 
498
 
 
499
    def test_home_is_non_existant_dir_under_root(self):
 
500
        """The test_home_dir for TestCaseWithMemoryTransport is missing.
 
501
 
 
502
        This is because TestCaseWithMemoryTransport is for tests that do not
 
503
        need any disk resources: they should be hooked into bzrlib in such a
 
504
        way that no global settings are being changed by the test (only a
 
505
        few tests should need to do that), and having a missing dir as home is
 
506
        an effective way to ensure that this is the case.
 
507
        """
 
508
        self.assertIsSameRealPath(
 
509
            self.TEST_ROOT + "/MemoryTransportMissingHomeDir",
 
510
            self.test_home_dir)
 
511
        self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
 
512
 
 
513
    def test_cwd_is_TEST_ROOT(self):
 
514
        self.assertIsSameRealPath(self.test_dir, self.TEST_ROOT)
 
515
        cwd = osutils.getcwd()
 
516
        self.assertIsSameRealPath(self.test_dir, cwd)
 
517
 
 
518
    def test_make_branch_and_memory_tree(self):
 
519
        """In TestCaseWithMemoryTransport we should not make the branch on disk.
 
520
 
 
521
        This is hard to comprehensively robustly test, so we settle for making
 
522
        a branch and checking no directory was created at its relpath.
 
523
        """
 
524
        tree = self.make_branch_and_memory_tree('dir')
 
525
        # Guard against regression into MemoryTransport leaking
 
526
        # files to disk instead of keeping them in memory.
 
527
        self.failIf(osutils.lexists('dir'))
 
528
        self.assertIsInstance(tree, memorytree.MemoryTree)
 
529
 
 
530
    def test_make_branch_and_memory_tree_with_format(self):
 
531
        """make_branch_and_memory_tree should accept a format option."""
 
532
        format = bzrdir.BzrDirMetaFormat1()
 
533
        format.repository_format = weaverepo.RepositoryFormat7()
 
534
        tree = self.make_branch_and_memory_tree('dir', format=format)
 
535
        # Guard against regression into MemoryTransport leaking
 
536
        # files to disk instead of keeping them in memory.
 
537
        self.failIf(osutils.lexists('dir'))
 
538
        self.assertIsInstance(tree, memorytree.MemoryTree)
 
539
        self.assertEqual(format.repository_format.__class__,
 
540
            tree.branch.repository._format.__class__)
 
541
 
 
542
    def test_make_branch_builder(self):
 
543
        builder = self.make_branch_builder('dir')
 
544
        self.assertIsInstance(builder, branchbuilder.BranchBuilder)
 
545
        # Guard against regression into MemoryTransport leaking
 
546
        # files to disk instead of keeping them in memory.
 
547
        self.failIf(osutils.lexists('dir'))
 
548
 
 
549
    def test_make_branch_builder_with_format(self):
 
550
        # Use a repo layout that doesn't conform to a 'named' layout, to ensure
 
551
        # that the format objects are used.
 
552
        format = bzrdir.BzrDirMetaFormat1()
 
553
        repo_format = weaverepo.RepositoryFormat7()
 
554
        format.repository_format = repo_format
 
555
        builder = self.make_branch_builder('dir', format=format)
 
556
        the_branch = builder.get_branch()
 
557
        # Guard against regression into MemoryTransport leaking
 
558
        # files to disk instead of keeping them in memory.
 
559
        self.failIf(osutils.lexists('dir'))
 
560
        self.assertEqual(format.repository_format.__class__,
 
561
                         the_branch.repository._format.__class__)
 
562
        self.assertEqual(repo_format.get_format_string(),
 
563
                         self.get_transport().get_bytes(
 
564
                            'dir/.bzr/repository/format'))
 
565
 
 
566
    def test_make_branch_builder_with_format_name(self):
 
567
        builder = self.make_branch_builder('dir', format='knit')
 
568
        the_branch = builder.get_branch()
 
569
        # Guard against regression into MemoryTransport leaking
 
570
        # files to disk instead of keeping them in memory.
 
571
        self.failIf(osutils.lexists('dir'))
 
572
        dir_format = bzrdir.format_registry.make_bzrdir('knit')
 
573
        self.assertEqual(dir_format.repository_format.__class__,
 
574
                         the_branch.repository._format.__class__)
 
575
        self.assertEqual('Bazaar-NG Knit Repository Format 1',
 
576
                         self.get_transport().get_bytes(
 
577
                            'dir/.bzr/repository/format'))
 
578
 
 
579
    def test_safety_net(self):
 
580
        """No test should modify the safety .bzr directory.
 
581
 
 
582
        We just test that the _check_safety_net private method raises
 
583
        AssertionError, it's easier than building a test suite with the same
 
584
        test.
 
585
        """
 
586
        # Oops, a commit in the current directory (i.e. without local .bzr
 
587
        # directory) will crawl up the hierarchy to find a .bzr directory.
 
588
        self.run_bzr(['commit', '-mfoo', '--unchanged'])
 
589
        # But we have a safety net in place.
 
590
        self.assertRaises(AssertionError, self._check_safety_net)
 
591
 
 
592
    def test_dangling_locks_cause_failures(self):
 
593
        class TestDanglingLock(tests.TestCaseWithMemoryTransport):
 
594
            def test_function(self):
 
595
                t = self.get_transport('.')
 
596
                l = lockdir.LockDir(t, 'lock')
 
597
                l.create()
 
598
                l.attempt_lock()
 
599
        test = TestDanglingLock('test_function')
 
600
        result = test.run()
 
601
        if self._lock_check_thorough:
 
602
            self.assertEqual(1, len(result.errors))
 
603
        else:
 
604
            # When _lock_check_thorough is disabled, then we don't trigger a
 
605
            # failure
 
606
            self.assertEqual(0, len(result.errors))
 
607
 
 
608
 
 
609
class TestTestCaseWithTransport(tests.TestCaseWithTransport):
 
610
    """Tests for the convenience functions TestCaseWithTransport introduces."""
 
611
 
 
612
    def test_get_readonly_url_none(self):
 
613
        from bzrlib.transport import get_transport
 
614
        from bzrlib.transport.memory import MemoryServer
 
615
        from bzrlib.transport.readonly import ReadonlyTransportDecorator
 
616
        self.vfs_transport_factory = MemoryServer
 
617
        self.transport_readonly_server = None
 
618
        # calling get_readonly_transport() constructs a decorator on the url
 
619
        # for the server
 
620
        url = self.get_readonly_url()
 
621
        url2 = self.get_readonly_url('foo/bar')
 
622
        t = get_transport(url)
 
623
        t2 = get_transport(url2)
 
624
        self.failUnless(isinstance(t, ReadonlyTransportDecorator))
 
625
        self.failUnless(isinstance(t2, ReadonlyTransportDecorator))
 
626
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
 
627
 
 
628
    def test_get_readonly_url_http(self):
 
629
        from bzrlib.tests.http_server import HttpServer
 
630
        from bzrlib.transport import get_transport
 
631
        from bzrlib.transport.local import LocalURLServer
 
632
        from bzrlib.transport.http import HttpTransportBase
 
633
        self.transport_server = LocalURLServer
 
634
        self.transport_readonly_server = HttpServer
 
635
        # calling get_readonly_transport() gives us a HTTP server instance.
 
636
        url = self.get_readonly_url()
 
637
        url2 = self.get_readonly_url('foo/bar')
 
638
        # the transport returned may be any HttpTransportBase subclass
 
639
        t = get_transport(url)
 
640
        t2 = get_transport(url2)
 
641
        self.failUnless(isinstance(t, HttpTransportBase))
 
642
        self.failUnless(isinstance(t2, HttpTransportBase))
 
643
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
 
644
 
 
645
    def test_is_directory(self):
 
646
        """Test assertIsDirectory assertion"""
 
647
        t = self.get_transport()
 
648
        self.build_tree(['a_dir/', 'a_file'], transport=t)
 
649
        self.assertIsDirectory('a_dir', t)
 
650
        self.assertRaises(AssertionError, self.assertIsDirectory, 'a_file', t)
 
651
        self.assertRaises(AssertionError, self.assertIsDirectory, 'not_here', t)
 
652
 
 
653
    def test_make_branch_builder(self):
 
654
        builder = self.make_branch_builder('dir')
 
655
        rev_id = builder.build_commit()
 
656
        self.failUnlessExists('dir')
 
657
        a_dir = bzrdir.BzrDir.open('dir')
 
658
        self.assertRaises(errors.NoWorkingTree, a_dir.open_workingtree)
 
659
        a_branch = a_dir.open_branch()
 
660
        builder_branch = builder.get_branch()
 
661
        self.assertEqual(a_branch.base, builder_branch.base)
 
662
        self.assertEqual((1, rev_id), builder_branch.last_revision_info())
 
663
        self.assertEqual((1, rev_id), a_branch.last_revision_info())
 
664
 
 
665
 
 
666
class TestTestCaseTransports(tests.TestCaseWithTransport):
 
667
 
 
668
    def setUp(self):
 
669
        super(TestTestCaseTransports, self).setUp()
 
670
        self.vfs_transport_factory = MemoryServer
 
671
 
 
672
    def test_make_bzrdir_preserves_transport(self):
 
673
        t = self.get_transport()
 
674
        result_bzrdir = self.make_bzrdir('subdir')
 
675
        self.assertIsInstance(result_bzrdir.transport,
 
676
                              MemoryTransport)
 
677
        # should not be on disk, should only be in memory
 
678
        self.failIfExists('subdir')
 
679
 
 
680
 
 
681
class TestChrootedTest(tests.ChrootedTestCase):
 
682
 
 
683
    def test_root_is_root(self):
 
684
        from bzrlib.transport import get_transport
 
685
        t = get_transport(self.get_readonly_url())
 
686
        url = t.base
 
687
        self.assertEqual(url, t.clone('..').base)
 
688
 
 
689
 
 
690
class TestProfileResult(tests.TestCase):
 
691
 
 
692
    def test_profiles_tests(self):
 
693
        self.requireFeature(test_lsprof.LSProfFeature)
 
694
        terminal = unittest.TestResult()
 
695
        result = tests.ProfileResult(terminal)
 
696
        class Sample(tests.TestCase):
 
697
            def a(self):
 
698
                self.sample_function()
 
699
            def sample_function(self):
 
700
                pass
 
701
        test = Sample("a")
 
702
        test.attrs_to_keep = test.attrs_to_keep + ('_benchcalls',)
 
703
        test.run(result)
 
704
        self.assertLength(1, test._benchcalls)
 
705
        # We must be able to unpack it as the test reporting code wants
 
706
        (_, _, _), stats = test._benchcalls[0]
 
707
        self.assertTrue(callable(stats.pprint))
 
708
 
 
709
 
 
710
class TestTestResult(tests.TestCase):
 
711
 
 
712
    def check_timing(self, test_case, expected_re):
 
713
        result = bzrlib.tests.TextTestResult(self._log_file,
 
714
                descriptions=0,
 
715
                verbosity=1,
 
716
                )
 
717
        test_case.run(result)
 
718
        timed_string = result._testTimeString(test_case)
 
719
        self.assertContainsRe(timed_string, expected_re)
 
720
 
 
721
    def test_test_reporting(self):
 
722
        class ShortDelayTestCase(tests.TestCase):
 
723
            def test_short_delay(self):
 
724
                time.sleep(0.003)
 
725
            def test_short_benchmark(self):
 
726
                self.time(time.sleep, 0.003)
 
727
        self.check_timing(ShortDelayTestCase('test_short_delay'),
 
728
                          r"^ +[0-9]+ms$")
 
729
        # if a benchmark time is given, we now show just that time followed by
 
730
        # a star
 
731
        self.check_timing(ShortDelayTestCase('test_short_benchmark'),
 
732
                          r"^ +[0-9]+ms\*$")
 
733
 
 
734
    def test_unittest_reporting_unittest_class(self):
 
735
        # getting the time from a non-bzrlib test works ok
 
736
        class ShortDelayTestCase(unittest.TestCase):
 
737
            def test_short_delay(self):
 
738
                time.sleep(0.003)
 
739
        self.check_timing(ShortDelayTestCase('test_short_delay'),
 
740
                          r"^ +[0-9]+ms$")
 
741
 
 
742
    def test_assigned_benchmark_file_stores_date(self):
 
743
        output = StringIO()
 
744
        result = bzrlib.tests.TextTestResult(self._log_file,
 
745
                                        descriptions=0,
 
746
                                        verbosity=1,
 
747
                                        bench_history=output
 
748
                                        )
 
749
        output_string = output.getvalue()
 
750
        # if you are wondering about the regexp please read the comment in
 
751
        # test_bench_history (bzrlib.tests.test_selftest.TestRunner)
 
752
        # XXX: what comment?  -- Andrew Bennetts
 
753
        self.assertContainsRe(output_string, "--date [0-9.]+")
 
754
 
 
755
    def test_benchhistory_records_test_times(self):
 
756
        result_stream = StringIO()
 
757
        result = bzrlib.tests.TextTestResult(
 
758
            self._log_file,
 
759
            descriptions=0,
 
760
            verbosity=1,
 
761
            bench_history=result_stream
 
762
            )
 
763
 
 
764
        # we want profile a call and check that its test duration is recorded
 
765
        # make a new test instance that when run will generate a benchmark
 
766
        example_test_case = TestTestResult("_time_hello_world_encoding")
 
767
        # execute the test, which should succeed and record times
 
768
        example_test_case.run(result)
 
769
        lines = result_stream.getvalue().splitlines()
 
770
        self.assertEqual(2, len(lines))
 
771
        self.assertContainsRe(lines[1],
 
772
            " *[0-9]+ms bzrlib.tests.test_selftest.TestTestResult"
 
773
            "._time_hello_world_encoding")
 
774
 
 
775
    def _time_hello_world_encoding(self):
 
776
        """Profile two sleep calls
 
777
 
 
778
        This is used to exercise the test framework.
 
779
        """
 
780
        self.time(unicode, 'hello', errors='replace')
 
781
        self.time(unicode, 'world', errors='replace')
 
782
 
 
783
    def test_lsprofiling(self):
 
784
        """Verbose test result prints lsprof statistics from test cases."""
 
785
        self.requireFeature(test_lsprof.LSProfFeature)
 
786
        result_stream = StringIO()
 
787
        result = bzrlib.tests.VerboseTestResult(
 
788
            unittest._WritelnDecorator(result_stream),
 
789
            descriptions=0,
 
790
            verbosity=2,
 
791
            )
 
792
        # we want profile a call of some sort and check it is output by
 
793
        # addSuccess. We dont care about addError or addFailure as they
 
794
        # are not that interesting for performance tuning.
 
795
        # make a new test instance that when run will generate a profile
 
796
        example_test_case = TestTestResult("_time_hello_world_encoding")
 
797
        example_test_case._gather_lsprof_in_benchmarks = True
 
798
        # execute the test, which should succeed and record profiles
 
799
        example_test_case.run(result)
 
800
        # lsprofile_something()
 
801
        # if this worked we want
 
802
        # LSProf output for <built in function unicode> (['hello'], {'errors': 'replace'})
 
803
        #    CallCount    Recursive    Total(ms)   Inline(ms) module:lineno(function)
 
804
        # (the lsprof header)
 
805
        # ... an arbitrary number of lines
 
806
        # and the function call which is time.sleep.
 
807
        #           1        0            ???         ???       ???(sleep)
 
808
        # and then repeated but with 'world', rather than 'hello'.
 
809
        # this should appear in the output stream of our test result.
 
810
        output = result_stream.getvalue()
 
811
        self.assertContainsRe(output,
 
812
            r"LSProf output for <type 'unicode'>\(\('hello',\), {'errors': 'replace'}\)")
 
813
        self.assertContainsRe(output,
 
814
            r" *CallCount *Recursive *Total\(ms\) *Inline\(ms\) *module:lineno\(function\)\n")
 
815
        self.assertContainsRe(output,
 
816
            r"( +1 +0 +0\.\d+ +0\.\d+ +<method 'disable' of '_lsprof\.Profiler' objects>\n)?")
 
817
        self.assertContainsRe(output,
 
818
            r"LSProf output for <type 'unicode'>\(\('world',\), {'errors': 'replace'}\)\n")
 
819
 
 
820
    def test_known_failure(self):
 
821
        """A KnownFailure being raised should trigger several result actions."""
 
822
        class InstrumentedTestResult(tests.ExtendedTestResult):
 
823
            def done(self): pass
 
824
            def startTests(self): pass
 
825
            def report_test_start(self, test): pass
 
826
            def report_known_failure(self, test, err):
 
827
                self._call = test, err
 
828
        result = InstrumentedTestResult(None, None, None, None)
 
829
        def test_function():
 
830
            raise tests.KnownFailure('failed!')
 
831
        test = unittest.FunctionTestCase(test_function)
 
832
        test.run(result)
 
833
        # it should invoke 'report_known_failure'.
 
834
        self.assertEqual(2, len(result._call))
 
835
        self.assertEqual(test, result._call[0])
 
836
        self.assertEqual(tests.KnownFailure, result._call[1][0])
 
837
        self.assertIsInstance(result._call[1][1], tests.KnownFailure)
 
838
        # we dont introspec the traceback, if the rest is ok, it would be
 
839
        # exceptional for it not to be.
 
840
        # it should update the known_failure_count on the object.
 
841
        self.assertEqual(1, result.known_failure_count)
 
842
        # the result should be successful.
 
843
        self.assertTrue(result.wasSuccessful())
 
844
 
 
845
    def test_verbose_report_known_failure(self):
 
846
        # verbose test output formatting
 
847
        result_stream = StringIO()
 
848
        result = bzrlib.tests.VerboseTestResult(
 
849
            unittest._WritelnDecorator(result_stream),
 
850
            descriptions=0,
 
851
            verbosity=2,
 
852
            )
 
853
        test = self.get_passing_test()
 
854
        result.startTest(test)
 
855
        prefix = len(result_stream.getvalue())
 
856
        # the err parameter has the shape:
 
857
        # (class, exception object, traceback)
 
858
        # KnownFailures dont get their tracebacks shown though, so we
 
859
        # can skip that.
 
860
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
 
861
        result.report_known_failure(test, err)
 
862
        output = result_stream.getvalue()[prefix:]
 
863
        lines = output.splitlines()
 
864
        self.assertContainsRe(lines[0], r'XFAIL *\d+ms$')
 
865
        self.assertEqual(lines[1], '    foo')
 
866
        self.assertEqual(2, len(lines))
 
867
 
 
868
    def get_passing_test(self):
 
869
        """Return a test object that can't be run usefully."""
 
870
        def passing_test():
 
871
            pass
 
872
        return unittest.FunctionTestCase(passing_test)
 
873
 
 
874
    def test_add_not_supported(self):
 
875
        """Test the behaviour of invoking addNotSupported."""
 
876
        class InstrumentedTestResult(tests.ExtendedTestResult):
 
877
            def done(self): pass
 
878
            def startTests(self): pass
 
879
            def report_test_start(self, test): pass
 
880
            def report_unsupported(self, test, feature):
 
881
                self._call = test, feature
 
882
        result = InstrumentedTestResult(None, None, None, None)
 
883
        test = SampleTestCase('_test_pass')
 
884
        feature = tests.Feature()
 
885
        result.startTest(test)
 
886
        result.addNotSupported(test, feature)
 
887
        # it should invoke 'report_unsupported'.
 
888
        self.assertEqual(2, len(result._call))
 
889
        self.assertEqual(test, result._call[0])
 
890
        self.assertEqual(feature, result._call[1])
 
891
        # the result should be successful.
 
892
        self.assertTrue(result.wasSuccessful())
 
893
        # it should record the test against a count of tests not run due to
 
894
        # this feature.
 
895
        self.assertEqual(1, result.unsupported['Feature'])
 
896
        # and invoking it again should increment that counter
 
897
        result.addNotSupported(test, feature)
 
898
        self.assertEqual(2, result.unsupported['Feature'])
 
899
 
 
900
    def test_verbose_report_unsupported(self):
 
901
        # verbose test output formatting
 
902
        result_stream = StringIO()
 
903
        result = bzrlib.tests.VerboseTestResult(
 
904
            unittest._WritelnDecorator(result_stream),
 
905
            descriptions=0,
 
906
            verbosity=2,
 
907
            )
 
908
        test = self.get_passing_test()
 
909
        feature = tests.Feature()
 
910
        result.startTest(test)
 
911
        prefix = len(result_stream.getvalue())
 
912
        result.report_unsupported(test, feature)
 
913
        output = result_stream.getvalue()[prefix:]
 
914
        lines = output.splitlines()
 
915
        self.assertEqual(lines, ['NODEP        0ms',
 
916
                                 "    The feature 'Feature' is not available."])
 
917
 
 
918
    def test_unavailable_exception(self):
 
919
        """An UnavailableFeature being raised should invoke addNotSupported."""
 
920
        class InstrumentedTestResult(tests.ExtendedTestResult):
 
921
            def done(self): pass
 
922
            def startTests(self): pass
 
923
            def report_test_start(self, test): pass
 
924
            def addNotSupported(self, test, feature):
 
925
                self._call = test, feature
 
926
        result = InstrumentedTestResult(None, None, None, None)
 
927
        feature = tests.Feature()
 
928
        def test_function():
 
929
            raise tests.UnavailableFeature(feature)
 
930
        test = unittest.FunctionTestCase(test_function)
 
931
        test.run(result)
 
932
        # it should invoke 'addNotSupported'.
 
933
        self.assertEqual(2, len(result._call))
 
934
        self.assertEqual(test, result._call[0])
 
935
        self.assertEqual(feature, result._call[1])
 
936
        # and not count as an error
 
937
        self.assertEqual(0, result.error_count)
 
938
 
 
939
    def test_strict_with_unsupported_feature(self):
 
940
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
 
941
                                             verbosity=1)
 
942
        test = self.get_passing_test()
 
943
        feature = "Unsupported Feature"
 
944
        result.addNotSupported(test, feature)
 
945
        self.assertFalse(result.wasStrictlySuccessful())
 
946
        self.assertEqual(None, result._extractBenchmarkTime(test))
 
947
 
 
948
    def test_strict_with_known_failure(self):
 
949
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
 
950
                                             verbosity=1)
 
951
        test = self.get_passing_test()
 
952
        err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
 
953
        result._addKnownFailure(test, err)
 
954
        self.assertFalse(result.wasStrictlySuccessful())
 
955
        self.assertEqual(None, result._extractBenchmarkTime(test))
 
956
 
 
957
    def test_strict_with_success(self):
 
958
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
 
959
                                             verbosity=1)
 
960
        test = self.get_passing_test()
 
961
        result.addSuccess(test)
 
962
        self.assertTrue(result.wasStrictlySuccessful())
 
963
        self.assertEqual(None, result._extractBenchmarkTime(test))
 
964
 
 
965
    def test_startTests(self):
 
966
        """Starting the first test should trigger startTests."""
 
967
        class InstrumentedTestResult(tests.ExtendedTestResult):
 
968
            calls = 0
 
969
            def startTests(self): self.calls += 1
 
970
            def report_test_start(self, test): pass
 
971
        result = InstrumentedTestResult(None, None, None, None)
 
972
        def test_function():
 
973
            pass
 
974
        test = unittest.FunctionTestCase(test_function)
 
975
        test.run(result)
 
976
        self.assertEquals(1, result.calls)
 
977
 
 
978
 
 
979
class TestUnicodeFilenameFeature(tests.TestCase):
 
980
 
 
981
    def test_probe_passes(self):
 
982
        """UnicodeFilenameFeature._probe passes."""
 
983
        # We can't test much more than that because the behaviour depends
 
984
        # on the platform.
 
985
        tests.UnicodeFilenameFeature._probe()
 
986
 
 
987
 
 
988
class TestRunner(tests.TestCase):
 
989
 
 
990
    def dummy_test(self):
 
991
        pass
 
992
 
 
993
    def run_test_runner(self, testrunner, test):
 
994
        """Run suite in testrunner, saving global state and restoring it.
 
995
 
 
996
        This current saves and restores:
 
997
        TestCaseInTempDir.TEST_ROOT
 
998
 
 
999
        There should be no tests in this file that use
 
1000
        bzrlib.tests.TextTestRunner without using this convenience method,
 
1001
        because of our use of global state.
 
1002
        """
 
1003
        old_root = tests.TestCaseInTempDir.TEST_ROOT
 
1004
        try:
 
1005
            tests.TestCaseInTempDir.TEST_ROOT = None
 
1006
            return testrunner.run(test)
 
1007
        finally:
 
1008
            tests.TestCaseInTempDir.TEST_ROOT = old_root
 
1009
 
 
1010
    def test_known_failure_failed_run(self):
 
1011
        # run a test that generates a known failure which should be printed in
 
1012
        # the final output when real failures occur.
 
1013
        def known_failure_test():
 
1014
            raise tests.KnownFailure('failed')
 
1015
        test = unittest.TestSuite()
 
1016
        test.addTest(unittest.FunctionTestCase(known_failure_test))
 
1017
        def failing_test():
 
1018
            raise AssertionError('foo')
 
1019
        test.addTest(unittest.FunctionTestCase(failing_test))
 
1020
        stream = StringIO()
 
1021
        runner = tests.TextTestRunner(stream=stream)
 
1022
        result = self.run_test_runner(runner, test)
 
1023
        lines = stream.getvalue().splitlines()
 
1024
        self.assertContainsRe(stream.getvalue(),
 
1025
            '(?sm)^testing.*$'
 
1026
            '.*'
 
1027
            '^======================================================================\n'
 
1028
            '^FAIL: unittest.FunctionTestCase \\(failing_test\\)\n'
 
1029
            '^----------------------------------------------------------------------\n'
 
1030
            'Traceback \\(most recent call last\\):\n'
 
1031
            '  .*' # File .*, line .*, in failing_test' - but maybe not from .pyc
 
1032
            '    raise AssertionError\\(\'foo\'\\)\n'
 
1033
            '.*'
 
1034
            '^----------------------------------------------------------------------\n'
 
1035
            '.*'
 
1036
            'FAILED \\(failures=1, known_failure_count=1\\)'
 
1037
            )
 
1038
 
 
1039
    def test_known_failure_ok_run(self):
 
1040
        # run a test that generates a known failure which should be printed in the final output.
 
1041
        def known_failure_test():
 
1042
            raise tests.KnownFailure('failed')
 
1043
        test = unittest.FunctionTestCase(known_failure_test)
 
1044
        stream = StringIO()
 
1045
        runner = tests.TextTestRunner(stream=stream)
 
1046
        result = self.run_test_runner(runner, test)
 
1047
        self.assertContainsRe(stream.getvalue(),
 
1048
            '\n'
 
1049
            '-*\n'
 
1050
            'Ran 1 test in .*\n'
 
1051
            '\n'
 
1052
            'OK \\(known_failures=1\\)\n')
 
1053
 
 
1054
    def test_result_decorator(self):
 
1055
        # decorate results
 
1056
        calls = []
 
1057
        class LoggingDecorator(tests.ForwardingResult):
 
1058
            def startTest(self, test):
 
1059
                tests.ForwardingResult.startTest(self, test)
 
1060
                calls.append('start')
 
1061
        test = unittest.FunctionTestCase(lambda:None)
 
1062
        stream = StringIO()
 
1063
        runner = tests.TextTestRunner(stream=stream,
 
1064
            result_decorators=[LoggingDecorator])
 
1065
        result = self.run_test_runner(runner, test)
 
1066
        self.assertLength(1, calls)
 
1067
 
 
1068
    def test_skipped_test(self):
 
1069
        # run a test that is skipped, and check the suite as a whole still
 
1070
        # succeeds.
 
1071
        # skipping_test must be hidden in here so it's not run as a real test
 
1072
        class SkippingTest(tests.TestCase):
 
1073
            def skipping_test(self):
 
1074
                raise tests.TestSkipped('test intentionally skipped')
 
1075
        runner = tests.TextTestRunner(stream=self._log_file)
 
1076
        test = SkippingTest("skipping_test")
 
1077
        result = self.run_test_runner(runner, test)
 
1078
        self.assertTrue(result.wasSuccessful())
 
1079
 
 
1080
    def test_skipped_from_setup(self):
 
1081
        calls = []
 
1082
        class SkippedSetupTest(tests.TestCase):
 
1083
 
 
1084
            def setUp(self):
 
1085
                calls.append('setUp')
 
1086
                self.addCleanup(self.cleanup)
 
1087
                raise tests.TestSkipped('skipped setup')
 
1088
 
 
1089
            def test_skip(self):
 
1090
                self.fail('test reached')
 
1091
 
 
1092
            def cleanup(self):
 
1093
                calls.append('cleanup')
 
1094
 
 
1095
        runner = tests.TextTestRunner(stream=self._log_file)
 
1096
        test = SkippedSetupTest('test_skip')
 
1097
        result = self.run_test_runner(runner, test)
 
1098
        self.assertTrue(result.wasSuccessful())
 
1099
        # Check if cleanup was called the right number of times.
 
1100
        self.assertEqual(['setUp', 'cleanup'], calls)
 
1101
 
 
1102
    def test_skipped_from_test(self):
 
1103
        calls = []
 
1104
        class SkippedTest(tests.TestCase):
 
1105
 
 
1106
            def setUp(self):
 
1107
                tests.TestCase.setUp(self)
 
1108
                calls.append('setUp')
 
1109
                self.addCleanup(self.cleanup)
 
1110
 
 
1111
            def test_skip(self):
 
1112
                raise tests.TestSkipped('skipped test')
 
1113
 
 
1114
            def cleanup(self):
 
1115
                calls.append('cleanup')
 
1116
 
 
1117
        runner = tests.TextTestRunner(stream=self._log_file)
 
1118
        test = SkippedTest('test_skip')
 
1119
        result = self.run_test_runner(runner, test)
 
1120
        self.assertTrue(result.wasSuccessful())
 
1121
        # Check if cleanup was called the right number of times.
 
1122
        self.assertEqual(['setUp', 'cleanup'], calls)
 
1123
 
 
1124
    def test_not_applicable(self):
 
1125
        # run a test that is skipped because it's not applicable
 
1126
        def not_applicable_test():
 
1127
            raise tests.TestNotApplicable('this test never runs')
 
1128
        out = StringIO()
 
1129
        runner = tests.TextTestRunner(stream=out, verbosity=2)
 
1130
        test = unittest.FunctionTestCase(not_applicable_test)
 
1131
        result = self.run_test_runner(runner, test)
 
1132
        self._log_file.write(out.getvalue())
 
1133
        self.assertTrue(result.wasSuccessful())
 
1134
        self.assertTrue(result.wasStrictlySuccessful())
 
1135
        self.assertContainsRe(out.getvalue(),
 
1136
                r'(?m)not_applicable_test   * N/A')
 
1137
        self.assertContainsRe(out.getvalue(),
 
1138
                r'(?m)^    this test never runs')
 
1139
 
 
1140
    def test_unsupported_features_listed(self):
 
1141
        """When unsupported features are encountered they are detailed."""
 
1142
        class Feature1(tests.Feature):
 
1143
            def _probe(self): return False
 
1144
        class Feature2(tests.Feature):
 
1145
            def _probe(self): return False
 
1146
        # create sample tests
 
1147
        test1 = SampleTestCase('_test_pass')
 
1148
        test1._test_needs_features = [Feature1()]
 
1149
        test2 = SampleTestCase('_test_pass')
 
1150
        test2._test_needs_features = [Feature2()]
 
1151
        test = unittest.TestSuite()
 
1152
        test.addTest(test1)
 
1153
        test.addTest(test2)
 
1154
        stream = StringIO()
 
1155
        runner = tests.TextTestRunner(stream=stream)
 
1156
        result = self.run_test_runner(runner, test)
 
1157
        lines = stream.getvalue().splitlines()
 
1158
        self.assertEqual([
 
1159
            'OK',
 
1160
            "Missing feature 'Feature1' skipped 1 tests.",
 
1161
            "Missing feature 'Feature2' skipped 1 tests.",
 
1162
            ],
 
1163
            lines[-3:])
 
1164
 
 
1165
    def test_bench_history(self):
 
1166
        # tests that the running the benchmark produces a history file
 
1167
        # containing a timestamp and the revision id of the bzrlib source which
 
1168
        # was tested.
 
1169
        workingtree = _get_bzr_source_tree()
 
1170
        test = TestRunner('dummy_test')
 
1171
        output = StringIO()
 
1172
        runner = tests.TextTestRunner(stream=self._log_file,
 
1173
                                      bench_history=output)
 
1174
        result = self.run_test_runner(runner, test)
 
1175
        output_string = output.getvalue()
 
1176
        self.assertContainsRe(output_string, "--date [0-9.]+")
 
1177
        if workingtree is not None:
 
1178
            revision_id = workingtree.get_parent_ids()[0]
 
1179
            self.assertEndsWith(output_string.rstrip(), revision_id)
 
1180
 
 
1181
    def assertLogDeleted(self, test):
 
1182
        log = test._get_log()
 
1183
        self.assertEqual("DELETED log file to reduce memory footprint", log)
 
1184
        self.assertEqual('', test._log_contents)
 
1185
        self.assertIs(None, test._log_file_name)
 
1186
 
 
1187
    def test_success_log_deleted(self):
 
1188
        """Successful tests have their log deleted"""
 
1189
 
 
1190
        class LogTester(tests.TestCase):
 
1191
 
 
1192
            def test_success(self):
 
1193
                self.log('this will be removed\n')
 
1194
 
 
1195
        sio = StringIO()
 
1196
        runner = tests.TextTestRunner(stream=sio)
 
1197
        test = LogTester('test_success')
 
1198
        result = self.run_test_runner(runner, test)
 
1199
 
 
1200
        self.assertLogDeleted(test)
 
1201
 
 
1202
    def test_skipped_log_deleted(self):
 
1203
        """Skipped tests have their log deleted"""
 
1204
 
 
1205
        class LogTester(tests.TestCase):
 
1206
 
 
1207
            def test_skipped(self):
 
1208
                self.log('this will be removed\n')
 
1209
                raise tests.TestSkipped()
 
1210
 
 
1211
        sio = StringIO()
 
1212
        runner = tests.TextTestRunner(stream=sio)
 
1213
        test = LogTester('test_skipped')
 
1214
        result = self.run_test_runner(runner, test)
 
1215
 
 
1216
        self.assertLogDeleted(test)
 
1217
 
 
1218
    def test_not_aplicable_log_deleted(self):
 
1219
        """Not applicable tests have their log deleted"""
 
1220
 
 
1221
        class LogTester(tests.TestCase):
 
1222
 
 
1223
            def test_not_applicable(self):
 
1224
                self.log('this will be removed\n')
 
1225
                raise tests.TestNotApplicable()
 
1226
 
 
1227
        sio = StringIO()
 
1228
        runner = tests.TextTestRunner(stream=sio)
 
1229
        test = LogTester('test_not_applicable')
 
1230
        result = self.run_test_runner(runner, test)
 
1231
 
 
1232
        self.assertLogDeleted(test)
 
1233
 
 
1234
    def test_known_failure_log_deleted(self):
 
1235
        """Know failure tests have their log deleted"""
 
1236
 
 
1237
        class LogTester(tests.TestCase):
 
1238
 
 
1239
            def test_known_failure(self):
 
1240
                self.log('this will be removed\n')
 
1241
                raise tests.KnownFailure()
 
1242
 
 
1243
        sio = StringIO()
 
1244
        runner = tests.TextTestRunner(stream=sio)
 
1245
        test = LogTester('test_known_failure')
 
1246
        result = self.run_test_runner(runner, test)
 
1247
 
 
1248
        self.assertLogDeleted(test)
 
1249
 
 
1250
    def test_fail_log_kept(self):
 
1251
        """Failed tests have their log kept"""
 
1252
 
 
1253
        class LogTester(tests.TestCase):
 
1254
 
 
1255
            def test_fail(self):
 
1256
                self.log('this will be kept\n')
 
1257
                self.fail('this test fails')
 
1258
 
 
1259
        sio = StringIO()
 
1260
        runner = tests.TextTestRunner(stream=sio)
 
1261
        test = LogTester('test_fail')
 
1262
        result = self.run_test_runner(runner, test)
 
1263
 
 
1264
        text = sio.getvalue()
 
1265
        self.assertContainsRe(text, 'this will be kept')
 
1266
        self.assertContainsRe(text, 'this test fails')
 
1267
 
 
1268
        log = test._get_log()
 
1269
        self.assertContainsRe(log, 'this will be kept')
 
1270
        self.assertEqual(log, test._log_contents)
 
1271
 
 
1272
    def test_error_log_kept(self):
 
1273
        """Tests with errors have their log kept"""
 
1274
 
 
1275
        class LogTester(tests.TestCase):
 
1276
 
 
1277
            def test_error(self):
 
1278
                self.log('this will be kept\n')
 
1279
                raise ValueError('random exception raised')
 
1280
 
 
1281
        sio = StringIO()
 
1282
        runner = tests.TextTestRunner(stream=sio)
 
1283
        test = LogTester('test_error')
 
1284
        result = self.run_test_runner(runner, test)
 
1285
 
 
1286
        text = sio.getvalue()
 
1287
        self.assertContainsRe(text, 'this will be kept')
 
1288
        self.assertContainsRe(text, 'random exception raised')
 
1289
 
 
1290
        log = test._get_log()
 
1291
        self.assertContainsRe(log, 'this will be kept')
 
1292
        self.assertEqual(log, test._log_contents)
 
1293
 
 
1294
 
 
1295
class SampleTestCase(tests.TestCase):
 
1296
 
 
1297
    def _test_pass(self):
 
1298
        pass
 
1299
 
 
1300
class _TestException(Exception):
 
1301
    pass
 
1302
 
 
1303
 
 
1304
class TestTestCase(tests.TestCase):
 
1305
    """Tests that test the core bzrlib TestCase."""
 
1306
 
 
1307
    def test_assertLength_matches_empty(self):
 
1308
        a_list = []
 
1309
        self.assertLength(0, a_list)
 
1310
 
 
1311
    def test_assertLength_matches_nonempty(self):
 
1312
        a_list = [1, 2, 3]
 
1313
        self.assertLength(3, a_list)
 
1314
 
 
1315
    def test_assertLength_fails_different(self):
 
1316
        a_list = []
 
1317
        self.assertRaises(AssertionError, self.assertLength, 1, a_list)
 
1318
 
 
1319
    def test_assertLength_shows_sequence_in_failure(self):
 
1320
        a_list = [1, 2, 3]
 
1321
        exception = self.assertRaises(AssertionError, self.assertLength, 2,
 
1322
            a_list)
 
1323
        self.assertEqual('Incorrect length: wanted 2, got 3 for [1, 2, 3]',
 
1324
            exception.args[0])
 
1325
 
 
1326
    def test_base_setUp_not_called_causes_failure(self):
 
1327
        class TestCaseWithBrokenSetUp(tests.TestCase):
 
1328
            def setUp(self):
 
1329
                pass # does not call TestCase.setUp
 
1330
            def test_foo(self):
 
1331
                pass
 
1332
        test = TestCaseWithBrokenSetUp('test_foo')
 
1333
        result = unittest.TestResult()
 
1334
        test.run(result)
 
1335
        self.assertFalse(result.wasSuccessful())
 
1336
        self.assertEqual(1, result.testsRun)
 
1337
 
 
1338
    def test_base_tearDown_not_called_causes_failure(self):
 
1339
        class TestCaseWithBrokenTearDown(tests.TestCase):
 
1340
            def tearDown(self):
 
1341
                pass # does not call TestCase.tearDown
 
1342
            def test_foo(self):
 
1343
                pass
 
1344
        test = TestCaseWithBrokenTearDown('test_foo')
 
1345
        result = unittest.TestResult()
 
1346
        test.run(result)
 
1347
        self.assertFalse(result.wasSuccessful())
 
1348
        self.assertEqual(1, result.testsRun)
 
1349
 
 
1350
    def test_debug_flags_sanitised(self):
 
1351
        """The bzrlib debug flags should be sanitised by setUp."""
 
1352
        if 'allow_debug' in tests.selftest_debug_flags:
 
1353
            raise tests.TestNotApplicable(
 
1354
                '-Eallow_debug option prevents debug flag sanitisation')
 
1355
        # we could set something and run a test that will check
 
1356
        # it gets santised, but this is probably sufficient for now:
 
1357
        # if someone runs the test with -Dsomething it will error.
 
1358
        flags = set()
 
1359
        if self._lock_check_thorough:
 
1360
            flags.add('strict_locks')
 
1361
        self.assertEqual(flags, bzrlib.debug.debug_flags)
 
1362
 
 
1363
    def change_selftest_debug_flags(self, new_flags):
 
1364
        orig_selftest_flags = tests.selftest_debug_flags
 
1365
        self.addCleanup(self._restore_selftest_debug_flags, orig_selftest_flags)
 
1366
        tests.selftest_debug_flags = set(new_flags)
 
1367
 
 
1368
    def _restore_selftest_debug_flags(self, flags):
 
1369
        tests.selftest_debug_flags = flags
 
1370
 
 
1371
    def test_allow_debug_flag(self):
 
1372
        """The -Eallow_debug flag prevents bzrlib.debug.debug_flags from being
 
1373
        sanitised (i.e. cleared) before running a test.
 
1374
        """
 
1375
        self.change_selftest_debug_flags(set(['allow_debug']))
 
1376
        bzrlib.debug.debug_flags = set(['a-flag'])
 
1377
        class TestThatRecordsFlags(tests.TestCase):
 
1378
            def test_foo(nested_self):
 
1379
                self.flags = set(bzrlib.debug.debug_flags)
 
1380
        test = TestThatRecordsFlags('test_foo')
 
1381
        test.run(self.make_test_result())
 
1382
        flags = set(['a-flag'])
 
1383
        if 'disable_lock_checks' not in tests.selftest_debug_flags:
 
1384
            flags.add('strict_locks')
 
1385
        self.assertEqual(flags, self.flags)
 
1386
 
 
1387
    def test_disable_lock_checks(self):
 
1388
        """The -Edisable_lock_checks flag disables thorough checks."""
 
1389
        class TestThatRecordsFlags(tests.TestCase):
 
1390
            def test_foo(nested_self):
 
1391
                self.flags = set(bzrlib.debug.debug_flags)
 
1392
                self.test_lock_check_thorough = nested_self._lock_check_thorough
 
1393
        self.change_selftest_debug_flags(set())
 
1394
        test = TestThatRecordsFlags('test_foo')
 
1395
        test.run(self.make_test_result())
 
1396
        # By default we do strict lock checking and thorough lock/unlock
 
1397
        # tracking.
 
1398
        self.assertTrue(self.test_lock_check_thorough)
 
1399
        self.assertEqual(set(['strict_locks']), self.flags)
 
1400
        # Now set the disable_lock_checks flag, and show that this changed.
 
1401
        self.change_selftest_debug_flags(set(['disable_lock_checks']))
 
1402
        test = TestThatRecordsFlags('test_foo')
 
1403
        test.run(self.make_test_result())
 
1404
        self.assertFalse(self.test_lock_check_thorough)
 
1405
        self.assertEqual(set(), self.flags)
 
1406
 
 
1407
    def test_this_fails_strict_lock_check(self):
 
1408
        class TestThatRecordsFlags(tests.TestCase):
 
1409
            def test_foo(nested_self):
 
1410
                self.flags1 = set(bzrlib.debug.debug_flags)
 
1411
                self.thisFailsStrictLockCheck()
 
1412
                self.flags2 = set(bzrlib.debug.debug_flags)
 
1413
        # Make sure lock checking is active
 
1414
        self.change_selftest_debug_flags(set())
 
1415
        test = TestThatRecordsFlags('test_foo')
 
1416
        test.run(self.make_test_result())
 
1417
        self.assertEqual(set(['strict_locks']), self.flags1)
 
1418
        self.assertEqual(set(), self.flags2)
 
1419
 
 
1420
    def test_debug_flags_restored(self):
 
1421
        """The bzrlib debug flags should be restored to their original state
 
1422
        after the test was run, even if allow_debug is set.
 
1423
        """
 
1424
        self.change_selftest_debug_flags(set(['allow_debug']))
 
1425
        # Now run a test that modifies debug.debug_flags.
 
1426
        bzrlib.debug.debug_flags = set(['original-state'])
 
1427
        class TestThatModifiesFlags(tests.TestCase):
 
1428
            def test_foo(self):
 
1429
                bzrlib.debug.debug_flags = set(['modified'])
 
1430
        test = TestThatModifiesFlags('test_foo')
 
1431
        test.run(self.make_test_result())
 
1432
        self.assertEqual(set(['original-state']), bzrlib.debug.debug_flags)
 
1433
 
 
1434
    def make_test_result(self):
 
1435
        return tests.TextTestResult(self._log_file, descriptions=0, verbosity=1)
 
1436
 
 
1437
    def inner_test(self):
 
1438
        # the inner child test
 
1439
        note("inner_test")
 
1440
 
 
1441
    def outer_child(self):
 
1442
        # the outer child test
 
1443
        note("outer_start")
 
1444
        self.inner_test = TestTestCase("inner_child")
 
1445
        result = self.make_test_result()
 
1446
        self.inner_test.run(result)
 
1447
        note("outer finish")
 
1448
 
 
1449
    def test_trace_nesting(self):
 
1450
        # this tests that each test case nests its trace facility correctly.
 
1451
        # we do this by running a test case manually. That test case (A)
 
1452
        # should setup a new log, log content to it, setup a child case (B),
 
1453
        # which should log independently, then case (A) should log a trailer
 
1454
        # and return.
 
1455
        # we do two nested children so that we can verify the state of the
 
1456
        # logs after the outer child finishes is correct, which a bad clean
 
1457
        # up routine in tearDown might trigger a fault in our test with only
 
1458
        # one child, we should instead see the bad result inside our test with
 
1459
        # the two children.
 
1460
        # the outer child test
 
1461
        original_trace = bzrlib.trace._trace_file
 
1462
        outer_test = TestTestCase("outer_child")
 
1463
        result = self.make_test_result()
 
1464
        outer_test.run(result)
 
1465
        self.assertEqual(original_trace, bzrlib.trace._trace_file)
 
1466
 
 
1467
    def method_that_times_a_bit_twice(self):
 
1468
        # call self.time twice to ensure it aggregates
 
1469
        self.time(time.sleep, 0.007)
 
1470
        self.time(time.sleep, 0.007)
 
1471
 
 
1472
    def test_time_creates_benchmark_in_result(self):
 
1473
        """Test that the TestCase.time() method accumulates a benchmark time."""
 
1474
        sample_test = TestTestCase("method_that_times_a_bit_twice")
 
1475
        output_stream = StringIO()
 
1476
        result = bzrlib.tests.VerboseTestResult(
 
1477
            unittest._WritelnDecorator(output_stream),
 
1478
            descriptions=0,
 
1479
            verbosity=2)
 
1480
        sample_test.run(result)
 
1481
        self.assertContainsRe(
 
1482
            output_stream.getvalue(),
 
1483
            r"\d+ms\*\n$")
 
1484
 
 
1485
    def test_hooks_sanitised(self):
 
1486
        """The bzrlib hooks should be sanitised by setUp."""
 
1487
        # Note this test won't fail with hooks that the core library doesn't
 
1488
        # use - but it trigger with a plugin that adds hooks, so its still a
 
1489
        # useful warning in that case.
 
1490
        self.assertEqual(bzrlib.branch.BranchHooks(),
 
1491
            bzrlib.branch.Branch.hooks)
 
1492
        self.assertEqual(bzrlib.smart.server.SmartServerHooks(),
 
1493
            bzrlib.smart.server.SmartTCPServer.hooks)
 
1494
        self.assertEqual(bzrlib.commands.CommandHooks(),
 
1495
            bzrlib.commands.Command.hooks)
 
1496
 
 
1497
    def test__gather_lsprof_in_benchmarks(self):
 
1498
        """When _gather_lsprof_in_benchmarks is on, accumulate profile data.
 
1499
 
 
1500
        Each self.time() call is individually and separately profiled.
 
1501
        """
 
1502
        self.requireFeature(test_lsprof.LSProfFeature)
 
1503
        # overrides the class member with an instance member so no cleanup
 
1504
        # needed.
 
1505
        self._gather_lsprof_in_benchmarks = True
 
1506
        self.time(time.sleep, 0.000)
 
1507
        self.time(time.sleep, 0.003)
 
1508
        self.assertEqual(2, len(self._benchcalls))
 
1509
        self.assertEqual((time.sleep, (0.000,), {}), self._benchcalls[0][0])
 
1510
        self.assertEqual((time.sleep, (0.003,), {}), self._benchcalls[1][0])
 
1511
        self.assertIsInstance(self._benchcalls[0][1], bzrlib.lsprof.Stats)
 
1512
        self.assertIsInstance(self._benchcalls[1][1], bzrlib.lsprof.Stats)
 
1513
        del self._benchcalls[:]
 
1514
 
 
1515
    def test_knownFailure(self):
 
1516
        """Self.knownFailure() should raise a KnownFailure exception."""
 
1517
        self.assertRaises(tests.KnownFailure, self.knownFailure, "A Failure")
 
1518
 
 
1519
    def test_requireFeature_available(self):
 
1520
        """self.requireFeature(available) is a no-op."""
 
1521
        class Available(tests.Feature):
 
1522
            def _probe(self):return True
 
1523
        feature = Available()
 
1524
        self.requireFeature(feature)
 
1525
 
 
1526
    def test_requireFeature_unavailable(self):
 
1527
        """self.requireFeature(unavailable) raises UnavailableFeature."""
 
1528
        class Unavailable(tests.Feature):
 
1529
            def _probe(self):return False
 
1530
        feature = Unavailable()
 
1531
        self.assertRaises(tests.UnavailableFeature,
 
1532
                          self.requireFeature, feature)
 
1533
 
 
1534
    def test_run_no_parameters(self):
 
1535
        test = SampleTestCase('_test_pass')
 
1536
        test.run()
 
1537
 
 
1538
    def test_run_enabled_unittest_result(self):
 
1539
        """Test we revert to regular behaviour when the test is enabled."""
 
1540
        test = SampleTestCase('_test_pass')
 
1541
        class EnabledFeature(object):
 
1542
            def available(self):
 
1543
                return True
 
1544
        test._test_needs_features = [EnabledFeature()]
 
1545
        result = unittest.TestResult()
 
1546
        test.run(result)
 
1547
        self.assertEqual(1, result.testsRun)
 
1548
        self.assertEqual([], result.errors)
 
1549
        self.assertEqual([], result.failures)
 
1550
 
 
1551
    def test_run_disabled_unittest_result(self):
 
1552
        """Test our compatability for disabled tests with unittest results."""
 
1553
        test = SampleTestCase('_test_pass')
 
1554
        class DisabledFeature(object):
 
1555
            def available(self):
 
1556
                return False
 
1557
        test._test_needs_features = [DisabledFeature()]
 
1558
        result = unittest.TestResult()
 
1559
        test.run(result)
 
1560
        self.assertEqual(1, result.testsRun)
 
1561
        self.assertEqual([], result.errors)
 
1562
        self.assertEqual([], result.failures)
 
1563
 
 
1564
    def test_run_disabled_supporting_result(self):
 
1565
        """Test disabled tests behaviour with support aware results."""
 
1566
        test = SampleTestCase('_test_pass')
 
1567
        class DisabledFeature(object):
 
1568
            def available(self):
 
1569
                return False
 
1570
        the_feature = DisabledFeature()
 
1571
        test._test_needs_features = [the_feature]
 
1572
        class InstrumentedTestResult(unittest.TestResult):
 
1573
            def __init__(self):
 
1574
                unittest.TestResult.__init__(self)
 
1575
                self.calls = []
 
1576
            def startTest(self, test):
 
1577
                self.calls.append(('startTest', test))
 
1578
            def stopTest(self, test):
 
1579
                self.calls.append(('stopTest', test))
 
1580
            def addNotSupported(self, test, feature):
 
1581
                self.calls.append(('addNotSupported', test, feature))
 
1582
        result = InstrumentedTestResult()
 
1583
        test.run(result)
 
1584
        self.assertEqual([
 
1585
            ('startTest', test),
 
1586
            ('addNotSupported', test, the_feature),
 
1587
            ('stopTest', test),
 
1588
            ],
 
1589
            result.calls)
 
1590
 
 
1591
    def test_assert_list_raises_on_generator(self):
 
1592
        def generator_which_will_raise():
 
1593
            # This will not raise until after the first yield
 
1594
            yield 1
 
1595
            raise _TestException()
 
1596
 
 
1597
        e = self.assertListRaises(_TestException, generator_which_will_raise)
 
1598
        self.assertIsInstance(e, _TestException)
 
1599
 
 
1600
        e = self.assertListRaises(Exception, generator_which_will_raise)
 
1601
        self.assertIsInstance(e, _TestException)
 
1602
 
 
1603
    def test_assert_list_raises_on_plain(self):
 
1604
        def plain_exception():
 
1605
            raise _TestException()
 
1606
            return []
 
1607
 
 
1608
        e = self.assertListRaises(_TestException, plain_exception)
 
1609
        self.assertIsInstance(e, _TestException)
 
1610
 
 
1611
        e = self.assertListRaises(Exception, plain_exception)
 
1612
        self.assertIsInstance(e, _TestException)
 
1613
 
 
1614
    def test_assert_list_raises_assert_wrong_exception(self):
 
1615
        class _NotTestException(Exception):
 
1616
            pass
 
1617
 
 
1618
        def wrong_exception():
 
1619
            raise _NotTestException()
 
1620
 
 
1621
        def wrong_exception_generator():
 
1622
            yield 1
 
1623
            yield 2
 
1624
            raise _NotTestException()
 
1625
 
 
1626
        # Wrong exceptions are not intercepted
 
1627
        self.assertRaises(_NotTestException,
 
1628
            self.assertListRaises, _TestException, wrong_exception)
 
1629
        self.assertRaises(_NotTestException,
 
1630
            self.assertListRaises, _TestException, wrong_exception_generator)
 
1631
 
 
1632
    def test_assert_list_raises_no_exception(self):
 
1633
        def success():
 
1634
            return []
 
1635
 
 
1636
        def success_generator():
 
1637
            yield 1
 
1638
            yield 2
 
1639
 
 
1640
        self.assertRaises(AssertionError,
 
1641
            self.assertListRaises, _TestException, success)
 
1642
 
 
1643
        self.assertRaises(AssertionError,
 
1644
            self.assertListRaises, _TestException, success_generator)
 
1645
 
 
1646
 
 
1647
# NB: Don't delete this; it's not actually from 0.11!
 
1648
@deprecated_function(deprecated_in((0, 11, 0)))
 
1649
def sample_deprecated_function():
 
1650
    """A deprecated function to test applyDeprecated with."""
 
1651
    return 2
 
1652
 
 
1653
 
 
1654
def sample_undeprecated_function(a_param):
 
1655
    """A undeprecated function to test applyDeprecated with."""
 
1656
 
 
1657
 
 
1658
class ApplyDeprecatedHelper(object):
 
1659
    """A helper class for ApplyDeprecated tests."""
 
1660
 
 
1661
    @deprecated_method(deprecated_in((0, 11, 0)))
 
1662
    def sample_deprecated_method(self, param_one):
 
1663
        """A deprecated method for testing with."""
 
1664
        return param_one
 
1665
 
 
1666
    def sample_normal_method(self):
 
1667
        """A undeprecated method."""
 
1668
 
 
1669
    @deprecated_method(deprecated_in((0, 10, 0)))
 
1670
    def sample_nested_deprecation(self):
 
1671
        return sample_deprecated_function()
 
1672
 
 
1673
 
 
1674
class TestExtraAssertions(tests.TestCase):
 
1675
    """Tests for new test assertions in bzrlib test suite"""
 
1676
 
 
1677
    def test_assert_isinstance(self):
 
1678
        self.assertIsInstance(2, int)
 
1679
        self.assertIsInstance(u'', basestring)
 
1680
        e = self.assertRaises(AssertionError, self.assertIsInstance, None, int)
 
1681
        self.assertEquals(str(e),
 
1682
            "None is an instance of <type 'NoneType'> rather than <type 'int'>")
 
1683
        self.assertRaises(AssertionError, self.assertIsInstance, 23.3, int)
 
1684
        e = self.assertRaises(AssertionError,
 
1685
            self.assertIsInstance, None, int, "it's just not")
 
1686
        self.assertEquals(str(e),
 
1687
            "None is an instance of <type 'NoneType'> rather than <type 'int'>"
 
1688
            ": it's just not")
 
1689
 
 
1690
    def test_assertEndsWith(self):
 
1691
        self.assertEndsWith('foo', 'oo')
 
1692
        self.assertRaises(AssertionError, self.assertEndsWith, 'o', 'oo')
 
1693
 
 
1694
    def test_applyDeprecated_not_deprecated(self):
 
1695
        sample_object = ApplyDeprecatedHelper()
 
1696
        # calling an undeprecated callable raises an assertion
 
1697
        self.assertRaises(AssertionError, self.applyDeprecated,
 
1698
            deprecated_in((0, 11, 0)),
 
1699
            sample_object.sample_normal_method)
 
1700
        self.assertRaises(AssertionError, self.applyDeprecated,
 
1701
            deprecated_in((0, 11, 0)),
 
1702
            sample_undeprecated_function, "a param value")
 
1703
        # calling a deprecated callable (function or method) with the wrong
 
1704
        # expected deprecation fails.
 
1705
        self.assertRaises(AssertionError, self.applyDeprecated,
 
1706
            deprecated_in((0, 10, 0)),
 
1707
            sample_object.sample_deprecated_method, "a param value")
 
1708
        self.assertRaises(AssertionError, self.applyDeprecated,
 
1709
            deprecated_in((0, 10, 0)),
 
1710
            sample_deprecated_function)
 
1711
        # calling a deprecated callable (function or method) with the right
 
1712
        # expected deprecation returns the functions result.
 
1713
        self.assertEqual("a param value",
 
1714
            self.applyDeprecated(deprecated_in((0, 11, 0)),
 
1715
            sample_object.sample_deprecated_method, "a param value"))
 
1716
        self.assertEqual(2, self.applyDeprecated(deprecated_in((0, 11, 0)),
 
1717
            sample_deprecated_function))
 
1718
        # calling a nested deprecation with the wrong deprecation version
 
1719
        # fails even if a deeper nested function was deprecated with the
 
1720
        # supplied version.
 
1721
        self.assertRaises(AssertionError, self.applyDeprecated,
 
1722
            deprecated_in((0, 11, 0)), sample_object.sample_nested_deprecation)
 
1723
        # calling a nested deprecation with the right deprecation value
 
1724
        # returns the calls result.
 
1725
        self.assertEqual(2, self.applyDeprecated(deprecated_in((0, 10, 0)),
 
1726
            sample_object.sample_nested_deprecation))
 
1727
 
 
1728
    def test_callDeprecated(self):
 
1729
        def testfunc(be_deprecated, result=None):
 
1730
            if be_deprecated is True:
 
1731
                symbol_versioning.warn('i am deprecated', DeprecationWarning,
 
1732
                                       stacklevel=1)
 
1733
            return result
 
1734
        result = self.callDeprecated(['i am deprecated'], testfunc, True)
 
1735
        self.assertIs(None, result)
 
1736
        result = self.callDeprecated([], testfunc, False, 'result')
 
1737
        self.assertEqual('result', result)
 
1738
        self.callDeprecated(['i am deprecated'], testfunc, be_deprecated=True)
 
1739
        self.callDeprecated([], testfunc, be_deprecated=False)
 
1740
 
 
1741
 
 
1742
class TestWarningTests(tests.TestCase):
 
1743
    """Tests for calling methods that raise warnings."""
 
1744
 
 
1745
    def test_callCatchWarnings(self):
 
1746
        def meth(a, b):
 
1747
            warnings.warn("this is your last warning")
 
1748
            return a + b
 
1749
        wlist, result = self.callCatchWarnings(meth, 1, 2)
 
1750
        self.assertEquals(3, result)
 
1751
        # would like just to compare them, but UserWarning doesn't implement
 
1752
        # eq well
 
1753
        w0, = wlist
 
1754
        self.assertIsInstance(w0, UserWarning)
 
1755
        self.assertEquals("this is your last warning", str(w0))
 
1756
 
 
1757
 
 
1758
class TestConvenienceMakers(tests.TestCaseWithTransport):
 
1759
    """Test for the make_* convenience functions."""
 
1760
 
 
1761
    def test_make_branch_and_tree_with_format(self):
 
1762
        # we should be able to supply a format to make_branch_and_tree
 
1763
        self.make_branch_and_tree('a', format=bzrlib.bzrdir.BzrDirMetaFormat1())
 
1764
        self.make_branch_and_tree('b', format=bzrlib.bzrdir.BzrDirFormat6())
 
1765
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('a')._format,
 
1766
                              bzrlib.bzrdir.BzrDirMetaFormat1)
 
1767
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('b')._format,
 
1768
                              bzrlib.bzrdir.BzrDirFormat6)
 
1769
 
 
1770
    def test_make_branch_and_memory_tree(self):
 
1771
        # we should be able to get a new branch and a mutable tree from
 
1772
        # TestCaseWithTransport
 
1773
        tree = self.make_branch_and_memory_tree('a')
 
1774
        self.assertIsInstance(tree, bzrlib.memorytree.MemoryTree)
 
1775
 
 
1776
    def test_make_tree_for_local_vfs_backed_transport(self):
 
1777
        # make_branch_and_tree has to use local branch and repositories
 
1778
        # when the vfs transport and local disk are colocated, even if
 
1779
        # a different transport is in use for url generation.
 
1780
        from bzrlib.transport.fakevfat import FakeVFATServer
 
1781
        self.transport_server = FakeVFATServer
 
1782
        self.assertFalse(self.get_url('t1').startswith('file://'))
 
1783
        tree = self.make_branch_and_tree('t1')
 
1784
        base = tree.bzrdir.root_transport.base
 
1785
        self.assertStartsWith(base, 'file://')
 
1786
        self.assertEquals(tree.bzrdir.root_transport,
 
1787
                tree.branch.bzrdir.root_transport)
 
1788
        self.assertEquals(tree.bzrdir.root_transport,
 
1789
                tree.branch.repository.bzrdir.root_transport)
 
1790
 
 
1791
 
 
1792
class SelfTestHelper:
 
1793
 
 
1794
    def run_selftest(self, **kwargs):
 
1795
        """Run selftest returning its output."""
 
1796
        output = StringIO()
 
1797
        old_transport = bzrlib.tests.default_transport
 
1798
        old_root = tests.TestCaseWithMemoryTransport.TEST_ROOT
 
1799
        tests.TestCaseWithMemoryTransport.TEST_ROOT = None
 
1800
        try:
 
1801
            self.assertEqual(True, tests.selftest(stream=output, **kwargs))
 
1802
        finally:
 
1803
            bzrlib.tests.default_transport = old_transport
 
1804
            tests.TestCaseWithMemoryTransport.TEST_ROOT = old_root
 
1805
        output.seek(0)
 
1806
        return output
 
1807
 
 
1808
 
 
1809
class TestSelftest(tests.TestCase, SelfTestHelper):
 
1810
    """Tests of bzrlib.tests.selftest."""
 
1811
 
 
1812
    def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
 
1813
        factory_called = []
 
1814
        def factory():
 
1815
            factory_called.append(True)
 
1816
            return TestUtil.TestSuite()
 
1817
        out = StringIO()
 
1818
        err = StringIO()
 
1819
        self.apply_redirected(out, err, None, bzrlib.tests.selftest,
 
1820
            test_suite_factory=factory)
 
1821
        self.assertEqual([True], factory_called)
 
1822
 
 
1823
    def factory(self):
 
1824
        """A test suite factory."""
 
1825
        class Test(tests.TestCase):
 
1826
            def a(self):
 
1827
                pass
 
1828
            def b(self):
 
1829
                pass
 
1830
            def c(self):
 
1831
                pass
 
1832
        return TestUtil.TestSuite([Test("a"), Test("b"), Test("c")])
 
1833
 
 
1834
    def test_list_only(self):
 
1835
        output = self.run_selftest(test_suite_factory=self.factory,
 
1836
            list_only=True)
 
1837
        self.assertEqual(3, len(output.readlines()))
 
1838
 
 
1839
    def test_list_only_filtered(self):
 
1840
        output = self.run_selftest(test_suite_factory=self.factory,
 
1841
            list_only=True, pattern="Test.b")
 
1842
        self.assertEndsWith(output.getvalue(), "Test.b\n")
 
1843
        self.assertLength(1, output.readlines())
 
1844
 
 
1845
    def test_list_only_excludes(self):
 
1846
        output = self.run_selftest(test_suite_factory=self.factory,
 
1847
            list_only=True, exclude_pattern="Test.b")
 
1848
        self.assertNotContainsRe("Test.b", output.getvalue())
 
1849
        self.assertLength(2, output.readlines())
 
1850
 
 
1851
    def test_lsprof_tests(self):
 
1852
        self.requireFeature(test_lsprof.LSProfFeature)
 
1853
        calls = []
 
1854
        class Test(object):
 
1855
            def __call__(test, result):
 
1856
                test.run(result)
 
1857
            def run(test, result):
 
1858
                self.assertIsInstance(result, tests.ForwardingResult)
 
1859
                calls.append("called")
 
1860
            def countTestCases(self):
 
1861
                return 1
 
1862
        self.run_selftest(test_suite_factory=Test, lsprof_tests=True)
 
1863
        self.assertLength(1, calls)
 
1864
 
 
1865
    def test_random(self):
 
1866
        # test randomising by listing a number of tests.
 
1867
        output_123 = self.run_selftest(test_suite_factory=self.factory,
 
1868
            list_only=True, random_seed="123")
 
1869
        output_234 = self.run_selftest(test_suite_factory=self.factory,
 
1870
            list_only=True, random_seed="234")
 
1871
        self.assertNotEqual(output_123, output_234)
 
1872
        # "Randominzing test order..\n\n
 
1873
        self.assertLength(5, output_123.readlines())
 
1874
        self.assertLength(5, output_234.readlines())
 
1875
 
 
1876
    def test_random_reuse_is_same_order(self):
 
1877
        # test randomising by listing a number of tests.
 
1878
        expected = self.run_selftest(test_suite_factory=self.factory,
 
1879
            list_only=True, random_seed="123")
 
1880
        repeated = self.run_selftest(test_suite_factory=self.factory,
 
1881
            list_only=True, random_seed="123")
 
1882
        self.assertEqual(expected.getvalue(), repeated.getvalue())
 
1883
 
 
1884
    def test_runner_class(self):
 
1885
        self.requireFeature(SubUnitFeature)
 
1886
        from subunit import ProtocolTestCase
 
1887
        stream = self.run_selftest(runner_class=tests.SubUnitBzrRunner,
 
1888
            test_suite_factory=self.factory)
 
1889
        test = ProtocolTestCase(stream)
 
1890
        result = unittest.TestResult()
 
1891
        test.run(result)
 
1892
        self.assertEqual(3, result.testsRun)
 
1893
 
 
1894
    def test_starting_with_single_argument(self):
 
1895
        output = self.run_selftest(test_suite_factory=self.factory,
 
1896
            starting_with=['bzrlib.tests.test_selftest.Test.a'],
 
1897
            list_only=True)
 
1898
        self.assertEqual('bzrlib.tests.test_selftest.Test.a\n',
 
1899
            output.getvalue())
 
1900
 
 
1901
    def test_starting_with_multiple_argument(self):
 
1902
        output = self.run_selftest(test_suite_factory=self.factory,
 
1903
            starting_with=['bzrlib.tests.test_selftest.Test.a',
 
1904
                'bzrlib.tests.test_selftest.Test.b'],
 
1905
            list_only=True)
 
1906
        self.assertEqual('bzrlib.tests.test_selftest.Test.a\n'
 
1907
            'bzrlib.tests.test_selftest.Test.b\n',
 
1908
            output.getvalue())
 
1909
 
 
1910
    def check_transport_set(self, transport_server):
 
1911
        captured_transport = []
 
1912
        def seen_transport(a_transport):
 
1913
            captured_transport.append(a_transport)
 
1914
        class Capture(tests.TestCase):
 
1915
            def a(self):
 
1916
                seen_transport(bzrlib.tests.default_transport)
 
1917
        def factory():
 
1918
            return TestUtil.TestSuite([Capture("a")])
 
1919
        self.run_selftest(transport=transport_server, test_suite_factory=factory)
 
1920
        self.assertEqual(transport_server, captured_transport[0])
 
1921
 
 
1922
    def test_transport_sftp(self):
 
1923
        try:
 
1924
            import bzrlib.transport.sftp
 
1925
        except errors.ParamikoNotPresent:
 
1926
            raise tests.TestSkipped("Paramiko not present")
 
1927
        self.check_transport_set(bzrlib.transport.sftp.SFTPAbsoluteServer)
 
1928
 
 
1929
    def test_transport_memory(self):
 
1930
        self.check_transport_set(bzrlib.transport.memory.MemoryServer)
 
1931
 
 
1932
 
 
1933
class TestSelftestWithIdList(tests.TestCaseInTempDir, SelfTestHelper):
 
1934
    # Does IO: reads test.list
 
1935
 
 
1936
    def test_load_list(self):
 
1937
        # Provide a list with one test - this test.
 
1938
        test_id_line = '%s\n' % self.id()
 
1939
        self.build_tree_contents([('test.list', test_id_line)])
 
1940
        # And generate a list of the tests in  the suite.
 
1941
        stream = self.run_selftest(load_list='test.list', list_only=True)
 
1942
        self.assertEqual(test_id_line, stream.getvalue())
 
1943
 
 
1944
    def test_load_unknown(self):
 
1945
        # Provide a list with one test - this test.
 
1946
        # And generate a list of the tests in  the suite.
 
1947
        err = self.assertRaises(errors.NoSuchFile, self.run_selftest,
 
1948
            load_list='missing file name', list_only=True)
 
1949
 
 
1950
 
 
1951
class TestRunBzr(tests.TestCase):
 
1952
 
 
1953
    out = ''
 
1954
    err = ''
 
1955
 
 
1956
    def _run_bzr_core(self, argv, retcode=0, encoding=None, stdin=None,
 
1957
                         working_dir=None):
 
1958
        """Override _run_bzr_core to test how it is invoked by run_bzr.
 
1959
 
 
1960
        Attempts to run bzr from inside this class don't actually run it.
 
1961
 
 
1962
        We test how run_bzr actually invokes bzr in another location.
 
1963
        Here we only need to test that it is run_bzr passes the right
 
1964
        parameters to run_bzr.
 
1965
        """
 
1966
        self.argv = list(argv)
 
1967
        self.retcode = retcode
 
1968
        self.encoding = encoding
 
1969
        self.stdin = stdin
 
1970
        self.working_dir = working_dir
 
1971
        return self.out, self.err
 
1972
 
 
1973
    def test_run_bzr_error(self):
 
1974
        self.out = "It sure does!\n"
 
1975
        out, err = self.run_bzr_error(['^$'], ['rocks'], retcode=34)
 
1976
        self.assertEqual(['rocks'], self.argv)
 
1977
        self.assertEqual(34, self.retcode)
 
1978
        self.assertEqual(out, 'It sure does!\n')
 
1979
 
 
1980
    def test_run_bzr_error_regexes(self):
 
1981
        self.out = ''
 
1982
        self.err = "bzr: ERROR: foobarbaz is not versioned"
 
1983
        out, err = self.run_bzr_error(
 
1984
                ["bzr: ERROR: foobarbaz is not versioned"],
 
1985
                ['file-id', 'foobarbaz'])
 
1986
 
 
1987
    def test_encoding(self):
 
1988
        """Test that run_bzr passes encoding to _run_bzr_core"""
 
1989
        self.run_bzr('foo bar')
 
1990
        self.assertEqual(None, self.encoding)
 
1991
        self.assertEqual(['foo', 'bar'], self.argv)
 
1992
 
 
1993
        self.run_bzr('foo bar', encoding='baz')
 
1994
        self.assertEqual('baz', self.encoding)
 
1995
        self.assertEqual(['foo', 'bar'], self.argv)
 
1996
 
 
1997
    def test_retcode(self):
 
1998
        """Test that run_bzr passes retcode to _run_bzr_core"""
 
1999
        # Default is retcode == 0
 
2000
        self.run_bzr('foo bar')
 
2001
        self.assertEqual(0, self.retcode)
 
2002
        self.assertEqual(['foo', 'bar'], self.argv)
 
2003
 
 
2004
        self.run_bzr('foo bar', retcode=1)
 
2005
        self.assertEqual(1, self.retcode)
 
2006
        self.assertEqual(['foo', 'bar'], self.argv)
 
2007
 
 
2008
        self.run_bzr('foo bar', retcode=None)
 
2009
        self.assertEqual(None, self.retcode)
 
2010
        self.assertEqual(['foo', 'bar'], self.argv)
 
2011
 
 
2012
        self.run_bzr(['foo', 'bar'], retcode=3)
 
2013
        self.assertEqual(3, self.retcode)
 
2014
        self.assertEqual(['foo', 'bar'], self.argv)
 
2015
 
 
2016
    def test_stdin(self):
 
2017
        # test that the stdin keyword to run_bzr is passed through to
 
2018
        # _run_bzr_core as-is. We do this by overriding
 
2019
        # _run_bzr_core in this class, and then calling run_bzr,
 
2020
        # which is a convenience function for _run_bzr_core, so
 
2021
        # should invoke it.
 
2022
        self.run_bzr('foo bar', stdin='gam')
 
2023
        self.assertEqual('gam', self.stdin)
 
2024
        self.assertEqual(['foo', 'bar'], self.argv)
 
2025
 
 
2026
        self.run_bzr('foo bar', stdin='zippy')
 
2027
        self.assertEqual('zippy', self.stdin)
 
2028
        self.assertEqual(['foo', 'bar'], self.argv)
 
2029
 
 
2030
    def test_working_dir(self):
 
2031
        """Test that run_bzr passes working_dir to _run_bzr_core"""
 
2032
        self.run_bzr('foo bar')
 
2033
        self.assertEqual(None, self.working_dir)
 
2034
        self.assertEqual(['foo', 'bar'], self.argv)
 
2035
 
 
2036
        self.run_bzr('foo bar', working_dir='baz')
 
2037
        self.assertEqual('baz', self.working_dir)
 
2038
        self.assertEqual(['foo', 'bar'], self.argv)
 
2039
 
 
2040
    def test_reject_extra_keyword_arguments(self):
 
2041
        self.assertRaises(TypeError, self.run_bzr, "foo bar",
 
2042
                          error_regex=['error message'])
 
2043
 
 
2044
 
 
2045
class TestRunBzrCaptured(tests.TestCaseWithTransport):
 
2046
    # Does IO when testing the working_dir parameter.
 
2047
 
 
2048
    def apply_redirected(self, stdin=None, stdout=None, stderr=None,
 
2049
                         a_callable=None, *args, **kwargs):
 
2050
        self.stdin = stdin
 
2051
        self.factory_stdin = getattr(bzrlib.ui.ui_factory, "stdin", None)
 
2052
        self.factory = bzrlib.ui.ui_factory
 
2053
        self.working_dir = osutils.getcwd()
 
2054
        stdout.write('foo\n')
 
2055
        stderr.write('bar\n')
 
2056
        return 0
 
2057
 
 
2058
    def test_stdin(self):
 
2059
        # test that the stdin keyword to _run_bzr_core is passed through to
 
2060
        # apply_redirected as a StringIO. We do this by overriding
 
2061
        # apply_redirected in this class, and then calling _run_bzr_core,
 
2062
        # which calls apply_redirected.
 
2063
        self.run_bzr(['foo', 'bar'], stdin='gam')
 
2064
        self.assertEqual('gam', self.stdin.read())
 
2065
        self.assertTrue(self.stdin is self.factory_stdin)
 
2066
        self.run_bzr(['foo', 'bar'], stdin='zippy')
 
2067
        self.assertEqual('zippy', self.stdin.read())
 
2068
        self.assertTrue(self.stdin is self.factory_stdin)
 
2069
 
 
2070
    def test_ui_factory(self):
 
2071
        # each invocation of self.run_bzr should get its
 
2072
        # own UI factory, which is an instance of TestUIFactory,
 
2073
        # with stdin, stdout and stderr attached to the stdin,
 
2074
        # stdout and stderr of the invoked run_bzr
 
2075
        current_factory = bzrlib.ui.ui_factory
 
2076
        self.run_bzr(['foo'])
 
2077
        self.failIf(current_factory is self.factory)
 
2078
        self.assertNotEqual(sys.stdout, self.factory.stdout)
 
2079
        self.assertNotEqual(sys.stderr, self.factory.stderr)
 
2080
        self.assertEqual('foo\n', self.factory.stdout.getvalue())
 
2081
        self.assertEqual('bar\n', self.factory.stderr.getvalue())
 
2082
        self.assertIsInstance(self.factory, tests.TestUIFactory)
 
2083
 
 
2084
    def test_working_dir(self):
 
2085
        self.build_tree(['one/', 'two/'])
 
2086
        cwd = osutils.getcwd()
 
2087
 
 
2088
        # Default is to work in the current directory
 
2089
        self.run_bzr(['foo', 'bar'])
 
2090
        self.assertEqual(cwd, self.working_dir)
 
2091
 
 
2092
        self.run_bzr(['foo', 'bar'], working_dir=None)
 
2093
        self.assertEqual(cwd, self.working_dir)
 
2094
 
 
2095
        # The function should be run in the alternative directory
 
2096
        # but afterwards the current working dir shouldn't be changed
 
2097
        self.run_bzr(['foo', 'bar'], working_dir='one')
 
2098
        self.assertNotEqual(cwd, self.working_dir)
 
2099
        self.assertEndsWith(self.working_dir, 'one')
 
2100
        self.assertEqual(cwd, osutils.getcwd())
 
2101
 
 
2102
        self.run_bzr(['foo', 'bar'], working_dir='two')
 
2103
        self.assertNotEqual(cwd, self.working_dir)
 
2104
        self.assertEndsWith(self.working_dir, 'two')
 
2105
        self.assertEqual(cwd, osutils.getcwd())
 
2106
 
 
2107
 
 
2108
class StubProcess(object):
 
2109
    """A stub process for testing run_bzr_subprocess."""
 
2110
    
 
2111
    def __init__(self, out="", err="", retcode=0):
 
2112
        self.out = out
 
2113
        self.err = err
 
2114
        self.returncode = retcode
 
2115
 
 
2116
    def communicate(self):
 
2117
        return self.out, self.err
 
2118
 
 
2119
 
 
2120
class TestWithFakedStartBzrSubprocess(tests.TestCaseWithTransport):
 
2121
    """Base class for tests testing how we might run bzr."""
 
2122
 
 
2123
    def setUp(self):
 
2124
        tests.TestCaseWithTransport.setUp(self)
 
2125
        self.subprocess_calls = []
 
2126
 
 
2127
    def start_bzr_subprocess(self, process_args, env_changes=None,
 
2128
                             skip_if_plan_to_signal=False,
 
2129
                             working_dir=None,
 
2130
                             allow_plugins=False):
 
2131
        """capture what run_bzr_subprocess tries to do."""
 
2132
        self.subprocess_calls.append({'process_args':process_args,
 
2133
            'env_changes':env_changes,
 
2134
            'skip_if_plan_to_signal':skip_if_plan_to_signal,
 
2135
            'working_dir':working_dir, 'allow_plugins':allow_plugins})
 
2136
        return self.next_subprocess
 
2137
 
 
2138
 
 
2139
class TestRunBzrSubprocess(TestWithFakedStartBzrSubprocess):
 
2140
 
 
2141
    def assertRunBzrSubprocess(self, expected_args, process, *args, **kwargs):
 
2142
        """Run run_bzr_subprocess with args and kwargs using a stubbed process.
 
2143
 
 
2144
        Inside TestRunBzrSubprocessCommands we use a stub start_bzr_subprocess
 
2145
        that will return static results. This assertion method populates those
 
2146
        results and also checks the arguments run_bzr_subprocess generates.
 
2147
        """
 
2148
        self.next_subprocess = process
 
2149
        try:
 
2150
            result = self.run_bzr_subprocess(*args, **kwargs)
 
2151
        except:
 
2152
            self.next_subprocess = None
 
2153
            for key, expected in expected_args.iteritems():
 
2154
                self.assertEqual(expected, self.subprocess_calls[-1][key])
 
2155
            raise
 
2156
        else:
 
2157
            self.next_subprocess = None
 
2158
            for key, expected in expected_args.iteritems():
 
2159
                self.assertEqual(expected, self.subprocess_calls[-1][key])
 
2160
            return result
 
2161
 
 
2162
    def test_run_bzr_subprocess(self):
 
2163
        """The run_bzr_helper_external command behaves nicely."""
 
2164
        self.assertRunBzrSubprocess({'process_args':['--version']},
 
2165
            StubProcess(), '--version')
 
2166
        self.assertRunBzrSubprocess({'process_args':['--version']},
 
2167
            StubProcess(), ['--version'])
 
2168
        # retcode=None disables retcode checking
 
2169
        result = self.assertRunBzrSubprocess({},
 
2170
            StubProcess(retcode=3), '--version', retcode=None)
 
2171
        result = self.assertRunBzrSubprocess({},
 
2172
            StubProcess(out="is free software"), '--version')
 
2173
        self.assertContainsRe(result[0], 'is free software')
 
2174
        # Running a subcommand that is missing errors
 
2175
        self.assertRaises(AssertionError, self.assertRunBzrSubprocess,
 
2176
            {'process_args':['--versionn']}, StubProcess(retcode=3),
 
2177
            '--versionn')
 
2178
        # Unless it is told to expect the error from the subprocess
 
2179
        result = self.assertRunBzrSubprocess({},
 
2180
            StubProcess(retcode=3), '--versionn', retcode=3)
 
2181
        # Or to ignore retcode checking
 
2182
        result = self.assertRunBzrSubprocess({},
 
2183
            StubProcess(err="unknown command", retcode=3), '--versionn',
 
2184
            retcode=None)
 
2185
        self.assertContainsRe(result[1], 'unknown command')
 
2186
 
 
2187
    def test_env_change_passes_through(self):
 
2188
        self.assertRunBzrSubprocess(
 
2189
            {'env_changes':{'new':'value', 'changed':'newvalue', 'deleted':None}},
 
2190
            StubProcess(), '',
 
2191
            env_changes={'new':'value', 'changed':'newvalue', 'deleted':None})
 
2192
 
 
2193
    def test_no_working_dir_passed_as_None(self):
 
2194
        self.assertRunBzrSubprocess({'working_dir': None}, StubProcess(), '')
 
2195
 
 
2196
    def test_no_working_dir_passed_through(self):
 
2197
        self.assertRunBzrSubprocess({'working_dir': 'dir'}, StubProcess(), '',
 
2198
            working_dir='dir')
 
2199
 
 
2200
    def test_run_bzr_subprocess_no_plugins(self):
 
2201
        self.assertRunBzrSubprocess({'allow_plugins': False},
 
2202
            StubProcess(), '')
 
2203
 
 
2204
    def test_allow_plugins(self):
 
2205
        self.assertRunBzrSubprocess({'allow_plugins': True},
 
2206
            StubProcess(), '', allow_plugins=True)
 
2207
 
 
2208
 
 
2209
class TestFinishBzrSubprocess(TestWithFakedStartBzrSubprocess):
 
2210
 
 
2211
    def test_finish_bzr_subprocess_with_error(self):
 
2212
        """finish_bzr_subprocess allows specification of the desired exit code.
 
2213
        """
 
2214
        process = StubProcess(err="unknown command", retcode=3)
 
2215
        result = self.finish_bzr_subprocess(process, retcode=3)
 
2216
        self.assertEqual('', result[0])
 
2217
        self.assertContainsRe(result[1], 'unknown command')
 
2218
 
 
2219
    def test_finish_bzr_subprocess_ignoring_retcode(self):
 
2220
        """finish_bzr_subprocess allows the exit code to be ignored."""
 
2221
        process = StubProcess(err="unknown command", retcode=3)
 
2222
        result = self.finish_bzr_subprocess(process, retcode=None)
 
2223
        self.assertEqual('', result[0])
 
2224
        self.assertContainsRe(result[1], 'unknown command')
 
2225
 
 
2226
    def test_finish_subprocess_with_unexpected_retcode(self):
 
2227
        """finish_bzr_subprocess raises self.failureException if the retcode is
 
2228
        not the expected one.
 
2229
        """
 
2230
        process = StubProcess(err="unknown command", retcode=3)
 
2231
        self.assertRaises(self.failureException, self.finish_bzr_subprocess,
 
2232
                          process)
 
2233
 
 
2234
 
 
2235
class _DontSpawnProcess(Exception):
 
2236
    """A simple exception which just allows us to skip unnecessary steps"""
 
2237
 
 
2238
 
 
2239
class TestStartBzrSubProcess(tests.TestCase):
 
2240
 
 
2241
    def check_popen_state(self):
 
2242
        """Replace to make assertions when popen is called."""
 
2243
 
 
2244
    def _popen(self, *args, **kwargs):
 
2245
        """Record the command that is run, so that we can ensure it is correct"""
 
2246
        self.check_popen_state()
 
2247
        self._popen_args = args
 
2248
        self._popen_kwargs = kwargs
 
2249
        raise _DontSpawnProcess()
 
2250
 
 
2251
    def test_run_bzr_subprocess_no_plugins(self):
 
2252
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [])
 
2253
        command = self._popen_args[0]
 
2254
        self.assertEqual(sys.executable, command[0])
 
2255
        self.assertEqual(self.get_bzr_path(), command[1])
 
2256
        self.assertEqual(['--no-plugins'], command[2:])
 
2257
 
 
2258
    def test_allow_plugins(self):
 
2259
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
 
2260
            allow_plugins=True)
 
2261
        command = self._popen_args[0]
 
2262
        self.assertEqual([], command[2:])
 
2263
 
 
2264
    def test_set_env(self):
 
2265
        self.failIf('EXISTANT_ENV_VAR' in os.environ)
 
2266
        # set in the child
 
2267
        def check_environment():
 
2268
            self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
 
2269
        self.check_popen_state = check_environment
 
2270
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
 
2271
            env_changes={'EXISTANT_ENV_VAR':'set variable'})
 
2272
        # not set in theparent
 
2273
        self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
 
2274
 
 
2275
    def test_run_bzr_subprocess_env_del(self):
 
2276
        """run_bzr_subprocess can remove environment variables too."""
 
2277
        self.failIf('EXISTANT_ENV_VAR' in os.environ)
 
2278
        def check_environment():
 
2279
            self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
 
2280
        os.environ['EXISTANT_ENV_VAR'] = 'set variable'
 
2281
        self.check_popen_state = check_environment
 
2282
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
 
2283
            env_changes={'EXISTANT_ENV_VAR':None})
 
2284
        # Still set in parent
 
2285
        self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
 
2286
        del os.environ['EXISTANT_ENV_VAR']
 
2287
 
 
2288
    def test_env_del_missing(self):
 
2289
        self.failIf('NON_EXISTANT_ENV_VAR' in os.environ)
 
2290
        def check_environment():
 
2291
            self.assertFalse('NON_EXISTANT_ENV_VAR' in os.environ)
 
2292
        self.check_popen_state = check_environment
 
2293
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
 
2294
            env_changes={'NON_EXISTANT_ENV_VAR':None})
 
2295
 
 
2296
    def test_working_dir(self):
 
2297
        """Test that we can specify the working dir for the child"""
 
2298
        orig_getcwd = osutils.getcwd
 
2299
        orig_chdir = os.chdir
 
2300
        chdirs = []
 
2301
        def chdir(path):
 
2302
            chdirs.append(path)
 
2303
        os.chdir = chdir
 
2304
        try:
 
2305
            def getcwd():
 
2306
                return 'current'
 
2307
            osutils.getcwd = getcwd
 
2308
            try:
 
2309
                self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
 
2310
                    working_dir='foo')
 
2311
            finally:
 
2312
                osutils.getcwd = orig_getcwd
 
2313
        finally:
 
2314
            os.chdir = orig_chdir
 
2315
        self.assertEqual(['foo', 'current'], chdirs)
 
2316
 
 
2317
 
 
2318
class TestActuallyStartBzrSubprocess(tests.TestCaseWithTransport):
 
2319
    """Tests that really need to do things with an external bzr."""
 
2320
 
 
2321
    def test_start_and_stop_bzr_subprocess_send_signal(self):
 
2322
        """finish_bzr_subprocess raises self.failureException if the retcode is
 
2323
        not the expected one.
 
2324
        """
 
2325
        process = self.start_bzr_subprocess(['wait-until-signalled'],
 
2326
                                            skip_if_plan_to_signal=True)
 
2327
        self.assertEqual('running\n', process.stdout.readline())
 
2328
        result = self.finish_bzr_subprocess(process, send_signal=signal.SIGINT,
 
2329
                                            retcode=3)
 
2330
        self.assertEqual('', result[0])
 
2331
        self.assertEqual('bzr: interrupted\n', result[1])
 
2332
 
 
2333
 
 
2334
class TestKnownFailure(tests.TestCase):
 
2335
 
 
2336
    def test_known_failure(self):
 
2337
        """Check that KnownFailure is defined appropriately."""
 
2338
        # a KnownFailure is an assertion error for compatability with unaware
 
2339
        # runners.
 
2340
        self.assertIsInstance(tests.KnownFailure(""), AssertionError)
 
2341
 
 
2342
    def test_expect_failure(self):
 
2343
        try:
 
2344
            self.expectFailure("Doomed to failure", self.assertTrue, False)
 
2345
        except tests.KnownFailure, e:
 
2346
            self.assertEqual('Doomed to failure', e.args[0])
 
2347
        try:
 
2348
            self.expectFailure("Doomed to failure", self.assertTrue, True)
 
2349
        except AssertionError, e:
 
2350
            self.assertEqual('Unexpected success.  Should have failed:'
 
2351
                             ' Doomed to failure', e.args[0])
 
2352
        else:
 
2353
            self.fail('Assertion not raised')
 
2354
 
 
2355
 
 
2356
class TestFeature(tests.TestCase):
 
2357
 
 
2358
    def test_caching(self):
 
2359
        """Feature._probe is called by the feature at most once."""
 
2360
        class InstrumentedFeature(tests.Feature):
 
2361
            def __init__(self):
 
2362
                super(InstrumentedFeature, self).__init__()
 
2363
                self.calls = []
 
2364
            def _probe(self):
 
2365
                self.calls.append('_probe')
 
2366
                return False
 
2367
        feature = InstrumentedFeature()
 
2368
        feature.available()
 
2369
        self.assertEqual(['_probe'], feature.calls)
 
2370
        feature.available()
 
2371
        self.assertEqual(['_probe'], feature.calls)
 
2372
 
 
2373
    def test_named_str(self):
 
2374
        """Feature.__str__ should thunk to feature_name()."""
 
2375
        class NamedFeature(tests.Feature):
 
2376
            def feature_name(self):
 
2377
                return 'symlinks'
 
2378
        feature = NamedFeature()
 
2379
        self.assertEqual('symlinks', str(feature))
 
2380
 
 
2381
    def test_default_str(self):
 
2382
        """Feature.__str__ should default to __class__.__name__."""
 
2383
        class NamedFeature(tests.Feature):
 
2384
            pass
 
2385
        feature = NamedFeature()
 
2386
        self.assertEqual('NamedFeature', str(feature))
 
2387
 
 
2388
 
 
2389
class TestUnavailableFeature(tests.TestCase):
 
2390
 
 
2391
    def test_access_feature(self):
 
2392
        feature = tests.Feature()
 
2393
        exception = tests.UnavailableFeature(feature)
 
2394
        self.assertIs(feature, exception.args[0])
 
2395
 
 
2396
 
 
2397
class TestSelftestFiltering(tests.TestCase):
 
2398
 
 
2399
    def setUp(self):
 
2400
        tests.TestCase.setUp(self)
 
2401
        self.suite = TestUtil.TestSuite()
 
2402
        self.loader = TestUtil.TestLoader()
 
2403
        self.suite.addTest(self.loader.loadTestsFromModule(
 
2404
            sys.modules['bzrlib.tests.test_selftest']))
 
2405
        self.all_names = _test_ids(self.suite)
 
2406
 
 
2407
    def test_condition_id_re(self):
 
2408
        test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2409
            'test_condition_id_re')
 
2410
        filtered_suite = tests.filter_suite_by_condition(
 
2411
            self.suite, tests.condition_id_re('test_condition_id_re'))
 
2412
        self.assertEqual([test_name], _test_ids(filtered_suite))
 
2413
 
 
2414
    def test_condition_id_in_list(self):
 
2415
        test_names = ['bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2416
                      'test_condition_id_in_list']
 
2417
        id_list = tests.TestIdList(test_names)
 
2418
        filtered_suite = tests.filter_suite_by_condition(
 
2419
            self.suite, tests.condition_id_in_list(id_list))
 
2420
        my_pattern = 'TestSelftestFiltering.*test_condition_id_in_list'
 
2421
        re_filtered = tests.filter_suite_by_re(self.suite, my_pattern)
 
2422
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
 
2423
 
 
2424
    def test_condition_id_startswith(self):
 
2425
        klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2426
        start1 = klass + 'test_condition_id_starts'
 
2427
        start2 = klass + 'test_condition_id_in'
 
2428
        test_names = [ klass + 'test_condition_id_in_list',
 
2429
                      klass + 'test_condition_id_startswith',
 
2430
                     ]
 
2431
        filtered_suite = tests.filter_suite_by_condition(
 
2432
            self.suite, tests.condition_id_startswith([start1, start2]))
 
2433
        self.assertEqual(test_names, _test_ids(filtered_suite))
 
2434
 
 
2435
    def test_condition_isinstance(self):
 
2436
        filtered_suite = tests.filter_suite_by_condition(
 
2437
            self.suite, tests.condition_isinstance(self.__class__))
 
2438
        class_pattern = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2439
        re_filtered = tests.filter_suite_by_re(self.suite, class_pattern)
 
2440
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
 
2441
 
 
2442
    def test_exclude_tests_by_condition(self):
 
2443
        excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2444
            'test_exclude_tests_by_condition')
 
2445
        filtered_suite = tests.exclude_tests_by_condition(self.suite,
 
2446
            lambda x:x.id() == excluded_name)
 
2447
        self.assertEqual(len(self.all_names) - 1,
 
2448
            filtered_suite.countTestCases())
 
2449
        self.assertFalse(excluded_name in _test_ids(filtered_suite))
 
2450
        remaining_names = list(self.all_names)
 
2451
        remaining_names.remove(excluded_name)
 
2452
        self.assertEqual(remaining_names, _test_ids(filtered_suite))
 
2453
 
 
2454
    def test_exclude_tests_by_re(self):
 
2455
        self.all_names = _test_ids(self.suite)
 
2456
        filtered_suite = tests.exclude_tests_by_re(self.suite,
 
2457
                                                   'exclude_tests_by_re')
 
2458
        excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2459
            'test_exclude_tests_by_re')
 
2460
        self.assertEqual(len(self.all_names) - 1,
 
2461
            filtered_suite.countTestCases())
 
2462
        self.assertFalse(excluded_name in _test_ids(filtered_suite))
 
2463
        remaining_names = list(self.all_names)
 
2464
        remaining_names.remove(excluded_name)
 
2465
        self.assertEqual(remaining_names, _test_ids(filtered_suite))
 
2466
 
 
2467
    def test_filter_suite_by_condition(self):
 
2468
        test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2469
            'test_filter_suite_by_condition')
 
2470
        filtered_suite = tests.filter_suite_by_condition(self.suite,
 
2471
            lambda x:x.id() == test_name)
 
2472
        self.assertEqual([test_name], _test_ids(filtered_suite))
 
2473
 
 
2474
    def test_filter_suite_by_re(self):
 
2475
        filtered_suite = tests.filter_suite_by_re(self.suite,
 
2476
                                                  'test_filter_suite_by_r')
 
2477
        filtered_names = _test_ids(filtered_suite)
 
2478
        self.assertEqual(filtered_names, ['bzrlib.tests.test_selftest.'
 
2479
            'TestSelftestFiltering.test_filter_suite_by_re'])
 
2480
 
 
2481
    def test_filter_suite_by_id_list(self):
 
2482
        test_list = ['bzrlib.tests.test_selftest.'
 
2483
                     'TestSelftestFiltering.test_filter_suite_by_id_list']
 
2484
        filtered_suite = tests.filter_suite_by_id_list(
 
2485
            self.suite, tests.TestIdList(test_list))
 
2486
        filtered_names = _test_ids(filtered_suite)
 
2487
        self.assertEqual(
 
2488
            filtered_names,
 
2489
            ['bzrlib.tests.test_selftest.'
 
2490
             'TestSelftestFiltering.test_filter_suite_by_id_list'])
 
2491
 
 
2492
    def test_filter_suite_by_id_startswith(self):
 
2493
        # By design this test may fail if another test is added whose name also
 
2494
        # begins with one of the start value used.
 
2495
        klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2496
        start1 = klass + 'test_filter_suite_by_id_starts'
 
2497
        start2 = klass + 'test_filter_suite_by_id_li'
 
2498
        test_list = [klass + 'test_filter_suite_by_id_list',
 
2499
                     klass + 'test_filter_suite_by_id_startswith',
 
2500
                     ]
 
2501
        filtered_suite = tests.filter_suite_by_id_startswith(
 
2502
            self.suite, [start1, start2])
 
2503
        self.assertEqual(
 
2504
            test_list,
 
2505
            _test_ids(filtered_suite),
 
2506
            )
 
2507
 
 
2508
    def test_preserve_input(self):
 
2509
        # NB: Surely this is something in the stdlib to do this?
 
2510
        self.assertTrue(self.suite is tests.preserve_input(self.suite))
 
2511
        self.assertTrue("@#$" is tests.preserve_input("@#$"))
 
2512
 
 
2513
    def test_randomize_suite(self):
 
2514
        randomized_suite = tests.randomize_suite(self.suite)
 
2515
        # randomizing should not add or remove test names.
 
2516
        self.assertEqual(set(_test_ids(self.suite)),
 
2517
                         set(_test_ids(randomized_suite)))
 
2518
        # Technically, this *can* fail, because random.shuffle(list) can be
 
2519
        # equal to list. Trying multiple times just pushes the frequency back.
 
2520
        # As its len(self.all_names)!:1, the failure frequency should be low
 
2521
        # enough to ignore. RBC 20071021.
 
2522
        # It should change the order.
 
2523
        self.assertNotEqual(self.all_names, _test_ids(randomized_suite))
 
2524
        # But not the length. (Possibly redundant with the set test, but not
 
2525
        # necessarily.)
 
2526
        self.assertEqual(len(self.all_names), len(_test_ids(randomized_suite)))
 
2527
 
 
2528
    def test_split_suit_by_condition(self):
 
2529
        self.all_names = _test_ids(self.suite)
 
2530
        condition = tests.condition_id_re('test_filter_suite_by_r')
 
2531
        split_suite = tests.split_suite_by_condition(self.suite, condition)
 
2532
        filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2533
            'test_filter_suite_by_re')
 
2534
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
 
2535
        self.assertFalse(filtered_name in _test_ids(split_suite[1]))
 
2536
        remaining_names = list(self.all_names)
 
2537
        remaining_names.remove(filtered_name)
 
2538
        self.assertEqual(remaining_names, _test_ids(split_suite[1]))
 
2539
 
 
2540
    def test_split_suit_by_re(self):
 
2541
        self.all_names = _test_ids(self.suite)
 
2542
        split_suite = tests.split_suite_by_re(self.suite,
 
2543
                                              'test_filter_suite_by_r')
 
2544
        filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
2545
            'test_filter_suite_by_re')
 
2546
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
 
2547
        self.assertFalse(filtered_name in _test_ids(split_suite[1]))
 
2548
        remaining_names = list(self.all_names)
 
2549
        remaining_names.remove(filtered_name)
 
2550
        self.assertEqual(remaining_names, _test_ids(split_suite[1]))
 
2551
 
 
2552
 
 
2553
class TestCheckInventoryShape(tests.TestCaseWithTransport):
 
2554
 
 
2555
    def test_check_inventory_shape(self):
 
2556
        files = ['a', 'b/', 'b/c']
 
2557
        tree = self.make_branch_and_tree('.')
 
2558
        self.build_tree(files)
 
2559
        tree.add(files)
 
2560
        tree.lock_read()
 
2561
        try:
 
2562
            self.check_inventory_shape(tree.inventory, files)
 
2563
        finally:
 
2564
            tree.unlock()
 
2565
 
 
2566
 
 
2567
class TestBlackboxSupport(tests.TestCase):
 
2568
    """Tests for testsuite blackbox features."""
 
2569
 
 
2570
    def test_run_bzr_failure_not_caught(self):
 
2571
        # When we run bzr in blackbox mode, we want any unexpected errors to
 
2572
        # propagate up to the test suite so that it can show the error in the
 
2573
        # usual way, and we won't get a double traceback.
 
2574
        e = self.assertRaises(
 
2575
            AssertionError,
 
2576
            self.run_bzr, ['assert-fail'])
 
2577
        # make sure we got the real thing, not an error from somewhere else in
 
2578
        # the test framework
 
2579
        self.assertEquals('always fails', str(e))
 
2580
        # check that there's no traceback in the test log
 
2581
        self.assertNotContainsRe(self._get_log(keep_log_file=True),
 
2582
            r'Traceback')
 
2583
 
 
2584
    def test_run_bzr_user_error_caught(self):
 
2585
        # Running bzr in blackbox mode, normal/expected/user errors should be
 
2586
        # caught in the regular way and turned into an error message plus exit
 
2587
        # code.
 
2588
        out, err = self.run_bzr(["log", "/nonexistantpath"], retcode=3)
 
2589
        self.assertEqual(out, '')
 
2590
        self.assertContainsRe(err,
 
2591
            'bzr: ERROR: Not a branch: ".*nonexistantpath/".\n')
 
2592
 
 
2593
 
 
2594
class TestTestLoader(tests.TestCase):
 
2595
    """Tests for the test loader."""
 
2596
 
 
2597
    def _get_loader_and_module(self):
 
2598
        """Gets a TestLoader and a module with one test in it."""
 
2599
        loader = TestUtil.TestLoader()
 
2600
        module = {}
 
2601
        class Stub(tests.TestCase):
 
2602
            def test_foo(self):
 
2603
                pass
 
2604
        class MyModule(object):
 
2605
            pass
 
2606
        MyModule.a_class = Stub
 
2607
        module = MyModule()
 
2608
        return loader, module
 
2609
 
 
2610
    def test_module_no_load_tests_attribute_loads_classes(self):
 
2611
        loader, module = self._get_loader_and_module()
 
2612
        self.assertEqual(1, loader.loadTestsFromModule(module).countTestCases())
 
2613
 
 
2614
    def test_module_load_tests_attribute_gets_called(self):
 
2615
        loader, module = self._get_loader_and_module()
 
2616
        # 'self' is here because we're faking the module with a class. Regular
 
2617
        # load_tests do not need that :)
 
2618
        def load_tests(self, standard_tests, module, loader):
 
2619
            result = loader.suiteClass()
 
2620
            for test in tests.iter_suite_tests(standard_tests):
 
2621
                result.addTests([test, test])
 
2622
            return result
 
2623
        # add a load_tests() method which multiplies the tests from the module.
 
2624
        module.__class__.load_tests = load_tests
 
2625
        self.assertEqual(2, loader.loadTestsFromModule(module).countTestCases())
 
2626
 
 
2627
    def test_load_tests_from_module_name_smoke_test(self):
 
2628
        loader = TestUtil.TestLoader()
 
2629
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2630
        self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
 
2631
                          _test_ids(suite))
 
2632
 
 
2633
    def test_load_tests_from_module_name_with_bogus_module_name(self):
 
2634
        loader = TestUtil.TestLoader()
 
2635
        self.assertRaises(ImportError, loader.loadTestsFromModuleName, 'bogus')
 
2636
 
 
2637
 
 
2638
class TestTestIdList(tests.TestCase):
 
2639
 
 
2640
    def _create_id_list(self, test_list):
 
2641
        return tests.TestIdList(test_list)
 
2642
 
 
2643
    def _create_suite(self, test_id_list):
 
2644
 
 
2645
        class Stub(tests.TestCase):
 
2646
            def test_foo(self):
 
2647
                pass
 
2648
 
 
2649
        def _create_test_id(id):
 
2650
            return lambda: id
 
2651
 
 
2652
        suite = TestUtil.TestSuite()
 
2653
        for id in test_id_list:
 
2654
            t  = Stub('test_foo')
 
2655
            t.id = _create_test_id(id)
 
2656
            suite.addTest(t)
 
2657
        return suite
 
2658
 
 
2659
    def _test_ids(self, test_suite):
 
2660
        """Get the ids for the tests in a test suite."""
 
2661
        return [t.id() for t in tests.iter_suite_tests(test_suite)]
 
2662
 
 
2663
    def test_empty_list(self):
 
2664
        id_list = self._create_id_list([])
 
2665
        self.assertEquals({}, id_list.tests)
 
2666
        self.assertEquals({}, id_list.modules)
 
2667
 
 
2668
    def test_valid_list(self):
 
2669
        id_list = self._create_id_list(
 
2670
            ['mod1.cl1.meth1', 'mod1.cl1.meth2',
 
2671
             'mod1.func1', 'mod1.cl2.meth2',
 
2672
             'mod1.submod1',
 
2673
             'mod1.submod2.cl1.meth1', 'mod1.submod2.cl2.meth2',
 
2674
             ])
 
2675
        self.assertTrue(id_list.refers_to('mod1'))
 
2676
        self.assertTrue(id_list.refers_to('mod1.submod1'))
 
2677
        self.assertTrue(id_list.refers_to('mod1.submod2'))
 
2678
        self.assertTrue(id_list.includes('mod1.cl1.meth1'))
 
2679
        self.assertTrue(id_list.includes('mod1.submod1'))
 
2680
        self.assertTrue(id_list.includes('mod1.func1'))
 
2681
 
 
2682
    def test_bad_chars_in_params(self):
 
2683
        id_list = self._create_id_list(['mod1.cl1.meth1(xx.yy)'])
 
2684
        self.assertTrue(id_list.refers_to('mod1'))
 
2685
        self.assertTrue(id_list.includes('mod1.cl1.meth1(xx.yy)'))
 
2686
 
 
2687
    def test_module_used(self):
 
2688
        id_list = self._create_id_list(['mod.class.meth'])
 
2689
        self.assertTrue(id_list.refers_to('mod'))
 
2690
        self.assertTrue(id_list.refers_to('mod.class'))
 
2691
        self.assertTrue(id_list.refers_to('mod.class.meth'))
 
2692
 
 
2693
    def test_test_suite_matches_id_list_with_unknown(self):
 
2694
        loader = TestUtil.TestLoader()
 
2695
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2696
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',
 
2697
                     'bogus']
 
2698
        not_found, duplicates = tests.suite_matches_id_list(suite, test_list)
 
2699
        self.assertEquals(['bogus'], not_found)
 
2700
        self.assertEquals([], duplicates)
 
2701
 
 
2702
    def test_suite_matches_id_list_with_duplicates(self):
 
2703
        loader = TestUtil.TestLoader()
 
2704
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2705
        dupes = loader.suiteClass()
 
2706
        for test in tests.iter_suite_tests(suite):
 
2707
            dupes.addTest(test)
 
2708
            dupes.addTest(test) # Add it again
 
2709
 
 
2710
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',]
 
2711
        not_found, duplicates = tests.suite_matches_id_list(
 
2712
            dupes, test_list)
 
2713
        self.assertEquals([], not_found)
 
2714
        self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
 
2715
                          duplicates)
 
2716
 
 
2717
 
 
2718
class TestTestSuite(tests.TestCase):
 
2719
 
 
2720
    def test__test_suite_testmod_names(self):
 
2721
        # Test that a plausible list of test module names are returned
 
2722
        # by _test_suite_testmod_names.
 
2723
        test_list = tests._test_suite_testmod_names()
 
2724
        self.assertSubset([
 
2725
            'bzrlib.tests.blackbox',
 
2726
            'bzrlib.tests.per_transport',
 
2727
            'bzrlib.tests.test_selftest',
 
2728
            ],
 
2729
            test_list)
 
2730
 
 
2731
    def test__test_suite_modules_to_doctest(self):
 
2732
        # Test that a plausible list of modules to doctest is returned
 
2733
        # by _test_suite_modules_to_doctest.
 
2734
        test_list = tests._test_suite_modules_to_doctest()
 
2735
        self.assertSubset([
 
2736
            'bzrlib.timestamp',
 
2737
            ],
 
2738
            test_list)
 
2739
 
 
2740
    def test_test_suite(self):
 
2741
        # test_suite() loads the entire test suite to operate. To avoid this
 
2742
        # overhead, and yet still be confident that things are happening,
 
2743
        # we temporarily replace two functions used by test_suite with 
 
2744
        # test doubles that supply a few sample tests to load, and check they
 
2745
        # are loaded.
 
2746
        calls = []
 
2747
        def _test_suite_testmod_names():
 
2748
            calls.append("testmod_names")
 
2749
            return [
 
2750
                'bzrlib.tests.blackbox.test_branch',
 
2751
                'bzrlib.tests.per_transport',
 
2752
                'bzrlib.tests.test_selftest',
 
2753
                ]
 
2754
        original_testmod_names = tests._test_suite_testmod_names
 
2755
        def _test_suite_modules_to_doctest():
 
2756
            calls.append("modules_to_doctest")
 
2757
            return ['bzrlib.timestamp']
 
2758
        orig_modules_to_doctest = tests._test_suite_modules_to_doctest
 
2759
        def restore_names():
 
2760
            tests._test_suite_testmod_names = original_testmod_names
 
2761
            tests._test_suite_modules_to_doctest = orig_modules_to_doctest
 
2762
        self.addCleanup(restore_names)
 
2763
        tests._test_suite_testmod_names = _test_suite_testmod_names
 
2764
        tests._test_suite_modules_to_doctest = _test_suite_modules_to_doctest
 
2765
        expected_test_list = [
 
2766
            # testmod_names
 
2767
            'bzrlib.tests.blackbox.test_branch.TestBranch.test_branch',
 
2768
            ('bzrlib.tests.per_transport.TransportTests'
 
2769
             '.test_abspath(LocalURLServer)'),
 
2770
            'bzrlib.tests.test_selftest.TestTestSuite.test_test_suite',
 
2771
            # modules_to_doctest
 
2772
            'bzrlib.timestamp.format_highres_date',
 
2773
            # plugins can't be tested that way since selftest may be run with
 
2774
            # --no-plugins
 
2775
            ]
 
2776
        suite = tests.test_suite()
 
2777
        self.assertEqual(set(["testmod_names", "modules_to_doctest"]),
 
2778
            set(calls))
 
2779
        self.assertSubset(expected_test_list, _test_ids(suite))
 
2780
 
 
2781
    def test_test_suite_list_and_start(self):
 
2782
        # We cannot test this at the same time as the main load, because we want
 
2783
        # to know that starting_with == None works. So a second load is
 
2784
        # incurred - note that the starting_with parameter causes a partial load
 
2785
        # rather than a full load so this test should be pretty quick.
 
2786
        test_list = ['bzrlib.tests.test_selftest.TestTestSuite.test_test_suite']
 
2787
        suite = tests.test_suite(test_list,
 
2788
                                 ['bzrlib.tests.test_selftest.TestTestSuite'])
 
2789
        # test_test_suite_list_and_start is not included 
 
2790
        self.assertEquals(test_list, _test_ids(suite))
 
2791
 
 
2792
 
 
2793
class TestLoadTestIdList(tests.TestCaseInTempDir):
 
2794
 
 
2795
    def _create_test_list_file(self, file_name, content):
 
2796
        fl = open(file_name, 'wt')
 
2797
        fl.write(content)
 
2798
        fl.close()
 
2799
 
 
2800
    def test_load_unknown(self):
 
2801
        self.assertRaises(errors.NoSuchFile,
 
2802
                          tests.load_test_id_list, 'i_do_not_exist')
 
2803
 
 
2804
    def test_load_test_list(self):
 
2805
        test_list_fname = 'test.list'
 
2806
        self._create_test_list_file(test_list_fname,
 
2807
                                    'mod1.cl1.meth1\nmod2.cl2.meth2\n')
 
2808
        tlist = tests.load_test_id_list(test_list_fname)
 
2809
        self.assertEquals(2, len(tlist))
 
2810
        self.assertEquals('mod1.cl1.meth1', tlist[0])
 
2811
        self.assertEquals('mod2.cl2.meth2', tlist[1])
 
2812
 
 
2813
    def test_load_dirty_file(self):
 
2814
        test_list_fname = 'test.list'
 
2815
        self._create_test_list_file(test_list_fname,
 
2816
                                    '  mod1.cl1.meth1\n\nmod2.cl2.meth2  \n'
 
2817
                                    'bar baz\n')
 
2818
        tlist = tests.load_test_id_list(test_list_fname)
 
2819
        self.assertEquals(4, len(tlist))
 
2820
        self.assertEquals('mod1.cl1.meth1', tlist[0])
 
2821
        self.assertEquals('', tlist[1])
 
2822
        self.assertEquals('mod2.cl2.meth2', tlist[2])
 
2823
        self.assertEquals('bar baz', tlist[3])
 
2824
 
 
2825
 
 
2826
class TestFilteredByModuleTestLoader(tests.TestCase):
 
2827
 
 
2828
    def _create_loader(self, test_list):
 
2829
        id_filter = tests.TestIdList(test_list)
 
2830
        loader = TestUtil.FilteredByModuleTestLoader(id_filter.refers_to)
 
2831
        return loader
 
2832
 
 
2833
    def test_load_tests(self):
 
2834
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
 
2835
        loader = self._create_loader(test_list)
 
2836
 
 
2837
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2838
        self.assertEquals(test_list, _test_ids(suite))
 
2839
 
 
2840
    def test_exclude_tests(self):
 
2841
        test_list = ['bogus']
 
2842
        loader = self._create_loader(test_list)
 
2843
 
 
2844
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2845
        self.assertEquals([], _test_ids(suite))
 
2846
 
 
2847
 
 
2848
class TestFilteredByNameStartTestLoader(tests.TestCase):
 
2849
 
 
2850
    def _create_loader(self, name_start):
 
2851
        def needs_module(name):
 
2852
            return name.startswith(name_start) or name_start.startswith(name)
 
2853
        loader = TestUtil.FilteredByModuleTestLoader(needs_module)
 
2854
        return loader
 
2855
 
 
2856
    def test_load_tests(self):
 
2857
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
 
2858
        loader = self._create_loader('bzrlib.tests.test_samp')
 
2859
 
 
2860
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2861
        self.assertEquals(test_list, _test_ids(suite))
 
2862
 
 
2863
    def test_load_tests_inside_module(self):
 
2864
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
 
2865
        loader = self._create_loader('bzrlib.tests.test_sampler.Demo')
 
2866
 
 
2867
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2868
        self.assertEquals(test_list, _test_ids(suite))
 
2869
 
 
2870
    def test_exclude_tests(self):
 
2871
        test_list = ['bogus']
 
2872
        loader = self._create_loader('bogus')
 
2873
 
 
2874
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2875
        self.assertEquals([], _test_ids(suite))
 
2876
 
 
2877
 
 
2878
class TestTestPrefixRegistry(tests.TestCase):
 
2879
 
 
2880
    def _get_registry(self):
 
2881
        tp_registry = tests.TestPrefixAliasRegistry()
 
2882
        return tp_registry
 
2883
 
 
2884
    def test_register_new_prefix(self):
 
2885
        tpr = self._get_registry()
 
2886
        tpr.register('foo', 'fff.ooo.ooo')
 
2887
        self.assertEquals('fff.ooo.ooo', tpr.get('foo'))
 
2888
 
 
2889
    def test_register_existing_prefix(self):
 
2890
        tpr = self._get_registry()
 
2891
        tpr.register('bar', 'bbb.aaa.rrr')
 
2892
        tpr.register('bar', 'bBB.aAA.rRR')
 
2893
        self.assertEquals('bbb.aaa.rrr', tpr.get('bar'))
 
2894
        self.assertContainsRe(self._get_log(keep_log_file=True),
 
2895
                              r'.*bar.*bbb.aaa.rrr.*bBB.aAA.rRR')
 
2896
 
 
2897
    def test_get_unknown_prefix(self):
 
2898
        tpr = self._get_registry()
 
2899
        self.assertRaises(KeyError, tpr.get, 'I am not a prefix')
 
2900
 
 
2901
    def test_resolve_prefix(self):
 
2902
        tpr = self._get_registry()
 
2903
        tpr.register('bar', 'bb.aa.rr')
 
2904
        self.assertEquals('bb.aa.rr', tpr.resolve_alias('bar'))
 
2905
 
 
2906
    def test_resolve_unknown_alias(self):
 
2907
        tpr = self._get_registry()
 
2908
        self.assertRaises(errors.BzrCommandError,
 
2909
                          tpr.resolve_alias, 'I am not a prefix')
 
2910
 
 
2911
    def test_predefined_prefixes(self):
 
2912
        tpr = tests.test_prefix_alias_registry
 
2913
        self.assertEquals('bzrlib', tpr.resolve_alias('bzrlib'))
 
2914
        self.assertEquals('bzrlib.doc', tpr.resolve_alias('bd'))
 
2915
        self.assertEquals('bzrlib.utils', tpr.resolve_alias('bu'))
 
2916
        self.assertEquals('bzrlib.tests', tpr.resolve_alias('bt'))
 
2917
        self.assertEquals('bzrlib.tests.blackbox', tpr.resolve_alias('bb'))
 
2918
        self.assertEquals('bzrlib.plugins', tpr.resolve_alias('bp'))
 
2919
 
 
2920
 
 
2921
class TestRunSuite(tests.TestCase):
 
2922
 
 
2923
    def test_runner_class(self):
 
2924
        """run_suite accepts and uses a runner_class keyword argument."""
 
2925
        class Stub(tests.TestCase):
 
2926
            def test_foo(self):
 
2927
                pass
 
2928
        suite = Stub("test_foo")
 
2929
        calls = []
 
2930
        class MyRunner(tests.TextTestRunner):
 
2931
            def run(self, test):
 
2932
                calls.append(test)
 
2933
                return tests.ExtendedTestResult(self.stream, self.descriptions,
 
2934
                                                self.verbosity)
 
2935
        tests.run_suite(suite, runner_class=MyRunner, stream=StringIO())
 
2936
        self.assertLength(1, calls)
 
2937
 
 
2938
    def test_done(self):
 
2939
        """run_suite should call result.done()"""
 
2940
        self.calls = 0
 
2941
        def one_more_call(): self.calls += 1
 
2942
        def test_function():
 
2943
            pass
 
2944
        test = unittest.FunctionTestCase(test_function)
 
2945
        class InstrumentedTestResult(tests.ExtendedTestResult):
 
2946
            def done(self): one_more_call()
 
2947
        class MyRunner(tests.TextTestRunner):
 
2948
            def run(self, test):
 
2949
                return InstrumentedTestResult(self.stream, self.descriptions,
 
2950
                                              self.verbosity)
 
2951
        tests.run_suite(test, runner_class=MyRunner, stream=StringIO())
 
2952
        self.assertEquals(1, self.calls)