~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_selftest.py

  • Committer: Martin Pool
  • Date: 2007-04-04 06:17:31 UTC
  • mto: This revision was merged to the branch mainline in revision 2397.
  • Revision ID: mbp@sourcefrog.net-20070404061731-tt2xrzllqhbodn83
Contents of TODO file moved into bug tracker

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
"""Tests for the test framework."""
18
18
 
26
26
 
27
27
import bzrlib
28
28
from bzrlib import (
29
 
    branchbuilder,
30
29
    bzrdir,
31
 
    debug,
32
30
    errors,
33
 
    lockdir,
34
31
    memorytree,
35
32
    osutils,
36
 
    remote,
37
33
    repository,
38
34
    symbol_versioning,
39
 
    tests,
40
 
    workingtree,
41
35
    )
42
36
from bzrlib.progress import _BaseProgressBar
43
 
from bzrlib.repofmt import (
44
 
    pack_repo,
45
 
    weaverepo,
46
 
    )
47
 
from bzrlib.symbol_versioning import (
48
 
    deprecated_function,
49
 
    deprecated_in,
50
 
    deprecated_method,
51
 
    )
 
37
from bzrlib.repofmt import weaverepo
 
38
from bzrlib.symbol_versioning import zero_ten, zero_eleven
52
39
from bzrlib.tests import (
53
40
                          ChrootedTestCase,
54
41
                          ExtendedTestResult,
58
45
                          TestCaseInTempDir,
59
46
                          TestCaseWithMemoryTransport,
60
47
                          TestCaseWithTransport,
61
 
                          TestNotApplicable,
62
48
                          TestSkipped,
63
49
                          TestSuite,
64
 
                          TestUtil,
65
50
                          TextTestRunner,
66
51
                          UnavailableFeature,
67
 
                          condition_id_re,
68
 
                          condition_isinstance,
69
 
                          exclude_tests_by_condition,
70
 
                          exclude_tests_by_re,
71
 
                          filter_suite_by_condition,
72
 
                          filter_suite_by_re,
73
 
                          iter_suite_tests,
74
 
                          preserve_input,
75
 
                          randomize_suite,
76
 
                          run_suite,
77
 
                          split_suite_by_condition,
78
 
                          split_suite_by_re,
79
 
                          test_lsprof,
80
 
                          test_suite,
81
52
                          )
82
53
from bzrlib.tests.test_sftp_transport import TestCaseWithSFTPServer
83
54
from bzrlib.tests.TestUtil import _load_module_by_name
86
57
from bzrlib.version import _get_bzr_source_tree
87
58
 
88
59
 
89
 
def _test_ids(test_suite):
90
 
    """Get the ids for the tests in a test suite."""
91
 
    return [t.id() for t in iter_suite_tests(test_suite)]
92
 
 
93
 
 
94
60
class SelftestTests(TestCase):
95
61
 
96
62
    def test_import_tests(self):
112
78
                              'a test message\n')
113
79
 
114
80
 
115
 
class TestUnicodeFilename(TestCase):
116
 
 
117
 
    def test_probe_passes(self):
118
 
        """UnicodeFilename._probe passes."""
119
 
        # We can't test much more than that because the behaviour depends
120
 
        # on the platform.
121
 
        tests.UnicodeFilename._probe()
122
 
 
123
 
 
124
81
class TestTreeShape(TestCaseInTempDir):
125
82
 
126
83
    def test_unicode_paths(self):
127
 
        self.requireFeature(tests.UnicodeFilename)
128
 
 
129
84
        filename = u'hell\u00d8'
130
 
        self.build_tree_contents([(filename, 'contents of hello')])
 
85
        try:
 
86
            self.build_tree_contents([(filename, 'contents of hello')])
 
87
        except UnicodeEncodeError:
 
88
            raise TestSkipped("can't build unicode working tree in "
 
89
                "filesystem encoding %s" % sys.getfilesystemencoding())
131
90
        self.failUnlessExists(filename)
132
91
 
133
92
 
134
 
class TestTransportScenarios(TestCase):
 
93
class TestTransportProviderAdapter(TestCase):
135
94
    """A group of tests that test the transport implementation adaption core.
136
95
 
137
 
    This is a meta test that the tests are applied to all available
 
96
    This is a meta test that the tests are applied to all available 
138
97
    transports.
139
98
 
140
 
    This will be generalised in the future which is why it is in this
 
99
    This will be generalised in the future which is why it is in this 
141
100
    test file even though it is specific to transport tests at the moment.
142
101
    """
143
102
 
144
103
    def test_get_transport_permutations(self):
145
 
        # this checks that get_test_permutations defined by the module is
146
 
        # called by the get_transport_test_permutations function.
 
104
        # this checks that we the module get_test_permutations call
 
105
        # is made by the adapter get_transport_test_permitations method.
147
106
        class MockModule(object):
148
107
            def get_test_permutations(self):
149
108
                return sample_permutation
150
109
        sample_permutation = [(1,2), (3,4)]
151
 
        from bzrlib.tests.test_transport_implementations \
152
 
            import get_transport_test_permutations
 
110
        from bzrlib.transport import TransportTestProviderAdapter
 
111
        adapter = TransportTestProviderAdapter()
153
112
        self.assertEqual(sample_permutation,
154
 
                         get_transport_test_permutations(MockModule()))
 
113
                         adapter.get_transport_test_permutations(MockModule()))
155
114
 
156
 
    def test_scenarios_invlude_all_modules(self):
157
 
        # this checks that the scenario generator returns as many permutations
158
 
        # as there are in all the registered transport modules - we assume if
159
 
        # this matches its probably doing the right thing especially in
160
 
        # combination with the tests for setting the right classes below.
161
 
        from bzrlib.tests.test_transport_implementations \
162
 
            import transport_test_permutations
163
 
        from bzrlib.transport import _get_transport_modules
 
115
    def test_adapter_checks_all_modules(self):
 
116
        # this checks that the adapter returns as many permurtations as
 
117
        # there are in all the registered# transport modules for there
 
118
        # - we assume if this matches its probably doing the right thing
 
119
        # especially in combination with the tests for setting the right
 
120
        # classes below.
 
121
        from bzrlib.transport import (TransportTestProviderAdapter,
 
122
                                      _get_transport_modules
 
123
                                      )
164
124
        modules = _get_transport_modules()
165
125
        permutation_count = 0
166
126
        for module in modules:
167
127
            try:
168
 
                permutation_count += len(reduce(getattr,
 
128
                permutation_count += len(reduce(getattr, 
169
129
                    (module + ".get_test_permutations").split('.')[1:],
170
130
                     __import__(module))())
171
131
            except errors.DependencyNotPresent:
172
132
                pass
173
 
        scenarios = transport_test_permutations()
174
 
        self.assertEqual(permutation_count, len(scenarios))
 
133
        input_test = TestTransportProviderAdapter(
 
134
            "test_adapter_sets_transport_class")
 
135
        adapter = TransportTestProviderAdapter()
 
136
        self.assertEqual(permutation_count,
 
137
                         len(list(iter(adapter.adapt(input_test)))))
175
138
 
176
 
    def test_scenarios_include_transport_class(self):
 
139
    def test_adapter_sets_transport_class(self):
 
140
        # Check that the test adapter inserts a transport and server into the
 
141
        # generated test.
 
142
        #
177
143
        # This test used to know about all the possible transports and the
178
144
        # order they were returned but that seems overly brittle (mbp
179
145
        # 20060307)
180
 
        from bzrlib.tests.test_transport_implementations \
181
 
            import transport_test_permutations
182
 
        scenarios = transport_test_permutations()
 
146
        input_test = TestTransportProviderAdapter(
 
147
            "test_adapter_sets_transport_class")
 
148
        from bzrlib.transport import TransportTestProviderAdapter
 
149
        suite = TransportTestProviderAdapter().adapt(input_test)
 
150
        tests = list(iter(suite))
 
151
        self.assertTrue(len(tests) > 6)
183
152
        # there are at least that many builtin transports
184
 
        self.assertTrue(len(scenarios) > 6)
185
 
        one_scenario = scenarios[0]
186
 
        self.assertIsInstance(one_scenario[0], str)
187
 
        self.assertTrue(issubclass(one_scenario[1]["transport_class"],
 
153
        one_test = tests[0]
 
154
        self.assertTrue(issubclass(one_test.transport_class, 
188
155
                                   bzrlib.transport.Transport))
189
 
        self.assertTrue(issubclass(one_scenario[1]["transport_server"],
 
156
        self.assertTrue(issubclass(one_test.transport_server, 
190
157
                                   bzrlib.transport.Server))
191
158
 
192
159
 
193
 
class TestBranchScenarios(TestCase):
 
160
class TestBranchProviderAdapter(TestCase):
 
161
    """A group of tests that test the branch implementation test adapter."""
194
162
 
195
 
    def test_scenarios(self):
 
163
    def test_adapted_tests(self):
196
164
        # check that constructor parameters are passed through to the adapted
197
165
        # test.
198
 
        from bzrlib.tests.branch_implementations import make_scenarios
 
166
        from bzrlib.branch import BranchTestProviderAdapter
 
167
        input_test = TestBranchProviderAdapter(
 
168
            "test_adapted_tests")
199
169
        server1 = "a"
200
170
        server2 = "b"
201
171
        formats = [("c", "C"), ("d", "D")]
202
 
        scenarios = make_scenarios(server1, server2, formats)
203
 
        self.assertEqual(2, len(scenarios))
204
 
        self.assertEqual([
205
 
            ('str',
206
 
             {'branch_format': 'c',
207
 
              'bzrdir_format': 'C',
208
 
              'transport_readonly_server': 'b',
209
 
              'transport_server': 'a'}),
210
 
            ('str',
211
 
             {'branch_format': 'd',
212
 
              'bzrdir_format': 'D',
213
 
              'transport_readonly_server': 'b',
214
 
              'transport_server': 'a'})],
215
 
            scenarios)
216
 
 
217
 
 
218
 
class TestBzrDirScenarios(TestCase):
219
 
 
220
 
    def test_scenarios(self):
 
172
        adapter = BranchTestProviderAdapter(server1, server2, formats)
 
173
        suite = adapter.adapt(input_test)
 
174
        tests = list(iter(suite))
 
175
        self.assertEqual(2, len(tests))
 
176
        self.assertEqual(tests[0].branch_format, formats[0][0])
 
177
        self.assertEqual(tests[0].bzrdir_format, formats[0][1])
 
178
        self.assertEqual(tests[0].transport_server, server1)
 
179
        self.assertEqual(tests[0].transport_readonly_server, server2)
 
180
        self.assertEqual(tests[1].branch_format, formats[1][0])
 
181
        self.assertEqual(tests[1].bzrdir_format, formats[1][1])
 
182
        self.assertEqual(tests[1].transport_server, server1)
 
183
        self.assertEqual(tests[1].transport_readonly_server, server2)
 
184
 
 
185
 
 
186
class TestBzrDirProviderAdapter(TestCase):
 
187
    """A group of tests that test the bzr dir implementation test adapter."""
 
188
 
 
189
    def test_adapted_tests(self):
221
190
        # check that constructor parameters are passed through to the adapted
222
191
        # test.
223
 
        from bzrlib.tests.bzrdir_implementations import make_scenarios
224
 
        vfs_factory = "v"
 
192
        from bzrlib.bzrdir import BzrDirTestProviderAdapter
 
193
        input_test = TestBzrDirProviderAdapter(
 
194
            "test_adapted_tests")
225
195
        server1 = "a"
226
196
        server2 = "b"
227
197
        formats = ["c", "d"]
228
 
        scenarios = make_scenarios(vfs_factory, server1, server2, formats)
229
 
        self.assertEqual([
230
 
            ('str',
231
 
             {'bzrdir_format': 'c',
232
 
              'transport_readonly_server': 'b',
233
 
              'transport_server': 'a',
234
 
              'vfs_transport_factory': 'v'}),
235
 
            ('str',
236
 
             {'bzrdir_format': 'd',
237
 
              'transport_readonly_server': 'b',
238
 
              'transport_server': 'a',
239
 
              'vfs_transport_factory': 'v'})],
240
 
            scenarios)
241
 
 
242
 
 
243
 
class TestRepositoryScenarios(TestCase):
244
 
 
245
 
    def test_formats_to_scenarios(self):
246
 
        from bzrlib.tests.per_repository import formats_to_scenarios
247
 
        formats = [("(c)", remote.RemoteRepositoryFormat()),
248
 
                   ("(d)", repository.format_registry.get(
249
 
                        'Bazaar pack repository format 1 (needs bzr 0.92)\n'))]
250
 
        no_vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
251
 
            None)
252
 
        vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
253
 
            vfs_transport_factory="vfs")
254
 
        # no_vfs generate scenarios without vfs_transport_factory
255
 
        self.assertEqual([
256
 
            ('RemoteRepositoryFormat(c)',
257
 
             {'bzrdir_format': remote.RemoteBzrDirFormat(),
258
 
              'repository_format': remote.RemoteRepositoryFormat(),
259
 
              'transport_readonly_server': 'readonly',
260
 
              'transport_server': 'server'}),
261
 
            ('RepositoryFormatKnitPack1(d)',
262
 
             {'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
263
 
              'repository_format': pack_repo.RepositoryFormatKnitPack1(),
264
 
              'transport_readonly_server': 'readonly',
265
 
              'transport_server': 'server'})],
266
 
            no_vfs_scenarios)
267
 
        self.assertEqual([
268
 
            ('RemoteRepositoryFormat(c)',
269
 
             {'bzrdir_format': remote.RemoteBzrDirFormat(),
270
 
              'repository_format': remote.RemoteRepositoryFormat(),
271
 
              'transport_readonly_server': 'readonly',
272
 
              'transport_server': 'server',
273
 
              'vfs_transport_factory': 'vfs'}),
274
 
            ('RepositoryFormatKnitPack1(d)',
275
 
             {'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
276
 
              'repository_format': pack_repo.RepositoryFormatKnitPack1(),
277
 
              'transport_readonly_server': 'readonly',
278
 
              'transport_server': 'server',
279
 
              'vfs_transport_factory': 'vfs'})],
280
 
            vfs_scenarios)
281
 
 
282
 
 
283
 
class TestTestScenarioApplication(TestCase):
284
 
    """Tests for the test adaption facilities."""
285
 
 
286
 
    def test_apply_scenario(self):
287
 
        from bzrlib.tests import apply_scenario
288
 
        input_test = TestTestScenarioApplication("test_apply_scenario")
289
 
        # setup two adapted tests
290
 
        adapted_test1 = apply_scenario(input_test,
291
 
            ("new id",
292
 
            {"bzrdir_format":"bzr_format",
293
 
             "repository_format":"repo_fmt",
294
 
             "transport_server":"transport_server",
295
 
             "transport_readonly_server":"readonly-server"}))
296
 
        adapted_test2 = apply_scenario(input_test,
297
 
            ("new id 2", {"bzrdir_format":None}))
298
 
        # input_test should have been altered.
299
 
        self.assertRaises(AttributeError, getattr, input_test, "bzrdir_format")
300
 
        # the new tests are mutually incompatible, ensuring it has
301
 
        # made new ones, and unspecified elements in the scenario
302
 
        # should not have been altered.
303
 
        self.assertEqual("bzr_format", adapted_test1.bzrdir_format)
304
 
        self.assertEqual("repo_fmt", adapted_test1.repository_format)
305
 
        self.assertEqual("transport_server", adapted_test1.transport_server)
306
 
        self.assertEqual("readonly-server",
307
 
            adapted_test1.transport_readonly_server)
308
 
        self.assertEqual(
309
 
            "bzrlib.tests.test_selftest.TestTestScenarioApplication."
310
 
            "test_apply_scenario(new id)",
311
 
            adapted_test1.id())
312
 
        self.assertEqual(None, adapted_test2.bzrdir_format)
313
 
        self.assertEqual(
314
 
            "bzrlib.tests.test_selftest.TestTestScenarioApplication."
315
 
            "test_apply_scenario(new id 2)",
316
 
            adapted_test2.id())
317
 
 
318
 
 
319
 
class TestInterRepositoryScenarios(TestCase):
320
 
 
321
 
    def test_scenarios(self):
322
 
        # check that constructor parameters are passed through to the adapted
323
 
        # test.
324
 
        from bzrlib.tests.interrepository_implementations import \
325
 
            make_scenarios
326
 
        server1 = "a"
327
 
        server2 = "b"
328
 
        formats = [(str, "C1", "C2"), (int, "D1", "D2")]
329
 
        scenarios = make_scenarios(server1, server2, formats)
330
 
        self.assertEqual([
331
 
            ('str,str,str',
332
 
             {'interrepo_class': str,
333
 
              'repository_format': 'C1',
334
 
              'repository_format_to': 'C2',
335
 
              'transport_readonly_server': 'b',
336
 
              'transport_server': 'a'}),
337
 
            ('int,str,str',
338
 
             {'interrepo_class': int,
339
 
              'repository_format': 'D1',
340
 
              'repository_format_to': 'D2',
341
 
              'transport_readonly_server': 'b',
342
 
              'transport_server': 'a'})],
343
 
            scenarios)
344
 
 
345
 
 
346
 
class TestWorkingTreeScenarios(TestCase):
347
 
 
348
 
    def test_scenarios(self):
349
 
        # check that constructor parameters are passed through to the adapted
350
 
        # test.
351
 
        from bzrlib.tests.workingtree_implementations \
352
 
            import make_scenarios
353
 
        server1 = "a"
354
 
        server2 = "b"
355
 
        formats = [workingtree.WorkingTreeFormat2(),
356
 
                   workingtree.WorkingTreeFormat3(),]
357
 
        scenarios = make_scenarios(server1, server2, formats)
358
 
        self.assertEqual([
359
 
            ('WorkingTreeFormat2',
360
 
             {'bzrdir_format': formats[0]._matchingbzrdir,
361
 
              'transport_readonly_server': 'b',
362
 
              'transport_server': 'a',
363
 
              'workingtree_format': formats[0]}),
364
 
            ('WorkingTreeFormat3',
365
 
             {'bzrdir_format': formats[1]._matchingbzrdir,
366
 
              'transport_readonly_server': 'b',
367
 
              'transport_server': 'a',
368
 
              'workingtree_format': formats[1]})],
369
 
            scenarios)
370
 
 
371
 
 
372
 
class TestTreeScenarios(TestCase):
373
 
 
374
 
    def test_scenarios(self):
375
 
        # the tree implementation scenario generator is meant to setup one
376
 
        # instance for each working tree format, and one additional instance
377
 
        # that will use the default wt format, but create a revision tree for
378
 
        # the tests.  this means that the wt ones should have the
379
 
        # workingtree_to_test_tree attribute set to 'return_parameter' and the
380
 
        # revision one set to revision_tree_from_workingtree.
 
198
        adapter = BzrDirTestProviderAdapter(server1, server2, formats)
 
199
        suite = adapter.adapt(input_test)
 
200
        tests = list(iter(suite))
 
201
        self.assertEqual(2, len(tests))
 
202
        self.assertEqual(tests[0].bzrdir_format, formats[0])
 
203
        self.assertEqual(tests[0].transport_server, server1)
 
204
        self.assertEqual(tests[0].transport_readonly_server, server2)
 
205
        self.assertEqual(tests[1].bzrdir_format, formats[1])
 
206
        self.assertEqual(tests[1].transport_server, server1)
 
207
        self.assertEqual(tests[1].transport_readonly_server, server2)
 
208
 
 
209
 
 
210
class TestRepositoryProviderAdapter(TestCase):
 
211
    """A group of tests that test the repository implementation test adapter."""
 
212
 
 
213
    def test_adapted_tests(self):
 
214
        # check that constructor parameters are passed through to the adapted
 
215
        # test.
 
216
        from bzrlib.repository import RepositoryTestProviderAdapter
 
217
        input_test = TestRepositoryProviderAdapter(
 
218
            "test_adapted_tests")
 
219
        server1 = "a"
 
220
        server2 = "b"
 
221
        formats = [("c", "C"), ("d", "D")]
 
222
        adapter = RepositoryTestProviderAdapter(server1, server2, formats)
 
223
        suite = adapter.adapt(input_test)
 
224
        tests = list(iter(suite))
 
225
        self.assertEqual(2, len(tests))
 
226
        self.assertEqual(tests[0].bzrdir_format, formats[0][1])
 
227
        self.assertEqual(tests[0].repository_format, formats[0][0])
 
228
        self.assertEqual(tests[0].transport_server, server1)
 
229
        self.assertEqual(tests[0].transport_readonly_server, server2)
 
230
        self.assertEqual(tests[1].bzrdir_format, formats[1][1])
 
231
        self.assertEqual(tests[1].repository_format, formats[1][0])
 
232
        self.assertEqual(tests[1].transport_server, server1)
 
233
        self.assertEqual(tests[1].transport_readonly_server, server2)
 
234
 
 
235
 
 
236
class TestInterRepositoryProviderAdapter(TestCase):
 
237
    """A group of tests that test the InterRepository test adapter."""
 
238
 
 
239
    def test_adapted_tests(self):
 
240
        # check that constructor parameters are passed through to the adapted
 
241
        # test.
 
242
        from bzrlib.repository import InterRepositoryTestProviderAdapter
 
243
        input_test = TestInterRepositoryProviderAdapter(
 
244
            "test_adapted_tests")
 
245
        server1 = "a"
 
246
        server2 = "b"
 
247
        formats = [(str, "C1", "C2"), (int, "D1", "D2")]
 
248
        adapter = InterRepositoryTestProviderAdapter(server1, server2, formats)
 
249
        suite = adapter.adapt(input_test)
 
250
        tests = list(iter(suite))
 
251
        self.assertEqual(2, len(tests))
 
252
        self.assertEqual(tests[0].interrepo_class, formats[0][0])
 
253
        self.assertEqual(tests[0].repository_format, formats[0][1])
 
254
        self.assertEqual(tests[0].repository_format_to, formats[0][2])
 
255
        self.assertEqual(tests[0].transport_server, server1)
 
256
        self.assertEqual(tests[0].transport_readonly_server, server2)
 
257
        self.assertEqual(tests[1].interrepo_class, formats[1][0])
 
258
        self.assertEqual(tests[1].repository_format, formats[1][1])
 
259
        self.assertEqual(tests[1].repository_format_to, formats[1][2])
 
260
        self.assertEqual(tests[1].transport_server, server1)
 
261
        self.assertEqual(tests[1].transport_readonly_server, server2)
 
262
 
 
263
 
 
264
class TestInterVersionedFileProviderAdapter(TestCase):
 
265
    """A group of tests that test the InterVersionedFile test adapter."""
 
266
 
 
267
    def test_adapted_tests(self):
 
268
        # check that constructor parameters are passed through to the adapted
 
269
        # test.
 
270
        from bzrlib.versionedfile import InterVersionedFileTestProviderAdapter
 
271
        input_test = TestInterRepositoryProviderAdapter(
 
272
            "test_adapted_tests")
 
273
        server1 = "a"
 
274
        server2 = "b"
 
275
        formats = [(str, "C1", "C2"), (int, "D1", "D2")]
 
276
        adapter = InterVersionedFileTestProviderAdapter(server1, server2, formats)
 
277
        suite = adapter.adapt(input_test)
 
278
        tests = list(iter(suite))
 
279
        self.assertEqual(2, len(tests))
 
280
        self.assertEqual(tests[0].interversionedfile_class, formats[0][0])
 
281
        self.assertEqual(tests[0].versionedfile_factory, formats[0][1])
 
282
        self.assertEqual(tests[0].versionedfile_factory_to, formats[0][2])
 
283
        self.assertEqual(tests[0].transport_server, server1)
 
284
        self.assertEqual(tests[0].transport_readonly_server, server2)
 
285
        self.assertEqual(tests[1].interversionedfile_class, formats[1][0])
 
286
        self.assertEqual(tests[1].versionedfile_factory, formats[1][1])
 
287
        self.assertEqual(tests[1].versionedfile_factory_to, formats[1][2])
 
288
        self.assertEqual(tests[1].transport_server, server1)
 
289
        self.assertEqual(tests[1].transport_readonly_server, server2)
 
290
 
 
291
 
 
292
class TestRevisionStoreProviderAdapter(TestCase):
 
293
    """A group of tests that test the RevisionStore test adapter."""
 
294
 
 
295
    def test_adapted_tests(self):
 
296
        # check that constructor parameters are passed through to the adapted
 
297
        # test.
 
298
        from bzrlib.store.revision import RevisionStoreTestProviderAdapter
 
299
        input_test = TestRevisionStoreProviderAdapter(
 
300
            "test_adapted_tests")
 
301
        # revision stores need a store factory - i.e. RevisionKnit
 
302
        #, a readonly and rw transport 
 
303
        # transport servers:
 
304
        server1 = "a"
 
305
        server2 = "b"
 
306
        store_factories = ["c", "d"]
 
307
        adapter = RevisionStoreTestProviderAdapter(server1, server2, store_factories)
 
308
        suite = adapter.adapt(input_test)
 
309
        tests = list(iter(suite))
 
310
        self.assertEqual(2, len(tests))
 
311
        self.assertEqual(tests[0].store_factory, store_factories[0][0])
 
312
        self.assertEqual(tests[0].transport_server, server1)
 
313
        self.assertEqual(tests[0].transport_readonly_server, server2)
 
314
        self.assertEqual(tests[1].store_factory, store_factories[1][0])
 
315
        self.assertEqual(tests[1].transport_server, server1)
 
316
        self.assertEqual(tests[1].transport_readonly_server, server2)
 
317
 
 
318
 
 
319
class TestWorkingTreeProviderAdapter(TestCase):
 
320
    """A group of tests that test the workingtree implementation test adapter."""
 
321
 
 
322
    def test_adapted_tests(self):
 
323
        # check that constructor parameters are passed through to the adapted
 
324
        # test.
 
325
        from bzrlib.workingtree import WorkingTreeTestProviderAdapter
 
326
        input_test = TestWorkingTreeProviderAdapter(
 
327
            "test_adapted_tests")
 
328
        server1 = "a"
 
329
        server2 = "b"
 
330
        formats = [("c", "C"), ("d", "D")]
 
331
        adapter = WorkingTreeTestProviderAdapter(server1, server2, formats)
 
332
        suite = adapter.adapt(input_test)
 
333
        tests = list(iter(suite))
 
334
        self.assertEqual(2, len(tests))
 
335
        self.assertEqual(tests[0].workingtree_format, formats[0][0])
 
336
        self.assertEqual(tests[0].bzrdir_format, formats[0][1])
 
337
        self.assertEqual(tests[0].transport_server, server1)
 
338
        self.assertEqual(tests[0].transport_readonly_server, server2)
 
339
        self.assertEqual(tests[1].workingtree_format, formats[1][0])
 
340
        self.assertEqual(tests[1].bzrdir_format, formats[1][1])
 
341
        self.assertEqual(tests[1].transport_server, server1)
 
342
        self.assertEqual(tests[1].transport_readonly_server, server2)
 
343
 
 
344
 
 
345
class TestTreeProviderAdapter(TestCase):
 
346
    """Test the setup of tree_implementation tests."""
 
347
 
 
348
    def test_adapted_tests(self):
 
349
        # the tree implementation adapter is meant to setup one instance for
 
350
        # each working tree format, and one additional instance that will
 
351
        # use the default wt format, but create a revision tree for the tests.
 
352
        # this means that the wt ones should have the workingtree_to_test_tree
 
353
        # attribute set to 'return_parameter' and the revision one set to
 
354
        # revision_tree_from_workingtree.
381
355
 
382
356
        from bzrlib.tests.tree_implementations import (
383
 
            _dirstate_tree_from_workingtree,
384
 
            make_scenarios,
385
 
            preview_tree_pre,
386
 
            preview_tree_post,
 
357
            TreeTestProviderAdapter,
387
358
            return_parameter,
388
359
            revision_tree_from_workingtree
389
360
            )
 
361
        from bzrlib.workingtree import WorkingTreeFormat, WorkingTreeFormat3
 
362
        input_test = TestTreeProviderAdapter(
 
363
            "test_adapted_tests")
390
364
        server1 = "a"
391
365
        server2 = "b"
392
 
        formats = [workingtree.WorkingTreeFormat2(),
393
 
                   workingtree.WorkingTreeFormat3(),]
394
 
        scenarios = make_scenarios(server1, server2, formats)
395
 
        self.assertEqual(7, len(scenarios))
396
 
        default_wt_format = workingtree.WorkingTreeFormat4._default_format
397
 
        wt4_format = workingtree.WorkingTreeFormat4()
398
 
        wt5_format = workingtree.WorkingTreeFormat5()
399
 
        expected_scenarios = [
400
 
            ('WorkingTreeFormat2',
401
 
             {'bzrdir_format': formats[0]._matchingbzrdir,
402
 
              'transport_readonly_server': 'b',
403
 
              'transport_server': 'a',
404
 
              'workingtree_format': formats[0],
405
 
              '_workingtree_to_test_tree': return_parameter,
406
 
              }),
407
 
            ('WorkingTreeFormat3',
408
 
             {'bzrdir_format': formats[1]._matchingbzrdir,
409
 
              'transport_readonly_server': 'b',
410
 
              'transport_server': 'a',
411
 
              'workingtree_format': formats[1],
412
 
              '_workingtree_to_test_tree': return_parameter,
413
 
             }),
414
 
            ('RevisionTree',
415
 
             {'_workingtree_to_test_tree': revision_tree_from_workingtree,
416
 
              'bzrdir_format': default_wt_format._matchingbzrdir,
417
 
              'transport_readonly_server': 'b',
418
 
              'transport_server': 'a',
419
 
              'workingtree_format': default_wt_format,
420
 
             }),
421
 
            ('DirStateRevisionTree,WT4',
422
 
             {'_workingtree_to_test_tree': _dirstate_tree_from_workingtree,
423
 
              'bzrdir_format': wt4_format._matchingbzrdir,
424
 
              'transport_readonly_server': 'b',
425
 
              'transport_server': 'a',
426
 
              'workingtree_format': wt4_format,
427
 
             }),
428
 
            ('DirStateRevisionTree,WT5',
429
 
             {'_workingtree_to_test_tree': _dirstate_tree_from_workingtree,
430
 
              'bzrdir_format': wt5_format._matchingbzrdir,
431
 
              'transport_readonly_server': 'b',
432
 
              'transport_server': 'a',
433
 
              'workingtree_format': wt5_format,
434
 
             }),
435
 
            ('PreviewTree',
436
 
             {'_workingtree_to_test_tree': preview_tree_pre,
437
 
              'bzrdir_format': default_wt_format._matchingbzrdir,
438
 
              'transport_readonly_server': 'b',
439
 
              'transport_server': 'a',
440
 
              'workingtree_format': default_wt_format}),
441
 
            ('PreviewTreePost',
442
 
             {'_workingtree_to_test_tree': preview_tree_post,
443
 
              'bzrdir_format': default_wt_format._matchingbzrdir,
444
 
              'transport_readonly_server': 'b',
445
 
              'transport_server': 'a',
446
 
              'workingtree_format': default_wt_format}),
447
 
             ]
448
 
        self.assertEqual(expected_scenarios, scenarios)
449
 
 
450
 
 
451
 
class TestInterTreeScenarios(TestCase):
 
366
        formats = [("c", "C"), ("d", "D")]
 
367
        adapter = TreeTestProviderAdapter(server1, server2, formats)
 
368
        suite = adapter.adapt(input_test)
 
369
        tests = list(iter(suite))
 
370
        self.assertEqual(4, len(tests))
 
371
        # this must match the default format setp up in
 
372
        # TreeTestProviderAdapter.adapt
 
373
        default_format = WorkingTreeFormat3
 
374
        self.assertEqual(tests[0].workingtree_format, formats[0][0])
 
375
        self.assertEqual(tests[0].bzrdir_format, formats[0][1])
 
376
        self.assertEqual(tests[0].transport_server, server1)
 
377
        self.assertEqual(tests[0].transport_readonly_server, server2)
 
378
        self.assertEqual(tests[0].workingtree_to_test_tree, return_parameter)
 
379
        self.assertEqual(tests[1].workingtree_format, formats[1][0])
 
380
        self.assertEqual(tests[1].bzrdir_format, formats[1][1])
 
381
        self.assertEqual(tests[1].transport_server, server1)
 
382
        self.assertEqual(tests[1].transport_readonly_server, server2)
 
383
        self.assertEqual(tests[1].workingtree_to_test_tree, return_parameter)
 
384
        self.assertIsInstance(tests[2].workingtree_format, default_format)
 
385
        #self.assertEqual(tests[2].bzrdir_format,
 
386
        #                 default_format._matchingbzrdir)
 
387
        self.assertEqual(tests[2].transport_server, server1)
 
388
        self.assertEqual(tests[2].transport_readonly_server, server2)
 
389
        self.assertEqual(tests[2].workingtree_to_test_tree,
 
390
            revision_tree_from_workingtree)
 
391
 
 
392
 
 
393
class TestInterTreeProviderAdapter(TestCase):
452
394
    """A group of tests that test the InterTreeTestAdapter."""
453
395
 
454
 
    def test_scenarios(self):
 
396
    def test_adapted_tests(self):
455
397
        # check that constructor parameters are passed through to the adapted
456
398
        # test.
457
399
        # for InterTree tests we want the machinery to bring up two trees in
459
401
        # because each optimiser can be direction specific, we need to test
460
402
        # each optimiser in its chosen direction.
461
403
        # unlike the TestProviderAdapter we dont want to automatically add a
462
 
        # parameterized one for WorkingTree - the optimisers will tell us what
 
404
        # parameterised one for WorkingTree - the optimisers will tell us what
463
405
        # ones to add.
464
406
        from bzrlib.tests.tree_implementations import (
465
407
            return_parameter,
466
408
            revision_tree_from_workingtree
467
409
            )
468
410
        from bzrlib.tests.intertree_implementations import (
469
 
            make_scenarios,
 
411
            InterTreeTestProviderAdapter,
470
412
            )
471
413
        from bzrlib.workingtree import WorkingTreeFormat2, WorkingTreeFormat3
472
 
        input_test = TestInterTreeScenarios(
473
 
            "test_scenarios")
 
414
        input_test = TestInterTreeProviderAdapter(
 
415
            "test_adapted_tests")
474
416
        server1 = "a"
475
417
        server2 = "b"
476
418
        format1 = WorkingTreeFormat2()
477
419
        format2 = WorkingTreeFormat3()
478
 
        formats = [("1", str, format1, format2, "converter1"),
479
 
            ("2", int, format2, format1, "converter2")]
480
 
        scenarios = make_scenarios(server1, server2, formats)
481
 
        self.assertEqual(2, len(scenarios))
482
 
        expected_scenarios = [
483
 
            ("1", {
484
 
                "bzrdir_format": format1._matchingbzrdir,
485
 
                "intertree_class": formats[0][1],
486
 
                "workingtree_format": formats[0][2],
487
 
                "workingtree_format_to": formats[0][3],
488
 
                "mutable_trees_to_test_trees": formats[0][4],
489
 
                "_workingtree_to_test_tree": return_parameter,
490
 
                "transport_server": server1,
491
 
                "transport_readonly_server": server2,
492
 
                }),
493
 
            ("2", {
494
 
                "bzrdir_format": format2._matchingbzrdir,
495
 
                "intertree_class": formats[1][1],
496
 
                "workingtree_format": formats[1][2],
497
 
                "workingtree_format_to": formats[1][3],
498
 
                "mutable_trees_to_test_trees": formats[1][4],
499
 
                "_workingtree_to_test_tree": return_parameter,
500
 
                "transport_server": server1,
501
 
                "transport_readonly_server": server2,
502
 
                }),
503
 
            ]
504
 
        self.assertEqual(scenarios, expected_scenarios)
 
420
        formats = [(str, format1, format2, "converter1"),
 
421
            (int, format2, format1, "converter2")]
 
422
        adapter = InterTreeTestProviderAdapter(server1, server2, formats)
 
423
        suite = adapter.adapt(input_test)
 
424
        tests = list(iter(suite))
 
425
        self.assertEqual(2, len(tests))
 
426
        self.assertEqual(tests[0].intertree_class, formats[0][0])
 
427
        self.assertEqual(tests[0].workingtree_format, formats[0][1])
 
428
        self.assertEqual(tests[0].workingtree_format_to, formats[0][2])
 
429
        self.assertEqual(tests[0].mutable_trees_to_test_trees, formats[0][3])
 
430
        self.assertEqual(tests[0].workingtree_to_test_tree, return_parameter)
 
431
        self.assertEqual(tests[0].transport_server, server1)
 
432
        self.assertEqual(tests[0].transport_readonly_server, server2)
 
433
        self.assertEqual(tests[1].intertree_class, formats[1][0])
 
434
        self.assertEqual(tests[1].workingtree_format, formats[1][1])
 
435
        self.assertEqual(tests[1].workingtree_format_to, formats[1][2])
 
436
        self.assertEqual(tests[1].mutable_trees_to_test_trees, formats[1][3])
 
437
        self.assertEqual(tests[1].workingtree_to_test_tree, return_parameter)
 
438
        self.assertEqual(tests[1].transport_server, server1)
 
439
        self.assertEqual(tests[1].transport_readonly_server, server2)
505
440
 
506
441
 
507
442
class TestTestCaseInTempDir(TestCaseInTempDir):
509
444
    def test_home_is_not_working(self):
510
445
        self.assertNotEqual(self.test_dir, self.test_home_dir)
511
446
        cwd = osutils.getcwd()
512
 
        self.assertIsSameRealPath(self.test_dir, cwd)
513
 
        self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
514
 
 
515
 
    def test_assertEqualStat_equal(self):
516
 
        from bzrlib.tests.test_dirstate import _FakeStat
517
 
        self.build_tree(["foo"])
518
 
        real = os.lstat("foo")
519
 
        fake = _FakeStat(real.st_size, real.st_mtime, real.st_ctime,
520
 
            real.st_dev, real.st_ino, real.st_mode)
521
 
        self.assertEqualStat(real, fake)
522
 
 
523
 
    def test_assertEqualStat_notequal(self):
524
 
        self.build_tree(["foo", "bar"])
525
 
        self.assertRaises(AssertionError, self.assertEqualStat,
526
 
            os.lstat("foo"), os.lstat("bar"))
 
447
        self.assertEqual(self.test_dir, cwd)
 
448
        self.assertEqual(self.test_home_dir, os.environ['HOME'])
527
449
 
528
450
 
529
451
class TestTestCaseWithMemoryTransport(TestCaseWithMemoryTransport):
532
454
        """The test_home_dir for TestCaseWithMemoryTransport is missing.
533
455
 
534
456
        This is because TestCaseWithMemoryTransport is for tests that do not
535
 
        need any disk resources: they should be hooked into bzrlib in such a
536
 
        way that no global settings are being changed by the test (only a
 
457
        need any disk resources: they should be hooked into bzrlib in such a 
 
458
        way that no global settings are being changed by the test (only a 
537
459
        few tests should need to do that), and having a missing dir as home is
538
460
        an effective way to ensure that this is the case.
539
461
        """
540
 
        self.assertIsSameRealPath(
541
 
            self.TEST_ROOT + "/MemoryTransportMissingHomeDir",
 
462
        self.assertEqual(self.TEST_ROOT + "/MemoryTransportMissingHomeDir",
542
463
            self.test_home_dir)
543
 
        self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
544
 
 
 
464
        self.assertEqual(self.test_home_dir, os.environ['HOME'])
 
465
        
545
466
    def test_cwd_is_TEST_ROOT(self):
546
 
        self.assertIsSameRealPath(self.test_dir, self.TEST_ROOT)
 
467
        self.assertEqual(self.test_dir, self.TEST_ROOT)
547
468
        cwd = osutils.getcwd()
548
 
        self.assertIsSameRealPath(self.test_dir, cwd)
 
469
        self.assertEqual(self.test_dir, cwd)
549
470
 
550
471
    def test_make_branch_and_memory_tree(self):
551
472
        """In TestCaseWithMemoryTransport we should not make the branch on disk.
571
492
        self.assertEqual(format.repository_format.__class__,
572
493
            tree.branch.repository._format.__class__)
573
494
 
574
 
    def test_make_branch_builder(self):
575
 
        builder = self.make_branch_builder('dir')
576
 
        self.assertIsInstance(builder, branchbuilder.BranchBuilder)
577
 
        # Guard against regression into MemoryTransport leaking
578
 
        # files to disk instead of keeping them in memory.
579
 
        self.failIf(osutils.lexists('dir'))
580
 
 
581
 
    def test_make_branch_builder_with_format(self):
582
 
        # Use a repo layout that doesn't conform to a 'named' layout, to ensure
583
 
        # that the format objects are used.
584
 
        format = bzrdir.BzrDirMetaFormat1()
585
 
        repo_format = weaverepo.RepositoryFormat7()
586
 
        format.repository_format = repo_format
587
 
        builder = self.make_branch_builder('dir', format=format)
588
 
        the_branch = builder.get_branch()
589
 
        # Guard against regression into MemoryTransport leaking
590
 
        # files to disk instead of keeping them in memory.
591
 
        self.failIf(osutils.lexists('dir'))
592
 
        self.assertEqual(format.repository_format.__class__,
593
 
                         the_branch.repository._format.__class__)
594
 
        self.assertEqual(repo_format.get_format_string(),
595
 
                         self.get_transport().get_bytes(
596
 
                            'dir/.bzr/repository/format'))
597
 
 
598
 
    def test_make_branch_builder_with_format_name(self):
599
 
        builder = self.make_branch_builder('dir', format='knit')
600
 
        the_branch = builder.get_branch()
601
 
        # Guard against regression into MemoryTransport leaking
602
 
        # files to disk instead of keeping them in memory.
603
 
        self.failIf(osutils.lexists('dir'))
604
 
        dir_format = bzrdir.format_registry.make_bzrdir('knit')
605
 
        self.assertEqual(dir_format.repository_format.__class__,
606
 
                         the_branch.repository._format.__class__)
607
 
        self.assertEqual('Bazaar-NG Knit Repository Format 1',
608
 
                         self.get_transport().get_bytes(
609
 
                            'dir/.bzr/repository/format'))
610
 
 
611
 
    def test_safety_net(self):
612
 
        """No test should modify the safety .bzr directory.
613
 
 
614
 
        We just test that the _check_safety_net private method raises
615
 
        AssertionError, it's easier than building a test suite with the same
616
 
        test.
617
 
        """
618
 
        # Oops, a commit in the current directory (i.e. without local .bzr
619
 
        # directory) will crawl up the hierarchy to find a .bzr directory.
620
 
        self.run_bzr(['commit', '-mfoo', '--unchanged'])
621
 
        # But we have a safety net in place.
622
 
        self.assertRaises(AssertionError, self._check_safety_net)
623
 
 
624
 
    def test_dangling_locks_cause_failures(self):
625
 
        # This is currently only enabled during debug runs, so turn debugging
626
 
        # on.
627
 
        debug.debug_flags.add('lock')
628
 
        class TestDanglingLock(TestCaseWithMemoryTransport):
629
 
            def test_function(self):
630
 
                t = self.get_transport('.')
631
 
                l = lockdir.LockDir(t, 'lock')
632
 
                l.create()
633
 
                l.attempt_lock()
634
 
        test = TestDanglingLock('test_function')
635
 
        result = test.run()
636
 
        self.assertEqual(1, len(result.errors))
637
 
 
638
495
 
639
496
class TestTestCaseWithTransport(TestCaseWithTransport):
640
497
    """Tests for the convenience functions TestCaseWithTransport introduces."""
656
513
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
657
514
 
658
515
    def test_get_readonly_url_http(self):
659
 
        from bzrlib.tests.http_server import HttpServer
 
516
        from bzrlib.tests.HttpServer import HttpServer
660
517
        from bzrlib.transport import get_transport
661
518
        from bzrlib.transport.local import LocalURLServer
662
519
        from bzrlib.transport.http import HttpTransportBase
680
537
        self.assertRaises(AssertionError, self.assertIsDirectory, 'a_file', t)
681
538
        self.assertRaises(AssertionError, self.assertIsDirectory, 'not_here', t)
682
539
 
683
 
    def test_make_branch_builder(self):
684
 
        builder = self.make_branch_builder('dir')
685
 
        rev_id = builder.build_commit()
686
 
        self.failUnlessExists('dir')
687
 
        a_dir = bzrdir.BzrDir.open('dir')
688
 
        self.assertRaises(errors.NoWorkingTree, a_dir.open_workingtree)
689
 
        a_branch = a_dir.open_branch()
690
 
        builder_branch = builder.get_branch()
691
 
        self.assertEqual(a_branch.base, builder_branch.base)
692
 
        self.assertEqual((1, rev_id), builder_branch.last_revision_info())
693
 
        self.assertEqual((1, rev_id), a_branch.last_revision_info())
694
 
 
695
540
 
696
541
class TestTestCaseTransports(TestCaseWithTransport):
697
542
 
702
547
    def test_make_bzrdir_preserves_transport(self):
703
548
        t = self.get_transport()
704
549
        result_bzrdir = self.make_bzrdir('subdir')
705
 
        self.assertIsInstance(result_bzrdir.transport,
 
550
        self.assertIsInstance(result_bzrdir.transport, 
706
551
                              MemoryTransport)
707
552
        # should not be on disk, should only be in memory
708
553
        self.failIfExists('subdir')
742
587
 
743
588
class TestTestResult(TestCase):
744
589
 
745
 
    def check_timing(self, test_case, expected_re):
 
590
    def test_elapsed_time_with_benchmarking(self):
746
591
        result = bzrlib.tests.TextTestResult(self._log_file,
747
 
                descriptions=0,
748
 
                verbosity=1,
749
 
                )
750
 
        test_case.run(result)
751
 
        timed_string = result._testTimeString(test_case)
752
 
        self.assertContainsRe(timed_string, expected_re)
753
 
 
754
 
    def test_test_reporting(self):
755
 
        class ShortDelayTestCase(TestCase):
756
 
            def test_short_delay(self):
757
 
                time.sleep(0.003)
758
 
            def test_short_benchmark(self):
759
 
                self.time(time.sleep, 0.003)
760
 
        self.check_timing(ShortDelayTestCase('test_short_delay'),
761
 
                          r"^ +[0-9]+ms$")
 
592
                                        descriptions=0,
 
593
                                        verbosity=1,
 
594
                                        )
 
595
        result._recordTestStartTime()
 
596
        time.sleep(0.003)
 
597
        result.extractBenchmarkTime(self)
 
598
        timed_string = result._testTimeString()
 
599
        # without explicit benchmarking, we should get a simple time.
 
600
        self.assertContainsRe(timed_string, "^ *[ 1-9][0-9]ms$")
762
601
        # if a benchmark time is given, we want a x of y style result.
763
 
        self.check_timing(ShortDelayTestCase('test_short_benchmark'),
764
 
                          r"^ +[0-9]+ms/ +[0-9]+ms$")
765
 
 
766
 
    def test_unittest_reporting_unittest_class(self):
767
 
        # getting the time from a non-bzrlib test works ok
768
 
        class ShortDelayTestCase(unittest.TestCase):
769
 
            def test_short_delay(self):
770
 
                time.sleep(0.003)
771
 
        self.check_timing(ShortDelayTestCase('test_short_delay'),
772
 
                          r"^ +[0-9]+ms$")
 
602
        self.time(time.sleep, 0.001)
 
603
        result.extractBenchmarkTime(self)
 
604
        timed_string = result._testTimeString()
 
605
        self.assertContainsRe(timed_string, "^ *[ 1-9][0-9]ms/ *[ 1-9][0-9]ms$")
 
606
        # extracting the time from a non-bzrlib testcase sets to None
 
607
        result._recordTestStartTime()
 
608
        result.extractBenchmarkTime(
 
609
            unittest.FunctionTestCase(self.test_elapsed_time_with_benchmarking))
 
610
        timed_string = result._testTimeString()
 
611
        self.assertContainsRe(timed_string, "^ *[ 1-9][0-9]ms$")
 
612
        # cheat. Yes, wash thy mouth out with soap.
 
613
        self._benchtime = None
773
614
 
774
615
    def test_assigned_benchmark_file_stores_date(self):
775
616
        output = StringIO()
779
620
                                        bench_history=output
780
621
                                        )
781
622
        output_string = output.getvalue()
 
623
        
782
624
        # if you are wondering about the regexp please read the comment in
783
625
        # test_bench_history (bzrlib.tests.test_selftest.TestRunner)
784
626
        # XXX: what comment?  -- Andrew Bennetts
803
645
        self.assertContainsRe(lines[1],
804
646
            " *[0-9]+ms bzrlib.tests.test_selftest.TestTestResult"
805
647
            "._time_hello_world_encoding")
806
 
 
 
648
 
807
649
    def _time_hello_world_encoding(self):
808
650
        """Profile two sleep calls
809
 
 
 
651
        
810
652
        This is used to exercise the test framework.
811
653
        """
812
654
        self.time(unicode, 'hello', errors='replace')
814
656
 
815
657
    def test_lsprofiling(self):
816
658
        """Verbose test result prints lsprof statistics from test cases."""
817
 
        self.requireFeature(test_lsprof.LSProfFeature)
 
659
        try:
 
660
            import bzrlib.lsprof
 
661
        except ImportError:
 
662
            raise TestSkipped("lsprof not installed.")
818
663
        result_stream = StringIO()
819
664
        result = bzrlib.tests.VerboseTestResult(
820
665
            unittest._WritelnDecorator(result_stream),
830
675
        # execute the test, which should succeed and record profiles
831
676
        example_test_case.run(result)
832
677
        # lsprofile_something()
833
 
        # if this worked we want
 
678
        # if this worked we want 
834
679
        # LSProf output for <built in function unicode> (['hello'], {'errors': 'replace'})
835
680
        #    CallCount    Recursive    Total(ms)   Inline(ms) module:lineno(function)
836
681
        # (the lsprof header)
837
682
        # ... an arbitrary number of lines
838
683
        # and the function call which is time.sleep.
839
 
        #           1        0            ???         ???       ???(sleep)
 
684
        #           1        0            ???         ???       ???(sleep) 
840
685
        # and then repeated but with 'world', rather than 'hello'.
841
686
        # this should appear in the output stream of our test result.
842
687
        output = result_stream.getvalue()
852
697
    def test_known_failure(self):
853
698
        """A KnownFailure being raised should trigger several result actions."""
854
699
        class InstrumentedTestResult(ExtendedTestResult):
855
 
            def done(self): pass
856
 
            def startTests(self): pass
 
700
 
857
701
            def report_test_start(self, test): pass
858
702
            def report_known_failure(self, test, err):
859
703
                self._call = test, err
884
728
            )
885
729
        test = self.get_passing_test()
886
730
        result.startTest(test)
 
731
        result.extractBenchmarkTime(test)
887
732
        prefix = len(result_stream.getvalue())
888
733
        # the err parameter has the shape:
889
734
        # (class, exception object, traceback)
893
738
        result.report_known_failure(test, err)
894
739
        output = result_stream.getvalue()[prefix:]
895
740
        lines = output.splitlines()
896
 
        self.assertContainsRe(lines[0], r'XFAIL *\d+ms$')
897
 
        self.assertEqual(lines[1], '    foo')
898
 
        self.assertEqual(2, len(lines))
899
 
 
 
741
        self.assertEqual(lines, ['XFAIL                   0ms', '    foo'])
 
742
    
900
743
    def test_text_report_known_failure(self):
901
744
        # text test output formatting
902
745
        pb = MockProgress()
903
746
        result = bzrlib.tests.TextTestResult(
904
 
            StringIO(),
 
747
            None,
905
748
            descriptions=0,
906
749
            verbosity=1,
907
750
            pb=pb,
909
752
        test = self.get_passing_test()
910
753
        # this seeds the state to handle reporting the test.
911
754
        result.startTest(test)
 
755
        result.extractBenchmarkTime(test)
912
756
        # the err parameter has the shape:
913
757
        # (class, exception object, traceback)
914
758
        # KnownFailures dont get their tracebacks shown though, so we
928
772
        test.run(result)
929
773
        self.assertEqual(
930
774
            [
931
 
            ('update', '[2 in 0s] passing_test', None, None),
 
775
            ('update', '[2 in 0s, 3 known failures] passing_test', None, None),
932
776
            ],
933
777
            pb.calls[2:])
934
778
 
941
785
    def test_add_not_supported(self):
942
786
        """Test the behaviour of invoking addNotSupported."""
943
787
        class InstrumentedTestResult(ExtendedTestResult):
944
 
            def done(self): pass
945
 
            def startTests(self): pass
946
788
            def report_test_start(self, test): pass
947
789
            def report_unsupported(self, test, feature):
948
790
                self._call = test, feature
975
817
        test = self.get_passing_test()
976
818
        feature = Feature()
977
819
        result.startTest(test)
 
820
        result.extractBenchmarkTime(test)
978
821
        prefix = len(result_stream.getvalue())
979
822
        result.report_unsupported(test, feature)
980
823
        output = result_stream.getvalue()[prefix:]
981
824
        lines = output.splitlines()
982
825
        self.assertEqual(lines, ['NODEP                   0ms', "    The feature 'Feature' is not available."])
983
 
 
 
826
    
984
827
    def test_text_report_unsupported(self):
985
828
        # text test output formatting
986
829
        pb = MockProgress()
987
830
        result = bzrlib.tests.TextTestResult(
988
 
            StringIO(),
 
831
            None,
989
832
            descriptions=0,
990
833
            verbosity=1,
991
834
            pb=pb,
994
837
        feature = Feature()
995
838
        # this seeds the state to handle reporting the test.
996
839
        result.startTest(test)
 
840
        result.extractBenchmarkTime(test)
997
841
        result.report_unsupported(test, feature)
998
842
        # no output on unsupported features
999
843
        self.assertEqual(
1006
850
        test.run(result)
1007
851
        self.assertEqual(
1008
852
            [
1009
 
            ('update', '[2 in 0s, 2 missing] passing_test', None, None),
 
853
            ('update', '[2 in 0s, 2 missing features] passing_test', None, None),
1010
854
            ],
1011
855
            pb.calls[1:])
1012
 
 
 
856
    
1013
857
    def test_unavailable_exception(self):
1014
858
        """An UnavailableFeature being raised should invoke addNotSupported."""
1015
859
        class InstrumentedTestResult(ExtendedTestResult):
1016
 
            def done(self): pass
1017
 
            def startTests(self): pass
 
860
 
1018
861
            def report_test_start(self, test): pass
1019
862
            def addNotSupported(self, test, feature):
1020
863
                self._call = test, feature
1031
874
        # and not count as an error
1032
875
        self.assertEqual(0, result.error_count)
1033
876
 
1034
 
    def test_strict_with_unsupported_feature(self):
1035
 
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
1036
 
                                             verbosity=1)
1037
 
        test = self.get_passing_test()
1038
 
        feature = "Unsupported Feature"
1039
 
        result.addNotSupported(test, feature)
1040
 
        self.assertFalse(result.wasStrictlySuccessful())
1041
 
        self.assertEqual(None, result._extractBenchmarkTime(test))
1042
 
 
1043
 
    def test_strict_with_known_failure(self):
1044
 
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
1045
 
                                             verbosity=1)
1046
 
        test = self.get_passing_test()
1047
 
        err = (KnownFailure, KnownFailure('foo'), None)
1048
 
        result._addKnownFailure(test, err)
1049
 
        self.assertFalse(result.wasStrictlySuccessful())
1050
 
        self.assertEqual(None, result._extractBenchmarkTime(test))
1051
 
 
1052
 
    def test_strict_with_success(self):
1053
 
        result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
1054
 
                                             verbosity=1)
1055
 
        test = self.get_passing_test()
1056
 
        result.addSuccess(test)
1057
 
        self.assertTrue(result.wasStrictlySuccessful())
1058
 
        self.assertEqual(None, result._extractBenchmarkTime(test))
1059
 
 
1060
 
    def test_startTests(self):
1061
 
        """Starting the first test should trigger startTests."""
1062
 
        class InstrumentedTestResult(ExtendedTestResult):
1063
 
            calls = 0
1064
 
            def startTests(self): self.calls += 1
1065
 
            def report_test_start(self, test): pass
1066
 
        result = InstrumentedTestResult(None, None, None, None)
1067
 
        def test_function():
1068
 
            pass
1069
 
        test = unittest.FunctionTestCase(test_function)
1070
 
        test.run(result)
1071
 
        self.assertEquals(1, result.calls)
1072
 
 
1073
 
 
1074
 
class TestUnicodeFilenameFeature(TestCase):
1075
 
 
1076
 
    def test_probe_passes(self):
1077
 
        """UnicodeFilenameFeature._probe passes."""
1078
 
        # We can't test much more than that because the behaviour depends
1079
 
        # on the platform.
1080
 
        tests.UnicodeFilenameFeature._probe()
1081
 
 
1082
877
 
1083
878
class TestRunner(TestCase):
1084
879
 
1090
885
 
1091
886
        This current saves and restores:
1092
887
        TestCaseInTempDir.TEST_ROOT
1093
 
 
 
888
        
1094
889
        There should be no tests in this file that use bzrlib.tests.TextTestRunner
1095
890
        without using this convenience method, because of our use of global state.
1096
891
        """
1127
922
            '----------------------------------------------------------------------',
1128
923
            '',
1129
924
            'FAILED (failures=1, known_failure_count=1)'],
1130
 
            lines[3:8] + lines[9:13] + lines[14:])
 
925
            lines[0:5] + lines[6:10] + lines[11:])
1131
926
 
1132
927
    def test_known_failure_ok_run(self):
1133
928
        # run a test that generates a known failure which should be printed in the final output.
1137
932
        stream = StringIO()
1138
933
        runner = TextTestRunner(stream=stream)
1139
934
        result = self.run_test_runner(runner, test)
1140
 
        self.assertContainsRe(stream.getvalue(),
1141
 
            '\n'
1142
 
            '-*\n'
1143
 
            'Ran 1 test in .*\n'
1144
 
            '\n'
1145
 
            'OK \\(known_failures=1\\)\n')
 
935
        self.assertEqual(
 
936
            '\n'
 
937
            '----------------------------------------------------------------------\n'
 
938
            'Ran 1 test in 0.000s\n'
 
939
            '\n'
 
940
            'OK (known_failures=1)\n',
 
941
            stream.getvalue())
1146
942
 
1147
943
    def test_skipped_test(self):
1148
944
        # run a test that is skipped, and check the suite as a whole still
1149
945
        # succeeds.
1150
946
        # skipping_test must be hidden in here so it's not run as a real test
1151
 
        class SkippingTest(TestCase):
1152
 
            def skipping_test(self):
1153
 
                raise TestSkipped('test intentionally skipped')
1154
 
        runner = TextTestRunner(stream=self._log_file)
1155
 
        test = SkippingTest("skipping_test")
 
947
        def skipping_test():
 
948
            raise TestSkipped('test intentionally skipped')
 
949
 
 
950
        runner = TextTestRunner(stream=self._log_file, keep_output=True)
 
951
        test = unittest.FunctionTestCase(skipping_test)
1156
952
        result = self.run_test_runner(runner, test)
1157
953
        self.assertTrue(result.wasSuccessful())
1158
954
 
1159
955
    def test_skipped_from_setup(self):
1160
 
        calls = []
1161
956
        class SkippedSetupTest(TestCase):
1162
957
 
1163
958
            def setUp(self):
1164
 
                calls.append('setUp')
 
959
                self.counter = 1
1165
960
                self.addCleanup(self.cleanup)
1166
961
                raise TestSkipped('skipped setup')
1167
962
 
1169
964
                self.fail('test reached')
1170
965
 
1171
966
            def cleanup(self):
1172
 
                calls.append('cleanup')
 
967
                self.counter -= 1
1173
968
 
1174
 
        runner = TextTestRunner(stream=self._log_file)
 
969
        runner = TextTestRunner(stream=self._log_file, keep_output=True)
1175
970
        test = SkippedSetupTest('test_skip')
1176
971
        result = self.run_test_runner(runner, test)
1177
972
        self.assertTrue(result.wasSuccessful())
1178
973
        # Check if cleanup was called the right number of times.
1179
 
        self.assertEqual(['setUp', 'cleanup'], calls)
 
974
        self.assertEqual(0, test.counter)
1180
975
 
1181
976
    def test_skipped_from_test(self):
1182
 
        calls = []
1183
977
        class SkippedTest(TestCase):
1184
978
 
1185
979
            def setUp(self):
1186
 
                TestCase.setUp(self)
1187
 
                calls.append('setUp')
 
980
                self.counter = 1
1188
981
                self.addCleanup(self.cleanup)
1189
982
 
1190
983
            def test_skip(self):
1191
984
                raise TestSkipped('skipped test')
1192
985
 
1193
986
            def cleanup(self):
1194
 
                calls.append('cleanup')
 
987
                self.counter -= 1
1195
988
 
1196
 
        runner = TextTestRunner(stream=self._log_file)
 
989
        runner = TextTestRunner(stream=self._log_file, keep_output=True)
1197
990
        test = SkippedTest('test_skip')
1198
991
        result = self.run_test_runner(runner, test)
1199
992
        self.assertTrue(result.wasSuccessful())
1200
993
        # Check if cleanup was called the right number of times.
1201
 
        self.assertEqual(['setUp', 'cleanup'], calls)
1202
 
 
1203
 
    def test_not_applicable(self):
1204
 
        # run a test that is skipped because it's not applicable
1205
 
        def not_applicable_test():
1206
 
            from bzrlib.tests import TestNotApplicable
1207
 
            raise TestNotApplicable('this test never runs')
1208
 
        out = StringIO()
1209
 
        runner = TextTestRunner(stream=out, verbosity=2)
1210
 
        test = unittest.FunctionTestCase(not_applicable_test)
1211
 
        result = self.run_test_runner(runner, test)
1212
 
        self._log_file.write(out.getvalue())
1213
 
        self.assertTrue(result.wasSuccessful())
1214
 
        self.assertTrue(result.wasStrictlySuccessful())
1215
 
        self.assertContainsRe(out.getvalue(),
1216
 
                r'(?m)not_applicable_test   * N/A')
1217
 
        self.assertContainsRe(out.getvalue(),
1218
 
                r'(?m)^    this test never runs')
1219
 
 
1220
 
    def test_not_applicable_demo(self):
1221
 
        # just so you can see it in the test output
1222
 
        raise TestNotApplicable('this test is just a demonstation')
 
994
        self.assertEqual(0, test.counter)
1223
995
 
1224
996
    def test_unsupported_features_listed(self):
1225
997
        """When unsupported features are encountered they are detailed."""
1261
1033
            revision_id = workingtree.get_parent_ids()[0]
1262
1034
            self.assertEndsWith(output_string.rstrip(), revision_id)
1263
1035
 
1264
 
    def assertLogDeleted(self, test):
1265
 
        log = test._get_log()
1266
 
        self.assertEqual("DELETED log file to reduce memory footprint", log)
1267
 
        self.assertEqual('', test._log_contents)
1268
 
        self.assertIs(None, test._log_file_name)
1269
 
 
1270
1036
    def test_success_log_deleted(self):
1271
1037
        """Successful tests have their log deleted"""
1272
1038
 
1280
1046
        test = LogTester('test_success')
1281
1047
        result = self.run_test_runner(runner, test)
1282
1048
 
1283
 
        self.assertLogDeleted(test)
1284
 
 
1285
 
    def test_skipped_log_deleted(self):
1286
 
        """Skipped tests have their log deleted"""
1287
 
 
1288
 
        class LogTester(TestCase):
1289
 
 
1290
 
            def test_skipped(self):
1291
 
                self.log('this will be removed\n')
1292
 
                raise tests.TestSkipped()
1293
 
 
1294
 
        sio = cStringIO.StringIO()
1295
 
        runner = TextTestRunner(stream=sio)
1296
 
        test = LogTester('test_skipped')
1297
 
        result = self.run_test_runner(runner, test)
1298
 
 
1299
 
        self.assertLogDeleted(test)
1300
 
 
1301
 
    def test_not_aplicable_log_deleted(self):
1302
 
        """Not applicable tests have their log deleted"""
1303
 
 
1304
 
        class LogTester(TestCase):
1305
 
 
1306
 
            def test_not_applicable(self):
1307
 
                self.log('this will be removed\n')
1308
 
                raise tests.TestNotApplicable()
1309
 
 
1310
 
        sio = cStringIO.StringIO()
1311
 
        runner = TextTestRunner(stream=sio)
1312
 
        test = LogTester('test_not_applicable')
1313
 
        result = self.run_test_runner(runner, test)
1314
 
 
1315
 
        self.assertLogDeleted(test)
1316
 
 
1317
 
    def test_known_failure_log_deleted(self):
1318
 
        """Know failure tests have their log deleted"""
1319
 
 
1320
 
        class LogTester(TestCase):
1321
 
 
1322
 
            def test_known_failure(self):
1323
 
                self.log('this will be removed\n')
1324
 
                raise tests.KnownFailure()
1325
 
 
1326
 
        sio = cStringIO.StringIO()
1327
 
        runner = TextTestRunner(stream=sio)
1328
 
        test = LogTester('test_known_failure')
1329
 
        result = self.run_test_runner(runner, test)
1330
 
 
1331
 
        self.assertLogDeleted(test)
 
1049
        log = test._get_log()
 
1050
        self.assertEqual("DELETED log file to reduce memory footprint", log)
 
1051
        self.assertEqual('', test._log_contents)
 
1052
        self.assertIs(None, test._log_file_name)
1332
1053
 
1333
1054
    def test_fail_log_kept(self):
1334
1055
        """Failed tests have their log kept"""
1380
1101
    def _test_pass(self):
1381
1102
        pass
1382
1103
 
1383
 
class _TestException(Exception):
1384
 
    pass
1385
1104
 
1386
1105
class TestTestCase(TestCase):
1387
1106
    """Tests that test the core bzrlib TestCase."""
1388
1107
 
1389
 
    def test_assertLength_matches_empty(self):
1390
 
        a_list = []
1391
 
        self.assertLength(0, a_list)
1392
 
 
1393
 
    def test_assertLength_matches_nonempty(self):
1394
 
        a_list = [1, 2, 3]
1395
 
        self.assertLength(3, a_list)
1396
 
 
1397
 
    def test_assertLength_fails_different(self):
1398
 
        a_list = []
1399
 
        self.assertRaises(AssertionError, self.assertLength, 1, a_list)
1400
 
 
1401
 
    def test_assertLength_shows_sequence_in_failure(self):
1402
 
        a_list = [1, 2, 3]
1403
 
        exception = self.assertRaises(AssertionError, self.assertLength, 2,
1404
 
            a_list)
1405
 
        self.assertEqual('Incorrect length: wanted 2, got 3 for [1, 2, 3]',
1406
 
            exception.args[0])
1407
 
 
1408
 
    def test_base_setUp_not_called_causes_failure(self):
1409
 
        class TestCaseWithBrokenSetUp(TestCase):
1410
 
            def setUp(self):
1411
 
                pass # does not call TestCase.setUp
1412
 
            def test_foo(self):
1413
 
                pass
1414
 
        test = TestCaseWithBrokenSetUp('test_foo')
1415
 
        result = unittest.TestResult()
1416
 
        test.run(result)
1417
 
        self.assertFalse(result.wasSuccessful())
1418
 
        self.assertEqual(1, result.testsRun)
1419
 
 
1420
 
    def test_base_tearDown_not_called_causes_failure(self):
1421
 
        class TestCaseWithBrokenTearDown(TestCase):
1422
 
            def tearDown(self):
1423
 
                pass # does not call TestCase.tearDown
1424
 
            def test_foo(self):
1425
 
                pass
1426
 
        test = TestCaseWithBrokenTearDown('test_foo')
1427
 
        result = unittest.TestResult()
1428
 
        test.run(result)
1429
 
        self.assertFalse(result.wasSuccessful())
1430
 
        self.assertEqual(1, result.testsRun)
1431
 
 
1432
 
    def test_debug_flags_sanitised(self):
1433
 
        """The bzrlib debug flags should be sanitised by setUp."""
1434
 
        if 'allow_debug' in tests.selftest_debug_flags:
1435
 
            raise TestNotApplicable(
1436
 
                '-Eallow_debug option prevents debug flag sanitisation')
1437
 
        # we could set something and run a test that will check
1438
 
        # it gets santised, but this is probably sufficient for now:
1439
 
        # if someone runs the test with -Dsomething it will error.
1440
 
        self.assertEqual(set(), bzrlib.debug.debug_flags)
1441
 
 
1442
 
    def change_selftest_debug_flags(self, new_flags):
1443
 
        orig_selftest_flags = tests.selftest_debug_flags
1444
 
        self.addCleanup(self._restore_selftest_debug_flags, orig_selftest_flags)
1445
 
        tests.selftest_debug_flags = set(new_flags)
1446
 
 
1447
 
    def _restore_selftest_debug_flags(self, flags):
1448
 
        tests.selftest_debug_flags = flags
1449
 
 
1450
 
    def test_allow_debug_flag(self):
1451
 
        """The -Eallow_debug flag prevents bzrlib.debug.debug_flags from being
1452
 
        sanitised (i.e. cleared) before running a test.
1453
 
        """
1454
 
        self.change_selftest_debug_flags(set(['allow_debug']))
1455
 
        bzrlib.debug.debug_flags = set(['a-flag'])
1456
 
        class TestThatRecordsFlags(TestCase):
1457
 
            def test_foo(nested_self):
1458
 
                self.flags = set(bzrlib.debug.debug_flags)
1459
 
        test = TestThatRecordsFlags('test_foo')
1460
 
        test.run(self.make_test_result())
1461
 
        self.assertEqual(set(['a-flag']), self.flags)
1462
 
 
1463
 
    def test_debug_flags_restored(self):
1464
 
        """The bzrlib debug flags should be restored to their original state
1465
 
        after the test was run, even if allow_debug is set.
1466
 
        """
1467
 
        self.change_selftest_debug_flags(set(['allow_debug']))
1468
 
        # Now run a test that modifies debug.debug_flags.
1469
 
        bzrlib.debug.debug_flags = set(['original-state'])
1470
 
        class TestThatModifiesFlags(TestCase):
1471
 
            def test_foo(self):
1472
 
                bzrlib.debug.debug_flags = set(['modified'])
1473
 
        test = TestThatModifiesFlags('test_foo')
1474
 
        test.run(self.make_test_result())
1475
 
        self.assertEqual(set(['original-state']), bzrlib.debug.debug_flags)
1476
 
 
1477
 
    def make_test_result(self):
1478
 
        return bzrlib.tests.TextTestResult(
1479
 
            self._log_file, descriptions=0, verbosity=1)
1480
 
 
1481
1108
    def inner_test(self):
1482
1109
        # the inner child test
1483
1110
        note("inner_test")
1486
1113
        # the outer child test
1487
1114
        note("outer_start")
1488
1115
        self.inner_test = TestTestCase("inner_child")
1489
 
        result = self.make_test_result()
 
1116
        result = bzrlib.tests.TextTestResult(self._log_file,
 
1117
                                        descriptions=0,
 
1118
                                        verbosity=1)
1490
1119
        self.inner_test.run(result)
1491
1120
        note("outer finish")
1492
1121
 
1496
1125
        # should setup a new log, log content to it, setup a child case (B),
1497
1126
        # which should log independently, then case (A) should log a trailer
1498
1127
        # and return.
1499
 
        # we do two nested children so that we can verify the state of the
 
1128
        # we do two nested children so that we can verify the state of the 
1500
1129
        # logs after the outer child finishes is correct, which a bad clean
1501
1130
        # up routine in tearDown might trigger a fault in our test with only
1502
1131
        # one child, we should instead see the bad result inside our test with
1504
1133
        # the outer child test
1505
1134
        original_trace = bzrlib.trace._trace_file
1506
1135
        outer_test = TestTestCase("outer_child")
1507
 
        result = self.make_test_result()
 
1136
        result = bzrlib.tests.TextTestResult(self._log_file,
 
1137
                                        descriptions=0,
 
1138
                                        verbosity=1)
1508
1139
        outer_test.run(result)
1509
1140
        self.assertEqual(original_trace, bzrlib.trace._trace_file)
1510
1141
 
1529
1160
 
1530
1161
    def test_hooks_sanitised(self):
1531
1162
        """The bzrlib hooks should be sanitised by setUp."""
1532
 
        # Note this test won't fail with hooks that the core library doesn't
1533
 
        # use - but it trigger with a plugin that adds hooks, so its still a
1534
 
        # useful warning in that case.
1535
1163
        self.assertEqual(bzrlib.branch.BranchHooks(),
1536
1164
            bzrlib.branch.Branch.hooks)
1537
 
        self.assertEqual(bzrlib.smart.server.SmartServerHooks(),
1538
 
            bzrlib.smart.server.SmartTCPServer.hooks)
1539
 
        self.assertEqual(bzrlib.commands.CommandHooks(),
1540
 
            bzrlib.commands.Command.hooks)
1541
1165
 
1542
1166
    def test__gather_lsprof_in_benchmarks(self):
1543
1167
        """When _gather_lsprof_in_benchmarks is on, accumulate profile data.
1544
 
 
 
1168
        
1545
1169
        Each self.time() call is individually and separately profiled.
1546
1170
        """
1547
 
        self.requireFeature(test_lsprof.LSProfFeature)
1548
 
        # overrides the class member with an instance member so no cleanup
 
1171
        try:
 
1172
            import bzrlib.lsprof
 
1173
        except ImportError:
 
1174
            raise TestSkipped("lsprof not installed.")
 
1175
        # overrides the class member with an instance member so no cleanup 
1549
1176
        # needed.
1550
1177
        self._gather_lsprof_in_benchmarks = True
1551
1178
        self.time(time.sleep, 0.000)
1577
1204
    def test_run_no_parameters(self):
1578
1205
        test = SampleTestCase('_test_pass')
1579
1206
        test.run()
1580
 
 
 
1207
    
1581
1208
    def test_run_enabled_unittest_result(self):
1582
1209
        """Test we revert to regular behaviour when the test is enabled."""
1583
1210
        test = SampleTestCase('_test_pass')
1631
1258
            ],
1632
1259
            result.calls)
1633
1260
 
1634
 
    def test_assert_list_raises_on_generator(self):
1635
 
        def generator_which_will_raise():
1636
 
            # This will not raise until after the first yield
1637
 
            yield 1
1638
 
            raise _TestException()
1639
 
 
1640
 
        e = self.assertListRaises(_TestException, generator_which_will_raise)
1641
 
        self.assertIsInstance(e, _TestException)
1642
 
 
1643
 
        e = self.assertListRaises(Exception, generator_which_will_raise)
1644
 
        self.assertIsInstance(e, _TestException)
1645
 
 
1646
 
    def test_assert_list_raises_on_plain(self):
1647
 
        def plain_exception():
1648
 
            raise _TestException()
1649
 
            return []
1650
 
 
1651
 
        e = self.assertListRaises(_TestException, plain_exception)
1652
 
        self.assertIsInstance(e, _TestException)
1653
 
 
1654
 
        e = self.assertListRaises(Exception, plain_exception)
1655
 
        self.assertIsInstance(e, _TestException)
1656
 
 
1657
 
    def test_assert_list_raises_assert_wrong_exception(self):
1658
 
        class _NotTestException(Exception):
1659
 
            pass
1660
 
 
1661
 
        def wrong_exception():
1662
 
            raise _NotTestException()
1663
 
 
1664
 
        def wrong_exception_generator():
1665
 
            yield 1
1666
 
            yield 2
1667
 
            raise _NotTestException()
1668
 
 
1669
 
        # Wrong exceptions are not intercepted
1670
 
        self.assertRaises(_NotTestException,
1671
 
            self.assertListRaises, _TestException, wrong_exception)
1672
 
        self.assertRaises(_NotTestException,
1673
 
            self.assertListRaises, _TestException, wrong_exception_generator)
1674
 
 
1675
 
    def test_assert_list_raises_no_exception(self):
1676
 
        def success():
1677
 
            return []
1678
 
 
1679
 
        def success_generator():
1680
 
            yield 1
1681
 
            yield 2
1682
 
 
1683
 
        self.assertRaises(AssertionError,
1684
 
            self.assertListRaises, _TestException, success)
1685
 
 
1686
 
        self.assertRaises(AssertionError,
1687
 
            self.assertListRaises, _TestException, success_generator)
1688
 
 
1689
 
 
1690
 
# NB: Don't delete this; it's not actually from 0.11!
1691
 
@deprecated_function(deprecated_in((0, 11, 0)))
 
1261
 
 
1262
@symbol_versioning.deprecated_function(zero_eleven)
1692
1263
def sample_deprecated_function():
1693
1264
    """A deprecated function to test applyDeprecated with."""
1694
1265
    return 2
1701
1272
class ApplyDeprecatedHelper(object):
1702
1273
    """A helper class for ApplyDeprecated tests."""
1703
1274
 
1704
 
    @deprecated_method(deprecated_in((0, 11, 0)))
 
1275
    @symbol_versioning.deprecated_method(zero_eleven)
1705
1276
    def sample_deprecated_method(self, param_one):
1706
1277
        """A deprecated method for testing with."""
1707
1278
        return param_one
1709
1280
    def sample_normal_method(self):
1710
1281
        """A undeprecated method."""
1711
1282
 
1712
 
    @deprecated_method(deprecated_in((0, 10, 0)))
 
1283
    @symbol_versioning.deprecated_method(zero_ten)
1713
1284
    def sample_nested_deprecation(self):
1714
1285
        return sample_deprecated_function()
1715
1286
 
1730
1301
    def test_applyDeprecated_not_deprecated(self):
1731
1302
        sample_object = ApplyDeprecatedHelper()
1732
1303
        # calling an undeprecated callable raises an assertion
1733
 
        self.assertRaises(AssertionError, self.applyDeprecated,
1734
 
            deprecated_in((0, 11, 0)),
 
1304
        self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
1735
1305
            sample_object.sample_normal_method)
1736
 
        self.assertRaises(AssertionError, self.applyDeprecated,
1737
 
            deprecated_in((0, 11, 0)),
 
1306
        self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
1738
1307
            sample_undeprecated_function, "a param value")
1739
1308
        # calling a deprecated callable (function or method) with the wrong
1740
1309
        # expected deprecation fails.
1741
 
        self.assertRaises(AssertionError, self.applyDeprecated,
1742
 
            deprecated_in((0, 10, 0)),
 
1310
        self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
1743
1311
            sample_object.sample_deprecated_method, "a param value")
1744
 
        self.assertRaises(AssertionError, self.applyDeprecated,
1745
 
            deprecated_in((0, 10, 0)),
 
1312
        self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
1746
1313
            sample_deprecated_function)
1747
1314
        # calling a deprecated callable (function or method) with the right
1748
1315
        # expected deprecation returns the functions result.
1749
 
        self.assertEqual("a param value",
1750
 
            self.applyDeprecated(deprecated_in((0, 11, 0)),
 
1316
        self.assertEqual("a param value", self.applyDeprecated(zero_eleven,
1751
1317
            sample_object.sample_deprecated_method, "a param value"))
1752
 
        self.assertEqual(2, self.applyDeprecated(deprecated_in((0, 11, 0)),
 
1318
        self.assertEqual(2, self.applyDeprecated(zero_eleven,
1753
1319
            sample_deprecated_function))
1754
1320
        # calling a nested deprecation with the wrong deprecation version
1755
 
        # fails even if a deeper nested function was deprecated with the
 
1321
        # fails even if a deeper nested function was deprecated with the 
1756
1322
        # supplied version.
1757
1323
        self.assertRaises(AssertionError, self.applyDeprecated,
1758
 
            deprecated_in((0, 11, 0)), sample_object.sample_nested_deprecation)
 
1324
            zero_eleven, sample_object.sample_nested_deprecation)
1759
1325
        # calling a nested deprecation with the right deprecation value
1760
1326
        # returns the calls result.
1761
 
        self.assertEqual(2, self.applyDeprecated(deprecated_in((0, 10, 0)),
 
1327
        self.assertEqual(2, self.applyDeprecated(zero_ten,
1762
1328
            sample_object.sample_nested_deprecation))
1763
1329
 
1764
1330
    def test_callDeprecated(self):
1765
1331
        def testfunc(be_deprecated, result=None):
1766
1332
            if be_deprecated is True:
1767
 
                symbol_versioning.warn('i am deprecated', DeprecationWarning,
 
1333
                symbol_versioning.warn('i am deprecated', DeprecationWarning, 
1768
1334
                                       stacklevel=1)
1769
1335
            return result
1770
1336
        result = self.callDeprecated(['i am deprecated'], testfunc, True)
1775
1341
        self.callDeprecated([], testfunc, be_deprecated=False)
1776
1342
 
1777
1343
 
1778
 
class TestWarningTests(TestCase):
1779
 
    """Tests for calling methods that raise warnings."""
1780
 
 
1781
 
    def test_callCatchWarnings(self):
1782
 
        def meth(a, b):
1783
 
            warnings.warn("this is your last warning")
1784
 
            return a + b
1785
 
        wlist, result = self.callCatchWarnings(meth, 1, 2)
1786
 
        self.assertEquals(3, result)
1787
 
        # would like just to compare them, but UserWarning doesn't implement
1788
 
        # eq well
1789
 
        w0, = wlist
1790
 
        self.assertIsInstance(w0, UserWarning)
1791
 
        self.assertEquals("this is your last warning", str(w0))
1792
 
 
1793
 
 
1794
1344
class TestConvenienceMakers(TestCaseWithTransport):
1795
1345
    """Test for the make_* convenience functions."""
1796
1346
 
1835
1385
            return TestSuite()
1836
1386
        out = StringIO()
1837
1387
        err = StringIO()
1838
 
        self.apply_redirected(out, err, None, bzrlib.tests.selftest,
 
1388
        self.apply_redirected(out, err, None, bzrlib.tests.selftest, 
1839
1389
            test_suite_factory=factory)
1840
1390
        self.assertEqual([True], factory_called)
1841
1391
 
1842
1392
 
 
1393
class TestSelftestCleanOutput(TestCaseInTempDir):
 
1394
 
 
1395
    def test_clean_output(self):
 
1396
        # test functionality of clean_selftest_output()
 
1397
        from bzrlib.tests import clean_selftest_output
 
1398
 
 
1399
        dirs = ('test0000.tmp', 'test0001.tmp', 'bzrlib', 'tests')
 
1400
        files = ('bzr', 'setup.py', 'test9999.tmp')
 
1401
        for i in dirs:
 
1402
            os.mkdir(i)
 
1403
        for i in files:
 
1404
            f = file(i, 'wb')
 
1405
            f.write('content of ')
 
1406
            f.write(i)
 
1407
            f.close()
 
1408
 
 
1409
        root = os.getcwdu()
 
1410
        before = os.listdir(root)
 
1411
        before.sort()
 
1412
        self.assertEquals(['bzr','bzrlib','setup.py',
 
1413
                           'test0000.tmp','test0001.tmp',
 
1414
                           'test9999.tmp','tests'],
 
1415
                           before)
 
1416
        clean_selftest_output(root, quiet=True)
 
1417
        after = os.listdir(root)
 
1418
        after.sort()
 
1419
        self.assertEquals(['bzr','bzrlib','setup.py',
 
1420
                           'test9999.tmp','tests'],
 
1421
                           after)
 
1422
 
 
1423
 
1843
1424
class TestKnownFailure(TestCase):
1844
1425
 
1845
1426
    def test_known_failure(self):
1848
1429
        # runners.
1849
1430
        self.assertIsInstance(KnownFailure(""), AssertionError)
1850
1431
 
1851
 
    def test_expect_failure(self):
1852
 
        try:
1853
 
            self.expectFailure("Doomed to failure", self.assertTrue, False)
1854
 
        except KnownFailure, e:
1855
 
            self.assertEqual('Doomed to failure', e.args[0])
1856
 
        try:
1857
 
            self.expectFailure("Doomed to failure", self.assertTrue, True)
1858
 
        except AssertionError, e:
1859
 
            self.assertEqual('Unexpected success.  Should have failed:'
1860
 
                             ' Doomed to failure', e.args[0])
1861
 
        else:
1862
 
            self.fail('Assertion not raised')
1863
 
 
1864
1432
 
1865
1433
class TestFeature(TestCase):
1866
1434
 
1901
1469
        feature = Feature()
1902
1470
        exception = UnavailableFeature(feature)
1903
1471
        self.assertIs(feature, exception.args[0])
1904
 
 
1905
 
 
1906
 
class TestSelftestFiltering(TestCase):
1907
 
 
1908
 
    def setUp(self):
1909
 
        TestCase.setUp(self)
1910
 
        self.suite = TestUtil.TestSuite()
1911
 
        self.loader = TestUtil.TestLoader()
1912
 
        self.suite.addTest(self.loader.loadTestsFromModuleNames([
1913
 
            'bzrlib.tests.test_selftest']))
1914
 
        self.all_names = _test_ids(self.suite)
1915
 
 
1916
 
    def test_condition_id_re(self):
1917
 
        test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1918
 
            'test_condition_id_re')
1919
 
        filtered_suite = filter_suite_by_condition(self.suite,
1920
 
            condition_id_re('test_condition_id_re'))
1921
 
        self.assertEqual([test_name], _test_ids(filtered_suite))
1922
 
 
1923
 
    def test_condition_id_in_list(self):
1924
 
        test_names = ['bzrlib.tests.test_selftest.TestSelftestFiltering.'
1925
 
                      'test_condition_id_in_list']
1926
 
        id_list = tests.TestIdList(test_names)
1927
 
        filtered_suite = filter_suite_by_condition(
1928
 
            self.suite, tests.condition_id_in_list(id_list))
1929
 
        my_pattern = 'TestSelftestFiltering.*test_condition_id_in_list'
1930
 
        re_filtered = filter_suite_by_re(self.suite, my_pattern)
1931
 
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
1932
 
 
1933
 
    def test_condition_id_startswith(self):
1934
 
        klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
1935
 
        start1 = klass + 'test_condition_id_starts'
1936
 
        start2 = klass + 'test_condition_id_in'
1937
 
        test_names = [ klass + 'test_condition_id_in_list',
1938
 
                      klass + 'test_condition_id_startswith',
1939
 
                     ]
1940
 
        filtered_suite = filter_suite_by_condition(
1941
 
            self.suite, tests.condition_id_startswith([start1, start2]))
1942
 
        self.assertEqual(test_names, _test_ids(filtered_suite))
1943
 
 
1944
 
    def test_condition_isinstance(self):
1945
 
        filtered_suite = filter_suite_by_condition(self.suite,
1946
 
            condition_isinstance(self.__class__))
1947
 
        class_pattern = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
1948
 
        re_filtered = filter_suite_by_re(self.suite, class_pattern)
1949
 
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
1950
 
 
1951
 
    def test_exclude_tests_by_condition(self):
1952
 
        excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1953
 
            'test_exclude_tests_by_condition')
1954
 
        filtered_suite = exclude_tests_by_condition(self.suite,
1955
 
            lambda x:x.id() == excluded_name)
1956
 
        self.assertEqual(len(self.all_names) - 1,
1957
 
            filtered_suite.countTestCases())
1958
 
        self.assertFalse(excluded_name in _test_ids(filtered_suite))
1959
 
        remaining_names = list(self.all_names)
1960
 
        remaining_names.remove(excluded_name)
1961
 
        self.assertEqual(remaining_names, _test_ids(filtered_suite))
1962
 
 
1963
 
    def test_exclude_tests_by_re(self):
1964
 
        self.all_names = _test_ids(self.suite)
1965
 
        filtered_suite = exclude_tests_by_re(self.suite, 'exclude_tests_by_re')
1966
 
        excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1967
 
            'test_exclude_tests_by_re')
1968
 
        self.assertEqual(len(self.all_names) - 1,
1969
 
            filtered_suite.countTestCases())
1970
 
        self.assertFalse(excluded_name in _test_ids(filtered_suite))
1971
 
        remaining_names = list(self.all_names)
1972
 
        remaining_names.remove(excluded_name)
1973
 
        self.assertEqual(remaining_names, _test_ids(filtered_suite))
1974
 
 
1975
 
    def test_filter_suite_by_condition(self):
1976
 
        test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
1977
 
            'test_filter_suite_by_condition')
1978
 
        filtered_suite = filter_suite_by_condition(self.suite,
1979
 
            lambda x:x.id() == test_name)
1980
 
        self.assertEqual([test_name], _test_ids(filtered_suite))
1981
 
 
1982
 
    def test_filter_suite_by_re(self):
1983
 
        filtered_suite = filter_suite_by_re(self.suite, 'test_filter_suite_by_r')
1984
 
        filtered_names = _test_ids(filtered_suite)
1985
 
        self.assertEqual(filtered_names, ['bzrlib.tests.test_selftest.'
1986
 
            'TestSelftestFiltering.test_filter_suite_by_re'])
1987
 
 
1988
 
    def test_filter_suite_by_id_list(self):
1989
 
        test_list = ['bzrlib.tests.test_selftest.'
1990
 
                     'TestSelftestFiltering.test_filter_suite_by_id_list']
1991
 
        filtered_suite = tests.filter_suite_by_id_list(
1992
 
            self.suite, tests.TestIdList(test_list))
1993
 
        filtered_names = _test_ids(filtered_suite)
1994
 
        self.assertEqual(
1995
 
            filtered_names,
1996
 
            ['bzrlib.tests.test_selftest.'
1997
 
             'TestSelftestFiltering.test_filter_suite_by_id_list'])
1998
 
 
1999
 
    def test_filter_suite_by_id_startswith(self):
2000
 
        # By design this test may fail if another test is added whose name also
2001
 
        # begins with one of the start value used.
2002
 
        klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
2003
 
        start1 = klass + 'test_filter_suite_by_id_starts'
2004
 
        start2 = klass + 'test_filter_suite_by_id_li'
2005
 
        test_list = [klass + 'test_filter_suite_by_id_list',
2006
 
                     klass + 'test_filter_suite_by_id_startswith',
2007
 
                     ]
2008
 
        filtered_suite = tests.filter_suite_by_id_startswith(
2009
 
            self.suite, [start1, start2])
2010
 
        self.assertEqual(
2011
 
            test_list,
2012
 
            _test_ids(filtered_suite),
2013
 
            )
2014
 
 
2015
 
    def test_preserve_input(self):
2016
 
        # NB: Surely this is something in the stdlib to do this?
2017
 
        self.assertTrue(self.suite is preserve_input(self.suite))
2018
 
        self.assertTrue("@#$" is preserve_input("@#$"))
2019
 
 
2020
 
    def test_randomize_suite(self):
2021
 
        randomized_suite = randomize_suite(self.suite)
2022
 
        # randomizing should not add or remove test names.
2023
 
        self.assertEqual(set(_test_ids(self.suite)),
2024
 
                         set(_test_ids(randomized_suite)))
2025
 
        # Technically, this *can* fail, because random.shuffle(list) can be
2026
 
        # equal to list. Trying multiple times just pushes the frequency back.
2027
 
        # As its len(self.all_names)!:1, the failure frequency should be low
2028
 
        # enough to ignore. RBC 20071021.
2029
 
        # It should change the order.
2030
 
        self.assertNotEqual(self.all_names, _test_ids(randomized_suite))
2031
 
        # But not the length. (Possibly redundant with the set test, but not
2032
 
        # necessarily.)
2033
 
        self.assertEqual(len(self.all_names), len(_test_ids(randomized_suite)))
2034
 
 
2035
 
    def test_split_suit_by_condition(self):
2036
 
        self.all_names = _test_ids(self.suite)
2037
 
        condition = condition_id_re('test_filter_suite_by_r')
2038
 
        split_suite = split_suite_by_condition(self.suite, condition)
2039
 
        filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2040
 
            'test_filter_suite_by_re')
2041
 
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
2042
 
        self.assertFalse(filtered_name in _test_ids(split_suite[1]))
2043
 
        remaining_names = list(self.all_names)
2044
 
        remaining_names.remove(filtered_name)
2045
 
        self.assertEqual(remaining_names, _test_ids(split_suite[1]))
2046
 
 
2047
 
    def test_split_suit_by_re(self):
2048
 
        self.all_names = _test_ids(self.suite)
2049
 
        split_suite = split_suite_by_re(self.suite, 'test_filter_suite_by_r')
2050
 
        filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2051
 
            'test_filter_suite_by_re')
2052
 
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
2053
 
        self.assertFalse(filtered_name in _test_ids(split_suite[1]))
2054
 
        remaining_names = list(self.all_names)
2055
 
        remaining_names.remove(filtered_name)
2056
 
        self.assertEqual(remaining_names, _test_ids(split_suite[1]))
2057
 
 
2058
 
 
2059
 
class TestCheckInventoryShape(TestCaseWithTransport):
2060
 
 
2061
 
    def test_check_inventory_shape(self):
2062
 
        files = ['a', 'b/', 'b/c']
2063
 
        tree = self.make_branch_and_tree('.')
2064
 
        self.build_tree(files)
2065
 
        tree.add(files)
2066
 
        tree.lock_read()
2067
 
        try:
2068
 
            self.check_inventory_shape(tree.inventory, files)
2069
 
        finally:
2070
 
            tree.unlock()
2071
 
 
2072
 
 
2073
 
class TestBlackboxSupport(TestCase):
2074
 
    """Tests for testsuite blackbox features."""
2075
 
 
2076
 
    def test_run_bzr_failure_not_caught(self):
2077
 
        # When we run bzr in blackbox mode, we want any unexpected errors to
2078
 
        # propagate up to the test suite so that it can show the error in the
2079
 
        # usual way, and we won't get a double traceback.
2080
 
        e = self.assertRaises(
2081
 
            AssertionError,
2082
 
            self.run_bzr, ['assert-fail'])
2083
 
        # make sure we got the real thing, not an error from somewhere else in
2084
 
        # the test framework
2085
 
        self.assertEquals('always fails', str(e))
2086
 
        # check that there's no traceback in the test log
2087
 
        self.assertNotContainsRe(self._get_log(keep_log_file=True),
2088
 
            r'Traceback')
2089
 
 
2090
 
    def test_run_bzr_user_error_caught(self):
2091
 
        # Running bzr in blackbox mode, normal/expected/user errors should be
2092
 
        # caught in the regular way and turned into an error message plus exit
2093
 
        # code.
2094
 
        out, err = self.run_bzr(["log", "/nonexistantpath"], retcode=3)
2095
 
        self.assertEqual(out, '')
2096
 
        self.assertContainsRe(err,
2097
 
            'bzr: ERROR: Not a branch: ".*nonexistantpath/".\n')
2098
 
 
2099
 
 
2100
 
class TestTestLoader(TestCase):
2101
 
    """Tests for the test loader."""
2102
 
 
2103
 
    def _get_loader_and_module(self):
2104
 
        """Gets a TestLoader and a module with one test in it."""
2105
 
        loader = TestUtil.TestLoader()
2106
 
        module = {}
2107
 
        class Stub(TestCase):
2108
 
            def test_foo(self):
2109
 
                pass
2110
 
        class MyModule(object):
2111
 
            pass
2112
 
        MyModule.a_class = Stub
2113
 
        module = MyModule()
2114
 
        return loader, module
2115
 
 
2116
 
    def test_module_no_load_tests_attribute_loads_classes(self):
2117
 
        loader, module = self._get_loader_and_module()
2118
 
        self.assertEqual(1, loader.loadTestsFromModule(module).countTestCases())
2119
 
 
2120
 
    def test_module_load_tests_attribute_gets_called(self):
2121
 
        loader, module = self._get_loader_and_module()
2122
 
        # 'self' is here because we're faking the module with a class. Regular
2123
 
        # load_tests do not need that :)
2124
 
        def load_tests(self, standard_tests, module, loader):
2125
 
            result = loader.suiteClass()
2126
 
            for test in iter_suite_tests(standard_tests):
2127
 
                result.addTests([test, test])
2128
 
            return result
2129
 
        # add a load_tests() method which multiplies the tests from the module.
2130
 
        module.__class__.load_tests = load_tests
2131
 
        self.assertEqual(2, loader.loadTestsFromModule(module).countTestCases())
2132
 
 
2133
 
    def test_load_tests_from_module_name_smoke_test(self):
2134
 
        loader = TestUtil.TestLoader()
2135
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2136
 
        self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
2137
 
                          _test_ids(suite))
2138
 
 
2139
 
    def test_load_tests_from_module_name_with_bogus_module_name(self):
2140
 
        loader = TestUtil.TestLoader()
2141
 
        self.assertRaises(ImportError, loader.loadTestsFromModuleName, 'bogus')
2142
 
 
2143
 
 
2144
 
class TestTestIdList(tests.TestCase):
2145
 
 
2146
 
    def _create_id_list(self, test_list):
2147
 
        return tests.TestIdList(test_list)
2148
 
 
2149
 
    def _create_suite(self, test_id_list):
2150
 
 
2151
 
        class Stub(TestCase):
2152
 
            def test_foo(self):
2153
 
                pass
2154
 
 
2155
 
        def _create_test_id(id):
2156
 
            return lambda: id
2157
 
 
2158
 
        suite = TestUtil.TestSuite()
2159
 
        for id in test_id_list:
2160
 
            t  = Stub('test_foo')
2161
 
            t.id = _create_test_id(id)
2162
 
            suite.addTest(t)
2163
 
        return suite
2164
 
 
2165
 
    def _test_ids(self, test_suite):
2166
 
        """Get the ids for the tests in a test suite."""
2167
 
        return [t.id() for t in iter_suite_tests(test_suite)]
2168
 
 
2169
 
    def test_empty_list(self):
2170
 
        id_list = self._create_id_list([])
2171
 
        self.assertEquals({}, id_list.tests)
2172
 
        self.assertEquals({}, id_list.modules)
2173
 
 
2174
 
    def test_valid_list(self):
2175
 
        id_list = self._create_id_list(
2176
 
            ['mod1.cl1.meth1', 'mod1.cl1.meth2',
2177
 
             'mod1.func1', 'mod1.cl2.meth2',
2178
 
             'mod1.submod1',
2179
 
             'mod1.submod2.cl1.meth1', 'mod1.submod2.cl2.meth2',
2180
 
             ])
2181
 
        self.assertTrue(id_list.refers_to('mod1'))
2182
 
        self.assertTrue(id_list.refers_to('mod1.submod1'))
2183
 
        self.assertTrue(id_list.refers_to('mod1.submod2'))
2184
 
        self.assertTrue(id_list.includes('mod1.cl1.meth1'))
2185
 
        self.assertTrue(id_list.includes('mod1.submod1'))
2186
 
        self.assertTrue(id_list.includes('mod1.func1'))
2187
 
 
2188
 
    def test_bad_chars_in_params(self):
2189
 
        id_list = self._create_id_list(['mod1.cl1.meth1(xx.yy)'])
2190
 
        self.assertTrue(id_list.refers_to('mod1'))
2191
 
        self.assertTrue(id_list.includes('mod1.cl1.meth1(xx.yy)'))
2192
 
 
2193
 
    def test_module_used(self):
2194
 
        id_list = self._create_id_list(['mod.class.meth'])
2195
 
        self.assertTrue(id_list.refers_to('mod'))
2196
 
        self.assertTrue(id_list.refers_to('mod.class'))
2197
 
        self.assertTrue(id_list.refers_to('mod.class.meth'))
2198
 
 
2199
 
    def test_test_suite(self):
2200
 
        # This test is slow, so we do a single test with one test in each
2201
 
        # category
2202
 
        test_list = [
2203
 
            # testmod_names
2204
 
            'bzrlib.tests.blackbox.test_branch.TestBranch.test_branch',
2205
 
            'bzrlib.tests.test_selftest.TestTestIdList.test_test_suite',
2206
 
            # transport implementations
2207
 
            'bzrlib.tests.test_transport_implementations.TransportTests'
2208
 
            '.test_abspath(LocalURLServer)',
2209
 
            # modules_to_doctest
2210
 
            'bzrlib.timestamp.format_highres_date',
2211
 
            # plugins can't be tested that way since selftest may be run with
2212
 
            # --no-plugins
2213
 
            ]
2214
 
        suite = tests.test_suite(test_list)
2215
 
        self.assertEquals(test_list, _test_ids(suite))
2216
 
 
2217
 
    def test_test_suite_matches_id_list_with_unknown(self):
2218
 
        loader = TestUtil.TestLoader()
2219
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2220
 
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',
2221
 
                     'bogus']
2222
 
        not_found, duplicates = tests.suite_matches_id_list(suite, test_list)
2223
 
        self.assertEquals(['bogus'], not_found)
2224
 
        self.assertEquals([], duplicates)
2225
 
 
2226
 
    def test_suite_matches_id_list_with_duplicates(self):
2227
 
        loader = TestUtil.TestLoader()
2228
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2229
 
        dupes = loader.suiteClass()
2230
 
        for test in iter_suite_tests(suite):
2231
 
            dupes.addTest(test)
2232
 
            dupes.addTest(test) # Add it again
2233
 
 
2234
 
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',]
2235
 
        not_found, duplicates = tests.suite_matches_id_list(
2236
 
            dupes, test_list)
2237
 
        self.assertEquals([], not_found)
2238
 
        self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
2239
 
                          duplicates)
2240
 
 
2241
 
 
2242
 
class TestLoadTestIdList(tests.TestCaseInTempDir):
2243
 
 
2244
 
    def _create_test_list_file(self, file_name, content):
2245
 
        fl = open(file_name, 'wt')
2246
 
        fl.write(content)
2247
 
        fl.close()
2248
 
 
2249
 
    def test_load_unknown(self):
2250
 
        self.assertRaises(errors.NoSuchFile,
2251
 
                          tests.load_test_id_list, 'i_do_not_exist')
2252
 
 
2253
 
    def test_load_test_list(self):
2254
 
        test_list_fname = 'test.list'
2255
 
        self._create_test_list_file(test_list_fname,
2256
 
                                    'mod1.cl1.meth1\nmod2.cl2.meth2\n')
2257
 
        tlist = tests.load_test_id_list(test_list_fname)
2258
 
        self.assertEquals(2, len(tlist))
2259
 
        self.assertEquals('mod1.cl1.meth1', tlist[0])
2260
 
        self.assertEquals('mod2.cl2.meth2', tlist[1])
2261
 
 
2262
 
    def test_load_dirty_file(self):
2263
 
        test_list_fname = 'test.list'
2264
 
        self._create_test_list_file(test_list_fname,
2265
 
                                    '  mod1.cl1.meth1\n\nmod2.cl2.meth2  \n'
2266
 
                                    'bar baz\n')
2267
 
        tlist = tests.load_test_id_list(test_list_fname)
2268
 
        self.assertEquals(4, len(tlist))
2269
 
        self.assertEquals('mod1.cl1.meth1', tlist[0])
2270
 
        self.assertEquals('', tlist[1])
2271
 
        self.assertEquals('mod2.cl2.meth2', tlist[2])
2272
 
        self.assertEquals('bar baz', tlist[3])
2273
 
 
2274
 
 
2275
 
class TestFilteredByModuleTestLoader(tests.TestCase):
2276
 
 
2277
 
    def _create_loader(self, test_list):
2278
 
        id_filter = tests.TestIdList(test_list)
2279
 
        loader = TestUtil.FilteredByModuleTestLoader(id_filter.refers_to)
2280
 
        return loader
2281
 
 
2282
 
    def test_load_tests(self):
2283
 
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
2284
 
        loader = self._create_loader(test_list)
2285
 
 
2286
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2287
 
        self.assertEquals(test_list, _test_ids(suite))
2288
 
 
2289
 
    def test_exclude_tests(self):
2290
 
        test_list = ['bogus']
2291
 
        loader = self._create_loader(test_list)
2292
 
 
2293
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2294
 
        self.assertEquals([], _test_ids(suite))
2295
 
 
2296
 
 
2297
 
class TestFilteredByNameStartTestLoader(tests.TestCase):
2298
 
 
2299
 
    def _create_loader(self, name_start):
2300
 
        def needs_module(name):
2301
 
            return name.startswith(name_start) or name_start.startswith(name)
2302
 
        loader = TestUtil.FilteredByModuleTestLoader(needs_module)
2303
 
        return loader
2304
 
 
2305
 
    def test_load_tests(self):
2306
 
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
2307
 
        loader = self._create_loader('bzrlib.tests.test_samp')
2308
 
 
2309
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2310
 
        self.assertEquals(test_list, _test_ids(suite))
2311
 
 
2312
 
    def test_load_tests_inside_module(self):
2313
 
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
2314
 
        loader = self._create_loader('bzrlib.tests.test_sampler.Demo')
2315
 
 
2316
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2317
 
        self.assertEquals(test_list, _test_ids(suite))
2318
 
 
2319
 
    def test_exclude_tests(self):
2320
 
        test_list = ['bogus']
2321
 
        loader = self._create_loader('bogus')
2322
 
 
2323
 
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2324
 
        self.assertEquals([], _test_ids(suite))
2325
 
 
2326
 
 
2327
 
class TestTestPrefixRegistry(tests.TestCase):
2328
 
 
2329
 
    def _get_registry(self):
2330
 
        tp_registry = tests.TestPrefixAliasRegistry()
2331
 
        return tp_registry
2332
 
 
2333
 
    def test_register_new_prefix(self):
2334
 
        tpr = self._get_registry()
2335
 
        tpr.register('foo', 'fff.ooo.ooo')
2336
 
        self.assertEquals('fff.ooo.ooo', tpr.get('foo'))
2337
 
 
2338
 
    def test_register_existing_prefix(self):
2339
 
        tpr = self._get_registry()
2340
 
        tpr.register('bar', 'bbb.aaa.rrr')
2341
 
        tpr.register('bar', 'bBB.aAA.rRR')
2342
 
        self.assertEquals('bbb.aaa.rrr', tpr.get('bar'))
2343
 
        self.assertContainsRe(self._get_log(keep_log_file=True),
2344
 
                              r'.*bar.*bbb.aaa.rrr.*bBB.aAA.rRR')
2345
 
 
2346
 
    def test_get_unknown_prefix(self):
2347
 
        tpr = self._get_registry()
2348
 
        self.assertRaises(KeyError, tpr.get, 'I am not a prefix')
2349
 
 
2350
 
    def test_resolve_prefix(self):
2351
 
        tpr = self._get_registry()
2352
 
        tpr.register('bar', 'bb.aa.rr')
2353
 
        self.assertEquals('bb.aa.rr', tpr.resolve_alias('bar'))
2354
 
 
2355
 
    def test_resolve_unknown_alias(self):
2356
 
        tpr = self._get_registry()
2357
 
        self.assertRaises(errors.BzrCommandError,
2358
 
                          tpr.resolve_alias, 'I am not a prefix')
2359
 
 
2360
 
    def test_predefined_prefixes(self):
2361
 
        tpr = tests.test_prefix_alias_registry
2362
 
        self.assertEquals('bzrlib', tpr.resolve_alias('bzrlib'))
2363
 
        self.assertEquals('bzrlib.doc', tpr.resolve_alias('bd'))
2364
 
        self.assertEquals('bzrlib.utils', tpr.resolve_alias('bu'))
2365
 
        self.assertEquals('bzrlib.tests', tpr.resolve_alias('bt'))
2366
 
        self.assertEquals('bzrlib.tests.blackbox', tpr.resolve_alias('bb'))
2367
 
        self.assertEquals('bzrlib.plugins', tpr.resolve_alias('bp'))
2368
 
 
2369
 
 
2370
 
class TestRunSuite(TestCase):
2371
 
 
2372
 
    def test_runner_class(self):
2373
 
        """run_suite accepts and uses a runner_class keyword argument."""
2374
 
        class Stub(TestCase):
2375
 
            def test_foo(self):
2376
 
                pass
2377
 
        suite = Stub("test_foo")
2378
 
        calls = []
2379
 
        class MyRunner(TextTestRunner):
2380
 
            def run(self, test):
2381
 
                calls.append(test)
2382
 
                return ExtendedTestResult(self.stream, self.descriptions,
2383
 
                    self.verbosity)
2384
 
        run_suite(suite, runner_class=MyRunner, stream=StringIO())
2385
 
        self.assertEqual(calls, [suite])
2386
 
 
2387
 
    def test_done(self):
2388
 
        """run_suite should call result.done()"""
2389
 
        self.calls = 0
2390
 
        def one_more_call(): self.calls += 1
2391
 
        def test_function():
2392
 
            pass
2393
 
        test = unittest.FunctionTestCase(test_function)
2394
 
        class InstrumentedTestResult(ExtendedTestResult):
2395
 
            def done(self): one_more_call()
2396
 
        class MyRunner(TextTestRunner):
2397
 
            def run(self, test):
2398
 
                return InstrumentedTestResult(self.stream, self.descriptions,
2399
 
                                              self.verbosity)
2400
 
        run_suite(test, runner_class=MyRunner, stream=StringIO())
2401
 
        self.assertEquals(1, self.calls)