/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_selftest.py

  • Committer: Robert Collins
  • Date: 2009-02-11 12:49:50 UTC
  • mto: (4000.2.2 test-result-registry)
  • mto: This revision was merged to the branch mainline in revision 4003.
  • Revision ID: robertc@robertcollins.net-20090211124950-70c4aa2a8ub65d0s
Add a new hook Commands['extend_command'] for plugins that want to alter commands without overriding the entire command.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006, 2007, 2008 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
    branchbuilder,
 
30
    bzrdir,
 
31
    errors,
 
32
    memorytree,
 
33
    osutils,
 
34
    remote,
 
35
    repository,
 
36
    symbol_versioning,
 
37
    tests,
 
38
    workingtree,
 
39
    )
 
40
from bzrlib.progress import _BaseProgressBar
 
41
from bzrlib.repofmt import (
 
42
    pack_repo,
 
43
    weaverepo,
 
44
    )
 
45
from bzrlib.symbol_versioning import (
 
46
    one_zero,
 
47
    zero_eleven,
 
48
    zero_ten,
 
49
    )
 
50
from bzrlib.tests import (
 
51
                          ChrootedTestCase,
 
52
                          ExtendedTestResult,
 
53
                          Feature,
 
54
                          KnownFailure,
 
55
                          TestCase,
 
56
                          TestCaseInTempDir,
 
57
                          TestCaseWithMemoryTransport,
 
58
                          TestCaseWithTransport,
 
59
                          TestNotApplicable,
 
60
                          TestSkipped,
 
61
                          TestSuite,
 
62
                          TestUtil,
 
63
                          TextTestRunner,
 
64
                          UnavailableFeature,
 
65
                          condition_id_re,
 
66
                          condition_isinstance,
 
67
                          exclude_tests_by_condition,
 
68
                          exclude_tests_by_re,
 
69
                          filter_suite_by_condition,
 
70
                          filter_suite_by_re,
 
71
                          iter_suite_tests,
 
72
                          preserve_input,
 
73
                          randomize_suite,
 
74
                          split_suite_by_condition,
 
75
                          split_suite_by_re,
 
76
                          test_lsprof,
 
77
                          test_suite,
 
78
                          )
 
79
from bzrlib.tests.test_sftp_transport import TestCaseWithSFTPServer
 
80
from bzrlib.tests.TestUtil import _load_module_by_name
 
81
from bzrlib.trace import note
 
82
from bzrlib.transport.memory import MemoryServer, MemoryTransport
 
83
from bzrlib.version import _get_bzr_source_tree
 
84
 
 
85
 
 
86
def _test_ids(test_suite):
 
87
    """Get the ids for the tests in a test suite."""
 
88
    return [t.id() for t in iter_suite_tests(test_suite)]
 
89
 
 
90
 
 
91
class SelftestTests(TestCase):
 
92
 
 
93
    def test_import_tests(self):
 
94
        mod = _load_module_by_name('bzrlib.tests.test_selftest')
 
95
        self.assertEqual(mod.SelftestTests, SelftestTests)
 
96
 
 
97
    def test_import_test_failure(self):
 
98
        self.assertRaises(ImportError,
 
99
                          _load_module_by_name,
 
100
                          'bzrlib.no-name-yet')
 
101
 
 
102
class MetaTestLog(TestCase):
 
103
 
 
104
    def test_logging(self):
 
105
        """Test logs are captured when a test fails."""
 
106
        self.log('a test message')
 
107
        self._log_file.flush()
 
108
        self.assertContainsRe(self._get_log(keep_log_file=True),
 
109
                              'a test message\n')
 
110
 
 
111
 
 
112
class TestUnicodeFilename(TestCase):
 
113
 
 
114
    def test_probe_passes(self):
 
115
        """UnicodeFilename._probe passes."""
 
116
        # We can't test much more than that because the behaviour depends
 
117
        # on the platform.
 
118
        tests.UnicodeFilename._probe()
 
119
 
 
120
 
 
121
class TestTreeShape(TestCaseInTempDir):
 
122
 
 
123
    def test_unicode_paths(self):
 
124
        self.requireFeature(tests.UnicodeFilename)
 
125
 
 
126
        filename = u'hell\u00d8'
 
127
        self.build_tree_contents([(filename, 'contents of hello')])
 
128
        self.failUnlessExists(filename)
 
129
 
 
130
 
 
131
class TestTransportProviderAdapter(TestCase):
 
132
    """A group of tests that test the transport implementation adaption core.
 
133
 
 
134
    This is a meta test that the tests are applied to all available 
 
135
    transports.
 
136
 
 
137
    This will be generalised in the future which is why it is in this 
 
138
    test file even though it is specific to transport tests at the moment.
 
139
    """
 
140
 
 
141
    def test_get_transport_permutations(self):
 
142
        # this checks that get_test_permutations defined by the module is
 
143
        # called by the adapter get_transport_test_permutations method.
 
144
        class MockModule(object):
 
145
            def get_test_permutations(self):
 
146
                return sample_permutation
 
147
        sample_permutation = [(1,2), (3,4)]
 
148
        from bzrlib.tests.test_transport_implementations \
 
149
            import TransportTestProviderAdapter
 
150
        adapter = TransportTestProviderAdapter()
 
151
        self.assertEqual(sample_permutation,
 
152
                         adapter.get_transport_test_permutations(MockModule()))
 
153
 
 
154
    def test_adapter_checks_all_modules(self):
 
155
        # this checks that the adapter returns as many permutations as there
 
156
        # are in all the registered transport modules - we assume if this
 
157
        # matches its probably doing the right thing especially in combination
 
158
        # with the tests for setting the right classes below.
 
159
        from bzrlib.tests.test_transport_implementations \
 
160
            import TransportTestProviderAdapter
 
161
        from bzrlib.transport import _get_transport_modules
 
162
        modules = _get_transport_modules()
 
163
        permutation_count = 0
 
164
        for module in modules:
 
165
            try:
 
166
                permutation_count += len(reduce(getattr, 
 
167
                    (module + ".get_test_permutations").split('.')[1:],
 
168
                     __import__(module))())
 
169
            except errors.DependencyNotPresent:
 
170
                pass
 
171
        input_test = TestTransportProviderAdapter(
 
172
            "test_adapter_sets_transport_class")
 
173
        adapter = TransportTestProviderAdapter()
 
174
        self.assertEqual(permutation_count,
 
175
                         len(list(iter(adapter.adapt(input_test)))))
 
176
 
 
177
    def test_adapter_sets_transport_class(self):
 
178
        # Check that the test adapter inserts a transport and server into the
 
179
        # generated test.
 
180
        #
 
181
        # This test used to know about all the possible transports and the
 
182
        # order they were returned but that seems overly brittle (mbp
 
183
        # 20060307)
 
184
        from bzrlib.tests.test_transport_implementations \
 
185
            import TransportTestProviderAdapter
 
186
        scenarios = TransportTestProviderAdapter().scenarios
 
187
        # there are at least that many builtin transports
 
188
        self.assertTrue(len(scenarios) > 6)
 
189
        one_scenario = scenarios[0]
 
190
        self.assertIsInstance(one_scenario[0], str)
 
191
        self.assertTrue(issubclass(one_scenario[1]["transport_class"],
 
192
                                   bzrlib.transport.Transport))
 
193
        self.assertTrue(issubclass(one_scenario[1]["transport_server"],
 
194
                                   bzrlib.transport.Server))
 
195
 
 
196
 
 
197
class TestBranchProviderAdapter(TestCase):
 
198
    """A group of tests that test the branch implementation test adapter."""
 
199
 
 
200
    def test_constructor(self):
 
201
        # check that constructor parameters are passed through to the adapted
 
202
        # test.
 
203
        from bzrlib.tests.branch_implementations import BranchTestProviderAdapter
 
204
        server1 = "a"
 
205
        server2 = "b"
 
206
        formats = [("c", "C"), ("d", "D")]
 
207
        adapter = BranchTestProviderAdapter(server1, server2, formats)
 
208
        self.assertEqual(2, len(adapter.scenarios))
 
209
        self.assertEqual([
 
210
            ('str',
 
211
             {'branch_format': 'c',
 
212
              'bzrdir_format': 'C',
 
213
              'transport_readonly_server': 'b',
 
214
              'transport_server': 'a'}),
 
215
            ('str',
 
216
             {'branch_format': 'd',
 
217
              'bzrdir_format': 'D',
 
218
              'transport_readonly_server': 'b',
 
219
              'transport_server': 'a'})],
 
220
            adapter.scenarios)
 
221
 
 
222
 
 
223
class TestBzrDirProviderAdapter(TestCase):
 
224
    """A group of tests that test the bzr dir implementation test adapter."""
 
225
 
 
226
    def test_adapted_tests(self):
 
227
        # check that constructor parameters are passed through to the adapted
 
228
        # test.
 
229
        from bzrlib.tests.bzrdir_implementations import BzrDirTestProviderAdapter
 
230
        vfs_factory = "v"
 
231
        server1 = "a"
 
232
        server2 = "b"
 
233
        formats = ["c", "d"]
 
234
        adapter = BzrDirTestProviderAdapter(vfs_factory,
 
235
            server1, server2, formats)
 
236
        self.assertEqual([
 
237
            ('str',
 
238
             {'bzrdir_format': 'c',
 
239
              'transport_readonly_server': 'b',
 
240
              'transport_server': 'a',
 
241
              'vfs_transport_factory': 'v'}),
 
242
            ('str',
 
243
             {'bzrdir_format': 'd',
 
244
              'transport_readonly_server': 'b',
 
245
              'transport_server': 'a',
 
246
              'vfs_transport_factory': 'v'})],
 
247
            adapter.scenarios)
 
248
 
 
249
 
 
250
class TestRepositoryParameterisation(TestCase):
 
251
    """A group of tests that test the repository implementation test adapter."""
 
252
 
 
253
    def test_formats_to_scenarios(self):
 
254
        """The adapter can generate all the scenarios needed."""
 
255
        from bzrlib.tests.per_repository import formats_to_scenarios
 
256
        formats = [("(c)", remote.RemoteRepositoryFormat()),
 
257
                   ("(d)", repository.format_registry.get(
 
258
                        'Bazaar pack repository format 1 (needs bzr 0.92)\n'))]
 
259
        no_vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
 
260
            None)
 
261
        vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
 
262
            vfs_transport_factory="vfs")
 
263
        # no_vfs generate scenarios without vfs_transport_factory
 
264
        self.assertEqual([
 
265
            ('RemoteRepositoryFormat(c)',
 
266
             {'bzrdir_format': remote.RemoteBzrDirFormat(),
 
267
              'repository_format': remote.RemoteRepositoryFormat(),
 
268
              'transport_readonly_server': 'readonly',
 
269
              'transport_server': 'server'}),
 
270
            ('RepositoryFormatKnitPack1(d)',
 
271
             {'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
 
272
              'repository_format': pack_repo.RepositoryFormatKnitPack1(),
 
273
              'transport_readonly_server': 'readonly',
 
274
              'transport_server': 'server'})],
 
275
            no_vfs_scenarios)
 
276
        self.assertEqual([
 
277
            ('RemoteRepositoryFormat(c)',
 
278
             {'bzrdir_format': remote.RemoteBzrDirFormat(),
 
279
              'repository_format': remote.RemoteRepositoryFormat(),
 
280
              'transport_readonly_server': 'readonly',
 
281
              'transport_server': 'server',
 
282
              'vfs_transport_factory': 'vfs'}),
 
283
            ('RepositoryFormatKnitPack1(d)',
 
284
             {'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
 
285
              'repository_format': pack_repo.RepositoryFormatKnitPack1(),
 
286
              'transport_readonly_server': 'readonly',
 
287
              'transport_server': 'server',
 
288
              'vfs_transport_factory': 'vfs'})],
 
289
            vfs_scenarios)
 
290
 
 
291
 
 
292
class TestTestScenarioApplier(TestCase):
 
293
    """Tests for the test adaption facilities."""
 
294
 
 
295
    def test_adapt_applies_scenarios(self):
 
296
        from bzrlib.tests.per_repository import TestScenarioApplier
 
297
        input_test = TestTestScenarioApplier("test_adapt_test_to_scenario")
 
298
        adapter = TestScenarioApplier()
 
299
        adapter.scenarios = [("1", "dict"), ("2", "settings")]
 
300
        calls = []
 
301
        def capture_call(test, scenario):
 
302
            calls.append((test, scenario))
 
303
            return test
 
304
        adapter.adapt_test_to_scenario = capture_call
 
305
        adapter.adapt(input_test)
 
306
        self.assertEqual([(input_test, ("1", "dict")),
 
307
            (input_test, ("2", "settings"))], calls)
 
308
 
 
309
    def test_adapt_test_to_scenario(self):
 
310
        from bzrlib.tests.per_repository import TestScenarioApplier
 
311
        input_test = TestTestScenarioApplier("test_adapt_test_to_scenario")
 
312
        adapter = TestScenarioApplier()
 
313
        # setup two adapted tests
 
314
        adapted_test1 = adapter.adapt_test_to_scenario(input_test,
 
315
            ("new id",
 
316
            {"bzrdir_format":"bzr_format",
 
317
             "repository_format":"repo_fmt",
 
318
             "transport_server":"transport_server",
 
319
             "transport_readonly_server":"readonly-server"}))
 
320
        adapted_test2 = adapter.adapt_test_to_scenario(input_test,
 
321
            ("new id 2", {"bzrdir_format":None}))
 
322
        # input_test should have been altered.
 
323
        self.assertRaises(AttributeError, getattr, input_test, "bzrdir_format")
 
324
        # the new tests are mutually incompatible, ensuring it has 
 
325
        # made new ones, and unspecified elements in the scenario
 
326
        # should not have been altered.
 
327
        self.assertEqual("bzr_format", adapted_test1.bzrdir_format)
 
328
        self.assertEqual("repo_fmt", adapted_test1.repository_format)
 
329
        self.assertEqual("transport_server", adapted_test1.transport_server)
 
330
        self.assertEqual("readonly-server",
 
331
            adapted_test1.transport_readonly_server)
 
332
        self.assertEqual(
 
333
            "bzrlib.tests.test_selftest.TestTestScenarioApplier."
 
334
            "test_adapt_test_to_scenario(new id)",
 
335
            adapted_test1.id())
 
336
        self.assertEqual(None, adapted_test2.bzrdir_format)
 
337
        self.assertEqual(
 
338
            "bzrlib.tests.test_selftest.TestTestScenarioApplier."
 
339
            "test_adapt_test_to_scenario(new id 2)",
 
340
            adapted_test2.id())
 
341
 
 
342
 
 
343
class TestInterRepositoryProviderAdapter(TestCase):
 
344
    """A group of tests that test the InterRepository test adapter."""
 
345
 
 
346
    def test_adapted_tests(self):
 
347
        # check that constructor parameters are passed through to the adapted
 
348
        # test.
 
349
        from bzrlib.tests.interrepository_implementations import \
 
350
            InterRepositoryTestProviderAdapter
 
351
        server1 = "a"
 
352
        server2 = "b"
 
353
        formats = [(str, "C1", "C2"), (int, "D1", "D2")]
 
354
        adapter = InterRepositoryTestProviderAdapter(server1, server2, formats)
 
355
        self.assertEqual([
 
356
            ('str,str,str',
 
357
             {'interrepo_class': str,
 
358
              'repository_format': 'C1',
 
359
              'repository_format_to': 'C2',
 
360
              'transport_readonly_server': 'b',
 
361
              'transport_server': 'a'}),
 
362
            ('int,str,str',
 
363
             {'interrepo_class': int,
 
364
              'repository_format': 'D1',
 
365
              'repository_format_to': 'D2',
 
366
              'transport_readonly_server': 'b',
 
367
              'transport_server': 'a'})],
 
368
            adapter.formats_to_scenarios(formats))
 
369
 
 
370
 
 
371
class TestWorkingTreeProviderAdapter(TestCase):
 
372
    """A group of tests that test the workingtree implementation test adapter."""
 
373
 
 
374
    def test_scenarios(self):
 
375
        # check that constructor parameters are passed through to the adapted
 
376
        # test.
 
377
        from bzrlib.tests.workingtree_implementations \
 
378
            import WorkingTreeTestProviderAdapter
 
379
        server1 = "a"
 
380
        server2 = "b"
 
381
        formats = [workingtree.WorkingTreeFormat2(),
 
382
                   workingtree.WorkingTreeFormat3(),]
 
383
        adapter = WorkingTreeTestProviderAdapter(server1, server2, formats)
 
384
        self.assertEqual([
 
385
            ('WorkingTreeFormat2',
 
386
             {'bzrdir_format': formats[0]._matchingbzrdir,
 
387
              'transport_readonly_server': 'b',
 
388
              'transport_server': 'a',
 
389
              'workingtree_format': formats[0]}),
 
390
            ('WorkingTreeFormat3',
 
391
             {'bzrdir_format': formats[1]._matchingbzrdir,
 
392
              'transport_readonly_server': 'b',
 
393
              'transport_server': 'a',
 
394
              'workingtree_format': formats[1]})],
 
395
            adapter.scenarios)
 
396
 
 
397
 
 
398
class TestTreeProviderAdapter(TestCase):
 
399
    """Test the setup of tree_implementation tests."""
 
400
 
 
401
    def test_adapted_tests(self):
 
402
        # the tree implementation adapter is meant to setup one instance for
 
403
        # each working tree format, and one additional instance that will
 
404
        # use the default wt format, but create a revision tree for the tests.
 
405
        # this means that the wt ones should have the workingtree_to_test_tree
 
406
        # attribute set to 'return_parameter' and the revision one set to
 
407
        # revision_tree_from_workingtree.
 
408
 
 
409
        from bzrlib.tests.tree_implementations import (
 
410
            TreeTestProviderAdapter,
 
411
            return_parameter,
 
412
            revision_tree_from_workingtree
 
413
            )
 
414
        input_test = TestTreeProviderAdapter(
 
415
            "test_adapted_tests")
 
416
        server1 = "a"
 
417
        server2 = "b"
 
418
        formats = [workingtree.WorkingTreeFormat2(),
 
419
                   workingtree.WorkingTreeFormat3(),]
 
420
        adapter = TreeTestProviderAdapter(server1, server2, formats)
 
421
        suite = adapter.adapt(input_test)
 
422
        tests = list(iter(suite))
 
423
        # XXX We should not have tests fail as we add more scenarios
 
424
        # abentley 20080412
 
425
        self.assertEqual(7, len(tests))
 
426
        # this must match the default format setp up in
 
427
        # TreeTestProviderAdapter.adapt
 
428
        default_format = workingtree.WorkingTreeFormat3
 
429
        self.assertEqual(tests[0].workingtree_format, formats[0])
 
430
        self.assertEqual(tests[0].bzrdir_format, formats[0]._matchingbzrdir)
 
431
        self.assertEqual(tests[0].transport_server, server1)
 
432
        self.assertEqual(tests[0].transport_readonly_server, server2)
 
433
        self.assertEqual(tests[0]._workingtree_to_test_tree, return_parameter)
 
434
        self.assertEqual(tests[1].workingtree_format, formats[1])
 
435
        self.assertEqual(tests[1].bzrdir_format, formats[1]._matchingbzrdir)
 
436
        self.assertEqual(tests[1].transport_server, server1)
 
437
        self.assertEqual(tests[1].transport_readonly_server, server2)
 
438
        self.assertEqual(tests[1]._workingtree_to_test_tree, return_parameter)
 
439
        self.assertIsInstance(tests[2].workingtree_format, default_format)
 
440
        #self.assertEqual(tests[2].bzrdir_format,
 
441
        #                 default_format._matchingbzrdir)
 
442
        self.assertEqual(tests[2].transport_server, server1)
 
443
        self.assertEqual(tests[2].transport_readonly_server, server2)
 
444
        self.assertEqual(tests[2]._workingtree_to_test_tree,
 
445
            revision_tree_from_workingtree)
 
446
 
 
447
 
 
448
class TestInterTreeProviderAdapter(TestCase):
 
449
    """A group of tests that test the InterTreeTestAdapter."""
 
450
 
 
451
    def test_adapted_tests(self):
 
452
        # check that constructor parameters are passed through to the adapted
 
453
        # test.
 
454
        # for InterTree tests we want the machinery to bring up two trees in
 
455
        # each instance: the base one, and the one we are interacting with.
 
456
        # because each optimiser can be direction specific, we need to test
 
457
        # each optimiser in its chosen direction.
 
458
        # unlike the TestProviderAdapter we dont want to automatically add a
 
459
        # parameterized one for WorkingTree - the optimisers will tell us what
 
460
        # ones to add.
 
461
        from bzrlib.tests.tree_implementations import (
 
462
            return_parameter,
 
463
            revision_tree_from_workingtree
 
464
            )
 
465
        from bzrlib.tests.intertree_implementations import (
 
466
            InterTreeTestProviderAdapter,
 
467
            )
 
468
        from bzrlib.workingtree import WorkingTreeFormat2, WorkingTreeFormat3
 
469
        input_test = TestInterTreeProviderAdapter(
 
470
            "test_adapted_tests")
 
471
        server1 = "a"
 
472
        server2 = "b"
 
473
        format1 = WorkingTreeFormat2()
 
474
        format2 = WorkingTreeFormat3()
 
475
        formats = [("1", str, format1, format2, "converter1"),
 
476
            ("2", int, format2, format1, "converter2")]
 
477
        adapter = InterTreeTestProviderAdapter(server1, server2, formats)
 
478
        suite = adapter.adapt(input_test)
 
479
        tests = list(iter(suite))
 
480
        self.assertEqual(2, len(tests))
 
481
        self.assertEqual(tests[0].intertree_class, formats[0][1])
 
482
        self.assertEqual(tests[0].workingtree_format, formats[0][2])
 
483
        self.assertEqual(tests[0].workingtree_format_to, formats[0][3])
 
484
        self.assertEqual(tests[0].mutable_trees_to_test_trees, formats[0][4])
 
485
        self.assertEqual(tests[0]._workingtree_to_test_tree, return_parameter)
 
486
        self.assertEqual(tests[0].transport_server, server1)
 
487
        self.assertEqual(tests[0].transport_readonly_server, server2)
 
488
        self.assertEqual(tests[1].intertree_class, formats[1][1])
 
489
        self.assertEqual(tests[1].workingtree_format, formats[1][2])
 
490
        self.assertEqual(tests[1].workingtree_format_to, formats[1][3])
 
491
        self.assertEqual(tests[1].mutable_trees_to_test_trees, formats[1][4])
 
492
        self.assertEqual(tests[1]._workingtree_to_test_tree, return_parameter)
 
493
        self.assertEqual(tests[1].transport_server, server1)
 
494
        self.assertEqual(tests[1].transport_readonly_server, server2)
 
495
 
 
496
 
 
497
class TestTestCaseInTempDir(TestCaseInTempDir):
 
498
 
 
499
    def test_home_is_not_working(self):
 
500
        self.assertNotEqual(self.test_dir, self.test_home_dir)
 
501
        cwd = osutils.getcwd()
 
502
        self.assertIsSameRealPath(self.test_dir, cwd)
 
503
        self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
 
504
 
 
505
    def test_assertEqualStat_equal(self):
 
506
        from bzrlib.tests.test_dirstate import _FakeStat
 
507
        self.build_tree(["foo"])
 
508
        real = os.lstat("foo")
 
509
        fake = _FakeStat(real.st_size, real.st_mtime, real.st_ctime,
 
510
            real.st_dev, real.st_ino, real.st_mode)
 
511
        self.assertEqualStat(real, fake)
 
512
 
 
513
    def test_assertEqualStat_notequal(self):
 
514
        self.build_tree(["foo", "bar"])
 
515
        self.assertRaises(AssertionError, self.assertEqualStat,
 
516
            os.lstat("foo"), os.lstat("bar"))
 
517
 
 
518
 
 
519
class TestTestCaseWithMemoryTransport(TestCaseWithMemoryTransport):
 
520
 
 
521
    def test_home_is_non_existant_dir_under_root(self):
 
522
        """The test_home_dir for TestCaseWithMemoryTransport is missing.
 
523
 
 
524
        This is because TestCaseWithMemoryTransport is for tests that do not
 
525
        need any disk resources: they should be hooked into bzrlib in such a 
 
526
        way that no global settings are being changed by the test (only a 
 
527
        few tests should need to do that), and having a missing dir as home is
 
528
        an effective way to ensure that this is the case.
 
529
        """
 
530
        self.assertIsSameRealPath(
 
531
            self.TEST_ROOT + "/MemoryTransportMissingHomeDir",
 
532
            self.test_home_dir)
 
533
        self.assertIsSameRealPath(self.test_home_dir, os.environ['HOME'])
 
534
        
 
535
    def test_cwd_is_TEST_ROOT(self):
 
536
        self.assertIsSameRealPath(self.test_dir, self.TEST_ROOT)
 
537
        cwd = osutils.getcwd()
 
538
        self.assertIsSameRealPath(self.test_dir, cwd)
 
539
 
 
540
    def test_make_branch_and_memory_tree(self):
 
541
        """In TestCaseWithMemoryTransport we should not make the branch on disk.
 
542
 
 
543
        This is hard to comprehensively robustly test, so we settle for making
 
544
        a branch and checking no directory was created at its relpath.
 
545
        """
 
546
        tree = self.make_branch_and_memory_tree('dir')
 
547
        # Guard against regression into MemoryTransport leaking
 
548
        # files to disk instead of keeping them in memory.
 
549
        self.failIf(osutils.lexists('dir'))
 
550
        self.assertIsInstance(tree, memorytree.MemoryTree)
 
551
 
 
552
    def test_make_branch_and_memory_tree_with_format(self):
 
553
        """make_branch_and_memory_tree should accept a format option."""
 
554
        format = bzrdir.BzrDirMetaFormat1()
 
555
        format.repository_format = weaverepo.RepositoryFormat7()
 
556
        tree = self.make_branch_and_memory_tree('dir', format=format)
 
557
        # Guard against regression into MemoryTransport leaking
 
558
        # files to disk instead of keeping them in memory.
 
559
        self.failIf(osutils.lexists('dir'))
 
560
        self.assertIsInstance(tree, memorytree.MemoryTree)
 
561
        self.assertEqual(format.repository_format.__class__,
 
562
            tree.branch.repository._format.__class__)
 
563
 
 
564
    def test_make_branch_builder(self):
 
565
        builder = self.make_branch_builder('dir')
 
566
        self.assertIsInstance(builder, branchbuilder.BranchBuilder)
 
567
        # Guard against regression into MemoryTransport leaking
 
568
        # files to disk instead of keeping them in memory.
 
569
        self.failIf(osutils.lexists('dir'))
 
570
 
 
571
    def test_make_branch_builder_with_format(self):
 
572
        # Use a repo layout that doesn't conform to a 'named' layout, to ensure
 
573
        # that the format objects are used.
 
574
        format = bzrdir.BzrDirMetaFormat1()
 
575
        repo_format = weaverepo.RepositoryFormat7()
 
576
        format.repository_format = repo_format
 
577
        builder = self.make_branch_builder('dir', format=format)
 
578
        the_branch = builder.get_branch()
 
579
        # Guard against regression into MemoryTransport leaking
 
580
        # files to disk instead of keeping them in memory.
 
581
        self.failIf(osutils.lexists('dir'))
 
582
        self.assertEqual(format.repository_format.__class__,
 
583
                         the_branch.repository._format.__class__)
 
584
        self.assertEqual(repo_format.get_format_string(),
 
585
                         self.get_transport().get_bytes(
 
586
                            'dir/.bzr/repository/format'))
 
587
 
 
588
    def test_make_branch_builder_with_format_name(self):
 
589
        builder = self.make_branch_builder('dir', format='knit')
 
590
        the_branch = builder.get_branch()
 
591
        # Guard against regression into MemoryTransport leaking
 
592
        # files to disk instead of keeping them in memory.
 
593
        self.failIf(osutils.lexists('dir'))
 
594
        dir_format = bzrdir.format_registry.make_bzrdir('knit')
 
595
        self.assertEqual(dir_format.repository_format.__class__,
 
596
                         the_branch.repository._format.__class__)
 
597
        self.assertEqual('Bazaar-NG Knit Repository Format 1',
 
598
                         self.get_transport().get_bytes(
 
599
                            'dir/.bzr/repository/format'))
 
600
 
 
601
    def test_safety_net(self):
 
602
        """No test should modify the safety .bzr directory.
 
603
 
 
604
        We just test that the _check_safety_net private method raises
 
605
        AssertionError, it's easier than building a test suite with the same
 
606
        test.
 
607
        """
 
608
        # Oops, a commit in the current directory (i.e. without local .bzr
 
609
        # directory) will crawl up the hierarchy to find a .bzr directory.
 
610
        self.run_bzr(['commit', '-mfoo', '--unchanged'])
 
611
        # But we have a safety net in place.
 
612
        self.assertRaises(AssertionError, self._check_safety_net)
 
613
 
 
614
 
 
615
class TestTestCaseWithTransport(TestCaseWithTransport):
 
616
    """Tests for the convenience functions TestCaseWithTransport introduces."""
 
617
 
 
618
    def test_get_readonly_url_none(self):
 
619
        from bzrlib.transport import get_transport
 
620
        from bzrlib.transport.memory import MemoryServer
 
621
        from bzrlib.transport.readonly import ReadonlyTransportDecorator
 
622
        self.vfs_transport_factory = MemoryServer
 
623
        self.transport_readonly_server = None
 
624
        # calling get_readonly_transport() constructs a decorator on the url
 
625
        # for the server
 
626
        url = self.get_readonly_url()
 
627
        url2 = self.get_readonly_url('foo/bar')
 
628
        t = get_transport(url)
 
629
        t2 = get_transport(url2)
 
630
        self.failUnless(isinstance(t, ReadonlyTransportDecorator))
 
631
        self.failUnless(isinstance(t2, ReadonlyTransportDecorator))
 
632
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
 
633
 
 
634
    def test_get_readonly_url_http(self):
 
635
        from bzrlib.tests.http_server import HttpServer
 
636
        from bzrlib.transport import get_transport
 
637
        from bzrlib.transport.local import LocalURLServer
 
638
        from bzrlib.transport.http import HttpTransportBase
 
639
        self.transport_server = LocalURLServer
 
640
        self.transport_readonly_server = HttpServer
 
641
        # calling get_readonly_transport() gives us a HTTP server instance.
 
642
        url = self.get_readonly_url()
 
643
        url2 = self.get_readonly_url('foo/bar')
 
644
        # the transport returned may be any HttpTransportBase subclass
 
645
        t = get_transport(url)
 
646
        t2 = get_transport(url2)
 
647
        self.failUnless(isinstance(t, HttpTransportBase))
 
648
        self.failUnless(isinstance(t2, HttpTransportBase))
 
649
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
 
650
 
 
651
    def test_is_directory(self):
 
652
        """Test assertIsDirectory assertion"""
 
653
        t = self.get_transport()
 
654
        self.build_tree(['a_dir/', 'a_file'], transport=t)
 
655
        self.assertIsDirectory('a_dir', t)
 
656
        self.assertRaises(AssertionError, self.assertIsDirectory, 'a_file', t)
 
657
        self.assertRaises(AssertionError, self.assertIsDirectory, 'not_here', t)
 
658
 
 
659
    def test_make_branch_builder(self):
 
660
        builder = self.make_branch_builder('dir')
 
661
        rev_id = builder.build_commit()
 
662
        self.failUnlessExists('dir')
 
663
        a_dir = bzrdir.BzrDir.open('dir')
 
664
        self.assertRaises(errors.NoWorkingTree, a_dir.open_workingtree)
 
665
        a_branch = a_dir.open_branch()
 
666
        builder_branch = builder.get_branch()
 
667
        self.assertEqual(a_branch.base, builder_branch.base)
 
668
        self.assertEqual((1, rev_id), builder_branch.last_revision_info())
 
669
        self.assertEqual((1, rev_id), a_branch.last_revision_info())
 
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
class _TestException(Exception):
 
1342
    pass
 
1343
 
 
1344
class TestTestCase(TestCase):
 
1345
    """Tests that test the core bzrlib TestCase."""
 
1346
 
 
1347
    def test_debug_flags_sanitised(self):
 
1348
        """The bzrlib debug flags should be sanitised by setUp."""
 
1349
        if 'allow_debug' in tests.selftest_debug_flags:
 
1350
            raise TestNotApplicable(
 
1351
                '-Eallow_debug option prevents debug flag sanitisation')
 
1352
        # we could set something and run a test that will check
 
1353
        # it gets santised, but this is probably sufficient for now:
 
1354
        # if someone runs the test with -Dsomething it will error.
 
1355
        self.assertEqual(set(), bzrlib.debug.debug_flags)
 
1356
 
 
1357
    def change_selftest_debug_flags(self, new_flags):
 
1358
        orig_selftest_flags = tests.selftest_debug_flags
 
1359
        self.addCleanup(self._restore_selftest_debug_flags, orig_selftest_flags)
 
1360
        tests.selftest_debug_flags = set(new_flags)
 
1361
        
 
1362
    def _restore_selftest_debug_flags(self, flags):
 
1363
        tests.selftest_debug_flags = flags
 
1364
 
 
1365
    def test_allow_debug_flag(self):
 
1366
        """The -Eallow_debug flag prevents bzrlib.debug.debug_flags from being
 
1367
        sanitised (i.e. cleared) before running a test.
 
1368
        """
 
1369
        self.change_selftest_debug_flags(set(['allow_debug']))
 
1370
        bzrlib.debug.debug_flags = set(['a-flag'])
 
1371
        class TestThatRecordsFlags(TestCase):
 
1372
            def test_foo(nested_self):
 
1373
                self.flags = set(bzrlib.debug.debug_flags)
 
1374
        test = TestThatRecordsFlags('test_foo')
 
1375
        test.run(self.make_test_result())
 
1376
        self.assertEqual(set(['a-flag']), self.flags)
 
1377
 
 
1378
    def test_debug_flags_restored(self):
 
1379
        """The bzrlib debug flags should be restored to their original state
 
1380
        after the test was run, even if allow_debug is set.
 
1381
        """
 
1382
        self.change_selftest_debug_flags(set(['allow_debug']))
 
1383
        # Now run a test that modifies debug.debug_flags.
 
1384
        bzrlib.debug.debug_flags = set(['original-state'])
 
1385
        class TestThatModifiesFlags(TestCase):
 
1386
            def test_foo(self):
 
1387
                bzrlib.debug.debug_flags = set(['modified'])
 
1388
        test = TestThatModifiesFlags('test_foo')
 
1389
        test.run(self.make_test_result())
 
1390
        self.assertEqual(set(['original-state']), bzrlib.debug.debug_flags)
 
1391
 
 
1392
    def make_test_result(self):
 
1393
        return bzrlib.tests.TextTestResult(
 
1394
            self._log_file, descriptions=0, verbosity=1)
 
1395
 
 
1396
    def inner_test(self):
 
1397
        # the inner child test
 
1398
        note("inner_test")
 
1399
 
 
1400
    def outer_child(self):
 
1401
        # the outer child test
 
1402
        note("outer_start")
 
1403
        self.inner_test = TestTestCase("inner_child")
 
1404
        result = self.make_test_result()
 
1405
        self.inner_test.run(result)
 
1406
        note("outer finish")
 
1407
 
 
1408
    def test_trace_nesting(self):
 
1409
        # this tests that each test case nests its trace facility correctly.
 
1410
        # we do this by running a test case manually. That test case (A)
 
1411
        # should setup a new log, log content to it, setup a child case (B),
 
1412
        # which should log independently, then case (A) should log a trailer
 
1413
        # and return.
 
1414
        # we do two nested children so that we can verify the state of the 
 
1415
        # logs after the outer child finishes is correct, which a bad clean
 
1416
        # up routine in tearDown might trigger a fault in our test with only
 
1417
        # one child, we should instead see the bad result inside our test with
 
1418
        # the two children.
 
1419
        # the outer child test
 
1420
        original_trace = bzrlib.trace._trace_file
 
1421
        outer_test = TestTestCase("outer_child")
 
1422
        result = self.make_test_result()
 
1423
        outer_test.run(result)
 
1424
        self.assertEqual(original_trace, bzrlib.trace._trace_file)
 
1425
 
 
1426
    def method_that_times_a_bit_twice(self):
 
1427
        # call self.time twice to ensure it aggregates
 
1428
        self.time(time.sleep, 0.007)
 
1429
        self.time(time.sleep, 0.007)
 
1430
 
 
1431
    def test_time_creates_benchmark_in_result(self):
 
1432
        """Test that the TestCase.time() method accumulates a benchmark time."""
 
1433
        sample_test = TestTestCase("method_that_times_a_bit_twice")
 
1434
        output_stream = StringIO()
 
1435
        result = bzrlib.tests.VerboseTestResult(
 
1436
            unittest._WritelnDecorator(output_stream),
 
1437
            descriptions=0,
 
1438
            verbosity=2,
 
1439
            num_tests=sample_test.countTestCases())
 
1440
        sample_test.run(result)
 
1441
        self.assertContainsRe(
 
1442
            output_stream.getvalue(),
 
1443
            r"\d+ms/ +\d+ms\n$")
 
1444
 
 
1445
    def test_hooks_sanitised(self):
 
1446
        """The bzrlib hooks should be sanitised by setUp."""
 
1447
        # Note this test won't fail with hooks that the core library doesn't
 
1448
        # use - but it trigger with a plugin that adds hooks, so its still a
 
1449
        # useful warning in that case.
 
1450
        self.assertEqual(bzrlib.branch.BranchHooks(),
 
1451
            bzrlib.branch.Branch.hooks)
 
1452
        self.assertEqual(bzrlib.smart.server.SmartServerHooks(),
 
1453
            bzrlib.smart.server.SmartTCPServer.hooks)
 
1454
        self.assertEqual(bzrlib.commands.CommandHooks(),
 
1455
            bzrlib.commands.Command.hooks)
 
1456
 
 
1457
    def test__gather_lsprof_in_benchmarks(self):
 
1458
        """When _gather_lsprof_in_benchmarks is on, accumulate profile data.
 
1459
        
 
1460
        Each self.time() call is individually and separately profiled.
 
1461
        """
 
1462
        self.requireFeature(test_lsprof.LSProfFeature)
 
1463
        # overrides the class member with an instance member so no cleanup 
 
1464
        # needed.
 
1465
        self._gather_lsprof_in_benchmarks = True
 
1466
        self.time(time.sleep, 0.000)
 
1467
        self.time(time.sleep, 0.003)
 
1468
        self.assertEqual(2, len(self._benchcalls))
 
1469
        self.assertEqual((time.sleep, (0.000,), {}), self._benchcalls[0][0])
 
1470
        self.assertEqual((time.sleep, (0.003,), {}), self._benchcalls[1][0])
 
1471
        self.assertIsInstance(self._benchcalls[0][1], bzrlib.lsprof.Stats)
 
1472
        self.assertIsInstance(self._benchcalls[1][1], bzrlib.lsprof.Stats)
 
1473
 
 
1474
    def test_knownFailure(self):
 
1475
        """Self.knownFailure() should raise a KnownFailure exception."""
 
1476
        self.assertRaises(KnownFailure, self.knownFailure, "A Failure")
 
1477
 
 
1478
    def test_requireFeature_available(self):
 
1479
        """self.requireFeature(available) is a no-op."""
 
1480
        class Available(Feature):
 
1481
            def _probe(self):return True
 
1482
        feature = Available()
 
1483
        self.requireFeature(feature)
 
1484
 
 
1485
    def test_requireFeature_unavailable(self):
 
1486
        """self.requireFeature(unavailable) raises UnavailableFeature."""
 
1487
        class Unavailable(Feature):
 
1488
            def _probe(self):return False
 
1489
        feature = Unavailable()
 
1490
        self.assertRaises(UnavailableFeature, self.requireFeature, feature)
 
1491
 
 
1492
    def test_run_no_parameters(self):
 
1493
        test = SampleTestCase('_test_pass')
 
1494
        test.run()
 
1495
    
 
1496
    def test_run_enabled_unittest_result(self):
 
1497
        """Test we revert to regular behaviour when the test is enabled."""
 
1498
        test = SampleTestCase('_test_pass')
 
1499
        class EnabledFeature(object):
 
1500
            def available(self):
 
1501
                return True
 
1502
        test._test_needs_features = [EnabledFeature()]
 
1503
        result = unittest.TestResult()
 
1504
        test.run(result)
 
1505
        self.assertEqual(1, result.testsRun)
 
1506
        self.assertEqual([], result.errors)
 
1507
        self.assertEqual([], result.failures)
 
1508
 
 
1509
    def test_run_disabled_unittest_result(self):
 
1510
        """Test our compatability for disabled tests with unittest results."""
 
1511
        test = SampleTestCase('_test_pass')
 
1512
        class DisabledFeature(object):
 
1513
            def available(self):
 
1514
                return False
 
1515
        test._test_needs_features = [DisabledFeature()]
 
1516
        result = unittest.TestResult()
 
1517
        test.run(result)
 
1518
        self.assertEqual(1, result.testsRun)
 
1519
        self.assertEqual([], result.errors)
 
1520
        self.assertEqual([], result.failures)
 
1521
 
 
1522
    def test_run_disabled_supporting_result(self):
 
1523
        """Test disabled tests behaviour with support aware results."""
 
1524
        test = SampleTestCase('_test_pass')
 
1525
        class DisabledFeature(object):
 
1526
            def available(self):
 
1527
                return False
 
1528
        the_feature = DisabledFeature()
 
1529
        test._test_needs_features = [the_feature]
 
1530
        class InstrumentedTestResult(unittest.TestResult):
 
1531
            def __init__(self):
 
1532
                unittest.TestResult.__init__(self)
 
1533
                self.calls = []
 
1534
            def startTest(self, test):
 
1535
                self.calls.append(('startTest', test))
 
1536
            def stopTest(self, test):
 
1537
                self.calls.append(('stopTest', test))
 
1538
            def addNotSupported(self, test, feature):
 
1539
                self.calls.append(('addNotSupported', test, feature))
 
1540
        result = InstrumentedTestResult()
 
1541
        test.run(result)
 
1542
        self.assertEqual([
 
1543
            ('startTest', test),
 
1544
            ('addNotSupported', test, the_feature),
 
1545
            ('stopTest', test),
 
1546
            ],
 
1547
            result.calls)
 
1548
 
 
1549
    def test_assert_list_raises_on_generator(self):
 
1550
        def generator_which_will_raise():
 
1551
            # This will not raise until after the first yield
 
1552
            yield 1
 
1553
            raise _TestException()
 
1554
 
 
1555
        e = self.assertListRaises(_TestException, generator_which_will_raise)
 
1556
        self.assertIsInstance(e, _TestException)
 
1557
 
 
1558
        e = self.assertListRaises(Exception, generator_which_will_raise)
 
1559
        self.assertIsInstance(e, _TestException)
 
1560
 
 
1561
    def test_assert_list_raises_on_plain(self):
 
1562
        def plain_exception():
 
1563
            raise _TestException()
 
1564
            return []
 
1565
 
 
1566
        e = self.assertListRaises(_TestException, plain_exception)
 
1567
        self.assertIsInstance(e, _TestException)
 
1568
 
 
1569
        e = self.assertListRaises(Exception, plain_exception)
 
1570
        self.assertIsInstance(e, _TestException)
 
1571
 
 
1572
    def test_assert_list_raises_assert_wrong_exception(self):
 
1573
        class _NotTestException(Exception):
 
1574
            pass
 
1575
 
 
1576
        def wrong_exception():
 
1577
            raise _NotTestException()
 
1578
 
 
1579
        def wrong_exception_generator():
 
1580
            yield 1
 
1581
            yield 2
 
1582
            raise _NotTestException()
 
1583
 
 
1584
        # Wrong exceptions are not intercepted
 
1585
        self.assertRaises(_NotTestException,
 
1586
            self.assertListRaises, _TestException, wrong_exception)
 
1587
        self.assertRaises(_NotTestException,
 
1588
            self.assertListRaises, _TestException, wrong_exception_generator)
 
1589
 
 
1590
    def test_assert_list_raises_no_exception(self):
 
1591
        def success():
 
1592
            return []
 
1593
 
 
1594
        def success_generator():
 
1595
            yield 1
 
1596
            yield 2
 
1597
 
 
1598
        self.assertRaises(AssertionError,
 
1599
            self.assertListRaises, _TestException, success)
 
1600
 
 
1601
        self.assertRaises(AssertionError,
 
1602
            self.assertListRaises, _TestException, success_generator)
 
1603
 
 
1604
 
 
1605
@symbol_versioning.deprecated_function(zero_eleven)
 
1606
def sample_deprecated_function():
 
1607
    """A deprecated function to test applyDeprecated with."""
 
1608
    return 2
 
1609
 
 
1610
 
 
1611
def sample_undeprecated_function(a_param):
 
1612
    """A undeprecated function to test applyDeprecated with."""
 
1613
 
 
1614
 
 
1615
class ApplyDeprecatedHelper(object):
 
1616
    """A helper class for ApplyDeprecated tests."""
 
1617
 
 
1618
    @symbol_versioning.deprecated_method(zero_eleven)
 
1619
    def sample_deprecated_method(self, param_one):
 
1620
        """A deprecated method for testing with."""
 
1621
        return param_one
 
1622
 
 
1623
    def sample_normal_method(self):
 
1624
        """A undeprecated method."""
 
1625
 
 
1626
    @symbol_versioning.deprecated_method(zero_ten)
 
1627
    def sample_nested_deprecation(self):
 
1628
        return sample_deprecated_function()
 
1629
 
 
1630
 
 
1631
class TestExtraAssertions(TestCase):
 
1632
    """Tests for new test assertions in bzrlib test suite"""
 
1633
 
 
1634
    def test_assert_isinstance(self):
 
1635
        self.assertIsInstance(2, int)
 
1636
        self.assertIsInstance(u'', basestring)
 
1637
        self.assertRaises(AssertionError, self.assertIsInstance, None, int)
 
1638
        self.assertRaises(AssertionError, self.assertIsInstance, 23.3, int)
 
1639
 
 
1640
    def test_assertEndsWith(self):
 
1641
        self.assertEndsWith('foo', 'oo')
 
1642
        self.assertRaises(AssertionError, self.assertEndsWith, 'o', 'oo')
 
1643
 
 
1644
    def test_applyDeprecated_not_deprecated(self):
 
1645
        sample_object = ApplyDeprecatedHelper()
 
1646
        # calling an undeprecated callable raises an assertion
 
1647
        self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
 
1648
            sample_object.sample_normal_method)
 
1649
        self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
 
1650
            sample_undeprecated_function, "a param value")
 
1651
        # calling a deprecated callable (function or method) with the wrong
 
1652
        # expected deprecation fails.
 
1653
        self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
 
1654
            sample_object.sample_deprecated_method, "a param value")
 
1655
        self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
 
1656
            sample_deprecated_function)
 
1657
        # calling a deprecated callable (function or method) with the right
 
1658
        # expected deprecation returns the functions result.
 
1659
        self.assertEqual("a param value", self.applyDeprecated(zero_eleven,
 
1660
            sample_object.sample_deprecated_method, "a param value"))
 
1661
        self.assertEqual(2, self.applyDeprecated(zero_eleven,
 
1662
            sample_deprecated_function))
 
1663
        # calling a nested deprecation with the wrong deprecation version
 
1664
        # fails even if a deeper nested function was deprecated with the 
 
1665
        # supplied version.
 
1666
        self.assertRaises(AssertionError, self.applyDeprecated,
 
1667
            zero_eleven, sample_object.sample_nested_deprecation)
 
1668
        # calling a nested deprecation with the right deprecation value
 
1669
        # returns the calls result.
 
1670
        self.assertEqual(2, self.applyDeprecated(zero_ten,
 
1671
            sample_object.sample_nested_deprecation))
 
1672
 
 
1673
    def test_callDeprecated(self):
 
1674
        def testfunc(be_deprecated, result=None):
 
1675
            if be_deprecated is True:
 
1676
                symbol_versioning.warn('i am deprecated', DeprecationWarning, 
 
1677
                                       stacklevel=1)
 
1678
            return result
 
1679
        result = self.callDeprecated(['i am deprecated'], testfunc, True)
 
1680
        self.assertIs(None, result)
 
1681
        result = self.callDeprecated([], testfunc, False, 'result')
 
1682
        self.assertEqual('result', result)
 
1683
        self.callDeprecated(['i am deprecated'], testfunc, be_deprecated=True)
 
1684
        self.callDeprecated([], testfunc, be_deprecated=False)
 
1685
 
 
1686
 
 
1687
class TestWarningTests(TestCase):
 
1688
    """Tests for calling methods that raise warnings."""
 
1689
 
 
1690
    def test_callCatchWarnings(self):
 
1691
        def meth(a, b):
 
1692
            warnings.warn("this is your last warning")
 
1693
            return a + b
 
1694
        wlist, result = self.callCatchWarnings(meth, 1, 2)
 
1695
        self.assertEquals(3, result)
 
1696
        # would like just to compare them, but UserWarning doesn't implement
 
1697
        # eq well
 
1698
        w0, = wlist
 
1699
        self.assertIsInstance(w0, UserWarning)
 
1700
        self.assertEquals("this is your last warning", str(w0))
 
1701
 
 
1702
 
 
1703
class TestConvenienceMakers(TestCaseWithTransport):
 
1704
    """Test for the make_* convenience functions."""
 
1705
 
 
1706
    def test_make_branch_and_tree_with_format(self):
 
1707
        # we should be able to supply a format to make_branch_and_tree
 
1708
        self.make_branch_and_tree('a', format=bzrlib.bzrdir.BzrDirMetaFormat1())
 
1709
        self.make_branch_and_tree('b', format=bzrlib.bzrdir.BzrDirFormat6())
 
1710
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('a')._format,
 
1711
                              bzrlib.bzrdir.BzrDirMetaFormat1)
 
1712
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('b')._format,
 
1713
                              bzrlib.bzrdir.BzrDirFormat6)
 
1714
 
 
1715
    def test_make_branch_and_memory_tree(self):
 
1716
        # we should be able to get a new branch and a mutable tree from
 
1717
        # TestCaseWithTransport
 
1718
        tree = self.make_branch_and_memory_tree('a')
 
1719
        self.assertIsInstance(tree, bzrlib.memorytree.MemoryTree)
 
1720
 
 
1721
 
 
1722
class TestSFTPMakeBranchAndTree(TestCaseWithSFTPServer):
 
1723
 
 
1724
    def test_make_tree_for_sftp_branch(self):
 
1725
        """Transports backed by local directories create local trees."""
 
1726
 
 
1727
        tree = self.make_branch_and_tree('t1')
 
1728
        base = tree.bzrdir.root_transport.base
 
1729
        self.failIf(base.startswith('sftp'),
 
1730
                'base %r is on sftp but should be local' % base)
 
1731
        self.assertEquals(tree.bzrdir.root_transport,
 
1732
                tree.branch.bzrdir.root_transport)
 
1733
        self.assertEquals(tree.bzrdir.root_transport,
 
1734
                tree.branch.repository.bzrdir.root_transport)
 
1735
 
 
1736
 
 
1737
class TestSelftest(TestCase):
 
1738
    """Tests of bzrlib.tests.selftest."""
 
1739
 
 
1740
    def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
 
1741
        factory_called = []
 
1742
        def factory():
 
1743
            factory_called.append(True)
 
1744
            return TestSuite()
 
1745
        out = StringIO()
 
1746
        err = StringIO()
 
1747
        self.apply_redirected(out, err, None, bzrlib.tests.selftest, 
 
1748
            test_suite_factory=factory)
 
1749
        self.assertEqual([True], factory_called)
 
1750
 
 
1751
 
 
1752
class TestKnownFailure(TestCase):
 
1753
 
 
1754
    def test_known_failure(self):
 
1755
        """Check that KnownFailure is defined appropriately."""
 
1756
        # a KnownFailure is an assertion error for compatability with unaware
 
1757
        # runners.
 
1758
        self.assertIsInstance(KnownFailure(""), AssertionError)
 
1759
 
 
1760
    def test_expect_failure(self):
 
1761
        try:
 
1762
            self.expectFailure("Doomed to failure", self.assertTrue, False)
 
1763
        except KnownFailure, e:
 
1764
            self.assertEqual('Doomed to failure', e.args[0])
 
1765
        try:
 
1766
            self.expectFailure("Doomed to failure", self.assertTrue, True)
 
1767
        except AssertionError, e:
 
1768
            self.assertEqual('Unexpected success.  Should have failed:'
 
1769
                             ' Doomed to failure', e.args[0])
 
1770
        else:
 
1771
            self.fail('Assertion not raised')
 
1772
 
 
1773
 
 
1774
class TestFeature(TestCase):
 
1775
 
 
1776
    def test_caching(self):
 
1777
        """Feature._probe is called by the feature at most once."""
 
1778
        class InstrumentedFeature(Feature):
 
1779
            def __init__(self):
 
1780
                Feature.__init__(self)
 
1781
                self.calls = []
 
1782
            def _probe(self):
 
1783
                self.calls.append('_probe')
 
1784
                return False
 
1785
        feature = InstrumentedFeature()
 
1786
        feature.available()
 
1787
        self.assertEqual(['_probe'], feature.calls)
 
1788
        feature.available()
 
1789
        self.assertEqual(['_probe'], feature.calls)
 
1790
 
 
1791
    def test_named_str(self):
 
1792
        """Feature.__str__ should thunk to feature_name()."""
 
1793
        class NamedFeature(Feature):
 
1794
            def feature_name(self):
 
1795
                return 'symlinks'
 
1796
        feature = NamedFeature()
 
1797
        self.assertEqual('symlinks', str(feature))
 
1798
 
 
1799
    def test_default_str(self):
 
1800
        """Feature.__str__ should default to __class__.__name__."""
 
1801
        class NamedFeature(Feature):
 
1802
            pass
 
1803
        feature = NamedFeature()
 
1804
        self.assertEqual('NamedFeature', str(feature))
 
1805
 
 
1806
 
 
1807
class TestUnavailableFeature(TestCase):
 
1808
 
 
1809
    def test_access_feature(self):
 
1810
        feature = Feature()
 
1811
        exception = UnavailableFeature(feature)
 
1812
        self.assertIs(feature, exception.args[0])
 
1813
 
 
1814
 
 
1815
class TestSelftestFiltering(TestCase):
 
1816
 
 
1817
    def setUp(self):
 
1818
        self.suite = TestUtil.TestSuite()
 
1819
        self.loader = TestUtil.TestLoader()
 
1820
        self.suite.addTest(self.loader.loadTestsFromModuleNames([
 
1821
            'bzrlib.tests.test_selftest']))
 
1822
        self.all_names = _test_ids(self.suite)
 
1823
 
 
1824
    def test_condition_id_re(self):
 
1825
        test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
1826
            'test_condition_id_re')
 
1827
        filtered_suite = filter_suite_by_condition(self.suite,
 
1828
            condition_id_re('test_condition_id_re'))
 
1829
        self.assertEqual([test_name], _test_ids(filtered_suite))
 
1830
 
 
1831
    def test_condition_id_in_list(self):
 
1832
        test_names = ['bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
1833
                      'test_condition_id_in_list']
 
1834
        id_list = tests.TestIdList(test_names)
 
1835
        filtered_suite = filter_suite_by_condition(
 
1836
            self.suite, tests.condition_id_in_list(id_list))
 
1837
        my_pattern = 'TestSelftestFiltering.*test_condition_id_in_list'
 
1838
        re_filtered = filter_suite_by_re(self.suite, my_pattern)
 
1839
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
 
1840
 
 
1841
    def test_condition_id_startswith(self):
 
1842
        klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
1843
        start1 = klass + 'test_condition_id_starts'
 
1844
        start2 = klass + 'test_condition_id_in'
 
1845
        test_names = [ klass + 'test_condition_id_in_list',
 
1846
                      klass + 'test_condition_id_startswith',
 
1847
                     ]
 
1848
        filtered_suite = filter_suite_by_condition(
 
1849
            self.suite, tests.condition_id_startswith([start1, start2]))
 
1850
        self.assertEqual(test_names, _test_ids(filtered_suite))
 
1851
 
 
1852
    def test_condition_isinstance(self):
 
1853
        filtered_suite = filter_suite_by_condition(self.suite,
 
1854
            condition_isinstance(self.__class__))
 
1855
        class_pattern = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
1856
        re_filtered = filter_suite_by_re(self.suite, class_pattern)
 
1857
        self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
 
1858
 
 
1859
    def test_exclude_tests_by_condition(self):
 
1860
        excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
1861
            'test_exclude_tests_by_condition')
 
1862
        filtered_suite = exclude_tests_by_condition(self.suite,
 
1863
            lambda x:x.id() == excluded_name)
 
1864
        self.assertEqual(len(self.all_names) - 1,
 
1865
            filtered_suite.countTestCases())
 
1866
        self.assertFalse(excluded_name in _test_ids(filtered_suite))
 
1867
        remaining_names = list(self.all_names)
 
1868
        remaining_names.remove(excluded_name)
 
1869
        self.assertEqual(remaining_names, _test_ids(filtered_suite))
 
1870
 
 
1871
    def test_exclude_tests_by_re(self):
 
1872
        self.all_names = _test_ids(self.suite)
 
1873
        filtered_suite = exclude_tests_by_re(self.suite, 'exclude_tests_by_re')
 
1874
        excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
1875
            'test_exclude_tests_by_re')
 
1876
        self.assertEqual(len(self.all_names) - 1,
 
1877
            filtered_suite.countTestCases())
 
1878
        self.assertFalse(excluded_name in _test_ids(filtered_suite))
 
1879
        remaining_names = list(self.all_names)
 
1880
        remaining_names.remove(excluded_name)
 
1881
        self.assertEqual(remaining_names, _test_ids(filtered_suite))
 
1882
 
 
1883
    def test_filter_suite_by_condition(self):
 
1884
        test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
1885
            'test_filter_suite_by_condition')
 
1886
        filtered_suite = filter_suite_by_condition(self.suite,
 
1887
            lambda x:x.id() == test_name)
 
1888
        self.assertEqual([test_name], _test_ids(filtered_suite))
 
1889
 
 
1890
    def test_filter_suite_by_re(self):
 
1891
        filtered_suite = filter_suite_by_re(self.suite, 'test_filter_suite_by_r')
 
1892
        filtered_names = _test_ids(filtered_suite)
 
1893
        self.assertEqual(filtered_names, ['bzrlib.tests.test_selftest.'
 
1894
            'TestSelftestFiltering.test_filter_suite_by_re'])
 
1895
 
 
1896
    def test_filter_suite_by_id_list(self):
 
1897
        test_list = ['bzrlib.tests.test_selftest.'
 
1898
                     'TestSelftestFiltering.test_filter_suite_by_id_list']
 
1899
        filtered_suite = tests.filter_suite_by_id_list(
 
1900
            self.suite, tests.TestIdList(test_list))
 
1901
        filtered_names = _test_ids(filtered_suite)
 
1902
        self.assertEqual(
 
1903
            filtered_names,
 
1904
            ['bzrlib.tests.test_selftest.'
 
1905
             'TestSelftestFiltering.test_filter_suite_by_id_list'])
 
1906
 
 
1907
    def test_filter_suite_by_id_startswith(self):
 
1908
        # By design this test may fail if another test is added whose name also
 
1909
        # begins with one of the start value used.
 
1910
        klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
1911
        start1 = klass + 'test_filter_suite_by_id_starts'
 
1912
        start2 = klass + 'test_filter_suite_by_id_li'
 
1913
        test_list = [klass + 'test_filter_suite_by_id_list',
 
1914
                     klass + 'test_filter_suite_by_id_startswith',
 
1915
                     ]
 
1916
        filtered_suite = tests.filter_suite_by_id_startswith(
 
1917
            self.suite, [start1, start2])
 
1918
        self.assertEqual(
 
1919
            test_list,
 
1920
            _test_ids(filtered_suite),
 
1921
            )
 
1922
 
 
1923
    def test_preserve_input(self):
 
1924
        # NB: Surely this is something in the stdlib to do this?
 
1925
        self.assertTrue(self.suite is preserve_input(self.suite))
 
1926
        self.assertTrue("@#$" is preserve_input("@#$"))
 
1927
 
 
1928
    def test_randomize_suite(self):
 
1929
        randomized_suite = randomize_suite(self.suite)
 
1930
        # randomizing should not add or remove test names.
 
1931
        self.assertEqual(set(_test_ids(self.suite)),
 
1932
                         set(_test_ids(randomized_suite)))
 
1933
        # Technically, this *can* fail, because random.shuffle(list) can be
 
1934
        # equal to list. Trying multiple times just pushes the frequency back.
 
1935
        # As its len(self.all_names)!:1, the failure frequency should be low
 
1936
        # enough to ignore. RBC 20071021.
 
1937
        # It should change the order.
 
1938
        self.assertNotEqual(self.all_names, _test_ids(randomized_suite))
 
1939
        # But not the length. (Possibly redundant with the set test, but not
 
1940
        # necessarily.)
 
1941
        self.assertEqual(len(self.all_names), len(_test_ids(randomized_suite)))
 
1942
 
 
1943
    def test_split_suit_by_condition(self):
 
1944
        self.all_names = _test_ids(self.suite)
 
1945
        condition = condition_id_re('test_filter_suite_by_r')
 
1946
        split_suite = split_suite_by_condition(self.suite, condition)
 
1947
        filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
1948
            'test_filter_suite_by_re')
 
1949
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
 
1950
        self.assertFalse(filtered_name in _test_ids(split_suite[1]))
 
1951
        remaining_names = list(self.all_names)
 
1952
        remaining_names.remove(filtered_name)
 
1953
        self.assertEqual(remaining_names, _test_ids(split_suite[1]))
 
1954
 
 
1955
    def test_split_suit_by_re(self):
 
1956
        self.all_names = _test_ids(self.suite)
 
1957
        split_suite = split_suite_by_re(self.suite, 'test_filter_suite_by_r')
 
1958
        filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
 
1959
            'test_filter_suite_by_re')
 
1960
        self.assertEqual([filtered_name], _test_ids(split_suite[0]))
 
1961
        self.assertFalse(filtered_name in _test_ids(split_suite[1]))
 
1962
        remaining_names = list(self.all_names)
 
1963
        remaining_names.remove(filtered_name)
 
1964
        self.assertEqual(remaining_names, _test_ids(split_suite[1]))
 
1965
 
 
1966
 
 
1967
class TestCheckInventoryShape(TestCaseWithTransport):
 
1968
 
 
1969
    def test_check_inventory_shape(self):
 
1970
        files = ['a', 'b/', 'b/c']
 
1971
        tree = self.make_branch_and_tree('.')
 
1972
        self.build_tree(files)
 
1973
        tree.add(files)
 
1974
        tree.lock_read()
 
1975
        try:
 
1976
            self.check_inventory_shape(tree.inventory, files)
 
1977
        finally:
 
1978
            tree.unlock()
 
1979
 
 
1980
 
 
1981
class TestBlackboxSupport(TestCase):
 
1982
    """Tests for testsuite blackbox features."""
 
1983
 
 
1984
    def test_run_bzr_failure_not_caught(self):
 
1985
        # When we run bzr in blackbox mode, we want any unexpected errors to
 
1986
        # propagate up to the test suite so that it can show the error in the
 
1987
        # usual way, and we won't get a double traceback.
 
1988
        e = self.assertRaises(
 
1989
            AssertionError,
 
1990
            self.run_bzr, ['assert-fail'])
 
1991
        # make sure we got the real thing, not an error from somewhere else in
 
1992
        # the test framework
 
1993
        self.assertEquals('always fails', str(e))
 
1994
        # check that there's no traceback in the test log
 
1995
        self.assertNotContainsRe(self._get_log(keep_log_file=True),
 
1996
            r'Traceback')
 
1997
 
 
1998
    def test_run_bzr_user_error_caught(self):
 
1999
        # Running bzr in blackbox mode, normal/expected/user errors should be
 
2000
        # caught in the regular way and turned into an error message plus exit
 
2001
        # code.
 
2002
        out, err = self.run_bzr(["log", "/nonexistantpath"], retcode=3)
 
2003
        self.assertEqual(out, '')
 
2004
        self.assertContainsRe(err,
 
2005
            'bzr: ERROR: Not a branch: ".*nonexistantpath/".\n')
 
2006
 
 
2007
 
 
2008
class TestTestLoader(TestCase):
 
2009
    """Tests for the test loader."""
 
2010
 
 
2011
    def _get_loader_and_module(self):
 
2012
        """Gets a TestLoader and a module with one test in it."""
 
2013
        loader = TestUtil.TestLoader()
 
2014
        module = {}
 
2015
        class Stub(TestCase):
 
2016
            def test_foo(self):
 
2017
                pass
 
2018
        class MyModule(object):
 
2019
            pass
 
2020
        MyModule.a_class = Stub
 
2021
        module = MyModule()
 
2022
        return loader, module
 
2023
 
 
2024
    def test_module_no_load_tests_attribute_loads_classes(self):
 
2025
        loader, module = self._get_loader_and_module()
 
2026
        self.assertEqual(1, loader.loadTestsFromModule(module).countTestCases())
 
2027
 
 
2028
    def test_module_load_tests_attribute_gets_called(self):
 
2029
        loader, module = self._get_loader_and_module()
 
2030
        # 'self' is here because we're faking the module with a class. Regular
 
2031
        # load_tests do not need that :)
 
2032
        def load_tests(self, standard_tests, module, loader):
 
2033
            result = loader.suiteClass()
 
2034
            for test in iter_suite_tests(standard_tests):
 
2035
                result.addTests([test, test])
 
2036
            return result
 
2037
        # add a load_tests() method which multiplies the tests from the module.
 
2038
        module.__class__.load_tests = load_tests
 
2039
        self.assertEqual(2, loader.loadTestsFromModule(module).countTestCases())
 
2040
 
 
2041
    def test_load_tests_from_module_name_smoke_test(self):
 
2042
        loader = TestUtil.TestLoader()
 
2043
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2044
        self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
 
2045
                          _test_ids(suite))
 
2046
 
 
2047
    def test_load_tests_from_module_name_with_bogus_module_name(self):
 
2048
        loader = TestUtil.TestLoader()
 
2049
        self.assertRaises(ImportError, loader.loadTestsFromModuleName, 'bogus')
 
2050
 
 
2051
 
 
2052
class TestTestIdList(tests.TestCase):
 
2053
 
 
2054
    def _create_id_list(self, test_list):
 
2055
        return tests.TestIdList(test_list)
 
2056
 
 
2057
    def _create_suite(self, test_id_list):
 
2058
 
 
2059
        class Stub(TestCase):
 
2060
            def test_foo(self):
 
2061
                pass
 
2062
 
 
2063
        def _create_test_id(id):
 
2064
            return lambda: id
 
2065
 
 
2066
        suite = TestUtil.TestSuite()
 
2067
        for id in test_id_list:
 
2068
            t  = Stub('test_foo')
 
2069
            t.id = _create_test_id(id)
 
2070
            suite.addTest(t)
 
2071
        return suite
 
2072
 
 
2073
    def _test_ids(self, test_suite):
 
2074
        """Get the ids for the tests in a test suite."""
 
2075
        return [t.id() for t in iter_suite_tests(test_suite)]
 
2076
 
 
2077
    def test_empty_list(self):
 
2078
        id_list = self._create_id_list([])
 
2079
        self.assertEquals({}, id_list.tests)
 
2080
        self.assertEquals({}, id_list.modules)
 
2081
 
 
2082
    def test_valid_list(self):
 
2083
        id_list = self._create_id_list(
 
2084
            ['mod1.cl1.meth1', 'mod1.cl1.meth2',
 
2085
             'mod1.func1', 'mod1.cl2.meth2',
 
2086
             'mod1.submod1',
 
2087
             'mod1.submod2.cl1.meth1', 'mod1.submod2.cl2.meth2',
 
2088
             ])
 
2089
        self.assertTrue(id_list.refers_to('mod1'))
 
2090
        self.assertTrue(id_list.refers_to('mod1.submod1'))
 
2091
        self.assertTrue(id_list.refers_to('mod1.submod2'))
 
2092
        self.assertTrue(id_list.includes('mod1.cl1.meth1'))
 
2093
        self.assertTrue(id_list.includes('mod1.submod1'))
 
2094
        self.assertTrue(id_list.includes('mod1.func1'))
 
2095
 
 
2096
    def test_bad_chars_in_params(self):
 
2097
        id_list = self._create_id_list(['mod1.cl1.meth1(xx.yy)'])
 
2098
        self.assertTrue(id_list.refers_to('mod1'))
 
2099
        self.assertTrue(id_list.includes('mod1.cl1.meth1(xx.yy)'))
 
2100
 
 
2101
    def test_module_used(self):
 
2102
        id_list = self._create_id_list(['mod.class.meth'])
 
2103
        self.assertTrue(id_list.refers_to('mod'))
 
2104
        self.assertTrue(id_list.refers_to('mod.class'))
 
2105
        self.assertTrue(id_list.refers_to('mod.class.meth'))
 
2106
 
 
2107
    def test_test_suite(self):
 
2108
        # This test is slow, so we do a single test with one test in each
 
2109
        # category
 
2110
        test_list = [
 
2111
            # testmod_names
 
2112
            'bzrlib.tests.blackbox.test_branch.TestBranch.test_branch',
 
2113
            'bzrlib.tests.test_selftest.TestTestIdList.test_test_suite',
 
2114
            # transport implementations
 
2115
            'bzrlib.tests.test_transport_implementations.TransportTests'
 
2116
            '.test_abspath(LocalURLServer)',
 
2117
            # modules_to_doctest
 
2118
            'bzrlib.timestamp.format_highres_date',
 
2119
            # plugins can't be tested that way since selftest may be run with
 
2120
            # --no-plugins
 
2121
            ]
 
2122
        suite = tests.test_suite(test_list)
 
2123
        self.assertEquals(test_list, _test_ids(suite))
 
2124
 
 
2125
    def test_test_suite_matches_id_list_with_unknown(self):
 
2126
        loader = TestUtil.TestLoader()
 
2127
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2128
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',
 
2129
                     'bogus']
 
2130
        not_found, duplicates = tests.suite_matches_id_list(suite, test_list)
 
2131
        self.assertEquals(['bogus'], not_found)
 
2132
        self.assertEquals([], duplicates)
 
2133
 
 
2134
    def test_suite_matches_id_list_with_duplicates(self):
 
2135
        loader = TestUtil.TestLoader()
 
2136
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2137
        dupes = loader.suiteClass()
 
2138
        for test in iter_suite_tests(suite):
 
2139
            dupes.addTest(test)
 
2140
            dupes.addTest(test) # Add it again
 
2141
 
 
2142
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',]
 
2143
        not_found, duplicates = tests.suite_matches_id_list(
 
2144
            dupes, test_list)
 
2145
        self.assertEquals([], not_found)
 
2146
        self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
 
2147
                          duplicates)
 
2148
 
 
2149
 
 
2150
class TestLoadTestIdList(tests.TestCaseInTempDir):
 
2151
 
 
2152
    def _create_test_list_file(self, file_name, content):
 
2153
        fl = open(file_name, 'wt')
 
2154
        fl.write(content)
 
2155
        fl.close()
 
2156
 
 
2157
    def test_load_unknown(self):
 
2158
        self.assertRaises(errors.NoSuchFile,
 
2159
                          tests.load_test_id_list, 'i_do_not_exist')
 
2160
 
 
2161
    def test_load_test_list(self):
 
2162
        test_list_fname = 'test.list'
 
2163
        self._create_test_list_file(test_list_fname,
 
2164
                                    'mod1.cl1.meth1\nmod2.cl2.meth2\n')
 
2165
        tlist = tests.load_test_id_list(test_list_fname)
 
2166
        self.assertEquals(2, len(tlist))
 
2167
        self.assertEquals('mod1.cl1.meth1', tlist[0])
 
2168
        self.assertEquals('mod2.cl2.meth2', tlist[1])
 
2169
 
 
2170
    def test_load_dirty_file(self):
 
2171
        test_list_fname = 'test.list'
 
2172
        self._create_test_list_file(test_list_fname,
 
2173
                                    '  mod1.cl1.meth1\n\nmod2.cl2.meth2  \n'
 
2174
                                    'bar baz\n')
 
2175
        tlist = tests.load_test_id_list(test_list_fname)
 
2176
        self.assertEquals(4, len(tlist))
 
2177
        self.assertEquals('mod1.cl1.meth1', tlist[0])
 
2178
        self.assertEquals('', tlist[1])
 
2179
        self.assertEquals('mod2.cl2.meth2', tlist[2])
 
2180
        self.assertEquals('bar baz', tlist[3])
 
2181
 
 
2182
 
 
2183
class TestFilteredByModuleTestLoader(tests.TestCase):
 
2184
 
 
2185
    def _create_loader(self, test_list):
 
2186
        id_filter = tests.TestIdList(test_list)
 
2187
        loader = TestUtil.FilteredByModuleTestLoader(id_filter.refers_to)
 
2188
        return loader
 
2189
 
 
2190
    def test_load_tests(self):
 
2191
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
 
2192
        loader = self._create_loader(test_list)
 
2193
 
 
2194
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2195
        self.assertEquals(test_list, _test_ids(suite))
 
2196
 
 
2197
    def test_exclude_tests(self):
 
2198
        test_list = ['bogus']
 
2199
        loader = self._create_loader(test_list)
 
2200
 
 
2201
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2202
        self.assertEquals([], _test_ids(suite))
 
2203
 
 
2204
 
 
2205
class TestFilteredByNameStartTestLoader(tests.TestCase):
 
2206
 
 
2207
    def _create_loader(self, name_start):
 
2208
        def needs_module(name):
 
2209
            return name.startswith(name_start) or name_start.startswith(name)
 
2210
        loader = TestUtil.FilteredByModuleTestLoader(needs_module)
 
2211
        return loader
 
2212
 
 
2213
    def test_load_tests(self):
 
2214
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
 
2215
        loader = self._create_loader('bzrlib.tests.test_samp')
 
2216
 
 
2217
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2218
        self.assertEquals(test_list, _test_ids(suite))
 
2219
 
 
2220
    def test_load_tests_inside_module(self):
 
2221
        test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
 
2222
        loader = self._create_loader('bzrlib.tests.test_sampler.Demo')
 
2223
 
 
2224
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2225
        self.assertEquals(test_list, _test_ids(suite))
 
2226
 
 
2227
    def test_exclude_tests(self):
 
2228
        test_list = ['bogus']
 
2229
        loader = self._create_loader('bogus')
 
2230
 
 
2231
        suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
 
2232
        self.assertEquals([], _test_ids(suite))
 
2233
 
 
2234
 
 
2235
class TestTestPrefixRegistry(tests.TestCase):
 
2236
 
 
2237
    def _get_registry(self):
 
2238
        tp_registry = tests.TestPrefixAliasRegistry()
 
2239
        return tp_registry
 
2240
 
 
2241
    def test_register_new_prefix(self):
 
2242
        tpr = self._get_registry()
 
2243
        tpr.register('foo', 'fff.ooo.ooo')
 
2244
        self.assertEquals('fff.ooo.ooo', tpr.get('foo'))
 
2245
 
 
2246
    def test_register_existing_prefix(self):
 
2247
        tpr = self._get_registry()
 
2248
        tpr.register('bar', 'bbb.aaa.rrr')
 
2249
        tpr.register('bar', 'bBB.aAA.rRR')
 
2250
        self.assertEquals('bbb.aaa.rrr', tpr.get('bar'))
 
2251
        self.assertContainsRe(self._get_log(keep_log_file=True),
 
2252
                              r'.*bar.*bbb.aaa.rrr.*bBB.aAA.rRR')
 
2253
 
 
2254
    def test_get_unknown_prefix(self):
 
2255
        tpr = self._get_registry()
 
2256
        self.assertRaises(KeyError, tpr.get, 'I am not a prefix')
 
2257
 
 
2258
    def test_resolve_prefix(self):
 
2259
        tpr = self._get_registry()
 
2260
        tpr.register('bar', 'bb.aa.rr')
 
2261
        self.assertEquals('bb.aa.rr', tpr.resolve_alias('bar'))
 
2262
 
 
2263
    def test_resolve_unknown_alias(self):
 
2264
        tpr = self._get_registry()
 
2265
        self.assertRaises(errors.BzrCommandError,
 
2266
                          tpr.resolve_alias, 'I am not a prefix')
 
2267
 
 
2268
    def test_predefined_prefixes(self):
 
2269
        tpr = tests.test_prefix_alias_registry
 
2270
        self.assertEquals('bzrlib', tpr.resolve_alias('bzrlib'))
 
2271
        self.assertEquals('bzrlib.doc', tpr.resolve_alias('bd'))
 
2272
        self.assertEquals('bzrlib.utils', tpr.resolve_alias('bu'))
 
2273
        self.assertEquals('bzrlib.tests', tpr.resolve_alias('bt'))
 
2274
        self.assertEquals('bzrlib.tests.blackbox', tpr.resolve_alias('bb'))
 
2275
        self.assertEquals('bzrlib.plugins', tpr.resolve_alias('bp'))