/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_selftest.py

  • Committer: Robert Collins
  • Date: 2007-08-22 23:43:36 UTC
  • mto: This revision was merged to the branch mainline in revision 2744.
  • Revision ID: robertc@robertcollins.net-20070822234336-pl9dspu4z6kbt8lg
Tighten the revision store implementation tests surrounding the
None/null: difference. (Robert Collins)

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006, 2007 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
"""Tests for the test framework."""
 
18
 
 
19
import cStringIO
 
20
import os
 
21
from StringIO import StringIO
 
22
import sys
 
23
import time
 
24
import unittest
 
25
import warnings
 
26
 
 
27
import bzrlib
 
28
from bzrlib import (
 
29
    bzrdir,
 
30
    errors,
 
31
    memorytree,
 
32
    osutils,
 
33
    repository,
 
34
    symbol_versioning,
 
35
    )
 
36
from bzrlib.progress import _BaseProgressBar
 
37
from bzrlib.repofmt import weaverepo
 
38
from bzrlib.symbol_versioning import (
 
39
        zero_ten,
 
40
        zero_eleven,
 
41
        )
 
42
from bzrlib.tests import (
 
43
                          ChrootedTestCase,
 
44
                          ExtendedTestResult,
 
45
                          Feature,
 
46
                          KnownFailure,
 
47
                          TestCase,
 
48
                          TestCaseInTempDir,
 
49
                          TestCaseWithMemoryTransport,
 
50
                          TestCaseWithTransport,
 
51
                          TestSkipped,
 
52
                          TestSuite,
 
53
                          TestUtil,
 
54
                          TextTestRunner,
 
55
                          UnavailableFeature,
 
56
                          iter_suite_tests,
 
57
                          filter_suite_by_re,
 
58
                          sort_suite_by_re,
 
59
                          test_lsprof,
 
60
                          test_suite,
 
61
                          )
 
62
from bzrlib.tests.test_sftp_transport import TestCaseWithSFTPServer
 
63
from bzrlib.tests.TestUtil import _load_module_by_name
 
64
from bzrlib.trace import note
 
65
from bzrlib.transport.memory import MemoryServer, MemoryTransport
 
66
from bzrlib.version import _get_bzr_source_tree
 
67
 
 
68
 
 
69
class SelftestTests(TestCase):
 
70
 
 
71
    def test_import_tests(self):
 
72
        mod = _load_module_by_name('bzrlib.tests.test_selftest')
 
73
        self.assertEqual(mod.SelftestTests, SelftestTests)
 
74
 
 
75
    def test_import_test_failure(self):
 
76
        self.assertRaises(ImportError,
 
77
                          _load_module_by_name,
 
78
                          'bzrlib.no-name-yet')
 
79
 
 
80
class MetaTestLog(TestCase):
 
81
 
 
82
    def test_logging(self):
 
83
        """Test logs are captured when a test fails."""
 
84
        self.log('a test message')
 
85
        self._log_file.flush()
 
86
        self.assertContainsRe(self._get_log(keep_log_file=True),
 
87
                              'a test message\n')
 
88
 
 
89
 
 
90
class TestTreeShape(TestCaseInTempDir):
 
91
 
 
92
    def test_unicode_paths(self):
 
93
        filename = u'hell\u00d8'
 
94
        try:
 
95
            self.build_tree_contents([(filename, 'contents of hello')])
 
96
        except UnicodeEncodeError:
 
97
            raise TestSkipped("can't build unicode working tree in "
 
98
                "filesystem encoding %s" % sys.getfilesystemencoding())
 
99
        self.failUnlessExists(filename)
 
100
 
 
101
 
 
102
class TestTransportProviderAdapter(TestCase):
 
103
    """A group of tests that test the transport implementation adaption core.
 
104
 
 
105
    This is a meta test that the tests are applied to all available 
 
106
    transports.
 
107
 
 
108
    This will be generalised in the future which is why it is in this 
 
109
    test file even though it is specific to transport tests at the moment.
 
110
    """
 
111
 
 
112
    def test_get_transport_permutations(self):
 
113
        # this checks that we the module get_test_permutations call
 
114
        # is made by the adapter get_transport_test_permitations method.
 
115
        class MockModule(object):
 
116
            def get_test_permutations(self):
 
117
                return sample_permutation
 
118
        sample_permutation = [(1,2), (3,4)]
 
119
        from bzrlib.tests.test_transport_implementations \
 
120
            import TransportTestProviderAdapter
 
121
        adapter = TransportTestProviderAdapter()
 
122
        self.assertEqual(sample_permutation,
 
123
                         adapter.get_transport_test_permutations(MockModule()))
 
124
 
 
125
    def test_adapter_checks_all_modules(self):
 
126
        # this checks that the adapter returns as many permurtations as
 
127
        # there are in all the registered# transport modules for there
 
128
        # - we assume if this matches its probably doing the right thing
 
129
        # especially in combination with the tests for setting the right
 
130
        # classes below.
 
131
        from bzrlib.tests.test_transport_implementations \
 
132
            import TransportTestProviderAdapter
 
133
        from bzrlib.transport import _get_transport_modules
 
134
        modules = _get_transport_modules()
 
135
        permutation_count = 0
 
136
        for module in modules:
 
137
            try:
 
138
                permutation_count += len(reduce(getattr, 
 
139
                    (module + ".get_test_permutations").split('.')[1:],
 
140
                     __import__(module))())
 
141
            except errors.DependencyNotPresent:
 
142
                pass
 
143
        input_test = TestTransportProviderAdapter(
 
144
            "test_adapter_sets_transport_class")
 
145
        adapter = TransportTestProviderAdapter()
 
146
        self.assertEqual(permutation_count,
 
147
                         len(list(iter(adapter.adapt(input_test)))))
 
148
 
 
149
    def test_adapter_sets_transport_class(self):
 
150
        # Check that the test adapter inserts a transport and server into the
 
151
        # generated test.
 
152
        #
 
153
        # This test used to know about all the possible transports and the
 
154
        # order they were returned but that seems overly brittle (mbp
 
155
        # 20060307)
 
156
        from bzrlib.tests.test_transport_implementations \
 
157
            import TransportTestProviderAdapter
 
158
        scenarios = TransportTestProviderAdapter().scenarios
 
159
        # there are at least that many builtin transports
 
160
        self.assertTrue(len(scenarios) > 6)
 
161
        one_scenario = scenarios[0]
 
162
        self.assertIsInstance(one_scenario[0], str)
 
163
        self.assertTrue(issubclass(one_scenario[1]["transport_class"],
 
164
                                   bzrlib.transport.Transport))
 
165
        self.assertTrue(issubclass(one_scenario[1]["transport_server"],
 
166
                                   bzrlib.transport.Server))
 
167
 
 
168
 
 
169
class TestBranchProviderAdapter(TestCase):
 
170
    """A group of tests that test the branch implementation test adapter."""
 
171
 
 
172
    def test_constructor(self):
 
173
        # check that constructor parameters are passed through to the adapted
 
174
        # test.
 
175
        from bzrlib.tests.branch_implementations import BranchTestProviderAdapter
 
176
        server1 = "a"
 
177
        server2 = "b"
 
178
        formats = [("c", "C"), ("d", "D")]
 
179
        adapter = BranchTestProviderAdapter(server1, server2, formats)
 
180
        self.assertEqual(2, len(adapter.scenarios))
 
181
        self.assertEqual([
 
182
            ('str',
 
183
             {'branch_format': 'c',
 
184
              'bzrdir_format': 'C',
 
185
              'transport_readonly_server': 'b',
 
186
              'transport_server': 'a'}),
 
187
            ('str',
 
188
             {'branch_format': 'd',
 
189
              'bzrdir_format': 'D',
 
190
              'transport_readonly_server': 'b',
 
191
              'transport_server': 'a'})],
 
192
            adapter.scenarios)
 
193
 
 
194
 
 
195
class TestBzrDirProviderAdapter(TestCase):
 
196
    """A group of tests that test the bzr dir implementation test adapter."""
 
197
 
 
198
    def test_adapted_tests(self):
 
199
        # check that constructor parameters are passed through to the adapted
 
200
        # test.
 
201
        from bzrlib.tests.bzrdir_implementations import BzrDirTestProviderAdapter
 
202
        vfs_factory = "v"
 
203
        server1 = "a"
 
204
        server2 = "b"
 
205
        formats = ["c", "d"]
 
206
        adapter = BzrDirTestProviderAdapter(vfs_factory,
 
207
            server1, server2, formats)
 
208
        self.assertEqual([
 
209
            ('str',
 
210
             {'bzrdir_format': 'c',
 
211
              'transport_readonly_server': 'b',
 
212
              'transport_server': 'a',
 
213
              'vfs_transport_factory': 'v'}),
 
214
            ('str',
 
215
             {'bzrdir_format': 'd',
 
216
              'transport_readonly_server': 'b',
 
217
              'transport_server': 'a',
 
218
              'vfs_transport_factory': 'v'})],
 
219
            adapter.scenarios)
 
220
 
 
221
 
 
222
class TestRepositoryProviderAdapter(TestCase):
 
223
    """A group of tests that test the repository implementation test adapter."""
 
224
 
 
225
    def test_constructor(self):
 
226
        # check that constructor parameters are passed through to the
 
227
        # scenarios.
 
228
        from bzrlib.tests.repository_implementations import RepositoryTestProviderAdapter
 
229
        server1 = "a"
 
230
        server2 = "b"
 
231
        formats = [("c", "C"), ("d", "D")]
 
232
        adapter = RepositoryTestProviderAdapter(server1, server2, formats)
 
233
        self.assertEqual([
 
234
            ('str',
 
235
             {'bzrdir_format': 'C',
 
236
              'repository_format': 'c',
 
237
              'transport_readonly_server': 'b',
 
238
              'transport_server': 'a'}),
 
239
            ('str',
 
240
             {'bzrdir_format': 'D',
 
241
              'repository_format': 'd',
 
242
              'transport_readonly_server': 'b',
 
243
              'transport_server': 'a'})],
 
244
            adapter.scenarios)
 
245
 
 
246
    def test_setting_vfs_transport(self):
 
247
        """The vfs_transport_factory can be set optionally."""
 
248
        from bzrlib.tests.repository_implementations import RepositoryTestProviderAdapter
 
249
        formats = [("a", "b"), ("c", "d")]
 
250
        adapter = RepositoryTestProviderAdapter(None, None, formats,
 
251
            vfs_transport_factory="vfs")
 
252
        self.assertEqual([
 
253
            ('str',
 
254
             {'bzrdir_format': 'b',
 
255
              'repository_format': 'a',
 
256
              'transport_readonly_server': None,
 
257
              'transport_server': None,
 
258
              'vfs_transport_factory': 'vfs'}),
 
259
            ('str',
 
260
             {'bzrdir_format': 'd',
 
261
              'repository_format': 'c',
 
262
              'transport_readonly_server': None,
 
263
              'transport_server': None,
 
264
              'vfs_transport_factory': 'vfs'})],
 
265
            adapter.scenarios)
 
266
 
 
267
    def test_formats_to_scenarios(self):
 
268
        """The adapter can generate all the scenarios needed."""
 
269
        from bzrlib.tests.repository_implementations import RepositoryTestProviderAdapter
 
270
        no_vfs_adapter = RepositoryTestProviderAdapter("server", "readonly",
 
271
            [], None)
 
272
        vfs_adapter = RepositoryTestProviderAdapter("server", "readonly",
 
273
            [], vfs_transport_factory="vfs")
 
274
        # no_vfs generate scenarios without vfs_transport_factor
 
275
        formats = [("c", "C"), (1, "D")]
 
276
        self.assertEqual([
 
277
            ('str',
 
278
             {'bzrdir_format': 'C',
 
279
              'repository_format': 'c',
 
280
              'transport_readonly_server': 'readonly',
 
281
              'transport_server': 'server'}),
 
282
            ('int',
 
283
             {'bzrdir_format': 'D',
 
284
              'repository_format': 1,
 
285
              'transport_readonly_server': 'readonly',
 
286
              'transport_server': 'server'})],
 
287
            no_vfs_adapter.formats_to_scenarios(formats))
 
288
        self.assertEqual([
 
289
            ('str',
 
290
             {'bzrdir_format': 'C',
 
291
              'repository_format': 'c',
 
292
              'transport_readonly_server': 'readonly',
 
293
              'transport_server': 'server',
 
294
              'vfs_transport_factory': 'vfs'}),
 
295
            ('int',
 
296
             {'bzrdir_format': 'D',
 
297
              'repository_format': 1,
 
298
              'transport_readonly_server': 'readonly',
 
299
              'transport_server': 'server',
 
300
              'vfs_transport_factory': 'vfs'})],
 
301
            vfs_adapter.formats_to_scenarios(formats))
 
302
 
 
303
 
 
304
class TestTestScenarioApplier(TestCase):
 
305
    """Tests for the test adaption facilities."""
 
306
 
 
307
    def test_adapt_applies_scenarios(self):
 
308
        from bzrlib.tests.repository_implementations import TestScenarioApplier
 
309
        input_test = TestTestScenarioApplier("test_adapt_test_to_scenario")
 
310
        adapter = TestScenarioApplier()
 
311
        adapter.scenarios = [("1", "dict"), ("2", "settings")]
 
312
        calls = []
 
313
        def capture_call(test, scenario):
 
314
            calls.append((test, scenario))
 
315
            return test
 
316
        adapter.adapt_test_to_scenario = capture_call
 
317
        adapter.adapt(input_test)
 
318
        self.assertEqual([(input_test, ("1", "dict")),
 
319
            (input_test, ("2", "settings"))], calls)
 
320
 
 
321
    def test_adapt_test_to_scenario(self):
 
322
        from bzrlib.tests.repository_implementations import TestScenarioApplier
 
323
        input_test = TestTestScenarioApplier("test_adapt_test_to_scenario")
 
324
        adapter = TestScenarioApplier()
 
325
        # setup two adapted tests
 
326
        adapted_test1 = adapter.adapt_test_to_scenario(input_test,
 
327
            ("new id",
 
328
            {"bzrdir_format":"bzr_format",
 
329
             "repository_format":"repo_fmt",
 
330
             "transport_server":"transport_server",
 
331
             "transport_readonly_server":"readonly-server"}))
 
332
        adapted_test2 = adapter.adapt_test_to_scenario(input_test,
 
333
            ("new id 2", {"bzrdir_format":None}))
 
334
        # input_test should have been altered.
 
335
        self.assertRaises(AttributeError, getattr, input_test, "bzrdir_format")
 
336
        # the new tests are mutually incompatible, ensuring it has 
 
337
        # made new ones, and unspecified elements in the scenario
 
338
        # should not have been altered.
 
339
        self.assertEqual("bzr_format", adapted_test1.bzrdir_format)
 
340
        self.assertEqual("repo_fmt", adapted_test1.repository_format)
 
341
        self.assertEqual("transport_server", adapted_test1.transport_server)
 
342
        self.assertEqual("readonly-server",
 
343
            adapted_test1.transport_readonly_server)
 
344
        self.assertEqual(
 
345
            "bzrlib.tests.test_selftest.TestTestScenarioApplier."
 
346
            "test_adapt_test_to_scenario(new id)",
 
347
            adapted_test1.id())
 
348
        self.assertEqual(None, adapted_test2.bzrdir_format)
 
349
        self.assertEqual(
 
350
            "bzrlib.tests.test_selftest.TestTestScenarioApplier."
 
351
            "test_adapt_test_to_scenario(new id 2)",
 
352
            adapted_test2.id())
 
353
 
 
354
 
 
355
class TestInterRepositoryProviderAdapter(TestCase):
 
356
    """A group of tests that test the InterRepository test adapter."""
 
357
 
 
358
    def test_adapted_tests(self):
 
359
        # check that constructor parameters are passed through to the adapted
 
360
        # test.
 
361
        from bzrlib.tests.interrepository_implementations import \
 
362
            InterRepositoryTestProviderAdapter
 
363
        server1 = "a"
 
364
        server2 = "b"
 
365
        formats = [(str, "C1", "C2"), (int, "D1", "D2")]
 
366
        adapter = InterRepositoryTestProviderAdapter(server1, server2, formats)
 
367
        self.assertEqual([
 
368
            ('str',
 
369
             {'interrepo_class': str,
 
370
              'repository_format': 'C1',
 
371
              'repository_format_to': 'C2',
 
372
              'transport_readonly_server': 'b',
 
373
              'transport_server': 'a'}),
 
374
            ('int',
 
375
             {'interrepo_class': int,
 
376
              'repository_format': 'D1',
 
377
              'repository_format_to': 'D2',
 
378
              'transport_readonly_server': 'b',
 
379
              'transport_server': 'a'})],
 
380
            adapter.formats_to_scenarios(formats))
 
381
 
 
382
 
 
383
class TestInterVersionedFileProviderAdapter(TestCase):
 
384
    """A group of tests that test the InterVersionedFile test adapter."""
 
385
 
 
386
    def test_scenarios(self):
 
387
        # check that constructor parameters are passed through to the adapted
 
388
        # test.
 
389
        from bzrlib.tests.interversionedfile_implementations \
 
390
            import InterVersionedFileTestProviderAdapter
 
391
        server1 = "a"
 
392
        server2 = "b"
 
393
        formats = [(str, "C1", "C2"), (int, "D1", "D2")]
 
394
        adapter = InterVersionedFileTestProviderAdapter(server1, server2, formats)
 
395
        self.assertEqual([
 
396
            ('str',
 
397
             {'interversionedfile_class':str,
 
398
              'transport_readonly_server': 'b',
 
399
              'transport_server': 'a',
 
400
              'versionedfile_factory': 'C1',
 
401
              'versionedfile_factory_to': 'C2'}),
 
402
            ('int',
 
403
             {'interversionedfile_class': int,
 
404
              'transport_readonly_server': 'b',
 
405
              'transport_server': 'a',
 
406
              'versionedfile_factory': 'D1',
 
407
              'versionedfile_factory_to': 'D2'})],
 
408
            adapter.scenarios)
 
409
 
 
410
 
 
411
class TestRevisionStoreProviderAdapter(TestCase):
 
412
    """A group of tests that test the RevisionStore test adapter."""
 
413
 
 
414
    def test_scenarios(self):
 
415
        # check that constructor parameters are passed through to the adapted
 
416
        # test.
 
417
        from bzrlib.tests.revisionstore_implementations \
 
418
            import RevisionStoreTestProviderAdapter
 
419
        # revision stores need a store factory - i.e. RevisionKnit
 
420
        #, a readonly and rw transport 
 
421
        # transport servers:
 
422
        server1 = "a"
 
423
        server2 = "b"
 
424
        store_factories = ["c", "d"]
 
425
        adapter = RevisionStoreTestProviderAdapter(server1, server2, store_factories)
 
426
        self.assertEqual([
 
427
            ('c',
 
428
             {'store_factory': 'c',
 
429
              'transport_readonly_server': 'b',
 
430
              'transport_server': 'a'}),
 
431
            ('d',
 
432
             {'store_factory': 'd',
 
433
              'transport_readonly_server': 'b',
 
434
              'transport_server': 'a'})],
 
435
            adapter.scenarios)
 
436
 
 
437
 
 
438
class TestWorkingTreeProviderAdapter(TestCase):
 
439
    """A group of tests that test the workingtree implementation test adapter."""
 
440
 
 
441
    def test_scenarios(self):
 
442
        # check that constructor parameters are passed through to the adapted
 
443
        # test.
 
444
        from bzrlib.tests.workingtree_implementations \
 
445
            import WorkingTreeTestProviderAdapter
 
446
        server1 = "a"
 
447
        server2 = "b"
 
448
        formats = [("c", "C"), ("d", "D")]
 
449
        adapter = WorkingTreeTestProviderAdapter(server1, server2, formats)
 
450
        self.assertEqual([
 
451
            ('str',
 
452
             {'bzrdir_format': 'C',
 
453
              'transport_readonly_server': 'b',
 
454
              'transport_server': 'a',
 
455
              'workingtree_format': 'c'}),
 
456
            ('str',
 
457
             {'bzrdir_format': 'D',
 
458
              'transport_readonly_server': 'b',
 
459
              'transport_server': 'a',
 
460
              'workingtree_format': 'd'})],
 
461
            adapter.scenarios)
 
462
 
 
463
 
 
464
class TestTreeProviderAdapter(TestCase):
 
465
    """Test the setup of tree_implementation tests."""
 
466
 
 
467
    def test_adapted_tests(self):
 
468
        # the tree implementation adapter is meant to setup one instance for
 
469
        # each working tree format, and one additional instance that will
 
470
        # use the default wt format, but create a revision tree for the tests.
 
471
        # this means that the wt ones should have the workingtree_to_test_tree
 
472
        # attribute set to 'return_parameter' and the revision one set to
 
473
        # revision_tree_from_workingtree.
 
474
 
 
475
        from bzrlib.tests.tree_implementations import (
 
476
            TreeTestProviderAdapter,
 
477
            return_parameter,
 
478
            revision_tree_from_workingtree
 
479
            )
 
480
        from bzrlib.workingtree import WorkingTreeFormat, WorkingTreeFormat3
 
481
        input_test = TestTreeProviderAdapter(
 
482
            "test_adapted_tests")
 
483
        server1 = "a"
 
484
        server2 = "b"
 
485
        formats = [("c", "C"), ("d", "D")]
 
486
        adapter = TreeTestProviderAdapter(server1, server2, formats)
 
487
        suite = adapter.adapt(input_test)
 
488
        tests = list(iter(suite))
 
489
        self.assertEqual(4, len(tests))
 
490
        # this must match the default format setp up in
 
491
        # TreeTestProviderAdapter.adapt
 
492
        default_format = WorkingTreeFormat3
 
493
        self.assertEqual(tests[0].workingtree_format, formats[0][0])
 
494
        self.assertEqual(tests[0].bzrdir_format, formats[0][1])
 
495
        self.assertEqual(tests[0].transport_server, server1)
 
496
        self.assertEqual(tests[0].transport_readonly_server, server2)
 
497
        self.assertEqual(tests[0].workingtree_to_test_tree, return_parameter)
 
498
        self.assertEqual(tests[1].workingtree_format, formats[1][0])
 
499
        self.assertEqual(tests[1].bzrdir_format, formats[1][1])
 
500
        self.assertEqual(tests[1].transport_server, server1)
 
501
        self.assertEqual(tests[1].transport_readonly_server, server2)
 
502
        self.assertEqual(tests[1].workingtree_to_test_tree, return_parameter)
 
503
        self.assertIsInstance(tests[2].workingtree_format, default_format)
 
504
        #self.assertEqual(tests[2].bzrdir_format,
 
505
        #                 default_format._matchingbzrdir)
 
506
        self.assertEqual(tests[2].transport_server, server1)
 
507
        self.assertEqual(tests[2].transport_readonly_server, server2)
 
508
        self.assertEqual(tests[2].workingtree_to_test_tree,
 
509
            revision_tree_from_workingtree)
 
510
 
 
511
 
 
512
class TestInterTreeProviderAdapter(TestCase):
 
513
    """A group of tests that test the InterTreeTestAdapter."""
 
514
 
 
515
    def test_adapted_tests(self):
 
516
        # check that constructor parameters are passed through to the adapted
 
517
        # test.
 
518
        # for InterTree tests we want the machinery to bring up two trees in
 
519
        # each instance: the base one, and the one we are interacting with.
 
520
        # because each optimiser can be direction specific, we need to test
 
521
        # each optimiser in its chosen direction.
 
522
        # unlike the TestProviderAdapter we dont want to automatically add a
 
523
        # parameterised one for WorkingTree - the optimisers will tell us what
 
524
        # ones to add.
 
525
        from bzrlib.tests.tree_implementations import (
 
526
            return_parameter,
 
527
            revision_tree_from_workingtree
 
528
            )
 
529
        from bzrlib.tests.intertree_implementations import (
 
530
            InterTreeTestProviderAdapter,
 
531
            )
 
532
        from bzrlib.workingtree import WorkingTreeFormat2, WorkingTreeFormat3
 
533
        input_test = TestInterTreeProviderAdapter(
 
534
            "test_adapted_tests")
 
535
        server1 = "a"
 
536
        server2 = "b"
 
537
        format1 = WorkingTreeFormat2()
 
538
        format2 = WorkingTreeFormat3()
 
539
        formats = [(str, format1, format2, "converter1"),
 
540
            (int, format2, format1, "converter2")]
 
541
        adapter = InterTreeTestProviderAdapter(server1, server2, formats)
 
542
        suite = adapter.adapt(input_test)
 
543
        tests = list(iter(suite))
 
544
        self.assertEqual(2, len(tests))
 
545
        self.assertEqual(tests[0].intertree_class, formats[0][0])
 
546
        self.assertEqual(tests[0].workingtree_format, formats[0][1])
 
547
        self.assertEqual(tests[0].workingtree_format_to, formats[0][2])
 
548
        self.assertEqual(tests[0].mutable_trees_to_test_trees, formats[0][3])
 
549
        self.assertEqual(tests[0].workingtree_to_test_tree, return_parameter)
 
550
        self.assertEqual(tests[0].transport_server, server1)
 
551
        self.assertEqual(tests[0].transport_readonly_server, server2)
 
552
        self.assertEqual(tests[1].intertree_class, formats[1][0])
 
553
        self.assertEqual(tests[1].workingtree_format, formats[1][1])
 
554
        self.assertEqual(tests[1].workingtree_format_to, formats[1][2])
 
555
        self.assertEqual(tests[1].mutable_trees_to_test_trees, formats[1][3])
 
556
        self.assertEqual(tests[1].workingtree_to_test_tree, return_parameter)
 
557
        self.assertEqual(tests[1].transport_server, server1)
 
558
        self.assertEqual(tests[1].transport_readonly_server, server2)
 
559
 
 
560
 
 
561
class TestTestCaseInTempDir(TestCaseInTempDir):
 
562
 
 
563
    def test_home_is_not_working(self):
 
564
        self.assertNotEqual(self.test_dir, self.test_home_dir)
 
565
        cwd = osutils.getcwd()
 
566
        self.assertEqual(self.test_dir, cwd)
 
567
        self.assertEqual(self.test_home_dir, os.environ['HOME'])
 
568
 
 
569
 
 
570
class TestTestCaseWithMemoryTransport(TestCaseWithMemoryTransport):
 
571
 
 
572
    def test_home_is_non_existant_dir_under_root(self):
 
573
        """The test_home_dir for TestCaseWithMemoryTransport is missing.
 
574
 
 
575
        This is because TestCaseWithMemoryTransport is for tests that do not
 
576
        need any disk resources: they should be hooked into bzrlib in such a 
 
577
        way that no global settings are being changed by the test (only a 
 
578
        few tests should need to do that), and having a missing dir as home is
 
579
        an effective way to ensure that this is the case.
 
580
        """
 
581
        self.assertEqual(self.TEST_ROOT + "/MemoryTransportMissingHomeDir",
 
582
            self.test_home_dir)
 
583
        self.assertEqual(self.test_home_dir, os.environ['HOME'])
 
584
        
 
585
    def test_cwd_is_TEST_ROOT(self):
 
586
        self.assertEqual(self.test_dir, self.TEST_ROOT)
 
587
        cwd = osutils.getcwd()
 
588
        self.assertEqual(self.test_dir, cwd)
 
589
 
 
590
    def test_make_branch_and_memory_tree(self):
 
591
        """In TestCaseWithMemoryTransport we should not make the branch on disk.
 
592
 
 
593
        This is hard to comprehensively robustly test, so we settle for making
 
594
        a branch and checking no directory was created at its relpath.
 
595
        """
 
596
        tree = self.make_branch_and_memory_tree('dir')
 
597
        # Guard against regression into MemoryTransport leaking
 
598
        # files to disk instead of keeping them in memory.
 
599
        self.failIf(osutils.lexists('dir'))
 
600
        self.assertIsInstance(tree, memorytree.MemoryTree)
 
601
 
 
602
    def test_make_branch_and_memory_tree_with_format(self):
 
603
        """make_branch_and_memory_tree should accept a format option."""
 
604
        format = bzrdir.BzrDirMetaFormat1()
 
605
        format.repository_format = weaverepo.RepositoryFormat7()
 
606
        tree = self.make_branch_and_memory_tree('dir', format=format)
 
607
        # Guard against regression into MemoryTransport leaking
 
608
        # files to disk instead of keeping them in memory.
 
609
        self.failIf(osutils.lexists('dir'))
 
610
        self.assertIsInstance(tree, memorytree.MemoryTree)
 
611
        self.assertEqual(format.repository_format.__class__,
 
612
            tree.branch.repository._format.__class__)
 
613
 
 
614
 
 
615
class TestTestCaseWithTransport(TestCaseWithTransport):
 
616
    """Tests for the convenience functions TestCaseWithTransport introduces."""
 
617
 
 
618
    def test_get_readonly_url_none(self):
 
619
        from bzrlib.transport import get_transport
 
620
        from bzrlib.transport.memory import MemoryServer
 
621
        from bzrlib.transport.readonly import ReadonlyTransportDecorator
 
622
        self.vfs_transport_factory = MemoryServer
 
623
        self.transport_readonly_server = None
 
624
        # calling get_readonly_transport() constructs a decorator on the url
 
625
        # for the server
 
626
        url = self.get_readonly_url()
 
627
        url2 = self.get_readonly_url('foo/bar')
 
628
        t = get_transport(url)
 
629
        t2 = get_transport(url2)
 
630
        self.failUnless(isinstance(t, ReadonlyTransportDecorator))
 
631
        self.failUnless(isinstance(t2, ReadonlyTransportDecorator))
 
632
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
 
633
 
 
634
    def test_get_readonly_url_http(self):
 
635
        from bzrlib.tests.HttpServer import HttpServer
 
636
        from bzrlib.transport import get_transport
 
637
        from bzrlib.transport.local import LocalURLServer
 
638
        from bzrlib.transport.http import HttpTransportBase
 
639
        self.transport_server = LocalURLServer
 
640
        self.transport_readonly_server = HttpServer
 
641
        # calling get_readonly_transport() gives us a HTTP server instance.
 
642
        url = self.get_readonly_url()
 
643
        url2 = self.get_readonly_url('foo/bar')
 
644
        # the transport returned may be any HttpTransportBase subclass
 
645
        t = get_transport(url)
 
646
        t2 = get_transport(url2)
 
647
        self.failUnless(isinstance(t, HttpTransportBase))
 
648
        self.failUnless(isinstance(t2, HttpTransportBase))
 
649
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
 
650
 
 
651
    def test_is_directory(self):
 
652
        """Test assertIsDirectory assertion"""
 
653
        t = self.get_transport()
 
654
        self.build_tree(['a_dir/', 'a_file'], transport=t)
 
655
        self.assertIsDirectory('a_dir', t)
 
656
        self.assertRaises(AssertionError, self.assertIsDirectory, 'a_file', t)
 
657
        self.assertRaises(AssertionError, self.assertIsDirectory, 'not_here', t)
 
658
 
 
659
 
 
660
class TestTestCaseTransports(TestCaseWithTransport):
 
661
 
 
662
    def setUp(self):
 
663
        super(TestTestCaseTransports, self).setUp()
 
664
        self.vfs_transport_factory = MemoryServer
 
665
 
 
666
    def test_make_bzrdir_preserves_transport(self):
 
667
        t = self.get_transport()
 
668
        result_bzrdir = self.make_bzrdir('subdir')
 
669
        self.assertIsInstance(result_bzrdir.transport, 
 
670
                              MemoryTransport)
 
671
        # should not be on disk, should only be in memory
 
672
        self.failIfExists('subdir')
 
673
 
 
674
 
 
675
class TestChrootedTest(ChrootedTestCase):
 
676
 
 
677
    def test_root_is_root(self):
 
678
        from bzrlib.transport import get_transport
 
679
        t = get_transport(self.get_readonly_url())
 
680
        url = t.base
 
681
        self.assertEqual(url, t.clone('..').base)
 
682
 
 
683
 
 
684
class MockProgress(_BaseProgressBar):
 
685
    """Progress-bar standin that records calls.
 
686
 
 
687
    Useful for testing pb using code.
 
688
    """
 
689
 
 
690
    def __init__(self):
 
691
        _BaseProgressBar.__init__(self)
 
692
        self.calls = []
 
693
 
 
694
    def tick(self):
 
695
        self.calls.append(('tick',))
 
696
 
 
697
    def update(self, msg=None, current=None, total=None):
 
698
        self.calls.append(('update', msg, current, total))
 
699
 
 
700
    def clear(self):
 
701
        self.calls.append(('clear',))
 
702
 
 
703
    def note(self, msg, *args):
 
704
        self.calls.append(('note', msg, args))
 
705
 
 
706
 
 
707
class TestTestResult(TestCase):
 
708
 
 
709
    def check_timing(self, test_case, expected_re):
 
710
        result = bzrlib.tests.TextTestResult(self._log_file,
 
711
                descriptions=0,
 
712
                verbosity=1,
 
713
                )
 
714
        test_case.run(result)
 
715
        timed_string = result._testTimeString(test_case)
 
716
        self.assertContainsRe(timed_string, expected_re)
 
717
 
 
718
    def test_test_reporting(self):
 
719
        class ShortDelayTestCase(TestCase):
 
720
            def test_short_delay(self):
 
721
                time.sleep(0.003)
 
722
            def test_short_benchmark(self):
 
723
                self.time(time.sleep, 0.003)
 
724
        self.check_timing(ShortDelayTestCase('test_short_delay'),
 
725
                          r"^ +[0-9]+ms$")
 
726
        # if a benchmark time is given, we want a x of y style result.
 
727
        self.check_timing(ShortDelayTestCase('test_short_benchmark'),
 
728
                          r"^ +[0-9]+ms/ +[0-9]+ms$")
 
729
 
 
730
    def test_unittest_reporting_unittest_class(self):
 
731
        # getting the time from a non-bzrlib test works ok
 
732
        class ShortDelayTestCase(unittest.TestCase):
 
733
            def test_short_delay(self):
 
734
                time.sleep(0.003)
 
735
        self.check_timing(ShortDelayTestCase('test_short_delay'),
 
736
                          r"^ +[0-9]+ms$")
 
737
        
 
738
    def test_assigned_benchmark_file_stores_date(self):
 
739
        output = StringIO()
 
740
        result = bzrlib.tests.TextTestResult(self._log_file,
 
741
                                        descriptions=0,
 
742
                                        verbosity=1,
 
743
                                        bench_history=output
 
744
                                        )
 
745
        output_string = output.getvalue()
 
746
        # if you are wondering about the regexp please read the comment in
 
747
        # test_bench_history (bzrlib.tests.test_selftest.TestRunner)
 
748
        # XXX: what comment?  -- Andrew Bennetts
 
749
        self.assertContainsRe(output_string, "--date [0-9.]+")
 
750
 
 
751
    def test_benchhistory_records_test_times(self):
 
752
        result_stream = StringIO()
 
753
        result = bzrlib.tests.TextTestResult(
 
754
            self._log_file,
 
755
            descriptions=0,
 
756
            verbosity=1,
 
757
            bench_history=result_stream
 
758
            )
 
759
 
 
760
        # we want profile a call and check that its test duration is recorded
 
761
        # make a new test instance that when run will generate a benchmark
 
762
        example_test_case = TestTestResult("_time_hello_world_encoding")
 
763
        # execute the test, which should succeed and record times
 
764
        example_test_case.run(result)
 
765
        lines = result_stream.getvalue().splitlines()
 
766
        self.assertEqual(2, len(lines))
 
767
        self.assertContainsRe(lines[1],
 
768
            " *[0-9]+ms bzrlib.tests.test_selftest.TestTestResult"
 
769
            "._time_hello_world_encoding")
 
770
 
 
771
    def _time_hello_world_encoding(self):
 
772
        """Profile two sleep calls
 
773
        
 
774
        This is used to exercise the test framework.
 
775
        """
 
776
        self.time(unicode, 'hello', errors='replace')
 
777
        self.time(unicode, 'world', errors='replace')
 
778
 
 
779
    def test_lsprofiling(self):
 
780
        """Verbose test result prints lsprof statistics from test cases."""
 
781
        self.requireFeature(test_lsprof.LSProfFeature)
 
782
        result_stream = StringIO()
 
783
        result = bzrlib.tests.VerboseTestResult(
 
784
            unittest._WritelnDecorator(result_stream),
 
785
            descriptions=0,
 
786
            verbosity=2,
 
787
            )
 
788
        # we want profile a call of some sort and check it is output by
 
789
        # addSuccess. We dont care about addError or addFailure as they
 
790
        # are not that interesting for performance tuning.
 
791
        # make a new test instance that when run will generate a profile
 
792
        example_test_case = TestTestResult("_time_hello_world_encoding")
 
793
        example_test_case._gather_lsprof_in_benchmarks = True
 
794
        # execute the test, which should succeed and record profiles
 
795
        example_test_case.run(result)
 
796
        # lsprofile_something()
 
797
        # if this worked we want 
 
798
        # LSProf output for <built in function unicode> (['hello'], {'errors': 'replace'})
 
799
        #    CallCount    Recursive    Total(ms)   Inline(ms) module:lineno(function)
 
800
        # (the lsprof header)
 
801
        # ... an arbitrary number of lines
 
802
        # and the function call which is time.sleep.
 
803
        #           1        0            ???         ???       ???(sleep) 
 
804
        # and then repeated but with 'world', rather than 'hello'.
 
805
        # this should appear in the output stream of our test result.
 
806
        output = result_stream.getvalue()
 
807
        self.assertContainsRe(output,
 
808
            r"LSProf output for <type 'unicode'>\(\('hello',\), {'errors': 'replace'}\)")
 
809
        self.assertContainsRe(output,
 
810
            r" *CallCount *Recursive *Total\(ms\) *Inline\(ms\) *module:lineno\(function\)\n")
 
811
        self.assertContainsRe(output,
 
812
            r"( +1 +0 +0\.\d+ +0\.\d+ +<method 'disable' of '_lsprof\.Profiler' objects>\n)?")
 
813
        self.assertContainsRe(output,
 
814
            r"LSProf output for <type 'unicode'>\(\('world',\), {'errors': 'replace'}\)\n")
 
815
 
 
816
    def test_known_failure(self):
 
817
        """A KnownFailure being raised should trigger several result actions."""
 
818
        class InstrumentedTestResult(ExtendedTestResult):
 
819
 
 
820
            def report_test_start(self, test): pass
 
821
            def report_known_failure(self, test, err):
 
822
                self._call = test, err
 
823
        result = InstrumentedTestResult(None, None, None, None)
 
824
        def test_function():
 
825
            raise KnownFailure('failed!')
 
826
        test = unittest.FunctionTestCase(test_function)
 
827
        test.run(result)
 
828
        # it should invoke 'report_known_failure'.
 
829
        self.assertEqual(2, len(result._call))
 
830
        self.assertEqual(test, result._call[0])
 
831
        self.assertEqual(KnownFailure, result._call[1][0])
 
832
        self.assertIsInstance(result._call[1][1], KnownFailure)
 
833
        # we dont introspec the traceback, if the rest is ok, it would be
 
834
        # exceptional for it not to be.
 
835
        # it should update the known_failure_count on the object.
 
836
        self.assertEqual(1, result.known_failure_count)
 
837
        # the result should be successful.
 
838
        self.assertTrue(result.wasSuccessful())
 
839
 
 
840
    def test_verbose_report_known_failure(self):
 
841
        # verbose test output formatting
 
842
        result_stream = StringIO()
 
843
        result = bzrlib.tests.VerboseTestResult(
 
844
            unittest._WritelnDecorator(result_stream),
 
845
            descriptions=0,
 
846
            verbosity=2,
 
847
            )
 
848
        test = self.get_passing_test()
 
849
        result.startTest(test)
 
850
        prefix = len(result_stream.getvalue())
 
851
        # the err parameter has the shape:
 
852
        # (class, exception object, traceback)
 
853
        # KnownFailures dont get their tracebacks shown though, so we
 
854
        # can skip that.
 
855
        err = (KnownFailure, KnownFailure('foo'), None)
 
856
        result.report_known_failure(test, err)
 
857
        output = result_stream.getvalue()[prefix:]
 
858
        lines = output.splitlines()
 
859
        self.assertContainsRe(lines[0], r'XFAIL *\d+ms$')
 
860
        self.assertEqual(lines[1], '    foo')
 
861
        self.assertEqual(2, len(lines))
 
862
 
 
863
    def test_text_report_known_failure(self):
 
864
        # text test output formatting
 
865
        pb = MockProgress()
 
866
        result = bzrlib.tests.TextTestResult(
 
867
            None,
 
868
            descriptions=0,
 
869
            verbosity=1,
 
870
            pb=pb,
 
871
            )
 
872
        test = self.get_passing_test()
 
873
        # this seeds the state to handle reporting the test.
 
874
        result.startTest(test)
 
875
        # the err parameter has the shape:
 
876
        # (class, exception object, traceback)
 
877
        # KnownFailures dont get their tracebacks shown though, so we
 
878
        # can skip that.
 
879
        err = (KnownFailure, KnownFailure('foo'), None)
 
880
        result.report_known_failure(test, err)
 
881
        self.assertEqual(
 
882
            [
 
883
            ('update', '[1 in 0s] passing_test', None, None),
 
884
            ('note', 'XFAIL: %s\n%s\n', ('passing_test', err[1]))
 
885
            ],
 
886
            pb.calls)
 
887
        # known_failures should be printed in the summary, so if we run a test
 
888
        # after there are some known failures, the update prefix should match
 
889
        # this.
 
890
        result.known_failure_count = 3
 
891
        test.run(result)
 
892
        self.assertEqual(
 
893
            [
 
894
            ('update', '[2 in 0s, 3 known failures] passing_test', None, None),
 
895
            ],
 
896
            pb.calls[2:])
 
897
 
 
898
    def get_passing_test(self):
 
899
        """Return a test object that can't be run usefully."""
 
900
        def passing_test():
 
901
            pass
 
902
        return unittest.FunctionTestCase(passing_test)
 
903
 
 
904
    def test_add_not_supported(self):
 
905
        """Test the behaviour of invoking addNotSupported."""
 
906
        class InstrumentedTestResult(ExtendedTestResult):
 
907
            def report_test_start(self, test): pass
 
908
            def report_unsupported(self, test, feature):
 
909
                self._call = test, feature
 
910
        result = InstrumentedTestResult(None, None, None, None)
 
911
        test = SampleTestCase('_test_pass')
 
912
        feature = Feature()
 
913
        result.startTest(test)
 
914
        result.addNotSupported(test, feature)
 
915
        # it should invoke 'report_unsupported'.
 
916
        self.assertEqual(2, len(result._call))
 
917
        self.assertEqual(test, result._call[0])
 
918
        self.assertEqual(feature, result._call[1])
 
919
        # the result should be successful.
 
920
        self.assertTrue(result.wasSuccessful())
 
921
        # it should record the test against a count of tests not run due to
 
922
        # this feature.
 
923
        self.assertEqual(1, result.unsupported['Feature'])
 
924
        # and invoking it again should increment that counter
 
925
        result.addNotSupported(test, feature)
 
926
        self.assertEqual(2, result.unsupported['Feature'])
 
927
 
 
928
    def test_verbose_report_unsupported(self):
 
929
        # verbose test output formatting
 
930
        result_stream = StringIO()
 
931
        result = bzrlib.tests.VerboseTestResult(
 
932
            unittest._WritelnDecorator(result_stream),
 
933
            descriptions=0,
 
934
            verbosity=2,
 
935
            )
 
936
        test = self.get_passing_test()
 
937
        feature = Feature()
 
938
        result.startTest(test)
 
939
        prefix = len(result_stream.getvalue())
 
940
        result.report_unsupported(test, feature)
 
941
        output = result_stream.getvalue()[prefix:]
 
942
        lines = output.splitlines()
 
943
        self.assertEqual(lines, ['NODEP                   0ms', "    The feature 'Feature' is not available."])
 
944
    
 
945
    def test_text_report_unsupported(self):
 
946
        # text test output formatting
 
947
        pb = MockProgress()
 
948
        result = bzrlib.tests.TextTestResult(
 
949
            None,
 
950
            descriptions=0,
 
951
            verbosity=1,
 
952
            pb=pb,
 
953
            )
 
954
        test = self.get_passing_test()
 
955
        feature = Feature()
 
956
        # this seeds the state to handle reporting the test.
 
957
        result.startTest(test)
 
958
        result.report_unsupported(test, feature)
 
959
        # no output on unsupported features
 
960
        self.assertEqual(
 
961
            [('update', '[1 in 0s] passing_test', None, None)
 
962
            ],
 
963
            pb.calls)
 
964
        # the number of missing features should be printed in the progress
 
965
        # summary, so check for that.
 
966
        result.unsupported = {'foo':0, 'bar':0}
 
967
        test.run(result)
 
968
        self.assertEqual(
 
969
            [
 
970
            ('update', '[2 in 0s, 2 missing features] passing_test', None, None),
 
971
            ],
 
972
            pb.calls[1:])
 
973
    
 
974
    def test_unavailable_exception(self):
 
975
        """An UnavailableFeature being raised should invoke addNotSupported."""
 
976
        class InstrumentedTestResult(ExtendedTestResult):
 
977
 
 
978
            def report_test_start(self, test): pass
 
979
            def addNotSupported(self, test, feature):
 
980
                self._call = test, feature
 
981
        result = InstrumentedTestResult(None, None, None, None)
 
982
        feature = Feature()
 
983
        def test_function():
 
984
            raise UnavailableFeature(feature)
 
985
        test = unittest.FunctionTestCase(test_function)
 
986
        test.run(result)
 
987
        # it should invoke 'addNotSupported'.
 
988
        self.assertEqual(2, len(result._call))
 
989
        self.assertEqual(test, result._call[0])
 
990
        self.assertEqual(feature, result._call[1])
 
991
        # and not count as an error
 
992
        self.assertEqual(0, result.error_count)
 
993
 
 
994
    def test_strict_with_unsupported_feature(self):
 
995
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
 
996
                                             verbosity=1)
 
997
        test = self.get_passing_test()
 
998
        feature = "Unsupported Feature"
 
999
        result.addNotSupported(test, feature)
 
1000
        self.assertFalse(result.wasStrictlySuccessful())
 
1001
        self.assertEqual(None, result._extractBenchmarkTime(test))
 
1002
 
 
1003
    def test_strict_with_known_failure(self):
 
1004
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
 
1005
                                             verbosity=1)
 
1006
        test = self.get_passing_test()
 
1007
        err = (KnownFailure, KnownFailure('foo'), None)
 
1008
        result._addKnownFailure(test, err)
 
1009
        self.assertFalse(result.wasStrictlySuccessful())
 
1010
        self.assertEqual(None, result._extractBenchmarkTime(test))
 
1011
 
 
1012
    def test_strict_with_success(self):
 
1013
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
 
1014
                                             verbosity=1)
 
1015
        test = self.get_passing_test()
 
1016
        result.addSuccess(test)
 
1017
        self.assertTrue(result.wasStrictlySuccessful())
 
1018
        self.assertEqual(None, result._extractBenchmarkTime(test))
 
1019
 
 
1020
 
 
1021
class TestRunner(TestCase):
 
1022
 
 
1023
    def dummy_test(self):
 
1024
        pass
 
1025
 
 
1026
    def run_test_runner(self, testrunner, test):
 
1027
        """Run suite in testrunner, saving global state and restoring it.
 
1028
 
 
1029
        This current saves and restores:
 
1030
        TestCaseInTempDir.TEST_ROOT
 
1031
        
 
1032
        There should be no tests in this file that use bzrlib.tests.TextTestRunner
 
1033
        without using this convenience method, because of our use of global state.
 
1034
        """
 
1035
        old_root = TestCaseInTempDir.TEST_ROOT
 
1036
        try:
 
1037
            TestCaseInTempDir.TEST_ROOT = None
 
1038
            return testrunner.run(test)
 
1039
        finally:
 
1040
            TestCaseInTempDir.TEST_ROOT = old_root
 
1041
 
 
1042
    def test_known_failure_failed_run(self):
 
1043
        # run a test that generates a known failure which should be printed in
 
1044
        # the final output when real failures occur.
 
1045
        def known_failure_test():
 
1046
            raise KnownFailure('failed')
 
1047
        test = unittest.TestSuite()
 
1048
        test.addTest(unittest.FunctionTestCase(known_failure_test))
 
1049
        def failing_test():
 
1050
            raise AssertionError('foo')
 
1051
        test.addTest(unittest.FunctionTestCase(failing_test))
 
1052
        stream = StringIO()
 
1053
        runner = TextTestRunner(stream=stream)
 
1054
        result = self.run_test_runner(runner, test)
 
1055
        lines = stream.getvalue().splitlines()
 
1056
        self.assertEqual([
 
1057
            '',
 
1058
            '======================================================================',
 
1059
            'FAIL: unittest.FunctionTestCase (failing_test)',
 
1060
            '----------------------------------------------------------------------',
 
1061
            'Traceback (most recent call last):',
 
1062
            '    raise AssertionError(\'foo\')',
 
1063
            'AssertionError: foo',
 
1064
            '',
 
1065
            '----------------------------------------------------------------------',
 
1066
            '',
 
1067
            'FAILED (failures=1, known_failure_count=1)'],
 
1068
            lines[0:5] + lines[6:10] + lines[11:])
 
1069
 
 
1070
    def test_known_failure_ok_run(self):
 
1071
        # run a test that generates a known failure which should be printed in the final output.
 
1072
        def known_failure_test():
 
1073
            raise KnownFailure('failed')
 
1074
        test = unittest.FunctionTestCase(known_failure_test)
 
1075
        stream = StringIO()
 
1076
        runner = TextTestRunner(stream=stream)
 
1077
        result = self.run_test_runner(runner, test)
 
1078
        self.assertContainsRe(stream.getvalue(),
 
1079
            '\n'
 
1080
            '-*\n'
 
1081
            'Ran 1 test in .*\n'
 
1082
            '\n'
 
1083
            'OK \\(known_failures=1\\)\n')
 
1084
 
 
1085
    def test_skipped_test(self):
 
1086
        # run a test that is skipped, and check the suite as a whole still
 
1087
        # succeeds.
 
1088
        # skipping_test must be hidden in here so it's not run as a real test
 
1089
        def skipping_test():
 
1090
            raise TestSkipped('test intentionally skipped')
 
1091
 
 
1092
        runner = TextTestRunner(stream=self._log_file)
 
1093
        test = unittest.FunctionTestCase(skipping_test)
 
1094
        result = self.run_test_runner(runner, test)
 
1095
        self.assertTrue(result.wasSuccessful())
 
1096
 
 
1097
    def test_skipped_from_setup(self):
 
1098
        class SkippedSetupTest(TestCase):
 
1099
 
 
1100
            def setUp(self):
 
1101
                self.counter = 1
 
1102
                self.addCleanup(self.cleanup)
 
1103
                raise TestSkipped('skipped setup')
 
1104
 
 
1105
            def test_skip(self):
 
1106
                self.fail('test reached')
 
1107
 
 
1108
            def cleanup(self):
 
1109
                self.counter -= 1
 
1110
 
 
1111
        runner = TextTestRunner(stream=self._log_file)
 
1112
        test = SkippedSetupTest('test_skip')
 
1113
        result = self.run_test_runner(runner, test)
 
1114
        self.assertTrue(result.wasSuccessful())
 
1115
        # Check if cleanup was called the right number of times.
 
1116
        self.assertEqual(0, test.counter)
 
1117
 
 
1118
    def test_skipped_from_test(self):
 
1119
        class SkippedTest(TestCase):
 
1120
 
 
1121
            def setUp(self):
 
1122
                self.counter = 1
 
1123
                self.addCleanup(self.cleanup)
 
1124
 
 
1125
            def test_skip(self):
 
1126
                raise TestSkipped('skipped test')
 
1127
 
 
1128
            def cleanup(self):
 
1129
                self.counter -= 1
 
1130
 
 
1131
        runner = TextTestRunner(stream=self._log_file)
 
1132
        test = SkippedTest('test_skip')
 
1133
        result = self.run_test_runner(runner, test)
 
1134
        self.assertTrue(result.wasSuccessful())
 
1135
        # Check if cleanup was called the right number of times.
 
1136
        self.assertEqual(0, test.counter)
 
1137
 
 
1138
    def test_unsupported_features_listed(self):
 
1139
        """When unsupported features are encountered they are detailed."""
 
1140
        class Feature1(Feature):
 
1141
            def _probe(self): return False
 
1142
        class Feature2(Feature):
 
1143
            def _probe(self): return False
 
1144
        # create sample tests
 
1145
        test1 = SampleTestCase('_test_pass')
 
1146
        test1._test_needs_features = [Feature1()]
 
1147
        test2 = SampleTestCase('_test_pass')
 
1148
        test2._test_needs_features = [Feature2()]
 
1149
        test = unittest.TestSuite()
 
1150
        test.addTest(test1)
 
1151
        test.addTest(test2)
 
1152
        stream = StringIO()
 
1153
        runner = TextTestRunner(stream=stream)
 
1154
        result = self.run_test_runner(runner, test)
 
1155
        lines = stream.getvalue().splitlines()
 
1156
        self.assertEqual([
 
1157
            'OK',
 
1158
            "Missing feature 'Feature1' skipped 1 tests.",
 
1159
            "Missing feature 'Feature2' skipped 1 tests.",
 
1160
            ],
 
1161
            lines[-3:])
 
1162
 
 
1163
    def test_bench_history(self):
 
1164
        # tests that the running the benchmark produces a history file
 
1165
        # containing a timestamp and the revision id of the bzrlib source which
 
1166
        # was tested.
 
1167
        workingtree = _get_bzr_source_tree()
 
1168
        test = TestRunner('dummy_test')
 
1169
        output = StringIO()
 
1170
        runner = TextTestRunner(stream=self._log_file, bench_history=output)
 
1171
        result = self.run_test_runner(runner, test)
 
1172
        output_string = output.getvalue()
 
1173
        self.assertContainsRe(output_string, "--date [0-9.]+")
 
1174
        if workingtree is not None:
 
1175
            revision_id = workingtree.get_parent_ids()[0]
 
1176
            self.assertEndsWith(output_string.rstrip(), revision_id)
 
1177
 
 
1178
    def test_success_log_deleted(self):
 
1179
        """Successful tests have their log deleted"""
 
1180
 
 
1181
        class LogTester(TestCase):
 
1182
 
 
1183
            def test_success(self):
 
1184
                self.log('this will be removed\n')
 
1185
 
 
1186
        sio = cStringIO.StringIO()
 
1187
        runner = TextTestRunner(stream=sio)
 
1188
        test = LogTester('test_success')
 
1189
        result = self.run_test_runner(runner, test)
 
1190
 
 
1191
        log = test._get_log()
 
1192
        self.assertEqual("DELETED log file to reduce memory footprint", log)
 
1193
        self.assertEqual('', test._log_contents)
 
1194
        self.assertIs(None, test._log_file_name)
 
1195
 
 
1196
    def test_fail_log_kept(self):
 
1197
        """Failed tests have their log kept"""
 
1198
 
 
1199
        class LogTester(TestCase):
 
1200
 
 
1201
            def test_fail(self):
 
1202
                self.log('this will be kept\n')
 
1203
                self.fail('this test fails')
 
1204
 
 
1205
        sio = cStringIO.StringIO()
 
1206
        runner = TextTestRunner(stream=sio)
 
1207
        test = LogTester('test_fail')
 
1208
        result = self.run_test_runner(runner, test)
 
1209
 
 
1210
        text = sio.getvalue()
 
1211
        self.assertContainsRe(text, 'this will be kept')
 
1212
        self.assertContainsRe(text, 'this test fails')
 
1213
 
 
1214
        log = test._get_log()
 
1215
        self.assertContainsRe(log, 'this will be kept')
 
1216
        self.assertEqual(log, test._log_contents)
 
1217
 
 
1218
    def test_error_log_kept(self):
 
1219
        """Tests with errors have their log kept"""
 
1220
 
 
1221
        class LogTester(TestCase):
 
1222
 
 
1223
            def test_error(self):
 
1224
                self.log('this will be kept\n')
 
1225
                raise ValueError('random exception raised')
 
1226
 
 
1227
        sio = cStringIO.StringIO()
 
1228
        runner = TextTestRunner(stream=sio)
 
1229
        test = LogTester('test_error')
 
1230
        result = self.run_test_runner(runner, test)
 
1231
 
 
1232
        text = sio.getvalue()
 
1233
        self.assertContainsRe(text, 'this will be kept')
 
1234
        self.assertContainsRe(text, 'random exception raised')
 
1235
 
 
1236
        log = test._get_log()
 
1237
        self.assertContainsRe(log, 'this will be kept')
 
1238
        self.assertEqual(log, test._log_contents)
 
1239
 
 
1240
 
 
1241
class SampleTestCase(TestCase):
 
1242
 
 
1243
    def _test_pass(self):
 
1244
        pass
 
1245
 
 
1246
 
 
1247
class TestTestCase(TestCase):
 
1248
    """Tests that test the core bzrlib TestCase."""
 
1249
 
 
1250
    def test_debug_flags_sanitised(self):
 
1251
        """The bzrlib debug flags should be sanitised by setUp."""
 
1252
        # we could set something and run a test that will check
 
1253
        # it gets santised, but this is probably sufficient for now:
 
1254
        # if someone runs the test with -Dsomething it will error.
 
1255
        self.assertEqual(set(), bzrlib.debug.debug_flags)
 
1256
 
 
1257
    def inner_test(self):
 
1258
        # the inner child test
 
1259
        note("inner_test")
 
1260
 
 
1261
    def outer_child(self):
 
1262
        # the outer child test
 
1263
        note("outer_start")
 
1264
        self.inner_test = TestTestCase("inner_child")
 
1265
        result = bzrlib.tests.TextTestResult(self._log_file,
 
1266
                                        descriptions=0,
 
1267
                                        verbosity=1)
 
1268
        self.inner_test.run(result)
 
1269
        note("outer finish")
 
1270
 
 
1271
    def test_trace_nesting(self):
 
1272
        # this tests that each test case nests its trace facility correctly.
 
1273
        # we do this by running a test case manually. That test case (A)
 
1274
        # should setup a new log, log content to it, setup a child case (B),
 
1275
        # which should log independently, then case (A) should log a trailer
 
1276
        # and return.
 
1277
        # we do two nested children so that we can verify the state of the 
 
1278
        # logs after the outer child finishes is correct, which a bad clean
 
1279
        # up routine in tearDown might trigger a fault in our test with only
 
1280
        # one child, we should instead see the bad result inside our test with
 
1281
        # the two children.
 
1282
        # the outer child test
 
1283
        original_trace = bzrlib.trace._trace_file
 
1284
        outer_test = TestTestCase("outer_child")
 
1285
        result = bzrlib.tests.TextTestResult(self._log_file,
 
1286
                                        descriptions=0,
 
1287
                                        verbosity=1)
 
1288
        outer_test.run(result)
 
1289
        self.assertEqual(original_trace, bzrlib.trace._trace_file)
 
1290
 
 
1291
    def method_that_times_a_bit_twice(self):
 
1292
        # call self.time twice to ensure it aggregates
 
1293
        self.time(time.sleep, 0.007)
 
1294
        self.time(time.sleep, 0.007)
 
1295
 
 
1296
    def test_time_creates_benchmark_in_result(self):
 
1297
        """Test that the TestCase.time() method accumulates a benchmark time."""
 
1298
        sample_test = TestTestCase("method_that_times_a_bit_twice")
 
1299
        output_stream = StringIO()
 
1300
        result = bzrlib.tests.VerboseTestResult(
 
1301
            unittest._WritelnDecorator(output_stream),
 
1302
            descriptions=0,
 
1303
            verbosity=2,
 
1304
            num_tests=sample_test.countTestCases())
 
1305
        sample_test.run(result)
 
1306
        self.assertContainsRe(
 
1307
            output_stream.getvalue(),
 
1308
            r"\d+ms/ +\d+ms\n$")
 
1309
 
 
1310
    def test_hooks_sanitised(self):
 
1311
        """The bzrlib hooks should be sanitised by setUp."""
 
1312
        self.assertEqual(bzrlib.branch.BranchHooks(),
 
1313
            bzrlib.branch.Branch.hooks)
 
1314
        self.assertEqual(bzrlib.smart.server.SmartServerHooks(),
 
1315
            bzrlib.smart.server.SmartTCPServer.hooks)
 
1316
 
 
1317
    def test__gather_lsprof_in_benchmarks(self):
 
1318
        """When _gather_lsprof_in_benchmarks is on, accumulate profile data.
 
1319
        
 
1320
        Each self.time() call is individually and separately profiled.
 
1321
        """
 
1322
        self.requireFeature(test_lsprof.LSProfFeature)
 
1323
        # overrides the class member with an instance member so no cleanup 
 
1324
        # needed.
 
1325
        self._gather_lsprof_in_benchmarks = True
 
1326
        self.time(time.sleep, 0.000)
 
1327
        self.time(time.sleep, 0.003)
 
1328
        self.assertEqual(2, len(self._benchcalls))
 
1329
        self.assertEqual((time.sleep, (0.000,), {}), self._benchcalls[0][0])
 
1330
        self.assertEqual((time.sleep, (0.003,), {}), self._benchcalls[1][0])
 
1331
        self.assertIsInstance(self._benchcalls[0][1], bzrlib.lsprof.Stats)
 
1332
        self.assertIsInstance(self._benchcalls[1][1], bzrlib.lsprof.Stats)
 
1333
 
 
1334
    def test_knownFailure(self):
 
1335
        """Self.knownFailure() should raise a KnownFailure exception."""
 
1336
        self.assertRaises(KnownFailure, self.knownFailure, "A Failure")
 
1337
 
 
1338
    def test_requireFeature_available(self):
 
1339
        """self.requireFeature(available) is a no-op."""
 
1340
        class Available(Feature):
 
1341
            def _probe(self):return True
 
1342
        feature = Available()
 
1343
        self.requireFeature(feature)
 
1344
 
 
1345
    def test_requireFeature_unavailable(self):
 
1346
        """self.requireFeature(unavailable) raises UnavailableFeature."""
 
1347
        class Unavailable(Feature):
 
1348
            def _probe(self):return False
 
1349
        feature = Unavailable()
 
1350
        self.assertRaises(UnavailableFeature, self.requireFeature, feature)
 
1351
 
 
1352
    def test_run_no_parameters(self):
 
1353
        test = SampleTestCase('_test_pass')
 
1354
        test.run()
 
1355
    
 
1356
    def test_run_enabled_unittest_result(self):
 
1357
        """Test we revert to regular behaviour when the test is enabled."""
 
1358
        test = SampleTestCase('_test_pass')
 
1359
        class EnabledFeature(object):
 
1360
            def available(self):
 
1361
                return True
 
1362
        test._test_needs_features = [EnabledFeature()]
 
1363
        result = unittest.TestResult()
 
1364
        test.run(result)
 
1365
        self.assertEqual(1, result.testsRun)
 
1366
        self.assertEqual([], result.errors)
 
1367
        self.assertEqual([], result.failures)
 
1368
 
 
1369
    def test_run_disabled_unittest_result(self):
 
1370
        """Test our compatability for disabled tests with unittest results."""
 
1371
        test = SampleTestCase('_test_pass')
 
1372
        class DisabledFeature(object):
 
1373
            def available(self):
 
1374
                return False
 
1375
        test._test_needs_features = [DisabledFeature()]
 
1376
        result = unittest.TestResult()
 
1377
        test.run(result)
 
1378
        self.assertEqual(1, result.testsRun)
 
1379
        self.assertEqual([], result.errors)
 
1380
        self.assertEqual([], result.failures)
 
1381
 
 
1382
    def test_run_disabled_supporting_result(self):
 
1383
        """Test disabled tests behaviour with support aware results."""
 
1384
        test = SampleTestCase('_test_pass')
 
1385
        class DisabledFeature(object):
 
1386
            def available(self):
 
1387
                return False
 
1388
        the_feature = DisabledFeature()
 
1389
        test._test_needs_features = [the_feature]
 
1390
        class InstrumentedTestResult(unittest.TestResult):
 
1391
            def __init__(self):
 
1392
                unittest.TestResult.__init__(self)
 
1393
                self.calls = []
 
1394
            def startTest(self, test):
 
1395
                self.calls.append(('startTest', test))
 
1396
            def stopTest(self, test):
 
1397
                self.calls.append(('stopTest', test))
 
1398
            def addNotSupported(self, test, feature):
 
1399
                self.calls.append(('addNotSupported', test, feature))
 
1400
        result = InstrumentedTestResult()
 
1401
        test.run(result)
 
1402
        self.assertEqual([
 
1403
            ('startTest', test),
 
1404
            ('addNotSupported', test, the_feature),
 
1405
            ('stopTest', test),
 
1406
            ],
 
1407
            result.calls)
 
1408
 
 
1409
 
 
1410
@symbol_versioning.deprecated_function(zero_eleven)
 
1411
def sample_deprecated_function():
 
1412
    """A deprecated function to test applyDeprecated with."""
 
1413
    return 2
 
1414
 
 
1415
 
 
1416
def sample_undeprecated_function(a_param):
 
1417
    """A undeprecated function to test applyDeprecated with."""
 
1418
 
 
1419
 
 
1420
class ApplyDeprecatedHelper(object):
 
1421
    """A helper class for ApplyDeprecated tests."""
 
1422
 
 
1423
    @symbol_versioning.deprecated_method(zero_eleven)
 
1424
    def sample_deprecated_method(self, param_one):
 
1425
        """A deprecated method for testing with."""
 
1426
        return param_one
 
1427
 
 
1428
    def sample_normal_method(self):
 
1429
        """A undeprecated method."""
 
1430
 
 
1431
    @symbol_versioning.deprecated_method(zero_ten)
 
1432
    def sample_nested_deprecation(self):
 
1433
        return sample_deprecated_function()
 
1434
 
 
1435
 
 
1436
class TestExtraAssertions(TestCase):
 
1437
    """Tests for new test assertions in bzrlib test suite"""
 
1438
 
 
1439
    def test_assert_isinstance(self):
 
1440
        self.assertIsInstance(2, int)
 
1441
        self.assertIsInstance(u'', basestring)
 
1442
        self.assertRaises(AssertionError, self.assertIsInstance, None, int)
 
1443
        self.assertRaises(AssertionError, self.assertIsInstance, 23.3, int)
 
1444
 
 
1445
    def test_assertEndsWith(self):
 
1446
        self.assertEndsWith('foo', 'oo')
 
1447
        self.assertRaises(AssertionError, self.assertEndsWith, 'o', 'oo')
 
1448
 
 
1449
    def test_applyDeprecated_not_deprecated(self):
 
1450
        sample_object = ApplyDeprecatedHelper()
 
1451
        # calling an undeprecated callable raises an assertion
 
1452
        self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
 
1453
            sample_object.sample_normal_method)
 
1454
        self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
 
1455
            sample_undeprecated_function, "a param value")
 
1456
        # calling a deprecated callable (function or method) with the wrong
 
1457
        # expected deprecation fails.
 
1458
        self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
 
1459
            sample_object.sample_deprecated_method, "a param value")
 
1460
        self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
 
1461
            sample_deprecated_function)
 
1462
        # calling a deprecated callable (function or method) with the right
 
1463
        # expected deprecation returns the functions result.
 
1464
        self.assertEqual("a param value", self.applyDeprecated(zero_eleven,
 
1465
            sample_object.sample_deprecated_method, "a param value"))
 
1466
        self.assertEqual(2, self.applyDeprecated(zero_eleven,
 
1467
            sample_deprecated_function))
 
1468
        # calling a nested deprecation with the wrong deprecation version
 
1469
        # fails even if a deeper nested function was deprecated with the 
 
1470
        # supplied version.
 
1471
        self.assertRaises(AssertionError, self.applyDeprecated,
 
1472
            zero_eleven, sample_object.sample_nested_deprecation)
 
1473
        # calling a nested deprecation with the right deprecation value
 
1474
        # returns the calls result.
 
1475
        self.assertEqual(2, self.applyDeprecated(zero_ten,
 
1476
            sample_object.sample_nested_deprecation))
 
1477
 
 
1478
    def test_callDeprecated(self):
 
1479
        def testfunc(be_deprecated, result=None):
 
1480
            if be_deprecated is True:
 
1481
                symbol_versioning.warn('i am deprecated', DeprecationWarning, 
 
1482
                                       stacklevel=1)
 
1483
            return result
 
1484
        result = self.callDeprecated(['i am deprecated'], testfunc, True)
 
1485
        self.assertIs(None, result)
 
1486
        result = self.callDeprecated([], testfunc, False, 'result')
 
1487
        self.assertEqual('result', result)
 
1488
        self.callDeprecated(['i am deprecated'], testfunc, be_deprecated=True)
 
1489
        self.callDeprecated([], testfunc, be_deprecated=False)
 
1490
 
 
1491
 
 
1492
class TestConvenienceMakers(TestCaseWithTransport):
 
1493
    """Test for the make_* convenience functions."""
 
1494
 
 
1495
    def test_make_branch_and_tree_with_format(self):
 
1496
        # we should be able to supply a format to make_branch_and_tree
 
1497
        self.make_branch_and_tree('a', format=bzrlib.bzrdir.BzrDirMetaFormat1())
 
1498
        self.make_branch_and_tree('b', format=bzrlib.bzrdir.BzrDirFormat6())
 
1499
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('a')._format,
 
1500
                              bzrlib.bzrdir.BzrDirMetaFormat1)
 
1501
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('b')._format,
 
1502
                              bzrlib.bzrdir.BzrDirFormat6)
 
1503
 
 
1504
    def test_make_branch_and_memory_tree(self):
 
1505
        # we should be able to get a new branch and a mutable tree from
 
1506
        # TestCaseWithTransport
 
1507
        tree = self.make_branch_and_memory_tree('a')
 
1508
        self.assertIsInstance(tree, bzrlib.memorytree.MemoryTree)
 
1509
 
 
1510
 
 
1511
class TestSFTPMakeBranchAndTree(TestCaseWithSFTPServer):
 
1512
 
 
1513
    def test_make_tree_for_sftp_branch(self):
 
1514
        """Transports backed by local directories create local trees."""
 
1515
 
 
1516
        tree = self.make_branch_and_tree('t1')
 
1517
        base = tree.bzrdir.root_transport.base
 
1518
        self.failIf(base.startswith('sftp'),
 
1519
                'base %r is on sftp but should be local' % base)
 
1520
        self.assertEquals(tree.bzrdir.root_transport,
 
1521
                tree.branch.bzrdir.root_transport)
 
1522
        self.assertEquals(tree.bzrdir.root_transport,
 
1523
                tree.branch.repository.bzrdir.root_transport)
 
1524
 
 
1525
 
 
1526
class TestSelftest(TestCase):
 
1527
    """Tests of bzrlib.tests.selftest."""
 
1528
 
 
1529
    def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
 
1530
        factory_called = []
 
1531
        def factory():
 
1532
            factory_called.append(True)
 
1533
            return TestSuite()
 
1534
        out = StringIO()
 
1535
        err = StringIO()
 
1536
        self.apply_redirected(out, err, None, bzrlib.tests.selftest, 
 
1537
            test_suite_factory=factory)
 
1538
        self.assertEqual([True], factory_called)
 
1539
 
 
1540
 
 
1541
class TestKnownFailure(TestCase):
 
1542
 
 
1543
    def test_known_failure(self):
 
1544
        """Check that KnownFailure is defined appropriately."""
 
1545
        # a KnownFailure is an assertion error for compatability with unaware
 
1546
        # runners.
 
1547
        self.assertIsInstance(KnownFailure(""), AssertionError)
 
1548
 
 
1549
    def test_expect_failure(self):
 
1550
        try:
 
1551
            self.expectFailure("Doomed to failure", self.assertTrue, False)
 
1552
        except KnownFailure, e:
 
1553
            self.assertEqual('Doomed to failure', e.args[0])
 
1554
        try:
 
1555
            self.expectFailure("Doomed to failure", self.assertTrue, True)
 
1556
        except AssertionError, e:
 
1557
            self.assertEqual('Unexpected success.  Should have failed:'
 
1558
                             ' Doomed to failure', e.args[0])
 
1559
        else:
 
1560
            self.fail('Assertion not raised')
 
1561
 
 
1562
 
 
1563
class TestFeature(TestCase):
 
1564
 
 
1565
    def test_caching(self):
 
1566
        """Feature._probe is called by the feature at most once."""
 
1567
        class InstrumentedFeature(Feature):
 
1568
            def __init__(self):
 
1569
                Feature.__init__(self)
 
1570
                self.calls = []
 
1571
            def _probe(self):
 
1572
                self.calls.append('_probe')
 
1573
                return False
 
1574
        feature = InstrumentedFeature()
 
1575
        feature.available()
 
1576
        self.assertEqual(['_probe'], feature.calls)
 
1577
        feature.available()
 
1578
        self.assertEqual(['_probe'], feature.calls)
 
1579
 
 
1580
    def test_named_str(self):
 
1581
        """Feature.__str__ should thunk to feature_name()."""
 
1582
        class NamedFeature(Feature):
 
1583
            def feature_name(self):
 
1584
                return 'symlinks'
 
1585
        feature = NamedFeature()
 
1586
        self.assertEqual('symlinks', str(feature))
 
1587
 
 
1588
    def test_default_str(self):
 
1589
        """Feature.__str__ should default to __class__.__name__."""
 
1590
        class NamedFeature(Feature):
 
1591
            pass
 
1592
        feature = NamedFeature()
 
1593
        self.assertEqual('NamedFeature', str(feature))
 
1594
 
 
1595
 
 
1596
class TestUnavailableFeature(TestCase):
 
1597
 
 
1598
    def test_access_feature(self):
 
1599
        feature = Feature()
 
1600
        exception = UnavailableFeature(feature)
 
1601
        self.assertIs(feature, exception.args[0])
 
1602
 
 
1603
 
 
1604
class TestSelftestFiltering(TestCase):
 
1605
 
 
1606
    def setUp(self):
 
1607
        self.suite = TestUtil.TestSuite()
 
1608
        self.loader = TestUtil.TestLoader()
 
1609
        self.suite.addTest(self.loader.loadTestsFromModuleNames([
 
1610
            'bzrlib.tests.test_selftest']))
 
1611
        self.all_names = [t.id() for t in iter_suite_tests(self.suite)]
 
1612
 
 
1613
    def test_filter_suite_by_re(self):
 
1614
        filtered_suite = filter_suite_by_re(self.suite, 'test_filter')
 
1615
        filtered_names = [t.id() for t in iter_suite_tests(filtered_suite)]
 
1616
        self.assertEqual(filtered_names, ['bzrlib.tests.test_selftest.'
 
1617
            'TestSelftestFiltering.test_filter_suite_by_re'])
 
1618
            
 
1619
    def test_sort_suite_by_re(self):
 
1620
        sorted_suite = sort_suite_by_re(self.suite, 'test_filter')
 
1621
        sorted_names = [t.id() for t in iter_suite_tests(sorted_suite)]
 
1622
        self.assertEqual(sorted_names[0], 'bzrlib.tests.test_selftest.'
 
1623
            'TestSelftestFiltering.test_filter_suite_by_re')
 
1624
        self.assertEquals(sorted(self.all_names), sorted(sorted_names))
 
1625
 
 
1626
 
 
1627
class TestCheckInventoryShape(TestCaseWithTransport):
 
1628
 
 
1629
    def test_check_inventory_shape(self):
 
1630
        files = ['a', 'b/', 'b/c']
 
1631
        tree = self.make_branch_and_tree('.')
 
1632
        self.build_tree(files)
 
1633
        tree.add(files)
 
1634
        tree.lock_read()
 
1635
        try:
 
1636
            self.check_inventory_shape(tree.inventory, files)
 
1637
        finally:
 
1638
            tree.unlock()