/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to breezy/tests/test_selftest.py

  • Committer: Jelmer Vernooij
  • Date: 2017-06-08 00:00:28 UTC
  • mto: This revision was merged to the branch mainline in revision 6672.
  • Revision ID: jelmer@jelmer.uk-20170608000028-e3ggtt4wjbcjh91j
Drop pycurl support.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005-2013, 2016 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
import gc
 
20
import doctest
 
21
import os
 
22
import signal
 
23
import sys
 
24
import threading
 
25
import time
 
26
import unittest
 
27
import warnings
 
28
 
 
29
from testtools import (
 
30
    ExtendedToOriginalDecorator,
 
31
    MultiTestResult,
 
32
    )
 
33
from testtools.content import Content
 
34
from testtools.content_type import ContentType
 
35
from testtools.matchers import (
 
36
    DocTestMatches,
 
37
    Equals,
 
38
    )
 
39
import testtools.testresult.doubles
 
40
 
 
41
import breezy
 
42
from .. import (
 
43
    branchbuilder,
 
44
    bzrdir,
 
45
    controldir,
 
46
    errors,
 
47
    hooks,
 
48
    lockdir,
 
49
    memorytree,
 
50
    osutils,
 
51
    remote,
 
52
    repository,
 
53
    symbol_versioning,
 
54
    tests,
 
55
    transport,
 
56
    workingtree,
 
57
    workingtree_3,
 
58
    workingtree_4,
 
59
    )
 
60
from ..repofmt import (
 
61
    groupcompress_repo,
 
62
    )
 
63
from ..sixish import (
 
64
    StringIO,
 
65
    )
 
66
from ..symbol_versioning import (
 
67
    deprecated_function,
 
68
    deprecated_in,
 
69
    deprecated_method,
 
70
    )
 
71
from . import (
 
72
    features,
 
73
    test_lsprof,
 
74
    test_server,
 
75
    TestUtil,
 
76
    )
 
77
from ..trace import note, mutter
 
78
from ..transport import memory
 
79
 
 
80
 
 
81
def _test_ids(test_suite):
 
82
    """Get the ids for the tests in a test suite."""
 
83
    return [t.id() for t in tests.iter_suite_tests(test_suite)]
 
84
 
 
85
 
 
86
class MetaTestLog(tests.TestCase):
 
87
 
 
88
    def test_logging(self):
 
89
        """Test logs are captured when a test fails."""
 
90
        self.log('a test message')
 
91
        details = self.getDetails()
 
92
        log = details['log']
 
93
        self.assertThat(log.content_type, Equals(ContentType(
 
94
            "text", "plain", {"charset": "utf8"})))
 
95
        self.assertThat(u"".join(log.iter_text()), Equals(self.get_log()))
 
96
        self.assertThat(self.get_log(),
 
97
            DocTestMatches(u"...a test message\n", doctest.ELLIPSIS))
 
98
 
 
99
 
 
100
class TestTreeShape(tests.TestCaseInTempDir):
 
101
 
 
102
    def test_unicode_paths(self):
 
103
        self.requireFeature(features.UnicodeFilenameFeature)
 
104
 
 
105
        filename = u'hell\u00d8'
 
106
        self.build_tree_contents([(filename, 'contents of hello')])
 
107
        self.assertPathExists(filename)
 
108
 
 
109
 
 
110
class TestClassesAvailable(tests.TestCase):
 
111
    """As a convenience we expose Test* classes from breezy.tests"""
 
112
 
 
113
    def test_test_case(self):
 
114
        from . import TestCase
 
115
 
 
116
    def test_test_loader(self):
 
117
        from . import TestLoader
 
118
 
 
119
    def test_test_suite(self):
 
120
        from . import TestSuite
 
121
 
 
122
 
 
123
class TestTransportScenarios(tests.TestCase):
 
124
    """A group of tests that test the transport implementation adaption core.
 
125
 
 
126
    This is a meta test that the tests are applied to all available
 
127
    transports.
 
128
 
 
129
    This will be generalised in the future which is why it is in this
 
130
    test file even though it is specific to transport tests at the moment.
 
131
    """
 
132
 
 
133
    def test_get_transport_permutations(self):
 
134
        # this checks that get_test_permutations defined by the module is
 
135
        # called by the get_transport_test_permutations function.
 
136
        class MockModule(object):
 
137
            def get_test_permutations(self):
 
138
                return sample_permutation
 
139
        sample_permutation = [(1,2), (3,4)]
 
140
        from .per_transport import get_transport_test_permutations
 
141
        self.assertEqual(sample_permutation,
 
142
                         get_transport_test_permutations(MockModule()))
 
143
 
 
144
    def test_scenarios_include_all_modules(self):
 
145
        # this checks that the scenario generator returns as many permutations
 
146
        # as there are in all the registered transport modules - we assume if
 
147
        # this matches its probably doing the right thing especially in
 
148
        # combination with the tests for setting the right classes below.
 
149
        from .per_transport import transport_test_permutations
 
150
        from ..transport import _get_transport_modules
 
151
        modules = _get_transport_modules()
 
152
        permutation_count = 0
 
153
        for module in modules:
 
154
            try:
 
155
                permutation_count += len(reduce(getattr,
 
156
                    (module + ".get_test_permutations").split('.')[1:],
 
157
                     __import__(module))())
 
158
            except errors.DependencyNotPresent:
 
159
                pass
 
160
        scenarios = transport_test_permutations()
 
161
        self.assertEqual(permutation_count, len(scenarios))
 
162
 
 
163
    def test_scenarios_include_transport_class(self):
 
164
        # This test used to know about all the possible transports and the
 
165
        # order they were returned but that seems overly brittle (mbp
 
166
        # 20060307)
 
167
        from .per_transport import transport_test_permutations
 
168
        scenarios = transport_test_permutations()
 
169
        # there are at least that many builtin transports
 
170
        self.assertTrue(len(scenarios) > 6)
 
171
        one_scenario = scenarios[0]
 
172
        self.assertIsInstance(one_scenario[0], str)
 
173
        self.assertTrue(issubclass(one_scenario[1]["transport_class"],
 
174
                                   breezy.transport.Transport))
 
175
        self.assertTrue(issubclass(one_scenario[1]["transport_server"],
 
176
                                   breezy.transport.Server))
 
177
 
 
178
 
 
179
class TestBranchScenarios(tests.TestCase):
 
180
 
 
181
    def test_scenarios(self):
 
182
        # check that constructor parameters are passed through to the adapted
 
183
        # test.
 
184
        from .per_branch import make_scenarios
 
185
        server1 = "a"
 
186
        server2 = "b"
 
187
        formats = [("c", "C"), ("d", "D")]
 
188
        scenarios = make_scenarios(server1, server2, formats)
 
189
        self.assertEqual(2, len(scenarios))
 
190
        self.assertEqual([
 
191
            ('str',
 
192
             {'branch_format': 'c',
 
193
              'bzrdir_format': 'C',
 
194
              'transport_readonly_server': 'b',
 
195
              'transport_server': 'a'}),
 
196
            ('str',
 
197
             {'branch_format': 'd',
 
198
              'bzrdir_format': 'D',
 
199
              'transport_readonly_server': 'b',
 
200
              'transport_server': 'a'})],
 
201
            scenarios)
 
202
 
 
203
 
 
204
class TestBzrDirScenarios(tests.TestCase):
 
205
 
 
206
    def test_scenarios(self):
 
207
        # check that constructor parameters are passed through to the adapted
 
208
        # test.
 
209
        from .per_controldir import make_scenarios
 
210
        vfs_factory = "v"
 
211
        server1 = "a"
 
212
        server2 = "b"
 
213
        formats = ["c", "d"]
 
214
        scenarios = make_scenarios(vfs_factory, server1, server2, formats)
 
215
        self.assertEqual([
 
216
            ('str',
 
217
             {'bzrdir_format': 'c',
 
218
              'transport_readonly_server': 'b',
 
219
              'transport_server': 'a',
 
220
              'vfs_transport_factory': 'v'}),
 
221
            ('str',
 
222
             {'bzrdir_format': 'd',
 
223
              'transport_readonly_server': 'b',
 
224
              'transport_server': 'a',
 
225
              'vfs_transport_factory': 'v'})],
 
226
            scenarios)
 
227
 
 
228
 
 
229
class TestRepositoryScenarios(tests.TestCase):
 
230
 
 
231
    def test_formats_to_scenarios(self):
 
232
        from .per_repository import formats_to_scenarios
 
233
        formats = [("(c)", remote.RemoteRepositoryFormat()),
 
234
                   ("(d)", repository.format_registry.get(
 
235
                    'Bazaar repository format 2a (needs bzr 1.16 or later)\n'))]
 
236
        no_vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
 
237
            None)
 
238
        vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
 
239
            vfs_transport_factory="vfs")
 
240
        # no_vfs generate scenarios without vfs_transport_factory
 
241
        expected = [
 
242
            ('RemoteRepositoryFormat(c)',
 
243
             {'bzrdir_format': remote.RemoteBzrDirFormat(),
 
244
              'repository_format': remote.RemoteRepositoryFormat(),
 
245
              'transport_readonly_server': 'readonly',
 
246
              'transport_server': 'server'}),
 
247
            ('RepositoryFormat2a(d)',
 
248
             {'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
 
249
              'repository_format': groupcompress_repo.RepositoryFormat2a(),
 
250
              'transport_readonly_server': 'readonly',
 
251
              'transport_server': 'server'})]
 
252
        self.assertEqual(expected, no_vfs_scenarios)
 
253
        self.assertEqual([
 
254
            ('RemoteRepositoryFormat(c)',
 
255
             {'bzrdir_format': remote.RemoteBzrDirFormat(),
 
256
              'repository_format': remote.RemoteRepositoryFormat(),
 
257
              'transport_readonly_server': 'readonly',
 
258
              'transport_server': 'server',
 
259
              'vfs_transport_factory': 'vfs'}),
 
260
            ('RepositoryFormat2a(d)',
 
261
             {'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
 
262
              'repository_format': groupcompress_repo.RepositoryFormat2a(),
 
263
              'transport_readonly_server': 'readonly',
 
264
              'transport_server': 'server',
 
265
              'vfs_transport_factory': 'vfs'})],
 
266
            vfs_scenarios)
 
267
 
 
268
 
 
269
class TestTestScenarioApplication(tests.TestCase):
 
270
    """Tests for the test adaption facilities."""
 
271
 
 
272
    def test_apply_scenario(self):
 
273
        from breezy.tests import apply_scenario
 
274
        input_test = TestTestScenarioApplication("test_apply_scenario")
 
275
        # setup two adapted tests
 
276
        adapted_test1 = apply_scenario(input_test,
 
277
            ("new id",
 
278
            {"bzrdir_format":"bzr_format",
 
279
             "repository_format":"repo_fmt",
 
280
             "transport_server":"transport_server",
 
281
             "transport_readonly_server":"readonly-server"}))
 
282
        adapted_test2 = apply_scenario(input_test,
 
283
            ("new id 2", {"bzrdir_format":None}))
 
284
        # input_test should have been altered.
 
285
        self.assertRaises(AttributeError, getattr, input_test, "bzrdir_format")
 
286
        # the new tests are mutually incompatible, ensuring it has
 
287
        # made new ones, and unspecified elements in the scenario
 
288
        # should not have been altered.
 
289
        self.assertEqual("bzr_format", adapted_test1.bzrdir_format)
 
290
        self.assertEqual("repo_fmt", adapted_test1.repository_format)
 
291
        self.assertEqual("transport_server", adapted_test1.transport_server)
 
292
        self.assertEqual("readonly-server",
 
293
            adapted_test1.transport_readonly_server)
 
294
        self.assertEqual(
 
295
            "breezy.tests.test_selftest.TestTestScenarioApplication."
 
296
            "test_apply_scenario(new id)",
 
297
            adapted_test1.id())
 
298
        self.assertEqual(None, adapted_test2.bzrdir_format)
 
299
        self.assertEqual(
 
300
            "breezy.tests.test_selftest.TestTestScenarioApplication."
 
301
            "test_apply_scenario(new id 2)",
 
302
            adapted_test2.id())
 
303
 
 
304
 
 
305
class TestInterRepositoryScenarios(tests.TestCase):
 
306
 
 
307
    def test_scenarios(self):
 
308
        # check that constructor parameters are passed through to the adapted
 
309
        # test.
 
310
        from .per_interrepository import make_scenarios
 
311
        server1 = "a"
 
312
        server2 = "b"
 
313
        formats = [("C0", "C1", "C2", "C3"), ("D0", "D1", "D2", "D3")]
 
314
        scenarios = make_scenarios(server1, server2, formats)
 
315
        self.assertEqual([
 
316
            ('C0,str,str',
 
317
             {'repository_format': 'C1',
 
318
              'repository_format_to': 'C2',
 
319
              'transport_readonly_server': 'b',
 
320
              'transport_server': 'a',
 
321
              'extra_setup': 'C3'}),
 
322
            ('D0,str,str',
 
323
             {'repository_format': 'D1',
 
324
              'repository_format_to': 'D2',
 
325
              'transport_readonly_server': 'b',
 
326
              'transport_server': 'a',
 
327
              'extra_setup': 'D3'})],
 
328
            scenarios)
 
329
 
 
330
 
 
331
class TestWorkingTreeScenarios(tests.TestCase):
 
332
 
 
333
    def test_scenarios(self):
 
334
        # check that constructor parameters are passed through to the adapted
 
335
        # test.
 
336
        from .per_workingtree import make_scenarios
 
337
        server1 = "a"
 
338
        server2 = "b"
 
339
        formats = [workingtree_4.WorkingTreeFormat4(),
 
340
                   workingtree_3.WorkingTreeFormat3(),
 
341
                   workingtree_4.WorkingTreeFormat6()]
 
342
        scenarios = make_scenarios(server1, server2, formats,
 
343
            remote_server='c', remote_readonly_server='d',
 
344
            remote_backing_server='e')
 
345
        self.assertEqual([
 
346
            ('WorkingTreeFormat4',
 
347
             {'bzrdir_format': formats[0]._matchingbzrdir,
 
348
              'transport_readonly_server': 'b',
 
349
              'transport_server': 'a',
 
350
              'workingtree_format': formats[0]}),
 
351
            ('WorkingTreeFormat3',
 
352
             {'bzrdir_format': formats[1]._matchingbzrdir,
 
353
              'transport_readonly_server': 'b',
 
354
              'transport_server': 'a',
 
355
              'workingtree_format': formats[1]}),
 
356
            ('WorkingTreeFormat6',
 
357
             {'bzrdir_format': formats[2]._matchingbzrdir,
 
358
              'transport_readonly_server': 'b',
 
359
              'transport_server': 'a',
 
360
              'workingtree_format': formats[2]}),
 
361
            ('WorkingTreeFormat6,remote',
 
362
             {'bzrdir_format': formats[2]._matchingbzrdir,
 
363
              'repo_is_remote': True,
 
364
              'transport_readonly_server': 'd',
 
365
              'transport_server': 'c',
 
366
              'vfs_transport_factory': 'e',
 
367
              'workingtree_format': formats[2]}),
 
368
            ], scenarios)
 
369
 
 
370
 
 
371
class TestTreeScenarios(tests.TestCase):
 
372
 
 
373
    def test_scenarios(self):
 
374
        # the tree implementation scenario generator is meant to setup one
 
375
        # instance for each working tree format, one additional instance
 
376
        # that will use the default wt format, but create a revision tree for
 
377
        # the tests, and one more that uses the default wt format as a
 
378
        # lightweight checkout of a remote repository.  This means that the wt
 
379
        # ones should have the workingtree_to_test_tree attribute set to
 
380
        # 'return_parameter' and the revision one set to
 
381
        # revision_tree_from_workingtree.
 
382
 
 
383
        from .per_tree import (
 
384
            _dirstate_tree_from_workingtree,
 
385
            make_scenarios,
 
386
            preview_tree_pre,
 
387
            preview_tree_post,
 
388
            return_parameter,
 
389
            revision_tree_from_workingtree
 
390
            )
 
391
        server1 = "a"
 
392
        server2 = "b"
 
393
        smart_server = test_server.SmartTCPServer_for_testing
 
394
        smart_readonly_server = test_server.ReadonlySmartTCPServer_for_testing
 
395
        mem_server = memory.MemoryServer
 
396
        formats = [workingtree_4.WorkingTreeFormat4(),
 
397
                   workingtree_3.WorkingTreeFormat3(),]
 
398
        scenarios = make_scenarios(server1, server2, formats)
 
399
        self.assertEqual(8, len(scenarios))
 
400
        default_wt_format = workingtree.format_registry.get_default()
 
401
        wt4_format = workingtree_4.WorkingTreeFormat4()
 
402
        wt5_format = workingtree_4.WorkingTreeFormat5()
 
403
        wt6_format = workingtree_4.WorkingTreeFormat6()
 
404
        expected_scenarios = [
 
405
            ('WorkingTreeFormat4',
 
406
             {'bzrdir_format': formats[0]._matchingbzrdir,
 
407
              'transport_readonly_server': 'b',
 
408
              'transport_server': 'a',
 
409
              'workingtree_format': formats[0],
 
410
              '_workingtree_to_test_tree': return_parameter,
 
411
              }),
 
412
            ('WorkingTreeFormat3',
 
413
             {'bzrdir_format': formats[1]._matchingbzrdir,
 
414
              'transport_readonly_server': 'b',
 
415
              'transport_server': 'a',
 
416
              'workingtree_format': formats[1],
 
417
              '_workingtree_to_test_tree': return_parameter,
 
418
             }),
 
419
            ('WorkingTreeFormat6,remote',
 
420
             {'bzrdir_format': wt6_format._matchingbzrdir,
 
421
              'repo_is_remote': True,
 
422
              'transport_readonly_server': smart_readonly_server,
 
423
              'transport_server': smart_server,
 
424
              'vfs_transport_factory': mem_server,
 
425
              'workingtree_format': wt6_format,
 
426
              '_workingtree_to_test_tree': return_parameter,
 
427
             }),
 
428
            ('RevisionTree',
 
429
             {'_workingtree_to_test_tree': revision_tree_from_workingtree,
 
430
              'bzrdir_format': default_wt_format._matchingbzrdir,
 
431
              'transport_readonly_server': 'b',
 
432
              'transport_server': 'a',
 
433
              'workingtree_format': default_wt_format,
 
434
             }),
 
435
            ('DirStateRevisionTree,WT4',
 
436
             {'_workingtree_to_test_tree': _dirstate_tree_from_workingtree,
 
437
              'bzrdir_format': wt4_format._matchingbzrdir,
 
438
              'transport_readonly_server': 'b',
 
439
              'transport_server': 'a',
 
440
              'workingtree_format': wt4_format,
 
441
             }),
 
442
            ('DirStateRevisionTree,WT5',
 
443
             {'_workingtree_to_test_tree': _dirstate_tree_from_workingtree,
 
444
              'bzrdir_format': wt5_format._matchingbzrdir,
 
445
              'transport_readonly_server': 'b',
 
446
              'transport_server': 'a',
 
447
              'workingtree_format': wt5_format,
 
448
             }),
 
449
            ('PreviewTree',
 
450
             {'_workingtree_to_test_tree': preview_tree_pre,
 
451
              'bzrdir_format': default_wt_format._matchingbzrdir,
 
452
              'transport_readonly_server': 'b',
 
453
              'transport_server': 'a',
 
454
              'workingtree_format': default_wt_format}),
 
455
            ('PreviewTreePost',
 
456
             {'_workingtree_to_test_tree': preview_tree_post,
 
457
              'bzrdir_format': default_wt_format._matchingbzrdir,
 
458
              'transport_readonly_server': 'b',
 
459
              'transport_server': 'a',
 
460
              'workingtree_format': default_wt_format}),
 
461
             ]
 
462
        self.assertEqual(expected_scenarios, scenarios)
 
463
 
 
464
 
 
465
class TestInterTreeScenarios(tests.TestCase):
 
466
    """A group of tests that test the InterTreeTestAdapter."""
 
467
 
 
468
    def test_scenarios(self):
 
469
        # check that constructor parameters are passed through to the adapted
 
470
        # test.
 
471
        # for InterTree tests we want the machinery to bring up two trees in
 
472
        # each instance: the base one, and the one we are interacting with.
 
473
        # because each optimiser can be direction specific, we need to test
 
474
        # each optimiser in its chosen direction.
 
475
        # unlike the TestProviderAdapter we dont want to automatically add a
 
476
        # parameterized one for WorkingTree - the optimisers will tell us what
 
477
        # ones to add.
 
478
        from .per_tree import (
 
479
            return_parameter,
 
480
            )
 
481
        from .per_intertree import (
 
482
            make_scenarios,
 
483
            )
 
484
        from ..workingtree_3 import WorkingTreeFormat3
 
485
        from ..workingtree_4 import WorkingTreeFormat4
 
486
        input_test = TestInterTreeScenarios(
 
487
            "test_scenarios")
 
488
        server1 = "a"
 
489
        server2 = "b"
 
490
        format1 = WorkingTreeFormat4()
 
491
        format2 = WorkingTreeFormat3()
 
492
        formats = [("1", str, format1, format2, "converter1"),
 
493
            ("2", int, format2, format1, "converter2")]
 
494
        scenarios = make_scenarios(server1, server2, formats)
 
495
        self.assertEqual(2, len(scenarios))
 
496
        expected_scenarios = [
 
497
            ("1", {
 
498
                "bzrdir_format": format1._matchingbzrdir,
 
499
                "intertree_class": formats[0][1],
 
500
                "workingtree_format": formats[0][2],
 
501
                "workingtree_format_to": formats[0][3],
 
502
                "mutable_trees_to_test_trees": formats[0][4],
 
503
                "_workingtree_to_test_tree": return_parameter,
 
504
                "transport_server": server1,
 
505
                "transport_readonly_server": server2,
 
506
                }),
 
507
            ("2", {
 
508
                "bzrdir_format": format2._matchingbzrdir,
 
509
                "intertree_class": formats[1][1],
 
510
                "workingtree_format": formats[1][2],
 
511
                "workingtree_format_to": formats[1][3],
 
512
                "mutable_trees_to_test_trees": formats[1][4],
 
513
                "_workingtree_to_test_tree": return_parameter,
 
514
                "transport_server": server1,
 
515
                "transport_readonly_server": server2,
 
516
                }),
 
517
            ]
 
518
        self.assertEqual(scenarios, expected_scenarios)
 
519
 
 
520
 
 
521
class TestTestCaseInTempDir(tests.TestCaseInTempDir):
 
522
 
 
523
    def test_home_is_not_working(self):
 
524
        self.assertNotEqual(self.test_dir, self.test_home_dir)
 
525
        cwd = osutils.getcwd()
 
526
        self.assertIsSameRealPath(self.test_dir, cwd)
 
527
        self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
 
528
 
 
529
    def test_assertEqualStat_equal(self):
 
530
        from .test_dirstate import _FakeStat
 
531
        self.build_tree(["foo"])
 
532
        real = os.lstat("foo")
 
533
        fake = _FakeStat(real.st_size, real.st_mtime, real.st_ctime,
 
534
            real.st_dev, real.st_ino, real.st_mode)
 
535
        self.assertEqualStat(real, fake)
 
536
 
 
537
    def test_assertEqualStat_notequal(self):
 
538
        self.build_tree(["foo", "longname"])
 
539
        self.assertRaises(AssertionError, self.assertEqualStat,
 
540
            os.lstat("foo"), os.lstat("longname"))
 
541
 
 
542
    def test_assertPathExists(self):
 
543
        self.assertPathExists('.')
 
544
        self.build_tree(['foo/', 'foo/bar'])
 
545
        self.assertPathExists('foo/bar')
 
546
        self.assertPathDoesNotExist('foo/foo')
 
547
 
 
548
 
 
549
class TestTestCaseWithMemoryTransport(tests.TestCaseWithMemoryTransport):
 
550
 
 
551
    def test_home_is_non_existant_dir_under_root(self):
 
552
        """The test_home_dir for TestCaseWithMemoryTransport is missing.
 
553
 
 
554
        This is because TestCaseWithMemoryTransport is for tests that do not
 
555
        need any disk resources: they should be hooked into breezy in such a
 
556
        way that no global settings are being changed by the test (only a
 
557
        few tests should need to do that), and having a missing dir as home is
 
558
        an effective way to ensure that this is the case.
 
559
        """
 
560
        self.assertIsSameRealPath(
 
561
            self.TEST_ROOT + "/MemoryTransportMissingHomeDir",
 
562
            self.test_home_dir)
 
563
        self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
 
564
 
 
565
    def test_cwd_is_TEST_ROOT(self):
 
566
        self.assertIsSameRealPath(self.test_dir, self.TEST_ROOT)
 
567
        cwd = osutils.getcwd()
 
568
        self.assertIsSameRealPath(self.test_dir, cwd)
 
569
 
 
570
    def test_BRZ_HOME_and_HOME_are_bytestrings(self):
 
571
        """The $BRZ_HOME and $HOME environment variables should not be unicode.
 
572
 
 
573
        See https://bugs.launchpad.net/bzr/+bug/464174
 
574
        """
 
575
        self.assertIsInstance(os.environ['BRZ_HOME'], str)
 
576
        self.assertIsInstance(os.environ['HOME'], str)
 
577
 
 
578
    def test_make_branch_and_memory_tree(self):
 
579
        """In TestCaseWithMemoryTransport we should not make the branch on disk.
 
580
 
 
581
        This is hard to comprehensively robustly test, so we settle for making
 
582
        a branch and checking no directory was created at its relpath.
 
583
        """
 
584
        tree = self.make_branch_and_memory_tree('dir')
 
585
        # Guard against regression into MemoryTransport leaking
 
586
        # files to disk instead of keeping them in memory.
 
587
        self.assertFalse(osutils.lexists('dir'))
 
588
        self.assertIsInstance(tree, memorytree.MemoryTree)
 
589
 
 
590
    def test_make_branch_and_memory_tree_with_format(self):
 
591
        """make_branch_and_memory_tree should accept a format option."""
 
592
        format = bzrdir.BzrDirMetaFormat1()
 
593
        format.repository_format = repository.format_registry.get_default()
 
594
        tree = self.make_branch_and_memory_tree('dir', format=format)
 
595
        # Guard against regression into MemoryTransport leaking
 
596
        # files to disk instead of keeping them in memory.
 
597
        self.assertFalse(osutils.lexists('dir'))
 
598
        self.assertIsInstance(tree, memorytree.MemoryTree)
 
599
        self.assertEqual(format.repository_format.__class__,
 
600
            tree.branch.repository._format.__class__)
 
601
 
 
602
    def test_make_branch_builder(self):
 
603
        builder = self.make_branch_builder('dir')
 
604
        self.assertIsInstance(builder, branchbuilder.BranchBuilder)
 
605
        # Guard against regression into MemoryTransport leaking
 
606
        # files to disk instead of keeping them in memory.
 
607
        self.assertFalse(osutils.lexists('dir'))
 
608
 
 
609
    def test_make_branch_builder_with_format(self):
 
610
        # Use a repo layout that doesn't conform to a 'named' layout, to ensure
 
611
        # that the format objects are used.
 
612
        format = bzrdir.BzrDirMetaFormat1()
 
613
        repo_format = repository.format_registry.get_default()
 
614
        format.repository_format = repo_format
 
615
        builder = self.make_branch_builder('dir', format=format)
 
616
        the_branch = builder.get_branch()
 
617
        # Guard against regression into MemoryTransport leaking
 
618
        # files to disk instead of keeping them in memory.
 
619
        self.assertFalse(osutils.lexists('dir'))
 
620
        self.assertEqual(format.repository_format.__class__,
 
621
                         the_branch.repository._format.__class__)
 
622
        self.assertEqual(repo_format.get_format_string(),
 
623
                         self.get_transport().get_bytes(
 
624
                            'dir/.bzr/repository/format'))
 
625
 
 
626
    def test_make_branch_builder_with_format_name(self):
 
627
        builder = self.make_branch_builder('dir', format='knit')
 
628
        the_branch = builder.get_branch()
 
629
        # Guard against regression into MemoryTransport leaking
 
630
        # files to disk instead of keeping them in memory.
 
631
        self.assertFalse(osutils.lexists('dir'))
 
632
        dir_format = controldir.format_registry.make_bzrdir('knit')
 
633
        self.assertEqual(dir_format.repository_format.__class__,
 
634
                         the_branch.repository._format.__class__)
 
635
        self.assertEqual('Bazaar-NG Knit Repository Format 1',
 
636
                         self.get_transport().get_bytes(
 
637
                            'dir/.bzr/repository/format'))
 
638
 
 
639
    def test_dangling_locks_cause_failures(self):
 
640
        class TestDanglingLock(tests.TestCaseWithMemoryTransport):
 
641
            def test_function(self):
 
642
                t = self.get_transport_from_path('.')
 
643
                l = lockdir.LockDir(t, 'lock')
 
644
                l.create()
 
645
                l.attempt_lock()
 
646
        test = TestDanglingLock('test_function')
 
647
        result = test.run()
 
648
        total_failures = result.errors + result.failures
 
649
        if self._lock_check_thorough:
 
650
            self.assertEqual(1, len(total_failures))
 
651
        else:
 
652
            # When _lock_check_thorough is disabled, then we don't trigger a
 
653
            # failure
 
654
            self.assertEqual(0, len(total_failures))
 
655
 
 
656
 
 
657
class TestTestCaseWithTransport(tests.TestCaseWithTransport):
 
658
    """Tests for the convenience functions TestCaseWithTransport introduces."""
 
659
 
 
660
    def test_get_readonly_url_none(self):
 
661
        from ..transport.readonly import ReadonlyTransportDecorator
 
662
        self.vfs_transport_factory = memory.MemoryServer
 
663
        self.transport_readonly_server = None
 
664
        # calling get_readonly_transport() constructs a decorator on the url
 
665
        # for the server
 
666
        url = self.get_readonly_url()
 
667
        url2 = self.get_readonly_url('foo/bar')
 
668
        t = transport.get_transport_from_url(url)
 
669
        t2 = transport.get_transport_from_url(url2)
 
670
        self.assertIsInstance(t, ReadonlyTransportDecorator)
 
671
        self.assertIsInstance(t2, ReadonlyTransportDecorator)
 
672
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
 
673
 
 
674
    def test_get_readonly_url_http(self):
 
675
        from .http_server import HttpServer
 
676
        from ..transport.http import HttpTransportBase
 
677
        self.transport_server = test_server.LocalURLServer
 
678
        self.transport_readonly_server = HttpServer
 
679
        # calling get_readonly_transport() gives us a HTTP server instance.
 
680
        url = self.get_readonly_url()
 
681
        url2 = self.get_readonly_url('foo/bar')
 
682
        # the transport returned may be any HttpTransportBase subclass
 
683
        t = transport.get_transport_from_url(url)
 
684
        t2 = transport.get_transport_from_url(url2)
 
685
        self.assertIsInstance(t, HttpTransportBase)
 
686
        self.assertIsInstance(t2, HttpTransportBase)
 
687
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
 
688
 
 
689
    def test_is_directory(self):
 
690
        """Test assertIsDirectory assertion"""
 
691
        t = self.get_transport()
 
692
        self.build_tree(['a_dir/', 'a_file'], transport=t)
 
693
        self.assertIsDirectory('a_dir', t)
 
694
        self.assertRaises(AssertionError, self.assertIsDirectory, 'a_file', t)
 
695
        self.assertRaises(AssertionError, self.assertIsDirectory, 'not_here', t)
 
696
 
 
697
    def test_make_branch_builder(self):
 
698
        builder = self.make_branch_builder('dir')
 
699
        rev_id = builder.build_commit()
 
700
        self.assertPathExists('dir')
 
701
        a_dir = controldir.ControlDir.open('dir')
 
702
        self.assertRaises(errors.NoWorkingTree, a_dir.open_workingtree)
 
703
        a_branch = a_dir.open_branch()
 
704
        builder_branch = builder.get_branch()
 
705
        self.assertEqual(a_branch.base, builder_branch.base)
 
706
        self.assertEqual((1, rev_id), builder_branch.last_revision_info())
 
707
        self.assertEqual((1, rev_id), a_branch.last_revision_info())
 
708
 
 
709
 
 
710
class TestTestCaseTransports(tests.TestCaseWithTransport):
 
711
 
 
712
    def setUp(self):
 
713
        super(TestTestCaseTransports, self).setUp()
 
714
        self.vfs_transport_factory = memory.MemoryServer
 
715
 
 
716
    def test_make_bzrdir_preserves_transport(self):
 
717
        t = self.get_transport()
 
718
        result_bzrdir = self.make_bzrdir('subdir')
 
719
        self.assertIsInstance(result_bzrdir.transport,
 
720
                              memory.MemoryTransport)
 
721
        # should not be on disk, should only be in memory
 
722
        self.assertPathDoesNotExist('subdir')
 
723
 
 
724
 
 
725
class TestChrootedTest(tests.ChrootedTestCase):
 
726
 
 
727
    def test_root_is_root(self):
 
728
        t = transport.get_transport_from_url(self.get_readonly_url())
 
729
        url = t.base
 
730
        self.assertEqual(url, t.clone('..').base)
 
731
 
 
732
 
 
733
class TestProfileResult(tests.TestCase):
 
734
 
 
735
    def test_profiles_tests(self):
 
736
        self.requireFeature(features.lsprof_feature)
 
737
        terminal = testtools.testresult.doubles.ExtendedTestResult()
 
738
        result = tests.ProfileResult(terminal)
 
739
        class Sample(tests.TestCase):
 
740
            def a(self):
 
741
                self.sample_function()
 
742
            def sample_function(self):
 
743
                pass
 
744
        test = Sample("a")
 
745
        test.run(result)
 
746
        case = terminal._events[0][1]
 
747
        self.assertLength(1, case._benchcalls)
 
748
        # We must be able to unpack it as the test reporting code wants
 
749
        (_, _, _), stats = case._benchcalls[0]
 
750
        self.assertTrue(callable(stats.pprint))
 
751
 
 
752
 
 
753
class TestTestResult(tests.TestCase):
 
754
 
 
755
    def check_timing(self, test_case, expected_re):
 
756
        result = tests.TextTestResult(StringIO(), descriptions=0, verbosity=1)
 
757
        capture = testtools.testresult.doubles.ExtendedTestResult()
 
758
        test_case.run(MultiTestResult(result, capture))
 
759
        run_case = capture._events[0][1]
 
760
        timed_string = result._testTimeString(run_case)
 
761
        self.assertContainsRe(timed_string, expected_re)
 
762
 
 
763
    def test_test_reporting(self):
 
764
        class ShortDelayTestCase(tests.TestCase):
 
765
            def test_short_delay(self):
 
766
                time.sleep(0.003)
 
767
            def test_short_benchmark(self):
 
768
                self.time(time.sleep, 0.003)
 
769
        self.check_timing(ShortDelayTestCase('test_short_delay'),
 
770
                          r"^ +[0-9]+ms$")
 
771
        # if a benchmark time is given, we now show just that time followed by
 
772
        # a star
 
773
        self.check_timing(ShortDelayTestCase('test_short_benchmark'),
 
774
                          r"^ +[0-9]+ms\*$")
 
775
 
 
776
    def test_unittest_reporting_unittest_class(self):
 
777
        # getting the time from a non-breezy test works ok
 
778
        class ShortDelayTestCase(unittest.TestCase):
 
779
            def test_short_delay(self):
 
780
                time.sleep(0.003)
 
781
        self.check_timing(ShortDelayTestCase('test_short_delay'),
 
782
                          r"^ +[0-9]+ms$")
 
783
 
 
784
    def _time_hello_world_encoding(self):
 
785
        """Profile two sleep calls
 
786
 
 
787
        This is used to exercise the test framework.
 
788
        """
 
789
        self.time(unicode, 'hello', errors='replace')
 
790
        self.time(unicode, 'world', errors='replace')
 
791
 
 
792
    def test_lsprofiling(self):
 
793
        """Verbose test result prints lsprof statistics from test cases."""
 
794
        self.requireFeature(features.lsprof_feature)
 
795
        result_stream = StringIO()
 
796
        result = breezy.tests.VerboseTestResult(
 
797
            result_stream,
 
798
            descriptions=0,
 
799
            verbosity=2,
 
800
            )
 
801
        # we want profile a call of some sort and check it is output by
 
802
        # addSuccess. We dont care about addError or addFailure as they
 
803
        # are not that interesting for performance tuning.
 
804
        # make a new test instance that when run will generate a profile
 
805
        example_test_case = TestTestResult("_time_hello_world_encoding")
 
806
        example_test_case._gather_lsprof_in_benchmarks = True
 
807
        # execute the test, which should succeed and record profiles
 
808
        example_test_case.run(result)
 
809
        # lsprofile_something()
 
810
        # if this worked we want
 
811
        # LSProf output for <built in function unicode> (['hello'], {'errors': 'replace'})
 
812
        #    CallCount    Recursive    Total(ms)   Inline(ms) module:lineno(function)
 
813
        # (the lsprof header)
 
814
        # ... an arbitrary number of lines
 
815
        # and the function call which is time.sleep.
 
816
        #           1        0            ???         ???       ???(sleep)
 
817
        # and then repeated but with 'world', rather than 'hello'.
 
818
        # this should appear in the output stream of our test result.
 
819
        output = result_stream.getvalue()
 
820
        self.assertContainsRe(output,
 
821
            r"LSProf output for <type 'unicode'>\(\('hello',\), {'errors': 'replace'}\)")
 
822
        self.assertContainsRe(output,
 
823
            r" *CallCount *Recursive *Total\(ms\) *Inline\(ms\) *module:lineno\(function\)\n")
 
824
        self.assertContainsRe(output,
 
825
            r"( +1 +0 +0\.\d+ +0\.\d+ +<method 'disable' of '_lsprof\.Profiler' objects>\n)?")
 
826
        self.assertContainsRe(output,
 
827
            r"LSProf output for <type 'unicode'>\(\('world',\), {'errors': 'replace'}\)\n")
 
828
 
 
829
    def test_uses_time_from_testtools(self):
 
830
        """Test case timings in verbose results should use testtools times"""
 
831
        import datetime
 
832
        class TimeAddedVerboseTestResult(tests.VerboseTestResult):
 
833
            def startTest(self, test):
 
834
                self.time(datetime.datetime.utcfromtimestamp(1.145))
 
835
                super(TimeAddedVerboseTestResult, self).startTest(test)
 
836
            def addSuccess(self, test):
 
837
                self.time(datetime.datetime.utcfromtimestamp(51.147))
 
838
                super(TimeAddedVerboseTestResult, self).addSuccess(test)
 
839
            def report_tests_starting(self): pass
 
840
        sio = StringIO()
 
841
        self.get_passing_test().run(TimeAddedVerboseTestResult(sio, 0, 2))
 
842
        self.assertEndsWith(sio.getvalue(), "OK    50002ms\n")
 
843
 
 
844
    def test_known_failure(self):
 
845
        """Using knownFailure should trigger several result actions."""
 
846
        class InstrumentedTestResult(tests.ExtendedTestResult):
 
847
            def stopTestRun(self): pass
 
848
            def report_tests_starting(self): pass
 
849
            def report_known_failure(self, test, err=None, details=None):
 
850
                self._call = test, 'known failure'
 
851
        result = InstrumentedTestResult(None, None, None, None)
 
852
        class Test(tests.TestCase):
 
853
            def test_function(self):
 
854
                self.knownFailure('failed!')
 
855
        test = Test("test_function")
 
856
        test.run(result)
 
857
        # it should invoke 'report_known_failure'.
 
858
        self.assertEqual(2, len(result._call))
 
859
        self.assertEqual(test.id(), result._call[0].id())
 
860
        self.assertEqual('known failure', result._call[1])
 
861
        # we dont introspec the traceback, if the rest is ok, it would be
 
862
        # exceptional for it not to be.
 
863
        # it should update the known_failure_count on the object.
 
864
        self.assertEqual(1, result.known_failure_count)
 
865
        # the result should be successful.
 
866
        self.assertTrue(result.wasSuccessful())
 
867
 
 
868
    def test_verbose_report_known_failure(self):
 
869
        # verbose test output formatting
 
870
        result_stream = StringIO()
 
871
        result = breezy.tests.VerboseTestResult(
 
872
            result_stream,
 
873
            descriptions=0,
 
874
            verbosity=2,
 
875
            )
 
876
        _get_test("test_xfail").run(result)
 
877
        self.assertContainsRe(result_stream.getvalue(),
 
878
            "\n\\S+\\.test_xfail\\s+XFAIL\\s+\\d+ms\n"
 
879
            "\\s*(?:Text attachment: )?reason"
 
880
            "(?:\n-+\n|: {{{)"
 
881
            "this_fails"
 
882
            "(?:\n-+\n|}}}\n)")
 
883
 
 
884
    def get_passing_test(self):
 
885
        """Return a test object that can't be run usefully."""
 
886
        def passing_test():
 
887
            pass
 
888
        return unittest.FunctionTestCase(passing_test)
 
889
 
 
890
    def test_add_not_supported(self):
 
891
        """Test the behaviour of invoking addNotSupported."""
 
892
        class InstrumentedTestResult(tests.ExtendedTestResult):
 
893
            def stopTestRun(self): pass
 
894
            def report_tests_starting(self): pass
 
895
            def report_unsupported(self, test, feature):
 
896
                self._call = test, feature
 
897
        result = InstrumentedTestResult(None, None, None, None)
 
898
        test = SampleTestCase('_test_pass')
 
899
        feature = features.Feature()
 
900
        result.startTest(test)
 
901
        result.addNotSupported(test, feature)
 
902
        # it should invoke 'report_unsupported'.
 
903
        self.assertEqual(2, len(result._call))
 
904
        self.assertEqual(test, result._call[0])
 
905
        self.assertEqual(feature, result._call[1])
 
906
        # the result should be successful.
 
907
        self.assertTrue(result.wasSuccessful())
 
908
        # it should record the test against a count of tests not run due to
 
909
        # this feature.
 
910
        self.assertEqual(1, result.unsupported['Feature'])
 
911
        # and invoking it again should increment that counter
 
912
        result.addNotSupported(test, feature)
 
913
        self.assertEqual(2, result.unsupported['Feature'])
 
914
 
 
915
    def test_verbose_report_unsupported(self):
 
916
        # verbose test output formatting
 
917
        result_stream = StringIO()
 
918
        result = breezy.tests.VerboseTestResult(
 
919
            result_stream,
 
920
            descriptions=0,
 
921
            verbosity=2,
 
922
            )
 
923
        test = self.get_passing_test()
 
924
        feature = features.Feature()
 
925
        result.startTest(test)
 
926
        prefix = len(result_stream.getvalue())
 
927
        result.report_unsupported(test, feature)
 
928
        output = result_stream.getvalue()[prefix:]
 
929
        lines = output.splitlines()
 
930
        # We don't check for the final '0ms' since it may fail on slow hosts
 
931
        self.assertStartsWith(lines[0], 'NODEP')
 
932
        self.assertEqual(lines[1],
 
933
                         "    The feature 'Feature' is not available.")
 
934
 
 
935
    def test_unavailable_exception(self):
 
936
        """An UnavailableFeature being raised should invoke addNotSupported."""
 
937
        class InstrumentedTestResult(tests.ExtendedTestResult):
 
938
            def stopTestRun(self): pass
 
939
            def report_tests_starting(self): pass
 
940
            def addNotSupported(self, test, feature):
 
941
                self._call = test, feature
 
942
        result = InstrumentedTestResult(None, None, None, None)
 
943
        feature = features.Feature()
 
944
        class Test(tests.TestCase):
 
945
            def test_function(self):
 
946
                raise tests.UnavailableFeature(feature)
 
947
        test = Test("test_function")
 
948
        test.run(result)
 
949
        # it should invoke 'addNotSupported'.
 
950
        self.assertEqual(2, len(result._call))
 
951
        self.assertEqual(test.id(), result._call[0].id())
 
952
        self.assertEqual(feature, result._call[1])
 
953
        # and not count as an error
 
954
        self.assertEqual(0, result.error_count)
 
955
 
 
956
    def test_strict_with_unsupported_feature(self):
 
957
        result = tests.TextTestResult(StringIO(), descriptions=0, verbosity=1)
 
958
        test = self.get_passing_test()
 
959
        feature = "Unsupported Feature"
 
960
        result.addNotSupported(test, feature)
 
961
        self.assertFalse(result.wasStrictlySuccessful())
 
962
        self.assertEqual(None, result._extractBenchmarkTime(test))
 
963
 
 
964
    def test_strict_with_known_failure(self):
 
965
        result = tests.TextTestResult(StringIO(), descriptions=0, verbosity=1)
 
966
        test = _get_test("test_xfail")
 
967
        test.run(result)
 
968
        self.assertFalse(result.wasStrictlySuccessful())
 
969
        self.assertEqual(None, result._extractBenchmarkTime(test))
 
970
 
 
971
    def test_strict_with_success(self):
 
972
        result = tests.TextTestResult(StringIO(), descriptions=0, verbosity=1)
 
973
        test = self.get_passing_test()
 
974
        result.addSuccess(test)
 
975
        self.assertTrue(result.wasStrictlySuccessful())
 
976
        self.assertEqual(None, result._extractBenchmarkTime(test))
 
977
 
 
978
    def test_startTests(self):
 
979
        """Starting the first test should trigger startTests."""
 
980
        class InstrumentedTestResult(tests.ExtendedTestResult):
 
981
            calls = 0
 
982
            def startTests(self): self.calls += 1
 
983
        result = InstrumentedTestResult(None, None, None, None)
 
984
        def test_function():
 
985
            pass
 
986
        test = unittest.FunctionTestCase(test_function)
 
987
        test.run(result)
 
988
        self.assertEqual(1, result.calls)
 
989
 
 
990
    def test_startTests_only_once(self):
 
991
        """With multiple tests startTests should still only be called once"""
 
992
        class InstrumentedTestResult(tests.ExtendedTestResult):
 
993
            calls = 0
 
994
            def startTests(self): self.calls += 1
 
995
        result = InstrumentedTestResult(None, None, None, None)
 
996
        suite = unittest.TestSuite([
 
997
            unittest.FunctionTestCase(lambda: None),
 
998
            unittest.FunctionTestCase(lambda: None)])
 
999
        suite.run(result)
 
1000
        self.assertEqual(1, result.calls)
 
1001
        self.assertEqual(2, result.count)
 
1002
 
 
1003
 
 
1004
class TestRunner(tests.TestCase):
 
1005
 
 
1006
    def dummy_test(self):
 
1007
        pass
 
1008
 
 
1009
    def run_test_runner(self, testrunner, test):
 
1010
        """Run suite in testrunner, saving global state and restoring it.
 
1011
 
 
1012
        This current saves and restores:
 
1013
        TestCaseInTempDir.TEST_ROOT
 
1014
 
 
1015
        There should be no tests in this file that use
 
1016
        breezy.tests.TextTestRunner without using this convenience method,
 
1017
        because of our use of global state.
 
1018
        """
 
1019
        old_root = tests.TestCaseInTempDir.TEST_ROOT
 
1020
        try:
 
1021
            tests.TestCaseInTempDir.TEST_ROOT = None
 
1022
            return testrunner.run(test)
 
1023
        finally:
 
1024
            tests.TestCaseInTempDir.TEST_ROOT = old_root
 
1025
 
 
1026
    def test_known_failure_failed_run(self):
 
1027
        # run a test that generates a known failure which should be printed in
 
1028
        # the final output when real failures occur.
 
1029
        class Test(tests.TestCase):
 
1030
            def known_failure_test(self):
 
1031
                self.expectFailure('failed', self.assertTrue, False)
 
1032
        test = unittest.TestSuite()
 
1033
        test.addTest(Test("known_failure_test"))
 
1034
        def failing_test():
 
1035
            raise AssertionError('foo')
 
1036
        test.addTest(unittest.FunctionTestCase(failing_test))
 
1037
        stream = StringIO()
 
1038
        runner = tests.TextTestRunner(stream=stream)
 
1039
        result = self.run_test_runner(runner, test)
 
1040
        lines = stream.getvalue().splitlines()
 
1041
        self.assertContainsRe(stream.getvalue(),
 
1042
            '(?sm)^brz selftest.*$'
 
1043
            '.*'
 
1044
            '^======================================================================\n'
 
1045
            '^FAIL: failing_test\n'
 
1046
            '^----------------------------------------------------------------------\n'
 
1047
            'Traceback \\(most recent call last\\):\n'
 
1048
            '  .*' # File .*, line .*, in failing_test' - but maybe not from .pyc
 
1049
            '    raise AssertionError\\(\'foo\'\\)\n'
 
1050
            '.*'
 
1051
            '^----------------------------------------------------------------------\n'
 
1052
            '.*'
 
1053
            'FAILED \\(failures=1, known_failure_count=1\\)'
 
1054
            )
 
1055
 
 
1056
    def test_known_failure_ok_run(self):
 
1057
        # run a test that generates a known failure which should be printed in
 
1058
        # the final output.
 
1059
        class Test(tests.TestCase):
 
1060
            def known_failure_test(self):
 
1061
                self.knownFailure("Never works...")
 
1062
        test = Test("known_failure_test")
 
1063
        stream = StringIO()
 
1064
        runner = tests.TextTestRunner(stream=stream)
 
1065
        result = self.run_test_runner(runner, test)
 
1066
        self.assertContainsRe(stream.getvalue(),
 
1067
            '\n'
 
1068
            '-*\n'
 
1069
            'Ran 1 test in .*\n'
 
1070
            '\n'
 
1071
            'OK \\(known_failures=1\\)\n')
 
1072
 
 
1073
    def test_unexpected_success_bad(self):
 
1074
        class Test(tests.TestCase):
 
1075
            def test_truth(self):
 
1076
                self.expectFailure("No absolute truth", self.assertTrue, True)
 
1077
        runner = tests.TextTestRunner(stream=StringIO())
 
1078
        result = self.run_test_runner(runner, Test("test_truth"))
 
1079
        self.assertContainsRe(runner.stream.getvalue(),
 
1080
            "=+\n"
 
1081
            "FAIL: \\S+\.test_truth\n"
 
1082
            "-+\n"
 
1083
            "(?:.*\n)*"
 
1084
            "\\s*(?:Text attachment: )?reason"
 
1085
            "(?:\n-+\n|: {{{)"
 
1086
            "No absolute truth"
 
1087
            "(?:\n-+\n|}}}\n)"
 
1088
            "(?:.*\n)*"
 
1089
            "-+\n"
 
1090
            "Ran 1 test in .*\n"
 
1091
            "\n"
 
1092
            "FAILED \\(failures=1\\)\n\\Z")
 
1093
 
 
1094
    def test_result_decorator(self):
 
1095
        # decorate results
 
1096
        calls = []
 
1097
        class LoggingDecorator(ExtendedToOriginalDecorator):
 
1098
            def startTest(self, test):
 
1099
                ExtendedToOriginalDecorator.startTest(self, test)
 
1100
                calls.append('start')
 
1101
        test = unittest.FunctionTestCase(lambda:None)
 
1102
        stream = StringIO()
 
1103
        runner = tests.TextTestRunner(stream=stream,
 
1104
            result_decorators=[LoggingDecorator])
 
1105
        result = self.run_test_runner(runner, test)
 
1106
        self.assertLength(1, calls)
 
1107
 
 
1108
    def test_skipped_test(self):
 
1109
        # run a test that is skipped, and check the suite as a whole still
 
1110
        # succeeds.
 
1111
        # skipping_test must be hidden in here so it's not run as a real test
 
1112
        class SkippingTest(tests.TestCase):
 
1113
            def skipping_test(self):
 
1114
                raise tests.TestSkipped('test intentionally skipped')
 
1115
        runner = tests.TextTestRunner(stream=StringIO())
 
1116
        test = SkippingTest("skipping_test")
 
1117
        result = self.run_test_runner(runner, test)
 
1118
        self.assertTrue(result.wasSuccessful())
 
1119
 
 
1120
    def test_skipped_from_setup(self):
 
1121
        calls = []
 
1122
        class SkippedSetupTest(tests.TestCase):
 
1123
 
 
1124
            def setUp(self):
 
1125
                calls.append('setUp')
 
1126
                self.addCleanup(self.cleanup)
 
1127
                raise tests.TestSkipped('skipped setup')
 
1128
 
 
1129
            def test_skip(self):
 
1130
                self.fail('test reached')
 
1131
 
 
1132
            def cleanup(self):
 
1133
                calls.append('cleanup')
 
1134
 
 
1135
        runner = tests.TextTestRunner(stream=StringIO())
 
1136
        test = SkippedSetupTest('test_skip')
 
1137
        result = self.run_test_runner(runner, test)
 
1138
        self.assertTrue(result.wasSuccessful())
 
1139
        # Check if cleanup was called the right number of times.
 
1140
        self.assertEqual(['setUp', 'cleanup'], calls)
 
1141
 
 
1142
    def test_skipped_from_test(self):
 
1143
        calls = []
 
1144
        class SkippedTest(tests.TestCase):
 
1145
 
 
1146
            def setUp(self):
 
1147
                super(SkippedTest, self).setUp()
 
1148
                calls.append('setUp')
 
1149
                self.addCleanup(self.cleanup)
 
1150
 
 
1151
            def test_skip(self):
 
1152
                raise tests.TestSkipped('skipped test')
 
1153
 
 
1154
            def cleanup(self):
 
1155
                calls.append('cleanup')
 
1156
 
 
1157
        runner = tests.TextTestRunner(stream=StringIO())
 
1158
        test = SkippedTest('test_skip')
 
1159
        result = self.run_test_runner(runner, test)
 
1160
        self.assertTrue(result.wasSuccessful())
 
1161
        # Check if cleanup was called the right number of times.
 
1162
        self.assertEqual(['setUp', 'cleanup'], calls)
 
1163
 
 
1164
    def test_not_applicable(self):
 
1165
        # run a test that is skipped because it's not applicable
 
1166
        class Test(tests.TestCase):
 
1167
            def not_applicable_test(self):
 
1168
                raise tests.TestNotApplicable('this test never runs')
 
1169
        out = StringIO()
 
1170
        runner = tests.TextTestRunner(stream=out, verbosity=2)
 
1171
        test = Test("not_applicable_test")
 
1172
        result = self.run_test_runner(runner, test)
 
1173
        self.log(out.getvalue())
 
1174
        self.assertTrue(result.wasSuccessful())
 
1175
        self.assertTrue(result.wasStrictlySuccessful())
 
1176
        self.assertContainsRe(out.getvalue(),
 
1177
                r'(?m)not_applicable_test  * N/A')
 
1178
        self.assertContainsRe(out.getvalue(),
 
1179
                r'(?m)^    this test never runs')
 
1180
 
 
1181
    def test_unsupported_features_listed(self):
 
1182
        """When unsupported features are encountered they are detailed."""
 
1183
        class Feature1(features.Feature):
 
1184
            def _probe(self): return False
 
1185
        class Feature2(features.Feature):
 
1186
            def _probe(self): return False
 
1187
        # create sample tests
 
1188
        test1 = SampleTestCase('_test_pass')
 
1189
        test1._test_needs_features = [Feature1()]
 
1190
        test2 = SampleTestCase('_test_pass')
 
1191
        test2._test_needs_features = [Feature2()]
 
1192
        test = unittest.TestSuite()
 
1193
        test.addTest(test1)
 
1194
        test.addTest(test2)
 
1195
        stream = StringIO()
 
1196
        runner = tests.TextTestRunner(stream=stream)
 
1197
        result = self.run_test_runner(runner, test)
 
1198
        lines = stream.getvalue().splitlines()
 
1199
        self.assertEqual([
 
1200
            'OK',
 
1201
            "Missing feature 'Feature1' skipped 1 tests.",
 
1202
            "Missing feature 'Feature2' skipped 1 tests.",
 
1203
            ],
 
1204
            lines[-3:])
 
1205
 
 
1206
    def test_verbose_test_count(self):
 
1207
        """A verbose test run reports the right test count at the start"""
 
1208
        suite = TestUtil.TestSuite([
 
1209
            unittest.FunctionTestCase(lambda:None),
 
1210
            unittest.FunctionTestCase(lambda:None)])
 
1211
        self.assertEqual(suite.countTestCases(), 2)
 
1212
        stream = StringIO()
 
1213
        runner = tests.TextTestRunner(stream=stream, verbosity=2)
 
1214
        # Need to use the CountingDecorator as that's what sets num_tests
 
1215
        result = self.run_test_runner(runner, tests.CountingDecorator(suite))
 
1216
        self.assertStartsWith(stream.getvalue(), "running 2 tests")
 
1217
 
 
1218
    def test_startTestRun(self):
 
1219
        """run should call result.startTestRun()"""
 
1220
        calls = []
 
1221
        class LoggingDecorator(ExtendedToOriginalDecorator):
 
1222
            def startTestRun(self):
 
1223
                ExtendedToOriginalDecorator.startTestRun(self)
 
1224
                calls.append('startTestRun')
 
1225
        test = unittest.FunctionTestCase(lambda:None)
 
1226
        stream = StringIO()
 
1227
        runner = tests.TextTestRunner(stream=stream,
 
1228
            result_decorators=[LoggingDecorator])
 
1229
        result = self.run_test_runner(runner, test)
 
1230
        self.assertLength(1, calls)
 
1231
 
 
1232
    def test_stopTestRun(self):
 
1233
        """run should call result.stopTestRun()"""
 
1234
        calls = []
 
1235
        class LoggingDecorator(ExtendedToOriginalDecorator):
 
1236
            def stopTestRun(self):
 
1237
                ExtendedToOriginalDecorator.stopTestRun(self)
 
1238
                calls.append('stopTestRun')
 
1239
        test = unittest.FunctionTestCase(lambda:None)
 
1240
        stream = StringIO()
 
1241
        runner = tests.TextTestRunner(stream=stream,
 
1242
            result_decorators=[LoggingDecorator])
 
1243
        result = self.run_test_runner(runner, test)
 
1244
        self.assertLength(1, calls)
 
1245
 
 
1246
    def test_unicode_test_output_on_ascii_stream(self):
 
1247
        """Showing results should always succeed even on an ascii console"""
 
1248
        class FailureWithUnicode(tests.TestCase):
 
1249
            def test_log_unicode(self):
 
1250
                self.log(u"\u2606")
 
1251
                self.fail("Now print that log!")
 
1252
        out = StringIO()
 
1253
        self.overrideAttr(osutils, "get_terminal_encoding",
 
1254
            lambda trace=False: "ascii")
 
1255
        result = self.run_test_runner(tests.TextTestRunner(stream=out),
 
1256
            FailureWithUnicode("test_log_unicode"))
 
1257
        self.assertContainsRe(out.getvalue(),
 
1258
            "(?:Text attachment: )?log"
 
1259
            "(?:\n-+\n|: {{{)"
 
1260
            "\d+\.\d+  \\\\u2606"
 
1261
            "(?:\n-+\n|}}}\n)")
 
1262
 
 
1263
 
 
1264
class SampleTestCase(tests.TestCase):
 
1265
 
 
1266
    def _test_pass(self):
 
1267
        pass
 
1268
 
 
1269
class _TestException(Exception):
 
1270
    pass
 
1271
 
 
1272
 
 
1273
class TestTestCase(tests.TestCase):
 
1274
    """Tests that test the core breezy TestCase."""
 
1275
 
 
1276
    def test_assertLength_matches_empty(self):
 
1277
        a_list = []
 
1278
        self.assertLength(0, a_list)
 
1279
 
 
1280
    def test_assertLength_matches_nonempty(self):
 
1281
        a_list = [1, 2, 3]
 
1282
        self.assertLength(3, a_list)
 
1283
 
 
1284
    def test_assertLength_fails_different(self):
 
1285
        a_list = []
 
1286
        self.assertRaises(AssertionError, self.assertLength, 1, a_list)
 
1287
 
 
1288
    def test_assertLength_shows_sequence_in_failure(self):
 
1289
        a_list = [1, 2, 3]
 
1290
        exception = self.assertRaises(AssertionError, self.assertLength, 2,
 
1291
            a_list)
 
1292
        self.assertEqual('Incorrect length: wanted 2, got 3 for [1, 2, 3]',
 
1293
            exception.args[0])
 
1294
 
 
1295
    def test_base_setUp_not_called_causes_failure(self):
 
1296
        class TestCaseWithBrokenSetUp(tests.TestCase):
 
1297
            def setUp(self):
 
1298
                pass # does not call TestCase.setUp
 
1299
            def test_foo(self):
 
1300
                pass
 
1301
        test = TestCaseWithBrokenSetUp('test_foo')
 
1302
        result = unittest.TestResult()
 
1303
        test.run(result)
 
1304
        self.assertFalse(result.wasSuccessful())
 
1305
        self.assertEqual(1, result.testsRun)
 
1306
 
 
1307
    def test_base_tearDown_not_called_causes_failure(self):
 
1308
        class TestCaseWithBrokenTearDown(tests.TestCase):
 
1309
            def tearDown(self):
 
1310
                pass # does not call TestCase.tearDown
 
1311
            def test_foo(self):
 
1312
                pass
 
1313
        test = TestCaseWithBrokenTearDown('test_foo')
 
1314
        result = unittest.TestResult()
 
1315
        test.run(result)
 
1316
        self.assertFalse(result.wasSuccessful())
 
1317
        self.assertEqual(1, result.testsRun)
 
1318
 
 
1319
    def test_debug_flags_sanitised(self):
 
1320
        """The breezy debug flags should be sanitised by setUp."""
 
1321
        if 'allow_debug' in tests.selftest_debug_flags:
 
1322
            raise tests.TestNotApplicable(
 
1323
                '-Eallow_debug option prevents debug flag sanitisation')
 
1324
        # we could set something and run a test that will check
 
1325
        # it gets santised, but this is probably sufficient for now:
 
1326
        # if someone runs the test with -Dsomething it will error.
 
1327
        flags = set()
 
1328
        if self._lock_check_thorough:
 
1329
            flags.add('strict_locks')
 
1330
        self.assertEqual(flags, breezy.debug.debug_flags)
 
1331
 
 
1332
    def change_selftest_debug_flags(self, new_flags):
 
1333
        self.overrideAttr(tests, 'selftest_debug_flags', set(new_flags))
 
1334
 
 
1335
    def test_allow_debug_flag(self):
 
1336
        """The -Eallow_debug flag prevents breezy.debug.debug_flags from being
 
1337
        sanitised (i.e. cleared) before running a test.
 
1338
        """
 
1339
        self.change_selftest_debug_flags({'allow_debug'})
 
1340
        breezy.debug.debug_flags = {'a-flag'}
 
1341
        class TestThatRecordsFlags(tests.TestCase):
 
1342
            def test_foo(nested_self):
 
1343
                self.flags = set(breezy.debug.debug_flags)
 
1344
        test = TestThatRecordsFlags('test_foo')
 
1345
        test.run(self.make_test_result())
 
1346
        flags = {'a-flag'}
 
1347
        if 'disable_lock_checks' not in tests.selftest_debug_flags:
 
1348
            flags.add('strict_locks')
 
1349
        self.assertEqual(flags, self.flags)
 
1350
 
 
1351
    def test_disable_lock_checks(self):
 
1352
        """The -Edisable_lock_checks flag disables thorough checks."""
 
1353
        class TestThatRecordsFlags(tests.TestCase):
 
1354
            def test_foo(nested_self):
 
1355
                self.flags = set(breezy.debug.debug_flags)
 
1356
                self.test_lock_check_thorough = nested_self._lock_check_thorough
 
1357
        self.change_selftest_debug_flags(set())
 
1358
        test = TestThatRecordsFlags('test_foo')
 
1359
        test.run(self.make_test_result())
 
1360
        # By default we do strict lock checking and thorough lock/unlock
 
1361
        # tracking.
 
1362
        self.assertTrue(self.test_lock_check_thorough)
 
1363
        self.assertEqual({'strict_locks'}, self.flags)
 
1364
        # Now set the disable_lock_checks flag, and show that this changed.
 
1365
        self.change_selftest_debug_flags({'disable_lock_checks'})
 
1366
        test = TestThatRecordsFlags('test_foo')
 
1367
        test.run(self.make_test_result())
 
1368
        self.assertFalse(self.test_lock_check_thorough)
 
1369
        self.assertEqual(set(), self.flags)
 
1370
 
 
1371
    def test_this_fails_strict_lock_check(self):
 
1372
        class TestThatRecordsFlags(tests.TestCase):
 
1373
            def test_foo(nested_self):
 
1374
                self.flags1 = set(breezy.debug.debug_flags)
 
1375
                self.thisFailsStrictLockCheck()
 
1376
                self.flags2 = set(breezy.debug.debug_flags)
 
1377
        # Make sure lock checking is active
 
1378
        self.change_selftest_debug_flags(set())
 
1379
        test = TestThatRecordsFlags('test_foo')
 
1380
        test.run(self.make_test_result())
 
1381
        self.assertEqual({'strict_locks'}, self.flags1)
 
1382
        self.assertEqual(set(), self.flags2)
 
1383
 
 
1384
    def test_debug_flags_restored(self):
 
1385
        """The breezy debug flags should be restored to their original state
 
1386
        after the test was run, even if allow_debug is set.
 
1387
        """
 
1388
        self.change_selftest_debug_flags({'allow_debug'})
 
1389
        # Now run a test that modifies debug.debug_flags.
 
1390
        breezy.debug.debug_flags = {'original-state'}
 
1391
        class TestThatModifiesFlags(tests.TestCase):
 
1392
            def test_foo(self):
 
1393
                breezy.debug.debug_flags = {'modified'}
 
1394
        test = TestThatModifiesFlags('test_foo')
 
1395
        test.run(self.make_test_result())
 
1396
        self.assertEqual({'original-state'}, breezy.debug.debug_flags)
 
1397
 
 
1398
    def make_test_result(self):
 
1399
        """Get a test result that writes to a StringIO."""
 
1400
        return tests.TextTestResult(StringIO(), descriptions=0, verbosity=1)
 
1401
 
 
1402
    def inner_test(self):
 
1403
        # the inner child test
 
1404
        note("inner_test")
 
1405
 
 
1406
    def outer_child(self):
 
1407
        # the outer child test
 
1408
        note("outer_start")
 
1409
        self.inner_test = TestTestCase("inner_child")
 
1410
        result = self.make_test_result()
 
1411
        self.inner_test.run(result)
 
1412
        note("outer finish")
 
1413
        self.addCleanup(osutils.delete_any, self._log_file_name)
 
1414
 
 
1415
    def test_trace_nesting(self):
 
1416
        # this tests that each test case nests its trace facility correctly.
 
1417
        # we do this by running a test case manually. That test case (A)
 
1418
        # should setup a new log, log content to it, setup a child case (B),
 
1419
        # which should log independently, then case (A) should log a trailer
 
1420
        # and return.
 
1421
        # we do two nested children so that we can verify the state of the
 
1422
        # logs after the outer child finishes is correct, which a bad clean
 
1423
        # up routine in tearDown might trigger a fault in our test with only
 
1424
        # one child, we should instead see the bad result inside our test with
 
1425
        # the two children.
 
1426
        # the outer child test
 
1427
        original_trace = breezy.trace._trace_file
 
1428
        outer_test = TestTestCase("outer_child")
 
1429
        result = self.make_test_result()
 
1430
        outer_test.run(result)
 
1431
        self.assertEqual(original_trace, breezy.trace._trace_file)
 
1432
 
 
1433
    def method_that_times_a_bit_twice(self):
 
1434
        # call self.time twice to ensure it aggregates
 
1435
        self.time(time.sleep, 0.007)
 
1436
        self.time(time.sleep, 0.007)
 
1437
 
 
1438
    def test_time_creates_benchmark_in_result(self):
 
1439
        """Test that the TestCase.time() method accumulates a benchmark time."""
 
1440
        sample_test = TestTestCase("method_that_times_a_bit_twice")
 
1441
        output_stream = StringIO()
 
1442
        result = breezy.tests.VerboseTestResult(
 
1443
            output_stream,
 
1444
            descriptions=0,
 
1445
            verbosity=2)
 
1446
        sample_test.run(result)
 
1447
        self.assertContainsRe(
 
1448
            output_stream.getvalue(),
 
1449
            r"\d+ms\*\n$")
 
1450
 
 
1451
    def test_hooks_sanitised(self):
 
1452
        """The breezy hooks should be sanitised by setUp."""
 
1453
        # Note this test won't fail with hooks that the core library doesn't
 
1454
        # use - but it trigger with a plugin that adds hooks, so its still a
 
1455
        # useful warning in that case.
 
1456
        self.assertEqual(breezy.branch.BranchHooks(), breezy.branch.Branch.hooks)
 
1457
        self.assertEqual(
 
1458
            breezy.smart.server.SmartServerHooks(),
 
1459
            breezy.smart.server.SmartTCPServer.hooks)
 
1460
        self.assertEqual(
 
1461
            breezy.commands.CommandHooks(), breezy.commands.Command.hooks)
 
1462
 
 
1463
    def test__gather_lsprof_in_benchmarks(self):
 
1464
        """When _gather_lsprof_in_benchmarks is on, accumulate profile data.
 
1465
 
 
1466
        Each self.time() call is individually and separately profiled.
 
1467
        """
 
1468
        self.requireFeature(features.lsprof_feature)
 
1469
        # overrides the class member with an instance member so no cleanup
 
1470
        # needed.
 
1471
        self._gather_lsprof_in_benchmarks = True
 
1472
        self.time(time.sleep, 0.000)
 
1473
        self.time(time.sleep, 0.003)
 
1474
        self.assertEqual(2, len(self._benchcalls))
 
1475
        self.assertEqual((time.sleep, (0.000,), {}), self._benchcalls[0][0])
 
1476
        self.assertEqual((time.sleep, (0.003,), {}), self._benchcalls[1][0])
 
1477
        self.assertIsInstance(self._benchcalls[0][1], breezy.lsprof.Stats)
 
1478
        self.assertIsInstance(self._benchcalls[1][1], breezy.lsprof.Stats)
 
1479
        del self._benchcalls[:]
 
1480
 
 
1481
    def test_knownFailure(self):
 
1482
        """Self.knownFailure() should raise a KnownFailure exception."""
 
1483
        self.assertRaises(tests.KnownFailure, self.knownFailure, "A Failure")
 
1484
 
 
1485
    def test_open_bzrdir_safe_roots(self):
 
1486
        # even a memory transport should fail to open when its url isn't 
 
1487
        # permitted.
 
1488
        # Manually set one up (TestCase doesn't and shouldn't provide magic
 
1489
        # machinery)
 
1490
        transport_server = memory.MemoryServer()
 
1491
        transport_server.start_server()
 
1492
        self.addCleanup(transport_server.stop_server)
 
1493
        t = transport.get_transport_from_url(transport_server.get_url())
 
1494
        controldir.ControlDir.create(t.base)
 
1495
        self.assertRaises(errors.BzrError,
 
1496
            controldir.ControlDir.open_from_transport, t)
 
1497
        # But if we declare this as safe, we can open the bzrdir.
 
1498
        self.permit_url(t.base)
 
1499
        self._bzr_selftest_roots.append(t.base)
 
1500
        controldir.ControlDir.open_from_transport(t)
 
1501
 
 
1502
    def test_requireFeature_available(self):
 
1503
        """self.requireFeature(available) is a no-op."""
 
1504
        class Available(features.Feature):
 
1505
            def _probe(self):return True
 
1506
        feature = Available()
 
1507
        self.requireFeature(feature)
 
1508
 
 
1509
    def test_requireFeature_unavailable(self):
 
1510
        """self.requireFeature(unavailable) raises UnavailableFeature."""
 
1511
        class Unavailable(features.Feature):
 
1512
            def _probe(self):return False
 
1513
        feature = Unavailable()
 
1514
        self.assertRaises(tests.UnavailableFeature,
 
1515
                          self.requireFeature, feature)
 
1516
 
 
1517
    def test_run_no_parameters(self):
 
1518
        test = SampleTestCase('_test_pass')
 
1519
        test.run()
 
1520
 
 
1521
    def test_run_enabled_unittest_result(self):
 
1522
        """Test we revert to regular behaviour when the test is enabled."""
 
1523
        test = SampleTestCase('_test_pass')
 
1524
        class EnabledFeature(object):
 
1525
            def available(self):
 
1526
                return True
 
1527
        test._test_needs_features = [EnabledFeature()]
 
1528
        result = unittest.TestResult()
 
1529
        test.run(result)
 
1530
        self.assertEqual(1, result.testsRun)
 
1531
        self.assertEqual([], result.errors)
 
1532
        self.assertEqual([], result.failures)
 
1533
 
 
1534
    def test_run_disabled_unittest_result(self):
 
1535
        """Test our compatability for disabled tests with unittest results."""
 
1536
        test = SampleTestCase('_test_pass')
 
1537
        class DisabledFeature(object):
 
1538
            def available(self):
 
1539
                return False
 
1540
        test._test_needs_features = [DisabledFeature()]
 
1541
        result = unittest.TestResult()
 
1542
        test.run(result)
 
1543
        self.assertEqual(1, result.testsRun)
 
1544
        self.assertEqual([], result.errors)
 
1545
        self.assertEqual([], result.failures)
 
1546
 
 
1547
    def test_run_disabled_supporting_result(self):
 
1548
        """Test disabled tests behaviour with support aware results."""
 
1549
        test = SampleTestCase('_test_pass')
 
1550
        class DisabledFeature(object):
 
1551
            def __eq__(self, other):
 
1552
                return isinstance(other, DisabledFeature)
 
1553
            def available(self):
 
1554
                return False
 
1555
        the_feature = DisabledFeature()
 
1556
        test._test_needs_features = [the_feature]
 
1557
        class InstrumentedTestResult(unittest.TestResult):
 
1558
            def __init__(self):
 
1559
                unittest.TestResult.__init__(self)
 
1560
                self.calls = []
 
1561
            def startTest(self, test):
 
1562
                self.calls.append(('startTest', test))
 
1563
            def stopTest(self, test):
 
1564
                self.calls.append(('stopTest', test))
 
1565
            def addNotSupported(self, test, feature):
 
1566
                self.calls.append(('addNotSupported', test, feature))
 
1567
        result = InstrumentedTestResult()
 
1568
        test.run(result)
 
1569
        case = result.calls[0][1]
 
1570
        self.assertEqual([
 
1571
            ('startTest', case),
 
1572
            ('addNotSupported', case, the_feature),
 
1573
            ('stopTest', case),
 
1574
            ],
 
1575
            result.calls)
 
1576
 
 
1577
    def test_start_server_registers_url(self):
 
1578
        transport_server = memory.MemoryServer()
 
1579
        # A little strict, but unlikely to be changed soon.
 
1580
        self.assertEqual([], self._bzr_selftest_roots)
 
1581
        self.start_server(transport_server)
 
1582
        self.assertSubset([transport_server.get_url()],
 
1583
            self._bzr_selftest_roots)
 
1584
 
 
1585
    def test_assert_list_raises_on_generator(self):
 
1586
        def generator_which_will_raise():
 
1587
            # This will not raise until after the first yield
 
1588
            yield 1
 
1589
            raise _TestException()
 
1590
 
 
1591
        e = self.assertListRaises(_TestException, generator_which_will_raise)
 
1592
        self.assertIsInstance(e, _TestException)
 
1593
 
 
1594
        e = self.assertListRaises(Exception, generator_which_will_raise)
 
1595
        self.assertIsInstance(e, _TestException)
 
1596
 
 
1597
    def test_assert_list_raises_on_plain(self):
 
1598
        def plain_exception():
 
1599
            raise _TestException()
 
1600
            return []
 
1601
 
 
1602
        e = self.assertListRaises(_TestException, plain_exception)
 
1603
        self.assertIsInstance(e, _TestException)
 
1604
 
 
1605
        e = self.assertListRaises(Exception, plain_exception)
 
1606
        self.assertIsInstance(e, _TestException)
 
1607
 
 
1608
    def test_assert_list_raises_assert_wrong_exception(self):
 
1609
        class _NotTestException(Exception):
 
1610
            pass
 
1611
 
 
1612
        def wrong_exception():
 
1613
            raise _NotTestException()
 
1614
 
 
1615
        def wrong_exception_generator():
 
1616
            yield 1
 
1617
            yield 2
 
1618
            raise _NotTestException()
 
1619
 
 
1620
        # Wrong exceptions are not intercepted
 
1621
        self.assertRaises(_NotTestException,
 
1622
            self.assertListRaises, _TestException, wrong_exception)
 
1623
        self.assertRaises(_NotTestException,
 
1624
            self.assertListRaises, _TestException, wrong_exception_generator)
 
1625
 
 
1626
    def test_assert_list_raises_no_exception(self):
 
1627
        def success():
 
1628
            return []
 
1629
 
 
1630
        def success_generator():
 
1631
            yield 1
 
1632
            yield 2
 
1633
 
 
1634
        self.assertRaises(AssertionError,
 
1635
            self.assertListRaises, _TestException, success)
 
1636
 
 
1637
        self.assertRaises(AssertionError,
 
1638
            self.assertListRaises, _TestException, success_generator)
 
1639
 
 
1640
    def _run_successful_test(self, test):
 
1641
        result = testtools.TestResult()
 
1642
        test.run(result)
 
1643
        self.assertTrue(result.wasSuccessful())
 
1644
        return result
 
1645
 
 
1646
    def test_overrideAttr_without_value(self):
 
1647
        self.test_attr = 'original' # Define a test attribute
 
1648
        obj = self # Make 'obj' visible to the embedded test
 
1649
        class Test(tests.TestCase):
 
1650
 
 
1651
            def setUp(self):
 
1652
                super(Test, self).setUp()
 
1653
                self.orig = self.overrideAttr(obj, 'test_attr')
 
1654
 
 
1655
            def test_value(self):
 
1656
                self.assertEqual('original', self.orig)
 
1657
                self.assertEqual('original', obj.test_attr)
 
1658
                obj.test_attr = 'modified'
 
1659
                self.assertEqual('modified', obj.test_attr)
 
1660
 
 
1661
        self._run_successful_test(Test('test_value'))
 
1662
        self.assertEqual('original', obj.test_attr)
 
1663
 
 
1664
    def test_overrideAttr_with_value(self):
 
1665
        self.test_attr = 'original' # Define a test attribute
 
1666
        obj = self # Make 'obj' visible to the embedded test
 
1667
        class Test(tests.TestCase):
 
1668
 
 
1669
            def setUp(self):
 
1670
                super(Test, self).setUp()
 
1671
                self.orig = self.overrideAttr(obj, 'test_attr', new='modified')
 
1672
 
 
1673
            def test_value(self):
 
1674
                self.assertEqual('original', self.orig)
 
1675
                self.assertEqual('modified', obj.test_attr)
 
1676
 
 
1677
        self._run_successful_test(Test('test_value'))
 
1678
        self.assertEqual('original', obj.test_attr)
 
1679
 
 
1680
    def test_overrideAttr_with_no_existing_value_and_value(self):
 
1681
        # Do not define the test_attribute
 
1682
        obj = self # Make 'obj' visible to the embedded test
 
1683
        class Test(tests.TestCase):
 
1684
 
 
1685
            def setUp(self):
 
1686
                tests.TestCase.setUp(self)
 
1687
                self.orig = self.overrideAttr(obj, 'test_attr', new='modified')
 
1688
 
 
1689
            def test_value(self):
 
1690
                self.assertEqual(tests._unitialized_attr, self.orig)
 
1691
                self.assertEqual('modified', obj.test_attr)
 
1692
 
 
1693
        self._run_successful_test(Test('test_value'))
 
1694
        self.assertRaises(AttributeError, getattr, obj, 'test_attr')
 
1695
 
 
1696
    def test_overrideAttr_with_no_existing_value_and_no_value(self):
 
1697
        # Do not define the test_attribute
 
1698
        obj = self # Make 'obj' visible to the embedded test
 
1699
        class Test(tests.TestCase):
 
1700
 
 
1701
            def setUp(self):
 
1702
                tests.TestCase.setUp(self)
 
1703
                self.orig = self.overrideAttr(obj, 'test_attr')
 
1704
 
 
1705
            def test_value(self):
 
1706
                self.assertEqual(tests._unitialized_attr, self.orig)
 
1707
                self.assertRaises(AttributeError, getattr, obj, 'test_attr')
 
1708
 
 
1709
        self._run_successful_test(Test('test_value'))
 
1710
        self.assertRaises(AttributeError, getattr, obj, 'test_attr')
 
1711
 
 
1712
    def test_recordCalls(self):
 
1713
        from breezy.tests import test_selftest
 
1714
        calls = self.recordCalls(
 
1715
            test_selftest, '_add_numbers')
 
1716
        self.assertEqual(test_selftest._add_numbers(2, 10),
 
1717
            12)
 
1718
        self.assertEqual(calls, [((2, 10), {})])
 
1719
 
 
1720
 
 
1721
def _add_numbers(a, b):
 
1722
    return a + b
 
1723
 
 
1724
 
 
1725
class _MissingFeature(features.Feature):
 
1726
    def _probe(self):
 
1727
        return False
 
1728
missing_feature = _MissingFeature()
 
1729
 
 
1730
 
 
1731
def _get_test(name):
 
1732
    """Get an instance of a specific example test.
 
1733
 
 
1734
    We protect this in a function so that they don't auto-run in the test
 
1735
    suite.
 
1736
    """
 
1737
 
 
1738
    class ExampleTests(tests.TestCase):
 
1739
 
 
1740
        def test_fail(self):
 
1741
            mutter('this was a failing test')
 
1742
            self.fail('this test will fail')
 
1743
 
 
1744
        def test_error(self):
 
1745
            mutter('this test errored')
 
1746
            raise RuntimeError('gotcha')
 
1747
 
 
1748
        def test_missing_feature(self):
 
1749
            mutter('missing the feature')
 
1750
            self.requireFeature(missing_feature)
 
1751
 
 
1752
        def test_skip(self):
 
1753
            mutter('this test will be skipped')
 
1754
            raise tests.TestSkipped('reason')
 
1755
 
 
1756
        def test_success(self):
 
1757
            mutter('this test succeeds')
 
1758
 
 
1759
        def test_xfail(self):
 
1760
            mutter('test with expected failure')
 
1761
            self.knownFailure('this_fails')
 
1762
 
 
1763
        def test_unexpected_success(self):
 
1764
            mutter('test with unexpected success')
 
1765
            self.expectFailure('should_fail', lambda: None)
 
1766
 
 
1767
    return ExampleTests(name)
 
1768
 
 
1769
 
 
1770
def _get_skip_reasons(result):
 
1771
    # GZ 2017-06-06: Newer testtools doesn't have this, uses detail instead
 
1772
    return result.skip_reasons
 
1773
 
 
1774
 
 
1775
class TestTestCaseLogDetails(tests.TestCase):
 
1776
 
 
1777
    def _run_test(self, test_name):
 
1778
        test = _get_test(test_name)
 
1779
        result = testtools.TestResult()
 
1780
        test.run(result)
 
1781
        return result
 
1782
 
 
1783
    def test_fail_has_log(self):
 
1784
        result = self._run_test('test_fail')
 
1785
        self.assertEqual(1, len(result.failures))
 
1786
        result_content = result.failures[0][1]
 
1787
        self.assertContainsRe(result_content,
 
1788
            '(?m)^(?:Text attachment: )?log(?:$|: )')
 
1789
        self.assertContainsRe(result_content, 'this was a failing test')
 
1790
 
 
1791
    def test_error_has_log(self):
 
1792
        result = self._run_test('test_error')
 
1793
        self.assertEqual(1, len(result.errors))
 
1794
        result_content = result.errors[0][1]
 
1795
        self.assertContainsRe(result_content,
 
1796
            '(?m)^(?:Text attachment: )?log(?:$|: )')
 
1797
        self.assertContainsRe(result_content, 'this test errored')
 
1798
 
 
1799
    def test_skip_has_no_log(self):
 
1800
        result = self._run_test('test_skip')
 
1801
        reasons = _get_skip_reasons(result)
 
1802
        self.assertEqual({'reason'}, set(reasons))
 
1803
        skips = reasons['reason']
 
1804
        self.assertEqual(1, len(skips))
 
1805
        test = skips[0]
 
1806
        self.assertFalse('log' in test.getDetails())
 
1807
 
 
1808
    def test_missing_feature_has_no_log(self):
 
1809
        # testtools doesn't know about addNotSupported, so it just gets
 
1810
        # considered as a skip
 
1811
        result = self._run_test('test_missing_feature')
 
1812
        reasons = _get_skip_reasons(result)
 
1813
        self.assertEqual({missing_feature}, set(reasons))
 
1814
        skips = reasons[missing_feature]
 
1815
        self.assertEqual(1, len(skips))
 
1816
        test = skips[0]
 
1817
        self.assertFalse('log' in test.getDetails())
 
1818
 
 
1819
    def test_xfail_has_no_log(self):
 
1820
        result = self._run_test('test_xfail')
 
1821
        self.assertEqual(1, len(result.expectedFailures))
 
1822
        result_content = result.expectedFailures[0][1]
 
1823
        self.assertNotContainsRe(result_content,
 
1824
            '(?m)^(?:Text attachment: )?log(?:$|: )')
 
1825
        self.assertNotContainsRe(result_content, 'test with expected failure')
 
1826
 
 
1827
    def test_unexpected_success_has_log(self):
 
1828
        result = self._run_test('test_unexpected_success')
 
1829
        self.assertEqual(1, len(result.unexpectedSuccesses))
 
1830
        # Inconsistency, unexpectedSuccesses is a list of tests,
 
1831
        # expectedFailures is a list of reasons?
 
1832
        test = result.unexpectedSuccesses[0]
 
1833
        details = test.getDetails()
 
1834
        self.assertTrue('log' in details)
 
1835
 
 
1836
 
 
1837
class TestTestCloning(tests.TestCase):
 
1838
    """Tests that test cloning of TestCases (as used by multiply_tests)."""
 
1839
 
 
1840
    def test_cloned_testcase_does_not_share_details(self):
 
1841
        """A TestCase cloned with clone_test does not share mutable attributes
 
1842
        such as details or cleanups.
 
1843
        """
 
1844
        class Test(tests.TestCase):
 
1845
            def test_foo(self):
 
1846
                self.addDetail('foo', Content('text/plain', lambda: 'foo'))
 
1847
        orig_test = Test('test_foo')
 
1848
        cloned_test = tests.clone_test(orig_test, orig_test.id() + '(cloned)')
 
1849
        orig_test.run(unittest.TestResult())
 
1850
        self.assertEqual('foo', orig_test.getDetails()['foo'].iter_bytes())
 
1851
        self.assertEqual(None, cloned_test.getDetails().get('foo'))
 
1852
 
 
1853
    def test_double_apply_scenario_preserves_first_scenario(self):
 
1854
        """Applying two levels of scenarios to a test preserves the attributes
 
1855
        added by both scenarios.
 
1856
        """
 
1857
        class Test(tests.TestCase):
 
1858
            def test_foo(self):
 
1859
                pass
 
1860
        test = Test('test_foo')
 
1861
        scenarios_x = [('x=1', {'x': 1}), ('x=2', {'x': 2})]
 
1862
        scenarios_y = [('y=1', {'y': 1}), ('y=2', {'y': 2})]
 
1863
        suite = tests.multiply_tests(test, scenarios_x, unittest.TestSuite())
 
1864
        suite = tests.multiply_tests(suite, scenarios_y, unittest.TestSuite())
 
1865
        all_tests = list(tests.iter_suite_tests(suite))
 
1866
        self.assertLength(4, all_tests)
 
1867
        all_xys = sorted((t.x, t.y) for t in all_tests)
 
1868
        self.assertEqual([(1, 1), (1, 2), (2, 1), (2, 2)], all_xys)
 
1869
 
 
1870
 
 
1871
# NB: Don't delete this; it's not actually from 0.11!
 
1872
@deprecated_function(deprecated_in((0, 11, 0)))
 
1873
def sample_deprecated_function():
 
1874
    """A deprecated function to test applyDeprecated with."""
 
1875
    return 2
 
1876
 
 
1877
 
 
1878
def sample_undeprecated_function(a_param):
 
1879
    """A undeprecated function to test applyDeprecated with."""
 
1880
 
 
1881
 
 
1882
class ApplyDeprecatedHelper(object):
 
1883
    """A helper class for ApplyDeprecated tests."""
 
1884
 
 
1885
    @deprecated_method(deprecated_in((0, 11, 0)))
 
1886
    def sample_deprecated_method(self, param_one):
 
1887
        """A deprecated method for testing with."""
 
1888
        return param_one
 
1889
 
 
1890
    def sample_normal_method(self):
 
1891
        """A undeprecated method."""
 
1892
 
 
1893
    @deprecated_method(deprecated_in((0, 10, 0)))
 
1894
    def sample_nested_deprecation(self):
 
1895
        return sample_deprecated_function()
 
1896
 
 
1897
 
 
1898
class TestExtraAssertions(tests.TestCase):
 
1899
    """Tests for new test assertions in breezy test suite"""
 
1900
 
 
1901
    def test_assert_isinstance(self):
 
1902
        self.assertIsInstance(2, int)
 
1903
        self.assertIsInstance(u'', basestring)
 
1904
        e = self.assertRaises(AssertionError, self.assertIsInstance, None, int)
 
1905
        self.assertEqual(str(e),
 
1906
            "None is an instance of <type 'NoneType'> rather than <type 'int'>")
 
1907
        self.assertRaises(AssertionError, self.assertIsInstance, 23.3, int)
 
1908
        e = self.assertRaises(AssertionError,
 
1909
            self.assertIsInstance, None, int, "it's just not")
 
1910
        self.assertEqual(str(e),
 
1911
            "None is an instance of <type 'NoneType'> rather than <type 'int'>"
 
1912
            ": it's just not")
 
1913
 
 
1914
    def test_assertEndsWith(self):
 
1915
        self.assertEndsWith('foo', 'oo')
 
1916
        self.assertRaises(AssertionError, self.assertEndsWith, 'o', 'oo')
 
1917
 
 
1918
    def test_assertEqualDiff(self):
 
1919
        e = self.assertRaises(AssertionError,
 
1920
                              self.assertEqualDiff, '', '\n')
 
1921
        self.assertEqual(str(e),
 
1922
                          # Don't blink ! The '+' applies to the second string
 
1923
                          'first string is missing a final newline.\n+ \n')
 
1924
        e = self.assertRaises(AssertionError,
 
1925
                              self.assertEqualDiff, '\n', '')
 
1926
        self.assertEqual(str(e),
 
1927
                          # Don't blink ! The '-' applies to the second string
 
1928
                          'second string is missing a final newline.\n- \n')
 
1929
 
 
1930
 
 
1931
class TestDeprecations(tests.TestCase):
 
1932
 
 
1933
    def test_applyDeprecated_not_deprecated(self):
 
1934
        sample_object = ApplyDeprecatedHelper()
 
1935
        # calling an undeprecated callable raises an assertion
 
1936
        self.assertRaises(AssertionError, self.applyDeprecated,
 
1937
            deprecated_in((0, 11, 0)),
 
1938
            sample_object.sample_normal_method)
 
1939
        self.assertRaises(AssertionError, self.applyDeprecated,
 
1940
            deprecated_in((0, 11, 0)),
 
1941
            sample_undeprecated_function, "a param value")
 
1942
        # calling a deprecated callable (function or method) with the wrong
 
1943
        # expected deprecation fails.
 
1944
        self.assertRaises(AssertionError, self.applyDeprecated,
 
1945
            deprecated_in((0, 10, 0)),
 
1946
            sample_object.sample_deprecated_method, "a param value")
 
1947
        self.assertRaises(AssertionError, self.applyDeprecated,
 
1948
            deprecated_in((0, 10, 0)),
 
1949
            sample_deprecated_function)
 
1950
        # calling a deprecated callable (function or method) with the right
 
1951
        # expected deprecation returns the functions result.
 
1952
        self.assertEqual("a param value",
 
1953
            self.applyDeprecated(deprecated_in((0, 11, 0)),
 
1954
            sample_object.sample_deprecated_method, "a param value"))
 
1955
        self.assertEqual(2, self.applyDeprecated(deprecated_in((0, 11, 0)),
 
1956
            sample_deprecated_function))
 
1957
        # calling a nested deprecation with the wrong deprecation version
 
1958
        # fails even if a deeper nested function was deprecated with the
 
1959
        # supplied version.
 
1960
        self.assertRaises(AssertionError, self.applyDeprecated,
 
1961
            deprecated_in((0, 11, 0)), sample_object.sample_nested_deprecation)
 
1962
        # calling a nested deprecation with the right deprecation value
 
1963
        # returns the calls result.
 
1964
        self.assertEqual(2, self.applyDeprecated(deprecated_in((0, 10, 0)),
 
1965
            sample_object.sample_nested_deprecation))
 
1966
 
 
1967
    def test_callDeprecated(self):
 
1968
        def testfunc(be_deprecated, result=None):
 
1969
            if be_deprecated is True:
 
1970
                symbol_versioning.warn('i am deprecated', DeprecationWarning,
 
1971
                                       stacklevel=1)
 
1972
            return result
 
1973
        result = self.callDeprecated(['i am deprecated'], testfunc, True)
 
1974
        self.assertIs(None, result)
 
1975
        result = self.callDeprecated([], testfunc, False, 'result')
 
1976
        self.assertEqual('result', result)
 
1977
        self.callDeprecated(['i am deprecated'], testfunc, be_deprecated=True)
 
1978
        self.callDeprecated([], testfunc, be_deprecated=False)
 
1979
 
 
1980
 
 
1981
class TestWarningTests(tests.TestCase):
 
1982
    """Tests for calling methods that raise warnings."""
 
1983
 
 
1984
    def test_callCatchWarnings(self):
 
1985
        def meth(a, b):
 
1986
            warnings.warn("this is your last warning")
 
1987
            return a + b
 
1988
        wlist, result = self.callCatchWarnings(meth, 1, 2)
 
1989
        self.assertEqual(3, result)
 
1990
        # would like just to compare them, but UserWarning doesn't implement
 
1991
        # eq well
 
1992
        w0, = wlist
 
1993
        self.assertIsInstance(w0, UserWarning)
 
1994
        self.assertEqual("this is your last warning", str(w0))
 
1995
 
 
1996
 
 
1997
class TestConvenienceMakers(tests.TestCaseWithTransport):
 
1998
    """Test for the make_* convenience functions."""
 
1999
 
 
2000
    def test_make_branch_and_tree_with_format(self):
 
2001
        # we should be able to supply a format to make_branch_and_tree
 
2002
        self.make_branch_and_tree('a', format=breezy.bzrdir.BzrDirMetaFormat1())
 
2003
        self.assertIsInstance(breezy.controldir.ControlDir.open('a')._format,
 
2004
                              breezy.bzrdir.BzrDirMetaFormat1)
 
2005
 
 
2006
    def test_make_branch_and_memory_tree(self):
 
2007
        # we should be able to get a new branch and a mutable tree from
 
2008
        # TestCaseWithTransport
 
2009
        tree = self.make_branch_and_memory_tree('a')
 
2010
        self.assertIsInstance(tree, breezy.memorytree.MemoryTree)
 
2011
 
 
2012
    def test_make_tree_for_local_vfs_backed_transport(self):
 
2013
        # make_branch_and_tree has to use local branch and repositories
 
2014
        # when the vfs transport and local disk are colocated, even if
 
2015
        # a different transport is in use for url generation.
 
2016
        self.transport_server = test_server.FakeVFATServer
 
2017
        self.assertFalse(self.get_url('t1').startswith('file://'))
 
2018
        tree = self.make_branch_and_tree('t1')
 
2019
        base = tree.bzrdir.root_transport.base
 
2020
        self.assertStartsWith(base, 'file://')
 
2021
        self.assertEqual(tree.bzrdir.root_transport,
 
2022
                tree.branch.bzrdir.root_transport)
 
2023
        self.assertEqual(tree.bzrdir.root_transport,
 
2024
                tree.branch.repository.bzrdir.root_transport)
 
2025
 
 
2026
 
 
2027
class SelfTestHelper(object):
 
2028
 
 
2029
    def run_selftest(self, **kwargs):
 
2030
        """Run selftest returning its output."""
 
2031
        output = StringIO()
 
2032
        old_transport = breezy.tests.default_transport
 
2033
        old_root = tests.TestCaseWithMemoryTransport.TEST_ROOT
 
2034
        tests.TestCaseWithMemoryTransport.TEST_ROOT = None
 
2035
        try:
 
2036
            self.assertEqual(True, tests.selftest(stream=output, **kwargs))
 
2037
        finally:
 
2038
            breezy.tests.default_transport = old_transport
 
2039
            tests.TestCaseWithMemoryTransport.TEST_ROOT = old_root
 
2040
        output.seek(0)
 
2041
        return output
 
2042
 
 
2043
 
 
2044
class TestSelftest(tests.TestCase, SelfTestHelper):
 
2045
    """Tests of breezy.tests.selftest."""
 
2046
 
 
2047
    def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
 
2048
        factory_called = []
 
2049
        def factory():
 
2050
            factory_called.append(True)
 
2051
            return TestUtil.TestSuite()
 
2052
        out = StringIO()
 
2053
        err = StringIO()
 
2054
        self.apply_redirected(out, err, None, breezy.tests.selftest,
 
2055
            test_suite_factory=factory)
 
2056
        self.assertEqual([True], factory_called)
 
2057
 
 
2058
    def factory(self):
 
2059
        """A test suite factory."""
 
2060
        class Test(tests.TestCase):
 
2061
            def a(self):
 
2062
                pass
 
2063
            def b(self):
 
2064
                pass
 
2065
            def c(self):
 
2066
                pass
 
2067
        return TestUtil.TestSuite([Test("a"), Test("b"), Test("c")])
 
2068
 
 
2069
    def test_list_only(self):
 
2070
        output = self.run_selftest(test_suite_factory=self.factory,
 
2071
            list_only=True)
 
2072
        self.assertEqual(3, len(output.readlines()))
 
2073
 
 
2074
    def test_list_only_filtered(self):
 
2075
        output = self.run_selftest(test_suite_factory=self.factory,
 
2076
            list_only=True, pattern="Test.b")
 
2077
        self.assertEndsWith(output.getvalue(), "Test.b\n")
 
2078
        self.assertLength(1, output.readlines())
 
2079
 
 
2080
    def test_list_only_excludes(self):
 
2081
        output = self.run_selftest(test_suite_factory=self.factory,
 
2082
            list_only=True, exclude_pattern="Test.b")
 
2083
        self.assertNotContainsRe("Test.b", output.getvalue())
 
2084
        self.assertLength(2, output.readlines())
 
2085
 
 
2086
    def test_lsprof_tests(self):
 
2087
        self.requireFeature(features.lsprof_feature)
 
2088
        results = []
 
2089
        class Test(object):
 
2090
            def __call__(test, result):
 
2091
                test.run(result)
 
2092
            def run(test, result):
 
2093
                results.append(result)
 
2094
            def countTestCases(self):
 
2095
                return 1
 
2096
        self.run_selftest(test_suite_factory=Test, lsprof_tests=True)
 
2097
        self.assertLength(1, results)
 
2098
        self.assertIsInstance(results.pop(), ExtendedToOriginalDecorator)
 
2099
 
 
2100
    def test_random(self):
 
2101
        # test randomising by listing a number of tests.
 
2102
        output_123 = self.run_selftest(test_suite_factory=self.factory,
 
2103
            list_only=True, random_seed="123")
 
2104
        output_234 = self.run_selftest(test_suite_factory=self.factory,
 
2105
            list_only=True, random_seed="234")
 
2106
        self.assertNotEqual(output_123, output_234)
 
2107
        # "Randominzing test order..\n\n
 
2108
        self.assertLength(5, output_123.readlines())
 
2109
        self.assertLength(5, output_234.readlines())
 
2110
 
 
2111
    def test_random_reuse_is_same_order(self):
 
2112
        # test randomising by listing a number of tests.
 
2113
        expected = self.run_selftest(test_suite_factory=self.factory,
 
2114
            list_only=True, random_seed="123")
 
2115
        repeated = self.run_selftest(test_suite_factory=self.factory,
 
2116
            list_only=True, random_seed="123")
 
2117
        self.assertEqual(expected.getvalue(), repeated.getvalue())
 
2118
 
 
2119
    def test_runner_class(self):
 
2120
        self.requireFeature(features.subunit)
 
2121
        from subunit import ProtocolTestCase
 
2122
        stream = self.run_selftest(runner_class=tests.SubUnitBzrRunner,
 
2123
            test_suite_factory=self.factory)
 
2124
        test = ProtocolTestCase(stream)
 
2125
        result = unittest.TestResult()
 
2126
        test.run(result)
 
2127
        self.assertEqual(3, result.testsRun)
 
2128
 
 
2129
    def test_starting_with_single_argument(self):
 
2130
        output = self.run_selftest(test_suite_factory=self.factory,
 
2131
            starting_with=['breezy.tests.test_selftest.Test.a'],
 
2132
            list_only=True)
 
2133
        self.assertEqual('breezy.tests.test_selftest.Test.a\n',
 
2134
            output.getvalue())
 
2135
 
 
2136
    def test_starting_with_multiple_argument(self):
 
2137
        output = self.run_selftest(test_suite_factory=self.factory,
 
2138
            starting_with=['breezy.tests.test_selftest.Test.a',
 
2139
                'breezy.tests.test_selftest.Test.b'],
 
2140
            list_only=True)
 
2141
        self.assertEqual('breezy.tests.test_selftest.Test.a\n'
 
2142
            'breezy.tests.test_selftest.Test.b\n',
 
2143
            output.getvalue())
 
2144
 
 
2145
    def check_transport_set(self, transport_server):
 
2146
        captured_transport = []
 
2147
        def seen_transport(a_transport):
 
2148
            captured_transport.append(a_transport)
 
2149
        class Capture(tests.TestCase):
 
2150
            def a(self):
 
2151
                seen_transport(breezy.tests.default_transport)
 
2152
        def factory():
 
2153
            return TestUtil.TestSuite([Capture("a")])
 
2154
        self.run_selftest(transport=transport_server, test_suite_factory=factory)
 
2155
        self.assertEqual(transport_server, captured_transport[0])
 
2156
 
 
2157
    def test_transport_sftp(self):
 
2158
        self.requireFeature(features.paramiko)
 
2159
        from breezy.tests import stub_sftp
 
2160
        self.check_transport_set(stub_sftp.SFTPAbsoluteServer)
 
2161
 
 
2162
    def test_transport_memory(self):
 
2163
        self.check_transport_set(memory.MemoryServer)
 
2164
 
 
2165
 
 
2166
class TestSelftestWithIdList(tests.TestCaseInTempDir, SelfTestHelper):
 
2167
    # Does IO: reads test.list
 
2168
 
 
2169
    def test_load_list(self):
 
2170
        # Provide a list with one test - this test.
 
2171
        test_id_line = '%s\n' % self.id()
 
2172
        self.build_tree_contents([('test.list', test_id_line)])
 
2173
        # And generate a list of the tests in  the suite.
 
2174
        stream = self.run_selftest(load_list='test.list', list_only=True)
 
2175
        self.assertEqual(test_id_line, stream.getvalue())
 
2176
 
 
2177
    def test_load_unknown(self):
 
2178
        # Provide a list with one test - this test.
 
2179
        # And generate a list of the tests in  the suite.
 
2180
        err = self.assertRaises(errors.NoSuchFile, self.run_selftest,
 
2181
            load_list='missing file name', list_only=True)
 
2182
 
 
2183
 
 
2184
class TestSubunitLogDetails(tests.TestCase, SelfTestHelper):
 
2185
 
 
2186
    _test_needs_features = [features.subunit]
 
2187
 
 
2188
    def run_subunit_stream(self, test_name):
 
2189
        from subunit import ProtocolTestCase
 
2190
        def factory():
 
2191
            return TestUtil.TestSuite([_get_test(test_name)])
 
2192
        stream = self.run_selftest(runner_class=tests.SubUnitBzrRunner,
 
2193
            test_suite_factory=factory)
 
2194
        test = ProtocolTestCase(stream)
 
2195
        result = testtools.TestResult()
 
2196
        test.run(result)
 
2197
        content = stream.getvalue()
 
2198
        return content, result
 
2199
 
 
2200
    def test_fail_has_log(self):
 
2201
        content, result = self.run_subunit_stream('test_fail')
 
2202
        self.assertEqual(1, len(result.failures))
 
2203
        self.assertContainsRe(content, '(?m)^log$')
 
2204
        self.assertContainsRe(content, 'this test will fail')
 
2205
 
 
2206
    def test_error_has_log(self):
 
2207
        content, result = self.run_subunit_stream('test_error')
 
2208
        self.assertContainsRe(content, '(?m)^log$')
 
2209
        self.assertContainsRe(content, 'this test errored')
 
2210
 
 
2211
    def test_skip_has_no_log(self):
 
2212
        content, result = self.run_subunit_stream('test_skip')
 
2213
        self.assertNotContainsRe(content, '(?m)^log$')
 
2214
        self.assertNotContainsRe(content, 'this test will be skipped')
 
2215
        reasons = _get_skip_reasons(result)
 
2216
        self.assertEqual({'reason'}, set(reasons))
 
2217
        skips = reasons['reason']
 
2218
        self.assertEqual(1, len(skips))
 
2219
        test = skips[0]
 
2220
        # RemotedTestCase doesn't preserve the "details"
 
2221
        ## self.assertFalse('log' in test.getDetails())
 
2222
 
 
2223
    def test_missing_feature_has_no_log(self):
 
2224
        content, result = self.run_subunit_stream('test_missing_feature')
 
2225
        self.assertNotContainsRe(content, '(?m)^log$')
 
2226
        self.assertNotContainsRe(content, 'missing the feature')
 
2227
        reasons = _get_skip_reasons(result)
 
2228
        self.assertEqual({'_MissingFeature\n'}, set(reasons))
 
2229
        skips = reasons['_MissingFeature\n']
 
2230
        self.assertEqual(1, len(skips))
 
2231
        test = skips[0]
 
2232
        # RemotedTestCase doesn't preserve the "details"
 
2233
        ## self.assertFalse('log' in test.getDetails())
 
2234
 
 
2235
    def test_xfail_has_no_log(self):
 
2236
        content, result = self.run_subunit_stream('test_xfail')
 
2237
        self.assertNotContainsRe(content, '(?m)^log$')
 
2238
        self.assertNotContainsRe(content, 'test with expected failure')
 
2239
        self.assertEqual(1, len(result.expectedFailures))
 
2240
        result_content = result.expectedFailures[0][1]
 
2241
        self.assertNotContainsRe(result_content,
 
2242
            '(?m)^(?:Text attachment: )?log(?:$|: )')
 
2243
        self.assertNotContainsRe(result_content, 'test with expected failure')
 
2244
 
 
2245
    def test_unexpected_success_has_log(self):
 
2246
        content, result = self.run_subunit_stream('test_unexpected_success')
 
2247
        self.assertContainsRe(content, '(?m)^log$')
 
2248
        self.assertContainsRe(content, 'test with unexpected success')
 
2249
        # GZ 2011-05-18: Old versions of subunit treat unexpected success as a
 
2250
        #                success, if a min version check is added remove this
 
2251
        from subunit import TestProtocolClient as _Client
 
2252
        if _Client.addUnexpectedSuccess.__func__ is _Client.addSuccess.__func__:
 
2253
            self.expectFailure('subunit treats "unexpectedSuccess"'
 
2254
                               ' as a plain success',
 
2255
                self.assertEqual, 1, len(result.unexpectedSuccesses))
 
2256
        self.assertEqual(1, len(result.unexpectedSuccesses))
 
2257
        test = result.unexpectedSuccesses[0]
 
2258
        # RemotedTestCase doesn't preserve the "details"
 
2259
        ## self.assertTrue('log' in test.getDetails())
 
2260
 
 
2261
    def test_success_has_no_log(self):
 
2262
        content, result = self.run_subunit_stream('test_success')
 
2263
        self.assertEqual(1, result.testsRun)
 
2264
        self.assertNotContainsRe(content, '(?m)^log$')
 
2265
        self.assertNotContainsRe(content, 'this test succeeds')
 
2266
 
 
2267
 
 
2268
class TestRunBzr(tests.TestCase):
 
2269
 
 
2270
    out = ''
 
2271
    err = ''
 
2272
 
 
2273
    def _run_bzr_core(self, argv, retcode=0, encoding=None, stdin=None,
 
2274
                         working_dir=None):
 
2275
        """Override _run_bzr_core to test how it is invoked by run_bzr.
 
2276
 
 
2277
        Attempts to run bzr from inside this class don't actually run it.
 
2278
 
 
2279
        We test how run_bzr actually invokes bzr in another location.  Here we
 
2280
        only need to test that it passes the right parameters to run_bzr.
 
2281
        """
 
2282
        self.argv = list(argv)
 
2283
        self.retcode = retcode
 
2284
        self.encoding = encoding
 
2285
        self.stdin = stdin
 
2286
        self.working_dir = working_dir
 
2287
        return self.retcode, self.out, self.err
 
2288
 
 
2289
    def test_run_bzr_error(self):
 
2290
        self.out = "It sure does!\n"
 
2291
        out, err = self.run_bzr_error(['^$'], ['rocks'], retcode=34)
 
2292
        self.assertEqual(['rocks'], self.argv)
 
2293
        self.assertEqual(34, self.retcode)
 
2294
        self.assertEqual('It sure does!\n', out)
 
2295
        self.assertEqual(out, self.out)
 
2296
        self.assertEqual('', err)
 
2297
        self.assertEqual(err, self.err)
 
2298
 
 
2299
    def test_run_bzr_error_regexes(self):
 
2300
        self.out = ''
 
2301
        self.err = "bzr: ERROR: foobarbaz is not versioned"
 
2302
        out, err = self.run_bzr_error(
 
2303
            ["bzr: ERROR: foobarbaz is not versioned"],
 
2304
            ['file-id', 'foobarbaz'])
 
2305
 
 
2306
    def test_encoding(self):
 
2307
        """Test that run_bzr passes encoding to _run_bzr_core"""
 
2308
        self.run_bzr('foo bar')
 
2309
        self.assertEqual(None, self.encoding)
 
2310
        self.assertEqual(['foo', 'bar'], self.argv)
 
2311
 
 
2312
        self.run_bzr('foo bar', encoding='baz')
 
2313
        self.assertEqual('baz', self.encoding)
 
2314
        self.assertEqual(['foo', 'bar'], self.argv)
 
2315
 
 
2316
    def test_retcode(self):
 
2317
        """Test that run_bzr passes retcode to _run_bzr_core"""
 
2318
        # Default is retcode == 0
 
2319
        self.run_bzr('foo bar')
 
2320
        self.assertEqual(0, self.retcode)
 
2321
        self.assertEqual(['foo', 'bar'], self.argv)
 
2322
 
 
2323
        self.run_bzr('foo bar', retcode=1)
 
2324
        self.assertEqual(1, self.retcode)
 
2325
        self.assertEqual(['foo', 'bar'], self.argv)
 
2326
 
 
2327
        self.run_bzr('foo bar', retcode=None)
 
2328
        self.assertEqual(None, self.retcode)
 
2329
        self.assertEqual(['foo', 'bar'], self.argv)
 
2330
 
 
2331
        self.run_bzr(['foo', 'bar'], retcode=3)
 
2332
        self.assertEqual(3, self.retcode)
 
2333
        self.assertEqual(['foo', 'bar'], self.argv)
 
2334
 
 
2335
    def test_stdin(self):
 
2336
        # test that the stdin keyword to run_bzr is passed through to
 
2337
        # _run_bzr_core as-is. We do this by overriding
 
2338
        # _run_bzr_core in this class, and then calling run_bzr,
 
2339
        # which is a convenience function for _run_bzr_core, so
 
2340
        # should invoke it.
 
2341
        self.run_bzr('foo bar', stdin='gam')
 
2342
        self.assertEqual('gam', self.stdin)
 
2343
        self.assertEqual(['foo', 'bar'], self.argv)
 
2344
 
 
2345
        self.run_bzr('foo bar', stdin='zippy')
 
2346
        self.assertEqual('zippy', self.stdin)
 
2347
        self.assertEqual(['foo', 'bar'], self.argv)
 
2348
 
 
2349
    def test_working_dir(self):
 
2350
        """Test that run_bzr passes working_dir to _run_bzr_core"""
 
2351
        self.run_bzr('foo bar')
 
2352
        self.assertEqual(None, self.working_dir)
 
2353
        self.assertEqual(['foo', 'bar'], self.argv)
 
2354
 
 
2355
        self.run_bzr('foo bar', working_dir='baz')
 
2356
        self.assertEqual('baz', self.working_dir)
 
2357
        self.assertEqual(['foo', 'bar'], self.argv)
 
2358
 
 
2359
    def test_reject_extra_keyword_arguments(self):
 
2360
        self.assertRaises(TypeError, self.run_bzr, "foo bar",
 
2361
                          error_regex=['error message'])
 
2362
 
 
2363
 
 
2364
class TestRunBzrCaptured(tests.TestCaseWithTransport):
 
2365
    # Does IO when testing the working_dir parameter.
 
2366
 
 
2367
    def apply_redirected(self, stdin=None, stdout=None, stderr=None,
 
2368
                         a_callable=None, *args, **kwargs):
 
2369
        self.stdin = stdin
 
2370
        self.factory_stdin = getattr(breezy.ui.ui_factory, "stdin", None)
 
2371
        self.factory = breezy.ui.ui_factory
 
2372
        self.working_dir = osutils.getcwd()
 
2373
        stdout.write('foo\n')
 
2374
        stderr.write('bar\n')
 
2375
        return 0
 
2376
 
 
2377
    def test_stdin(self):
 
2378
        # test that the stdin keyword to _run_bzr_core is passed through to
 
2379
        # apply_redirected as a StringIO. We do this by overriding
 
2380
        # apply_redirected in this class, and then calling _run_bzr_core,
 
2381
        # which calls apply_redirected.
 
2382
        self.run_bzr(['foo', 'bar'], stdin='gam')
 
2383
        self.assertEqual('gam', self.stdin.read())
 
2384
        self.assertTrue(self.stdin is self.factory_stdin)
 
2385
        self.run_bzr(['foo', 'bar'], stdin='zippy')
 
2386
        self.assertEqual('zippy', self.stdin.read())
 
2387
        self.assertTrue(self.stdin is self.factory_stdin)
 
2388
 
 
2389
    def test_ui_factory(self):
 
2390
        # each invocation of self.run_bzr should get its
 
2391
        # own UI factory, which is an instance of TestUIFactory,
 
2392
        # with stdin, stdout and stderr attached to the stdin,
 
2393
        # stdout and stderr of the invoked run_bzr
 
2394
        current_factory = breezy.ui.ui_factory
 
2395
        self.run_bzr(['foo'])
 
2396
        self.assertFalse(current_factory is self.factory)
 
2397
        self.assertNotEqual(sys.stdout, self.factory.stdout)
 
2398
        self.assertNotEqual(sys.stderr, self.factory.stderr)
 
2399
        self.assertEqual('foo\n', self.factory.stdout.getvalue())
 
2400
        self.assertEqual('bar\n', self.factory.stderr.getvalue())
 
2401
        self.assertIsInstance(self.factory, tests.TestUIFactory)
 
2402
 
 
2403
    def test_working_dir(self):
 
2404
        self.build_tree(['one/', 'two/'])
 
2405
        cwd = osutils.getcwd()
 
2406
 
 
2407
        # Default is to work in the current directory
 
2408
        self.run_bzr(['foo', 'bar'])
 
2409
        self.assertEqual(cwd, self.working_dir)
 
2410
 
 
2411
        self.run_bzr(['foo', 'bar'], working_dir=None)
 
2412
        self.assertEqual(cwd, self.working_dir)
 
2413
 
 
2414
        # The function should be run in the alternative directory
 
2415
        # but afterwards the current working dir shouldn't be changed
 
2416
        self.run_bzr(['foo', 'bar'], working_dir='one')
 
2417
        self.assertNotEqual(cwd, self.working_dir)
 
2418
        self.assertEndsWith(self.working_dir, 'one')
 
2419
        self.assertEqual(cwd, osutils.getcwd())
 
2420
 
 
2421
        self.run_bzr(['foo', 'bar'], working_dir='two')
 
2422
        self.assertNotEqual(cwd, self.working_dir)
 
2423
        self.assertEndsWith(self.working_dir, 'two')
 
2424
        self.assertEqual(cwd, osutils.getcwd())
 
2425
 
 
2426
 
 
2427
class StubProcess(object):
 
2428
    """A stub process for testing run_bzr_subprocess."""
 
2429
    
 
2430
    def __init__(self, out="", err="", retcode=0):
 
2431
        self.out = out
 
2432
        self.err = err
 
2433
        self.returncode = retcode
 
2434
 
 
2435
    def communicate(self):
 
2436
        return self.out, self.err
 
2437
 
 
2438
 
 
2439
class TestWithFakedStartBzrSubprocess(tests.TestCaseWithTransport):
 
2440
    """Base class for tests testing how we might run bzr."""
 
2441
 
 
2442
    def setUp(self):
 
2443
        super(TestWithFakedStartBzrSubprocess, self).setUp()
 
2444
        self.subprocess_calls = []
 
2445
 
 
2446
    def start_bzr_subprocess(self, process_args, env_changes=None,
 
2447
                             skip_if_plan_to_signal=False,
 
2448
                             working_dir=None,
 
2449
                             allow_plugins=False):
 
2450
        """capture what run_bzr_subprocess tries to do."""
 
2451
        self.subprocess_calls.append({'process_args':process_args,
 
2452
            'env_changes':env_changes,
 
2453
            'skip_if_plan_to_signal':skip_if_plan_to_signal,
 
2454
            'working_dir':working_dir, 'allow_plugins':allow_plugins})
 
2455
        return self.next_subprocess
 
2456
 
 
2457
 
 
2458
class TestRunBzrSubprocess(TestWithFakedStartBzrSubprocess):
 
2459
 
 
2460
    def assertRunBzrSubprocess(self, expected_args, process, *args, **kwargs):
 
2461
        """Run run_bzr_subprocess with args and kwargs using a stubbed process.
 
2462
 
 
2463
        Inside TestRunBzrSubprocessCommands we use a stub start_bzr_subprocess
 
2464
        that will return static results. This assertion method populates those
 
2465
        results and also checks the arguments run_bzr_subprocess generates.
 
2466
        """
 
2467
        self.next_subprocess = process
 
2468
        try:
 
2469
            result = self.run_bzr_subprocess(*args, **kwargs)
 
2470
        except:
 
2471
            self.next_subprocess = None
 
2472
            for key, expected in expected_args.items():
 
2473
                self.assertEqual(expected, self.subprocess_calls[-1][key])
 
2474
            raise
 
2475
        else:
 
2476
            self.next_subprocess = None
 
2477
            for key, expected in expected_args.items():
 
2478
                self.assertEqual(expected, self.subprocess_calls[-1][key])
 
2479
            return result
 
2480
 
 
2481
    def test_run_bzr_subprocess(self):
 
2482
        """The run_bzr_helper_external command behaves nicely."""
 
2483
        self.assertRunBzrSubprocess({'process_args':['--version']},
 
2484
            StubProcess(), '--version')
 
2485
        self.assertRunBzrSubprocess({'process_args':['--version']},
 
2486
            StubProcess(), ['--version'])
 
2487
        # retcode=None disables retcode checking
 
2488
        result = self.assertRunBzrSubprocess({},
 
2489
            StubProcess(retcode=3), '--version', retcode=None)
 
2490
        result = self.assertRunBzrSubprocess({},
 
2491
            StubProcess(out="is free software"), '--version')
 
2492
        self.assertContainsRe(result[0], 'is free software')
 
2493
        # Running a subcommand that is missing errors
 
2494
        self.assertRaises(AssertionError, self.assertRunBzrSubprocess,
 
2495
            {'process_args':['--versionn']}, StubProcess(retcode=3),
 
2496
            '--versionn')
 
2497
        # Unless it is told to expect the error from the subprocess
 
2498
        result = self.assertRunBzrSubprocess({},
 
2499
            StubProcess(retcode=3), '--versionn', retcode=3)
 
2500
        # Or to ignore retcode checking
 
2501
        result = self.assertRunBzrSubprocess({},
 
2502
            StubProcess(err="unknown command", retcode=3), '--versionn',
 
2503
            retcode=None)
 
2504
        self.assertContainsRe(result[1], 'unknown command')
 
2505
 
 
2506
    def test_env_change_passes_through(self):
 
2507
        self.assertRunBzrSubprocess(
 
2508
            {'env_changes':{'new':'value', 'changed':'newvalue', 'deleted':None}},
 
2509
            StubProcess(), '',
 
2510
            env_changes={'new':'value', 'changed':'newvalue', 'deleted':None})
 
2511
 
 
2512
    def test_no_working_dir_passed_as_None(self):
 
2513
        self.assertRunBzrSubprocess({'working_dir': None}, StubProcess(), '')
 
2514
 
 
2515
    def test_no_working_dir_passed_through(self):
 
2516
        self.assertRunBzrSubprocess({'working_dir': 'dir'}, StubProcess(), '',
 
2517
            working_dir='dir')
 
2518
 
 
2519
    def test_run_bzr_subprocess_no_plugins(self):
 
2520
        self.assertRunBzrSubprocess({'allow_plugins': False},
 
2521
            StubProcess(), '')
 
2522
 
 
2523
    def test_allow_plugins(self):
 
2524
        self.assertRunBzrSubprocess({'allow_plugins': True},
 
2525
            StubProcess(), '', allow_plugins=True)
 
2526
 
 
2527
 
 
2528
class TestFinishBzrSubprocess(TestWithFakedStartBzrSubprocess):
 
2529
 
 
2530
    def test_finish_bzr_subprocess_with_error(self):
 
2531
        """finish_bzr_subprocess allows specification of the desired exit code.
 
2532
        """
 
2533
        process = StubProcess(err="unknown command", retcode=3)
 
2534
        result = self.finish_bzr_subprocess(process, retcode=3)
 
2535
        self.assertEqual('', result[0])
 
2536
        self.assertContainsRe(result[1], 'unknown command')
 
2537
 
 
2538
    def test_finish_bzr_subprocess_ignoring_retcode(self):
 
2539
        """finish_bzr_subprocess allows the exit code to be ignored."""
 
2540
        process = StubProcess(err="unknown command", retcode=3)
 
2541
        result = self.finish_bzr_subprocess(process, retcode=None)
 
2542
        self.assertEqual('', result[0])
 
2543
        self.assertContainsRe(result[1], 'unknown command')
 
2544
 
 
2545
    def test_finish_subprocess_with_unexpected_retcode(self):
 
2546
        """finish_bzr_subprocess raises self.failureException if the retcode is
 
2547
        not the expected one.
 
2548
        """
 
2549
        process = StubProcess(err="unknown command", retcode=3)
 
2550
        self.assertRaises(self.failureException, self.finish_bzr_subprocess,
 
2551
                          process)
 
2552
 
 
2553
 
 
2554
class _DontSpawnProcess(Exception):
 
2555
    """A simple exception which just allows us to skip unnecessary steps"""
 
2556
 
 
2557
 
 
2558
class TestStartBzrSubProcess(tests.TestCase):
 
2559
    """Stub test start_bzr_subprocess."""
 
2560
 
 
2561
    def _subprocess_log_cleanup(self):
 
2562
        """Inhibits the base version as we don't produce a log file."""
 
2563
 
 
2564
    def _popen(self, *args, **kwargs):
 
2565
        """Override the base version to record the command that is run.
 
2566
 
 
2567
        From there we can ensure it is correct without spawning a real process.
 
2568
        """
 
2569
        self.check_popen_state()
 
2570
        self._popen_args = args
 
2571
        self._popen_kwargs = kwargs
 
2572
        raise _DontSpawnProcess()
 
2573
 
 
2574
    def check_popen_state(self):
 
2575
        """Replace to make assertions when popen is called."""
 
2576
 
 
2577
    def test_run_bzr_subprocess_no_plugins(self):
 
2578
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [])
 
2579
        command = self._popen_args[0]
 
2580
        self.assertEqual(sys.executable, command[0])
 
2581
        self.assertEqual(self.get_brz_path(), command[1])
 
2582
        self.assertEqual(['--no-plugins'], command[2:])
 
2583
 
 
2584
    def test_allow_plugins(self):
 
2585
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
 
2586
                          allow_plugins=True)
 
2587
        command = self._popen_args[0]
 
2588
        self.assertEqual([], command[2:])
 
2589
 
 
2590
    def test_set_env(self):
 
2591
        self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
 
2592
        # set in the child
 
2593
        def check_environment():
 
2594
            self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
 
2595
        self.check_popen_state = check_environment
 
2596
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
 
2597
                          env_changes={'EXISTANT_ENV_VAR':'set variable'})
 
2598
        # not set in theparent
 
2599
        self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
 
2600
 
 
2601
    def test_run_bzr_subprocess_env_del(self):
 
2602
        """run_bzr_subprocess can remove environment variables too."""
 
2603
        self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
 
2604
        def check_environment():
 
2605
            self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
 
2606
        os.environ['EXISTANT_ENV_VAR'] = 'set variable'
 
2607
        self.check_popen_state = check_environment
 
2608
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
 
2609
                          env_changes={'EXISTANT_ENV_VAR':None})
 
2610
        # Still set in parent
 
2611
        self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
 
2612
        del os.environ['EXISTANT_ENV_VAR']
 
2613
 
 
2614
    def test_env_del_missing(self):
 
2615
        self.assertFalse('NON_EXISTANT_ENV_VAR' in os.environ)
 
2616
        def check_environment():
 
2617
            self.assertFalse('NON_EXISTANT_ENV_VAR' in os.environ)
 
2618
        self.check_popen_state = check_environment
 
2619
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
 
2620
                          env_changes={'NON_EXISTANT_ENV_VAR':None})
 
2621
 
 
2622
    def test_working_dir(self):
 
2623
        """Test that we can specify the working dir for the child"""
 
2624
        orig_getcwd = osutils.getcwd
 
2625
        orig_chdir = os.chdir
 
2626
        chdirs = []
 
2627
        def chdir(path):
 
2628
            chdirs.append(path)
 
2629
        self.overrideAttr(os, 'chdir', chdir)
 
2630
        def getcwd():
 
2631
            return 'current'
 
2632
        self.overrideAttr(osutils, 'getcwd', getcwd)
 
2633
        self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
 
2634
                          working_dir='foo')
 
2635
        self.assertEqual(['foo', 'current'], chdirs)
 
2636
 
 
2637
    def test_get_brz_path_with_cwd_breezy(self):
 
2638
        self.get_source_path = lambda: ""
 
2639
        self.overrideAttr(os.path, "isfile", lambda path: True)
 
2640
        self.assertEqual(self.get_brz_path(), "brz")
 
2641
 
 
2642
 
 
2643
class TestActuallyStartBzrSubprocess(tests.TestCaseWithTransport):
 
2644
    """Tests that really need to do things with an external bzr."""
 
2645
 
 
2646
    def test_start_and_stop_bzr_subprocess_send_signal(self):
 
2647
        """finish_bzr_subprocess raises self.failureException if the retcode is
 
2648
        not the expected one.
 
2649
        """
 
2650
        self.disable_missing_extensions_warning()
 
2651
        process = self.start_bzr_subprocess(['wait-until-signalled'],
 
2652
                                            skip_if_plan_to_signal=True)
 
2653
        self.assertEqual('running\n', process.stdout.readline())
 
2654
        result = self.finish_bzr_subprocess(process, send_signal=signal.SIGINT,
 
2655
                                            retcode=3)
 
2656
        self.assertEqual('', result[0])
 
2657
        self.assertEqual('brz: interrupted\n', result[1])
 
2658
 
 
2659
 
 
2660
class TestSelftestFiltering(tests.TestCase):
 
2661
 
 
2662
    def setUp(self):
 
2663
        super(TestSelftestFiltering, self).setUp()
 
2664
        self.suite = TestUtil.TestSuite()
 
2665
        self.loader = TestUtil.TestLoader()
 
2666
        self.suite.addTest(self.loader.loadTestsFromModule(
 
2667
            sys.modules['breezy.tests.test_selftest']))
 
2668
        self.all_names = _test_ids(self.suite)
 
2669
 
 
2670
    def test_condition_id_re(self):
 
2671
        test_name = ('breezy.tests.test_selftest.TestSelftestFiltering.'
 
2672
            'test_condition_id_re')
 
2673
        filtered_suite = tests.filter_suite_by_condition(
 
2674
            self.suite, tests.condition_id_re('test_condition_id_re'))
 
2675
        self.assertEqual([test_name], _test_ids(filtered_suite))
 
2676
 
 
2677
    def test_condition_id_in_list(self):
 
2678
        test_names = ['breezy.tests.test_selftest.TestSelftestFiltering.'
 
2679
                      'test_condition_id_in_list']
 
2680
        id_list = tests.TestIdList(test_names)
 
2681
        filtered_suite = tests.filter_suite_by_condition(
 
2682
            self.suite, tests.condition_id_in_list(id_list))
 
2683
        my_pattern = 'TestSelftestFiltering.*test_condition_id_in_list'
 
2684
        re_filtered = tests.filter_suite_by_re(self.suite, my_pattern)
 
2685
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
 
2686
 
 
2687
    def test_condition_id_startswith(self):
 
2688
        klass = 'breezy.tests.test_selftest.TestSelftestFiltering.'
 
2689
        start1 = klass + 'test_condition_id_starts'
 
2690
        start2 = klass + 'test_condition_id_in'
 
2691
        test_names = [ klass + 'test_condition_id_in_list',
 
2692
                      klass + 'test_condition_id_startswith',
 
2693
                     ]
 
2694
        filtered_suite = tests.filter_suite_by_condition(
 
2695
            self.suite, tests.condition_id_startswith([start1, start2]))
 
2696
        self.assertEqual(test_names, _test_ids(filtered_suite))
 
2697
 
 
2698
    def test_condition_isinstance(self):
 
2699
        filtered_suite = tests.filter_suite_by_condition(
 
2700
            self.suite, tests.condition_isinstance(self.__class__))
 
2701
        class_pattern = 'breezy.tests.test_selftest.TestSelftestFiltering.'
 
2702
        re_filtered = tests.filter_suite_by_re(self.suite, class_pattern)
 
2703
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
 
2704
 
 
2705
    def test_exclude_tests_by_condition(self):
 
2706
        excluded_name = ('breezy.tests.test_selftest.TestSelftestFiltering.'
 
2707
            'test_exclude_tests_by_condition')
 
2708
        filtered_suite = tests.exclude_tests_by_condition(self.suite,
 
2709
            lambda x:x.id() == excluded_name)
 
2710
        self.assertEqual(len(self.all_names) - 1,
 
2711
            filtered_suite.countTestCases())
 
2712
        self.assertFalse(excluded_name in _test_ids(filtered_suite))
 
2713
        remaining_names = list(self.all_names)
 
2714
        remaining_names.remove(excluded_name)
 
2715
        self.assertEqual(remaining_names, _test_ids(filtered_suite))
 
2716
 
 
2717
    def test_exclude_tests_by_re(self):
 
2718
        self.all_names = _test_ids(self.suite)
 
2719
        filtered_suite = tests.exclude_tests_by_re(self.suite,
 
2720
                                                   'exclude_tests_by_re')
 
2721
        excluded_name = ('breezy.tests.test_selftest.TestSelftestFiltering.'
 
2722
            'test_exclude_tests_by_re')
 
2723
        self.assertEqual(len(self.all_names) - 1,
 
2724
            filtered_suite.countTestCases())
 
2725
        self.assertFalse(excluded_name in _test_ids(filtered_suite))
 
2726
        remaining_names = list(self.all_names)
 
2727
        remaining_names.remove(excluded_name)
 
2728
        self.assertEqual(remaining_names, _test_ids(filtered_suite))
 
2729
 
 
2730
    def test_filter_suite_by_condition(self):
 
2731
        test_name = ('breezy.tests.test_selftest.TestSelftestFiltering.'
 
2732
            'test_filter_suite_by_condition')
 
2733
        filtered_suite = tests.filter_suite_by_condition(self.suite,
 
2734
            lambda x:x.id() == test_name)
 
2735
        self.assertEqual([test_name], _test_ids(filtered_suite))
 
2736
 
 
2737
    def test_filter_suite_by_re(self):
 
2738
        filtered_suite = tests.filter_suite_by_re(self.suite,
 
2739
                                                  'test_filter_suite_by_r')
 
2740
        filtered_names = _test_ids(filtered_suite)
 
2741
        self.assertEqual(filtered_names, ['breezy.tests.test_selftest.'
 
2742
            'TestSelftestFiltering.test_filter_suite_by_re'])
 
2743
 
 
2744
    def test_filter_suite_by_id_list(self):
 
2745
        test_list = ['breezy.tests.test_selftest.'
 
2746
                     'TestSelftestFiltering.test_filter_suite_by_id_list']
 
2747
        filtered_suite = tests.filter_suite_by_id_list(
 
2748
            self.suite, tests.TestIdList(test_list))
 
2749
        filtered_names = _test_ids(filtered_suite)
 
2750
        self.assertEqual(
 
2751
            filtered_names,
 
2752
            ['breezy.tests.test_selftest.'
 
2753
             'TestSelftestFiltering.test_filter_suite_by_id_list'])
 
2754
 
 
2755
    def test_filter_suite_by_id_startswith(self):
 
2756
        # By design this test may fail if another test is added whose name also
 
2757
        # begins with one of the start value used.
 
2758
        klass = 'breezy.tests.test_selftest.TestSelftestFiltering.'
 
2759
        start1 = klass + 'test_filter_suite_by_id_starts'
 
2760
        start2 = klass + 'test_filter_suite_by_id_li'
 
2761
        test_list = [klass + 'test_filter_suite_by_id_list',
 
2762
                     klass + 'test_filter_suite_by_id_startswith',
 
2763
                     ]
 
2764
        filtered_suite = tests.filter_suite_by_id_startswith(
 
2765
            self.suite, [start1, start2])
 
2766
        self.assertEqual(
 
2767
            test_list,
 
2768
            _test_ids(filtered_suite),
 
2769
            )
 
2770
 
 
2771
    def test_preserve_input(self):
 
2772
        # NB: Surely this is something in the stdlib to do this?
 
2773
        self.assertTrue(self.suite is tests.preserve_input(self.suite))
 
2774
        self.assertTrue("@#$" is tests.preserve_input("@#$"))
 
2775
 
 
2776
    def test_randomize_suite(self):
 
2777
        randomized_suite = tests.randomize_suite(self.suite)
 
2778
        # randomizing should not add or remove test names.
 
2779
        self.assertEqual(set(_test_ids(self.suite)),
 
2780
                         set(_test_ids(randomized_suite)))
 
2781
        # Technically, this *can* fail, because random.shuffle(list) can be
 
2782
        # equal to list. Trying multiple times just pushes the frequency back.
 
2783
        # As its len(self.all_names)!:1, the failure frequency should be low
 
2784
        # enough to ignore. RBC 20071021.
 
2785
        # It should change the order.
 
2786
        self.assertNotEqual(self.all_names, _test_ids(randomized_suite))
 
2787
        # But not the length. (Possibly redundant with the set test, but not
 
2788
        # necessarily.)
 
2789
        self.assertEqual(len(self.all_names), len(_test_ids(randomized_suite)))
 
2790
 
 
2791
    def test_split_suit_by_condition(self):
 
2792
        self.all_names = _test_ids(self.suite)
 
2793
        condition = tests.condition_id_re('test_filter_suite_by_r')
 
2794
        split_suite = tests.split_suite_by_condition(self.suite, condition)
 
2795
        filtered_name = ('breezy.tests.test_selftest.TestSelftestFiltering.'
 
2796
            'test_filter_suite_by_re')
 
2797
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
 
2798
        self.assertFalse(filtered_name in _test_ids(split_suite[1]))
 
2799
        remaining_names = list(self.all_names)
 
2800
        remaining_names.remove(filtered_name)
 
2801
        self.assertEqual(remaining_names, _test_ids(split_suite[1]))
 
2802
 
 
2803
    def test_split_suit_by_re(self):
 
2804
        self.all_names = _test_ids(self.suite)
 
2805
        split_suite = tests.split_suite_by_re(self.suite,
 
2806
                                              'test_filter_suite_by_r')
 
2807
        filtered_name = ('breezy.tests.test_selftest.TestSelftestFiltering.'
 
2808
            'test_filter_suite_by_re')
 
2809
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
 
2810
        self.assertFalse(filtered_name in _test_ids(split_suite[1]))
 
2811
        remaining_names = list(self.all_names)
 
2812
        remaining_names.remove(filtered_name)
 
2813
        self.assertEqual(remaining_names, _test_ids(split_suite[1]))
 
2814
 
 
2815
 
 
2816
class TestCheckTreeShape(tests.TestCaseWithTransport):
 
2817
 
 
2818
    def test_check_tree_shape(self):
 
2819
        files = ['a', 'b/', 'b/c']
 
2820
        tree = self.make_branch_and_tree('.')
 
2821
        self.build_tree(files)
 
2822
        tree.add(files)
 
2823
        tree.lock_read()
 
2824
        try:
 
2825
            self.check_tree_shape(tree, files)
 
2826
        finally:
 
2827
            tree.unlock()
 
2828
 
 
2829
 
 
2830
class TestBlackboxSupport(tests.TestCase):
 
2831
    """Tests for testsuite blackbox features."""
 
2832
 
 
2833
    def test_run_bzr_failure_not_caught(self):
 
2834
        # When we run bzr in blackbox mode, we want any unexpected errors to
 
2835
        # propagate up to the test suite so that it can show the error in the
 
2836
        # usual way, and we won't get a double traceback.
 
2837
        e = self.assertRaises(
 
2838
            AssertionError,
 
2839
            self.run_bzr, ['assert-fail'])
 
2840
        # make sure we got the real thing, not an error from somewhere else in
 
2841
        # the test framework
 
2842
        self.assertEqual('always fails', str(e))
 
2843
        # check that there's no traceback in the test log
 
2844
        self.assertNotContainsRe(self.get_log(), r'Traceback')
 
2845
 
 
2846
    def test_run_bzr_user_error_caught(self):
 
2847
        # Running bzr in blackbox mode, normal/expected/user errors should be
 
2848
        # caught in the regular way and turned into an error message plus exit
 
2849
        # code.
 
2850
        transport_server = memory.MemoryServer()
 
2851
        transport_server.start_server()
 
2852
        self.addCleanup(transport_server.stop_server)
 
2853
        url = transport_server.get_url()
 
2854
        self.permit_url(url)
 
2855
        out, err = self.run_bzr(["log", "%s/nonexistantpath" % url], retcode=3)
 
2856
        self.assertEqual(out, '')
 
2857
        self.assertContainsRe(err,
 
2858
            'brz: ERROR: Not a branch: ".*nonexistantpath/".\n')
 
2859
 
 
2860
 
 
2861
class TestTestLoader(tests.TestCase):
 
2862
    """Tests for the test loader."""
 
2863
 
 
2864
    def _get_loader_and_module(self):
 
2865
        """Gets a TestLoader and a module with one test in it."""
 
2866
        loader = TestUtil.TestLoader()
 
2867
        module = {}
 
2868
        class Stub(tests.TestCase):
 
2869
            def test_foo(self):
 
2870
                pass
 
2871
        class MyModule(object):
 
2872
            pass
 
2873
        MyModule.a_class = Stub
 
2874
        module = MyModule()
 
2875
        module.__name__ = 'fake_module'
 
2876
        return loader, module
 
2877
 
 
2878
    def test_module_no_load_tests_attribute_loads_classes(self):
 
2879
        loader, module = self._get_loader_and_module()
 
2880
        self.assertEqual(1, loader.loadTestsFromModule(module).countTestCases())
 
2881
 
 
2882
    def test_module_load_tests_attribute_gets_called(self):
 
2883
        loader, module = self._get_loader_and_module()
 
2884
        def load_tests(loader, standard_tests, pattern):
 
2885
            result = loader.suiteClass()
 
2886
            for test in tests.iter_suite_tests(standard_tests):
 
2887
                result.addTests([test, test])
 
2888
            return result
 
2889
        # add a load_tests() method which multiplies the tests from the module.
 
2890
        module.__class__.load_tests = staticmethod(load_tests)
 
2891
        self.assertEqual(
 
2892
            2 * [str(module.a_class('test_foo'))],
 
2893
            list(map(str, loader.loadTestsFromModule(module))))
 
2894
 
 
2895
    def test_load_tests_from_module_name_smoke_test(self):
 
2896
        loader = TestUtil.TestLoader()
 
2897
        suite = loader.loadTestsFromModuleName('breezy.tests.test_sampler')
 
2898
        self.assertEqual(['breezy.tests.test_sampler.DemoTest.test_nothing'],
 
2899
                          _test_ids(suite))
 
2900
 
 
2901
    def test_load_tests_from_module_name_with_bogus_module_name(self):
 
2902
        loader = TestUtil.TestLoader()
 
2903
        self.assertRaises(ImportError, loader.loadTestsFromModuleName, 'bogus')
 
2904
 
 
2905
 
 
2906
class TestTestIdList(tests.TestCase):
 
2907
 
 
2908
    def _create_id_list(self, test_list):
 
2909
        return tests.TestIdList(test_list)
 
2910
 
 
2911
    def _create_suite(self, test_id_list):
 
2912
 
 
2913
        class Stub(tests.TestCase):
 
2914
            def test_foo(self):
 
2915
                pass
 
2916
 
 
2917
        def _create_test_id(id):
 
2918
            return lambda: id
 
2919
 
 
2920
        suite = TestUtil.TestSuite()
 
2921
        for id in test_id_list:
 
2922
            t  = Stub('test_foo')
 
2923
            t.id = _create_test_id(id)
 
2924
            suite.addTest(t)
 
2925
        return suite
 
2926
 
 
2927
    def _test_ids(self, test_suite):
 
2928
        """Get the ids for the tests in a test suite."""
 
2929
        return [t.id() for t in tests.iter_suite_tests(test_suite)]
 
2930
 
 
2931
    def test_empty_list(self):
 
2932
        id_list = self._create_id_list([])
 
2933
        self.assertEqual({}, id_list.tests)
 
2934
        self.assertEqual({}, id_list.modules)
 
2935
 
 
2936
    def test_valid_list(self):
 
2937
        id_list = self._create_id_list(
 
2938
            ['mod1.cl1.meth1', 'mod1.cl1.meth2',
 
2939
             'mod1.func1', 'mod1.cl2.meth2',
 
2940
             'mod1.submod1',
 
2941
             'mod1.submod2.cl1.meth1', 'mod1.submod2.cl2.meth2',
 
2942
             ])
 
2943
        self.assertTrue(id_list.refers_to('mod1'))
 
2944
        self.assertTrue(id_list.refers_to('mod1.submod1'))
 
2945
        self.assertTrue(id_list.refers_to('mod1.submod2'))
 
2946
        self.assertTrue(id_list.includes('mod1.cl1.meth1'))
 
2947
        self.assertTrue(id_list.includes('mod1.submod1'))
 
2948
        self.assertTrue(id_list.includes('mod1.func1'))
 
2949
 
 
2950
    def test_bad_chars_in_params(self):
 
2951
        id_list = self._create_id_list(['mod1.cl1.meth1(xx.yy)'])
 
2952
        self.assertTrue(id_list.refers_to('mod1'))
 
2953
        self.assertTrue(id_list.includes('mod1.cl1.meth1(xx.yy)'))
 
2954
 
 
2955
    def test_module_used(self):
 
2956
        id_list = self._create_id_list(['mod.class.meth'])
 
2957
        self.assertTrue(id_list.refers_to('mod'))
 
2958
        self.assertTrue(id_list.refers_to('mod.class'))
 
2959
        self.assertTrue(id_list.refers_to('mod.class.meth'))
 
2960
 
 
2961
    def test_test_suite_matches_id_list_with_unknown(self):
 
2962
        loader = TestUtil.TestLoader()
 
2963
        suite = loader.loadTestsFromModuleName('breezy.tests.test_sampler')
 
2964
        test_list = ['breezy.tests.test_sampler.DemoTest.test_nothing',
 
2965
                     'bogus']
 
2966
        not_found, duplicates = tests.suite_matches_id_list(suite, test_list)
 
2967
        self.assertEqual(['bogus'], not_found)
 
2968
        self.assertEqual([], duplicates)
 
2969
 
 
2970
    def test_suite_matches_id_list_with_duplicates(self):
 
2971
        loader = TestUtil.TestLoader()
 
2972
        suite = loader.loadTestsFromModuleName('breezy.tests.test_sampler')
 
2973
        dupes = loader.suiteClass()
 
2974
        for test in tests.iter_suite_tests(suite):
 
2975
            dupes.addTest(test)
 
2976
            dupes.addTest(test) # Add it again
 
2977
 
 
2978
        test_list = ['breezy.tests.test_sampler.DemoTest.test_nothing',]
 
2979
        not_found, duplicates = tests.suite_matches_id_list(
 
2980
            dupes, test_list)
 
2981
        self.assertEqual([], not_found)
 
2982
        self.assertEqual(['breezy.tests.test_sampler.DemoTest.test_nothing'],
 
2983
                          duplicates)
 
2984
 
 
2985
 
 
2986
class TestTestSuite(tests.TestCase):
 
2987
 
 
2988
    def test__test_suite_testmod_names(self):
 
2989
        # Test that a plausible list of test module names are returned
 
2990
        # by _test_suite_testmod_names.
 
2991
        test_list = tests._test_suite_testmod_names()
 
2992
        self.assertSubset([
 
2993
            'breezy.tests.blackbox',
 
2994
            'breezy.tests.per_transport',
 
2995
            'breezy.tests.test_selftest',
 
2996
            ],
 
2997
            test_list)
 
2998
 
 
2999
    def test__test_suite_modules_to_doctest(self):
 
3000
        # Test that a plausible list of modules to doctest is returned
 
3001
        # by _test_suite_modules_to_doctest.
 
3002
        test_list = tests._test_suite_modules_to_doctest()
 
3003
        if __doc__ is None:
 
3004
            # When docstrings are stripped, there are no modules to doctest
 
3005
            self.assertEqual([], test_list)
 
3006
            return
 
3007
        self.assertSubset([
 
3008
            'breezy.timestamp',
 
3009
            ],
 
3010
            test_list)
 
3011
 
 
3012
    def test_test_suite(self):
 
3013
        # test_suite() loads the entire test suite to operate. To avoid this
 
3014
        # overhead, and yet still be confident that things are happening,
 
3015
        # we temporarily replace two functions used by test_suite with 
 
3016
        # test doubles that supply a few sample tests to load, and check they
 
3017
        # are loaded.
 
3018
        calls = []
 
3019
        def testmod_names():
 
3020
            calls.append("testmod_names")
 
3021
            return [
 
3022
                'breezy.tests.blackbox.test_branch',
 
3023
                'breezy.tests.per_transport',
 
3024
                'breezy.tests.test_selftest',
 
3025
                ]
 
3026
        self.overrideAttr(tests, '_test_suite_testmod_names', testmod_names)
 
3027
        def doctests():
 
3028
            calls.append("modules_to_doctest")
 
3029
            if __doc__ is None:
 
3030
                return []
 
3031
            return ['breezy.timestamp']
 
3032
        self.overrideAttr(tests, '_test_suite_modules_to_doctest', doctests)
 
3033
        expected_test_list = [
 
3034
            # testmod_names
 
3035
            'breezy.tests.blackbox.test_branch.TestBranch.test_branch',
 
3036
            ('breezy.tests.per_transport.TransportTests'
 
3037
             '.test_abspath(LocalTransport,LocalURLServer)'),
 
3038
            'breezy.tests.test_selftest.TestTestSuite.test_test_suite',
 
3039
            # plugins can't be tested that way since selftest may be run with
 
3040
            # --no-plugins
 
3041
            ]
 
3042
        if __doc__ is not None:
 
3043
            expected_test_list.extend([
 
3044
                # modules_to_doctest
 
3045
                'breezy.timestamp.format_highres_date',
 
3046
                ])
 
3047
        suite = tests.test_suite()
 
3048
        self.assertEqual({"testmod_names", "modules_to_doctest"},
 
3049
            set(calls))
 
3050
        self.assertSubset(expected_test_list, _test_ids(suite))
 
3051
 
 
3052
    def test_test_suite_list_and_start(self):
 
3053
        # We cannot test this at the same time as the main load, because we want
 
3054
        # to know that starting_with == None works. So a second load is
 
3055
        # incurred - note that the starting_with parameter causes a partial load
 
3056
        # rather than a full load so this test should be pretty quick.
 
3057
        test_list = ['breezy.tests.test_selftest.TestTestSuite.test_test_suite']
 
3058
        suite = tests.test_suite(test_list,
 
3059
                                 ['breezy.tests.test_selftest.TestTestSuite'])
 
3060
        # test_test_suite_list_and_start is not included 
 
3061
        self.assertEqual(test_list, _test_ids(suite))
 
3062
 
 
3063
 
 
3064
class TestLoadTestIdList(tests.TestCaseInTempDir):
 
3065
 
 
3066
    def _create_test_list_file(self, file_name, content):
 
3067
        fl = open(file_name, 'wt')
 
3068
        fl.write(content)
 
3069
        fl.close()
 
3070
 
 
3071
    def test_load_unknown(self):
 
3072
        self.assertRaises(errors.NoSuchFile,
 
3073
                          tests.load_test_id_list, 'i_do_not_exist')
 
3074
 
 
3075
    def test_load_test_list(self):
 
3076
        test_list_fname = 'test.list'
 
3077
        self._create_test_list_file(test_list_fname,
 
3078
                                    'mod1.cl1.meth1\nmod2.cl2.meth2\n')
 
3079
        tlist = tests.load_test_id_list(test_list_fname)
 
3080
        self.assertEqual(2, len(tlist))
 
3081
        self.assertEqual('mod1.cl1.meth1', tlist[0])
 
3082
        self.assertEqual('mod2.cl2.meth2', tlist[1])
 
3083
 
 
3084
    def test_load_dirty_file(self):
 
3085
        test_list_fname = 'test.list'
 
3086
        self._create_test_list_file(test_list_fname,
 
3087
                                    '  mod1.cl1.meth1\n\nmod2.cl2.meth2  \n'
 
3088
                                    'bar baz\n')
 
3089
        tlist = tests.load_test_id_list(test_list_fname)
 
3090
        self.assertEqual(4, len(tlist))
 
3091
        self.assertEqual('mod1.cl1.meth1', tlist[0])
 
3092
        self.assertEqual('', tlist[1])
 
3093
        self.assertEqual('mod2.cl2.meth2', tlist[2])
 
3094
        self.assertEqual('bar baz', tlist[3])
 
3095
 
 
3096
 
 
3097
class TestFilteredByModuleTestLoader(tests.TestCase):
 
3098
 
 
3099
    def _create_loader(self, test_list):
 
3100
        id_filter = tests.TestIdList(test_list)
 
3101
        loader = TestUtil.FilteredByModuleTestLoader(id_filter.refers_to)
 
3102
        return loader
 
3103
 
 
3104
    def test_load_tests(self):
 
3105
        test_list = ['breezy.tests.test_sampler.DemoTest.test_nothing']
 
3106
        loader = self._create_loader(test_list)
 
3107
        suite = loader.loadTestsFromModuleName('breezy.tests.test_sampler')
 
3108
        self.assertEqual(test_list, _test_ids(suite))
 
3109
 
 
3110
    def test_exclude_tests(self):
 
3111
        test_list = ['bogus']
 
3112
        loader = self._create_loader(test_list)
 
3113
        suite = loader.loadTestsFromModuleName('breezy.tests.test_sampler')
 
3114
        self.assertEqual([], _test_ids(suite))
 
3115
 
 
3116
 
 
3117
class TestFilteredByNameStartTestLoader(tests.TestCase):
 
3118
 
 
3119
    def _create_loader(self, name_start):
 
3120
        def needs_module(name):
 
3121
            return name.startswith(name_start) or name_start.startswith(name)
 
3122
        loader = TestUtil.FilteredByModuleTestLoader(needs_module)
 
3123
        return loader
 
3124
 
 
3125
    def test_load_tests(self):
 
3126
        test_list = ['breezy.tests.test_sampler.DemoTest.test_nothing']
 
3127
        loader = self._create_loader('breezy.tests.test_samp')
 
3128
 
 
3129
        suite = loader.loadTestsFromModuleName('breezy.tests.test_sampler')
 
3130
        self.assertEqual(test_list, _test_ids(suite))
 
3131
 
 
3132
    def test_load_tests_inside_module(self):
 
3133
        test_list = ['breezy.tests.test_sampler.DemoTest.test_nothing']
 
3134
        loader = self._create_loader('breezy.tests.test_sampler.Demo')
 
3135
 
 
3136
        suite = loader.loadTestsFromModuleName('breezy.tests.test_sampler')
 
3137
        self.assertEqual(test_list, _test_ids(suite))
 
3138
 
 
3139
    def test_exclude_tests(self):
 
3140
        test_list = ['bogus']
 
3141
        loader = self._create_loader('bogus')
 
3142
 
 
3143
        suite = loader.loadTestsFromModuleName('breezy.tests.test_sampler')
 
3144
        self.assertEqual([], _test_ids(suite))
 
3145
 
 
3146
 
 
3147
class TestTestPrefixRegistry(tests.TestCase):
 
3148
 
 
3149
    def _get_registry(self):
 
3150
        tp_registry = tests.TestPrefixAliasRegistry()
 
3151
        return tp_registry
 
3152
 
 
3153
    def test_register_new_prefix(self):
 
3154
        tpr = self._get_registry()
 
3155
        tpr.register('foo', 'fff.ooo.ooo')
 
3156
        self.assertEqual('fff.ooo.ooo', tpr.get('foo'))
 
3157
 
 
3158
    def test_register_existing_prefix(self):
 
3159
        tpr = self._get_registry()
 
3160
        tpr.register('bar', 'bbb.aaa.rrr')
 
3161
        tpr.register('bar', 'bBB.aAA.rRR')
 
3162
        self.assertEqual('bbb.aaa.rrr', tpr.get('bar'))
 
3163
        self.assertThat(self.get_log(),
 
3164
            DocTestMatches("...bar...bbb.aaa.rrr...BB.aAA.rRR",
 
3165
                           doctest.ELLIPSIS))
 
3166
 
 
3167
    def test_get_unknown_prefix(self):
 
3168
        tpr = self._get_registry()
 
3169
        self.assertRaises(KeyError, tpr.get, 'I am not a prefix')
 
3170
 
 
3171
    def test_resolve_prefix(self):
 
3172
        tpr = self._get_registry()
 
3173
        tpr.register('bar', 'bb.aa.rr')
 
3174
        self.assertEqual('bb.aa.rr', tpr.resolve_alias('bar'))
 
3175
 
 
3176
    def test_resolve_unknown_alias(self):
 
3177
        tpr = self._get_registry()
 
3178
        self.assertRaises(errors.BzrCommandError,
 
3179
                          tpr.resolve_alias, 'I am not a prefix')
 
3180
 
 
3181
    def test_predefined_prefixes(self):
 
3182
        tpr = tests.test_prefix_alias_registry
 
3183
        self.assertEqual('breezy', tpr.resolve_alias('breezy'))
 
3184
        self.assertEqual('breezy.doc', tpr.resolve_alias('bd'))
 
3185
        self.assertEqual('breezy.utils', tpr.resolve_alias('bu'))
 
3186
        self.assertEqual('breezy.tests', tpr.resolve_alias('bt'))
 
3187
        self.assertEqual('breezy.tests.blackbox', tpr.resolve_alias('bb'))
 
3188
        self.assertEqual('breezy.plugins', tpr.resolve_alias('bp'))
 
3189
 
 
3190
 
 
3191
class TestThreadLeakDetection(tests.TestCase):
 
3192
    """Ensure when tests leak threads we detect and report it"""
 
3193
 
 
3194
    class LeakRecordingResult(tests.ExtendedTestResult):
 
3195
        def __init__(self):
 
3196
            tests.ExtendedTestResult.__init__(self, StringIO(), 0, 1)
 
3197
            self.leaks = []
 
3198
        def _report_thread_leak(self, test, leaks, alive):
 
3199
            self.leaks.append((test, leaks))
 
3200
 
 
3201
    def test_testcase_without_addCleanups(self):
 
3202
        """Check old TestCase instances don't break with leak detection"""
 
3203
        class Test(unittest.TestCase):
 
3204
            def runTest(self):
 
3205
                pass
 
3206
        result = self.LeakRecordingResult()
 
3207
        test = Test()
 
3208
        result.startTestRun()
 
3209
        test.run(result)
 
3210
        result.stopTestRun()
 
3211
        self.assertEqual(result._tests_leaking_threads_count, 0)
 
3212
        self.assertEqual(result.leaks, [])
 
3213
        
 
3214
    def test_thread_leak(self):
 
3215
        """Ensure a thread that outlives the running of a test is reported
 
3216
 
 
3217
        Uses a thread that blocks on an event, and is started by the inner
 
3218
        test case. As the thread outlives the inner case's run, it should be
 
3219
        detected as a leak, but the event is then set so that the thread can
 
3220
        be safely joined in cleanup so it's not leaked for real.
 
3221
        """
 
3222
        event = threading.Event()
 
3223
        thread = threading.Thread(name="Leaker", target=event.wait)
 
3224
        class Test(tests.TestCase):
 
3225
            def test_leak(self):
 
3226
                thread.start()
 
3227
        result = self.LeakRecordingResult()
 
3228
        test = Test("test_leak")
 
3229
        self.addCleanup(thread.join)
 
3230
        self.addCleanup(event.set)
 
3231
        result.startTestRun()
 
3232
        test.run(result)
 
3233
        result.stopTestRun()
 
3234
        self.assertEqual(result._tests_leaking_threads_count, 1)
 
3235
        self.assertEqual(result._first_thread_leaker_id, test.id())
 
3236
        self.assertEqual(result.leaks, [(test, {thread})])
 
3237
        self.assertContainsString(result.stream.getvalue(), "leaking threads")
 
3238
 
 
3239
    def test_multiple_leaks(self):
 
3240
        """Check multiple leaks are blamed on the test cases at fault
 
3241
 
 
3242
        Same concept as the previous test, but has one inner test method that
 
3243
        leaks two threads, and one that doesn't leak at all.
 
3244
        """
 
3245
        event = threading.Event()
 
3246
        thread_a = threading.Thread(name="LeakerA", target=event.wait)
 
3247
        thread_b = threading.Thread(name="LeakerB", target=event.wait)
 
3248
        thread_c = threading.Thread(name="LeakerC", target=event.wait)
 
3249
        class Test(tests.TestCase):
 
3250
            def test_first_leak(self):
 
3251
                thread_b.start()
 
3252
            def test_second_no_leak(self):
 
3253
                pass
 
3254
            def test_third_leak(self):
 
3255
                thread_c.start()
 
3256
                thread_a.start()
 
3257
        result = self.LeakRecordingResult()
 
3258
        first_test = Test("test_first_leak")
 
3259
        third_test = Test("test_third_leak")
 
3260
        self.addCleanup(thread_a.join)
 
3261
        self.addCleanup(thread_b.join)
 
3262
        self.addCleanup(thread_c.join)
 
3263
        self.addCleanup(event.set)
 
3264
        result.startTestRun()
 
3265
        unittest.TestSuite(
 
3266
            [first_test, Test("test_second_no_leak"), third_test]
 
3267
            ).run(result)
 
3268
        result.stopTestRun()
 
3269
        self.assertEqual(result._tests_leaking_threads_count, 2)
 
3270
        self.assertEqual(result._first_thread_leaker_id, first_test.id())
 
3271
        self.assertEqual(result.leaks, [
 
3272
            (first_test, {thread_b}),
 
3273
            (third_test, {thread_a, thread_c})])
 
3274
        self.assertContainsString(result.stream.getvalue(), "leaking threads")
 
3275
 
 
3276
 
 
3277
class TestPostMortemDebugging(tests.TestCase):
 
3278
    """Check post mortem debugging works when tests fail or error"""
 
3279
 
 
3280
    class TracebackRecordingResult(tests.ExtendedTestResult):
 
3281
        def __init__(self):
 
3282
            tests.ExtendedTestResult.__init__(self, StringIO(), 0, 1)
 
3283
            self.postcode = None
 
3284
        def _post_mortem(self, tb=None):
 
3285
            """Record the code object at the end of the current traceback"""
 
3286
            tb = tb or sys.exc_info()[2]
 
3287
            if tb is not None:
 
3288
                next = tb.tb_next
 
3289
                while next is not None:
 
3290
                    tb = next
 
3291
                    next = next.tb_next
 
3292
                self.postcode = tb.tb_frame.f_code
 
3293
        def report_error(self, test, err):
 
3294
            pass
 
3295
        def report_failure(self, test, err):
 
3296
            pass
 
3297
 
 
3298
    def test_location_unittest_error(self):
 
3299
        """Needs right post mortem traceback with erroring unittest case"""
 
3300
        class Test(unittest.TestCase):
 
3301
            def runTest(self):
 
3302
                raise RuntimeError
 
3303
        result = self.TracebackRecordingResult()
 
3304
        Test().run(result)
 
3305
        self.assertEqual(result.postcode, Test.runTest.__code__)
 
3306
 
 
3307
    def test_location_unittest_failure(self):
 
3308
        """Needs right post mortem traceback with failing unittest case"""
 
3309
        class Test(unittest.TestCase):
 
3310
            def runTest(self):
 
3311
                raise self.failureException
 
3312
        result = self.TracebackRecordingResult()
 
3313
        Test().run(result)
 
3314
        self.assertEqual(result.postcode, Test.runTest.__code__)
 
3315
 
 
3316
    def test_location_bt_error(self):
 
3317
        """Needs right post mortem traceback with erroring breezy.tests case"""
 
3318
        class Test(tests.TestCase):
 
3319
            def test_error(self):
 
3320
                raise RuntimeError
 
3321
        result = self.TracebackRecordingResult()
 
3322
        Test("test_error").run(result)
 
3323
        self.assertEqual(result.postcode, Test.test_error.__code__)
 
3324
 
 
3325
    def test_location_bt_failure(self):
 
3326
        """Needs right post mortem traceback with failing breezy.tests case"""
 
3327
        class Test(tests.TestCase):
 
3328
            def test_failure(self):
 
3329
                raise self.failureException
 
3330
        result = self.TracebackRecordingResult()
 
3331
        Test("test_failure").run(result)
 
3332
        self.assertEqual(result.postcode, Test.test_failure.__code__)
 
3333
 
 
3334
    def test_env_var_triggers_post_mortem(self):
 
3335
        """Check pdb.post_mortem is called iff BRZ_TEST_PDB is set"""
 
3336
        import pdb
 
3337
        result = tests.ExtendedTestResult(StringIO(), 0, 1)
 
3338
        post_mortem_calls = []
 
3339
        self.overrideAttr(pdb, "post_mortem", post_mortem_calls.append)
 
3340
        self.overrideEnv('BRZ_TEST_PDB', None)
 
3341
        result._post_mortem(1)
 
3342
        self.overrideEnv('BRZ_TEST_PDB', 'on')
 
3343
        result._post_mortem(2)
 
3344
        self.assertEqual([2], post_mortem_calls)
 
3345
 
 
3346
 
 
3347
class TestRunSuite(tests.TestCase):
 
3348
 
 
3349
    def test_runner_class(self):
 
3350
        """run_suite accepts and uses a runner_class keyword argument."""
 
3351
        class Stub(tests.TestCase):
 
3352
            def test_foo(self):
 
3353
                pass
 
3354
        suite = Stub("test_foo")
 
3355
        calls = []
 
3356
        class MyRunner(tests.TextTestRunner):
 
3357
            def run(self, test):
 
3358
                calls.append(test)
 
3359
                return tests.ExtendedTestResult(self.stream, self.descriptions,
 
3360
                                                self.verbosity)
 
3361
        tests.run_suite(suite, runner_class=MyRunner, stream=StringIO())
 
3362
        self.assertLength(1, calls)
 
3363
 
 
3364
 
 
3365
class _Selftest(object):
 
3366
    """Mixin for tests needing full selftest output"""
 
3367
 
 
3368
    def _inject_stream_into_subunit(self, stream):
 
3369
        """To be overridden by subclasses that run tests out of process"""
 
3370
 
 
3371
    def _run_selftest(self, **kwargs):
 
3372
        sio = StringIO()
 
3373
        self._inject_stream_into_subunit(sio)
 
3374
        tests.selftest(stream=sio, stop_on_failure=False, **kwargs)
 
3375
        return sio.getvalue()
 
3376
 
 
3377
 
 
3378
class _ForkedSelftest(_Selftest):
 
3379
    """Mixin for tests needing full selftest output with forked children"""
 
3380
 
 
3381
    _test_needs_features = [features.subunit]
 
3382
 
 
3383
    def _inject_stream_into_subunit(self, stream):
 
3384
        """Monkey-patch subunit so the extra output goes to stream not stdout
 
3385
 
 
3386
        Some APIs need rewriting so this kind of bogus hackery can be replaced
 
3387
        by passing the stream param from run_tests down into ProtocolTestCase.
 
3388
        """
 
3389
        from subunit import ProtocolTestCase
 
3390
        _original_init = ProtocolTestCase.__init__
 
3391
        def _init_with_passthrough(self, *args, **kwargs):
 
3392
            _original_init(self, *args, **kwargs)
 
3393
            self._passthrough = stream
 
3394
        self.overrideAttr(ProtocolTestCase, "__init__", _init_with_passthrough)
 
3395
 
 
3396
    def _run_selftest(self, **kwargs):
 
3397
        # GZ 2011-05-26: Add a PosixSystem feature so this check can go away
 
3398
        if getattr(os, "fork", None) is None:
 
3399
            raise tests.TestNotApplicable("Platform doesn't support forking")
 
3400
        # Make sure the fork code is actually invoked by claiming two cores
 
3401
        self.overrideAttr(osutils, "local_concurrency", lambda: 2)
 
3402
        kwargs.setdefault("suite_decorators", []).append(tests.fork_decorator)
 
3403
        return super(_ForkedSelftest, self)._run_selftest(**kwargs)
 
3404
 
 
3405
 
 
3406
class TestParallelFork(_ForkedSelftest, tests.TestCase):
 
3407
    """Check operation of --parallel=fork selftest option"""
 
3408
 
 
3409
    def test_error_in_child_during_fork(self):
 
3410
        """Error in a forked child during test setup should get reported"""
 
3411
        class Test(tests.TestCase):
 
3412
            def testMethod(self):
 
3413
                pass
 
3414
        # We don't care what, just break something that a child will run
 
3415
        self.overrideAttr(tests, "workaround_zealous_crypto_random", None)
 
3416
        out = self._run_selftest(test_suite_factory=Test)
 
3417
        # Lines from the tracebacks of the two child processes may be mixed
 
3418
        # together due to the way subunit parses and forwards the streams,
 
3419
        # so permit extra lines between each part of the error output.
 
3420
        self.assertContainsRe(out,
 
3421
            "Traceback.*:\n"
 
3422
            "(?:.*\n)*"
 
3423
            ".+ in fork_for_tests\n"
 
3424
            "(?:.*\n)*"
 
3425
            "\s*workaround_zealous_crypto_random\(\)\n"
 
3426
            "(?:.*\n)*"
 
3427
            "TypeError:")
 
3428
 
 
3429
 
 
3430
class TestUncollectedWarnings(_Selftest, tests.TestCase):
 
3431
    """Check a test case still alive after being run emits a warning"""
 
3432
 
 
3433
    class Test(tests.TestCase):
 
3434
        def test_pass(self):
 
3435
            pass
 
3436
        def test_self_ref(self):
 
3437
            self.also_self = self.test_self_ref
 
3438
        def test_skip(self):
 
3439
            self.skipTest("Don't need")
 
3440
 
 
3441
    def _get_suite(self):
 
3442
        return TestUtil.TestSuite([
 
3443
            self.Test("test_pass"),
 
3444
            self.Test("test_self_ref"),
 
3445
            self.Test("test_skip"),
 
3446
            ])
 
3447
 
 
3448
    def _run_selftest_with_suite(self, **kwargs):
 
3449
        old_flags = tests.selftest_debug_flags
 
3450
        tests.selftest_debug_flags = old_flags.union(["uncollected_cases"])
 
3451
        gc_on = gc.isenabled()
 
3452
        if gc_on:
 
3453
            gc.disable()
 
3454
        try:
 
3455
            output = self._run_selftest(test_suite_factory=self._get_suite,
 
3456
                **kwargs)
 
3457
        finally:
 
3458
            if gc_on:
 
3459
                gc.enable()
 
3460
            tests.selftest_debug_flags = old_flags
 
3461
        self.assertNotContainsRe(output, "Uncollected test case.*test_pass")
 
3462
        self.assertContainsRe(output, "Uncollected test case.*test_self_ref")
 
3463
        return output
 
3464
 
 
3465
    def test_testsuite(self):
 
3466
        self._run_selftest_with_suite()
 
3467
 
 
3468
    def test_pattern(self):
 
3469
        out = self._run_selftest_with_suite(pattern="test_(?:pass|self_ref)$")
 
3470
        self.assertNotContainsRe(out, "test_skip")
 
3471
 
 
3472
    def test_exclude_pattern(self):
 
3473
        out = self._run_selftest_with_suite(exclude_pattern="test_skip$")
 
3474
        self.assertNotContainsRe(out, "test_skip")
 
3475
 
 
3476
    def test_random_seed(self):
 
3477
        self._run_selftest_with_suite(random_seed="now")
 
3478
 
 
3479
    def test_matching_tests_first(self):
 
3480
        self._run_selftest_with_suite(matching_tests_first=True,
 
3481
            pattern="test_self_ref$")
 
3482
 
 
3483
    def test_starting_with_and_exclude(self):
 
3484
        out = self._run_selftest_with_suite(starting_with=["bt."],
 
3485
            exclude_pattern="test_skip$")
 
3486
        self.assertNotContainsRe(out, "test_skip")
 
3487
 
 
3488
    def test_additonal_decorator(self):
 
3489
        out = self._run_selftest_with_suite(
 
3490
            suite_decorators=[tests.TestDecorator])
 
3491
 
 
3492
 
 
3493
class TestUncollectedWarningsSubunit(TestUncollectedWarnings):
 
3494
    """Check warnings from tests staying alive are emitted with subunit"""
 
3495
 
 
3496
    _test_needs_features = [features.subunit]
 
3497
 
 
3498
    def _run_selftest_with_suite(self, **kwargs):
 
3499
        return TestUncollectedWarnings._run_selftest_with_suite(self,
 
3500
            runner_class=tests.SubUnitBzrRunner, **kwargs)
 
3501
 
 
3502
 
 
3503
class TestUncollectedWarningsForked(_ForkedSelftest, TestUncollectedWarnings):
 
3504
    """Check warnings from tests staying alive are emitted when forking"""
 
3505
 
 
3506
 
 
3507
class TestEnvironHandling(tests.TestCase):
 
3508
 
 
3509
    def test_overrideEnv_None_called_twice_doesnt_leak(self):
 
3510
        self.assertFalse('MYVAR' in os.environ)
 
3511
        self.overrideEnv('MYVAR', '42')
 
3512
        # We use an embedded test to make sure we fix the _captureVar bug
 
3513
        class Test(tests.TestCase):
 
3514
            def test_me(self):
 
3515
                # The first call save the 42 value
 
3516
                self.overrideEnv('MYVAR', None)
 
3517
                self.assertEqual(None, os.environ.get('MYVAR'))
 
3518
                # Make sure we can call it twice
 
3519
                self.overrideEnv('MYVAR', None)
 
3520
                self.assertEqual(None, os.environ.get('MYVAR'))
 
3521
        output = StringIO()
 
3522
        result = tests.TextTestResult(output, 0, 1)
 
3523
        Test('test_me').run(result)
 
3524
        if not result.wasStrictlySuccessful():
 
3525
            self.fail(output.getvalue())
 
3526
        # We get our value back
 
3527
        self.assertEqual('42', os.environ.get('MYVAR'))
 
3528
 
 
3529
 
 
3530
class TestIsolatedEnv(tests.TestCase):
 
3531
    """Test isolating tests from os.environ.
 
3532
 
 
3533
    Since we use tests that are already isolated from os.environ a bit of care
 
3534
    should be taken when designing the tests to avoid bootstrap side-effects.
 
3535
    The tests start an already clean os.environ which allow doing valid
 
3536
    assertions about which variables are present or not and design tests around
 
3537
    these assertions.
 
3538
    """
 
3539
 
 
3540
    class ScratchMonkey(tests.TestCase):
 
3541
 
 
3542
        def test_me(self):
 
3543
            pass
 
3544
 
 
3545
    def test_basics(self):
 
3546
        # Make sure we know the definition of BRZ_HOME: not part of os.environ
 
3547
        # for tests.TestCase.
 
3548
        self.assertTrue('BRZ_HOME' in tests.isolated_environ)
 
3549
        self.assertEqual(None, tests.isolated_environ['BRZ_HOME'])
 
3550
        # Being part of isolated_environ, BRZ_HOME should not appear here
 
3551
        self.assertFalse('BRZ_HOME' in os.environ)
 
3552
        # Make sure we know the definition of LINES: part of os.environ for
 
3553
        # tests.TestCase
 
3554
        self.assertTrue('LINES' in tests.isolated_environ)
 
3555
        self.assertEqual('25', tests.isolated_environ['LINES'])
 
3556
        self.assertEqual('25', os.environ['LINES'])
 
3557
 
 
3558
    def test_injecting_unknown_variable(self):
 
3559
        # BRZ_HOME is known to be absent from os.environ
 
3560
        test = self.ScratchMonkey('test_me')
 
3561
        tests.override_os_environ(test, {'BRZ_HOME': 'foo'})
 
3562
        self.assertEqual('foo', os.environ['BRZ_HOME'])
 
3563
        tests.restore_os_environ(test)
 
3564
        self.assertFalse('BRZ_HOME' in os.environ)
 
3565
 
 
3566
    def test_injecting_known_variable(self):
 
3567
        test = self.ScratchMonkey('test_me')
 
3568
        # LINES is known to be present in os.environ
 
3569
        tests.override_os_environ(test, {'LINES': '42'})
 
3570
        self.assertEqual('42', os.environ['LINES'])
 
3571
        tests.restore_os_environ(test)
 
3572
        self.assertEqual('25', os.environ['LINES'])
 
3573
 
 
3574
    def test_deleting_variable(self):
 
3575
        test = self.ScratchMonkey('test_me')
 
3576
        # LINES is known to be present in os.environ
 
3577
        tests.override_os_environ(test, {'LINES': None})
 
3578
        self.assertTrue('LINES' not in os.environ)
 
3579
        tests.restore_os_environ(test)
 
3580
        self.assertEqual('25', os.environ['LINES'])
 
3581
 
 
3582
 
 
3583
class TestDocTestSuiteIsolation(tests.TestCase):
 
3584
    """Test that `tests.DocTestSuite` isolates doc tests from os.environ.
 
3585
 
 
3586
    Since tests.TestCase alreay provides an isolation from os.environ, we use
 
3587
    the clean environment as a base for testing. To precisely capture the
 
3588
    isolation provided by tests.DocTestSuite, we use doctest.DocTestSuite to
 
3589
    compare against.
 
3590
 
 
3591
    We want to make sure `tests.DocTestSuite` respect `tests.isolated_environ`,
 
3592
    not `os.environ` so each test overrides it to suit its needs.
 
3593
 
 
3594
    """
 
3595
 
 
3596
    def get_doctest_suite_for_string(self, klass, string):
 
3597
        class Finder(doctest.DocTestFinder):
 
3598
 
 
3599
            def find(*args, **kwargs):
 
3600
                test = doctest.DocTestParser().get_doctest(
 
3601
                    string, {}, 'foo', 'foo.py', 0)
 
3602
                return [test]
 
3603
 
 
3604
        suite = klass(test_finder=Finder())
 
3605
        return suite
 
3606
 
 
3607
    def run_doctest_suite_for_string(self, klass, string):
 
3608
        suite = self.get_doctest_suite_for_string(klass, string)
 
3609
        output = StringIO()
 
3610
        result = tests.TextTestResult(output, 0, 1)
 
3611
        suite.run(result)
 
3612
        return result, output
 
3613
 
 
3614
    def assertDocTestStringSucceds(self, klass, string):
 
3615
        result, output = self.run_doctest_suite_for_string(klass, string)
 
3616
        if not result.wasStrictlySuccessful():
 
3617
            self.fail(output.getvalue())
 
3618
 
 
3619
    def assertDocTestStringFails(self, klass, string):
 
3620
        result, output = self.run_doctest_suite_for_string(klass, string)
 
3621
        if result.wasStrictlySuccessful():
 
3622
            self.fail(output.getvalue())
 
3623
 
 
3624
    def test_injected_variable(self):
 
3625
        self.overrideAttr(tests, 'isolated_environ', {'LINES': '42'})
 
3626
        test = """
 
3627
            >>> import os
 
3628
            >>> os.environ['LINES']
 
3629
            '42'
 
3630
            """
 
3631
        # doctest.DocTestSuite fails as it sees '25'
 
3632
        self.assertDocTestStringFails(doctest.DocTestSuite, test)
 
3633
        # tests.DocTestSuite sees '42'
 
3634
        self.assertDocTestStringSucceds(tests.IsolatedDocTestSuite, test)
 
3635
 
 
3636
    def test_deleted_variable(self):
 
3637
        self.overrideAttr(tests, 'isolated_environ', {'LINES': None})
 
3638
        test = """
 
3639
            >>> import os
 
3640
            >>> os.environ.get('LINES')
 
3641
            """
 
3642
        # doctest.DocTestSuite fails as it sees '25'
 
3643
        self.assertDocTestStringFails(doctest.DocTestSuite, test)
 
3644
        # tests.DocTestSuite sees None
 
3645
        self.assertDocTestStringSucceds(tests.IsolatedDocTestSuite, test)
 
3646
 
 
3647
 
 
3648
class TestSelftestExcludePatterns(tests.TestCase):
 
3649
 
 
3650
    def setUp(self):
 
3651
        super(TestSelftestExcludePatterns, self).setUp()
 
3652
        self.overrideAttr(tests, 'test_suite', self.suite_factory)
 
3653
 
 
3654
    def suite_factory(self, keep_only=None, starting_with=None):
 
3655
        """A test suite factory with only a few tests."""
 
3656
        class Test(tests.TestCase):
 
3657
            def id(self):
 
3658
                # We don't need the full class path
 
3659
                return self._testMethodName
 
3660
            def a(self):
 
3661
                pass
 
3662
            def b(self):
 
3663
                pass
 
3664
            def c(self):
 
3665
                pass
 
3666
        return TestUtil.TestSuite([Test("a"), Test("b"), Test("c")])
 
3667
 
 
3668
    def assertTestList(self, expected, *selftest_args):
 
3669
        # We rely on setUp installing the right test suite factory so we can
 
3670
        # test at the command level without loading the whole test suite
 
3671
        out, err = self.run_bzr(('selftest', '--list') + selftest_args)
 
3672
        actual = out.splitlines()
 
3673
        self.assertEqual(expected, actual)
 
3674
 
 
3675
    def test_full_list(self):
 
3676
        self.assertTestList(['a', 'b', 'c'])
 
3677
 
 
3678
    def test_single_exclude(self):
 
3679
        self.assertTestList(['b', 'c'], '-x', 'a')
 
3680
 
 
3681
    def test_mutiple_excludes(self):
 
3682
        self.assertTestList(['c'], '-x', 'a', '-x', 'b')
 
3683
 
 
3684
 
 
3685
class TestCounterHooks(tests.TestCase, SelfTestHelper):
 
3686
 
 
3687
    _test_needs_features = [features.subunit]
 
3688
 
 
3689
    def setUp(self):
 
3690
        super(TestCounterHooks, self).setUp()
 
3691
        class Test(tests.TestCase):
 
3692
 
 
3693
            def setUp(self):
 
3694
                super(Test, self).setUp()
 
3695
                self.hooks = hooks.Hooks()
 
3696
                self.hooks.add_hook('myhook', 'Foo bar blah', (2,4))
 
3697
                self.install_counter_hook(self.hooks, 'myhook')
 
3698
 
 
3699
            def no_hook(self):
 
3700
                pass
 
3701
 
 
3702
            def run_hook_once(self):
 
3703
                for hook in self.hooks['myhook']:
 
3704
                    hook(self)
 
3705
 
 
3706
        self.test_class = Test
 
3707
 
 
3708
    def assertHookCalls(self, expected_calls, test_name):
 
3709
        test = self.test_class(test_name)
 
3710
        result = unittest.TestResult()
 
3711
        test.run(result)
 
3712
        self.assertTrue(hasattr(test, '_counters'))
 
3713
        self.assertTrue('myhook' in test._counters)
 
3714
        self.assertEqual(expected_calls, test._counters['myhook'])
 
3715
 
 
3716
    def test_no_hook(self):
 
3717
        self.assertHookCalls(0, 'no_hook')
 
3718
 
 
3719
    def test_run_hook_once(self):
 
3720
        tt = features.testtools
 
3721
        if tt.module.__version__ < (0, 9, 8):
 
3722
            raise tests.TestSkipped('testtools-0.9.8 required for addDetail')
 
3723
        self.assertHookCalls(1, 'run_hook_once')