~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_selftest.py

  • Committer: Aaron Bentley
  • Date: 2008-03-11 14:29:08 UTC
  • mto: This revision was merged to the branch mainline in revision 3264.
  • Revision ID: aaron@aaronbentley.com-20080311142908-yyrvcpn2mldt0fnn
Update documentation to reflect conflict-handling difference

Show diffs side-by-side

added added

removed removed

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