/brz/remove-bazaar

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