~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_selftest.py

  • Committer: Martin Pool
  • Date: 2010-09-03 09:14:12 UTC
  • mto: This revision was merged to the branch mainline in revision 5417.
  • Revision ID: mbp@sourcefrog.net-20100903091412-1a40klgfg8c6k3xj
Split out user interaction developer guide to a separate file

Show diffs side-by-side

added added

removed removed

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