~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_selftest.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2008-06-20 01:09:18 UTC
  • mfrom: (3505.1.1 ianc-integration)
  • Revision ID: pqm@pqm.ubuntu.com-20080620010918-64z4xylh1ap5hgyf
Accept user names with @s in URLs (Neil Martinsen-Burrell)

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