/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: Canonical.com Patch Queue Manager
  • Date: 2006-07-19 21:44:16 UTC
  • mfrom: (1836.1.26 ignores)
  • Revision ID: pqm@pqm.ubuntu.com-20060719214416-9fab2f627df9f1aa
(jam) allow global user ignores, and include a small set by default

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006 by 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 version 2 as published by
 
5
# the Free Software Foundation.
 
6
#
 
7
# This program is distributed in the hope that it will be useful,
 
8
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
9
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
10
# GNU General Public License for more details.
 
11
#
 
12
# You should have received a copy of the GNU General Public License
 
13
# along with this program; if not, write to the Free Software
 
14
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
 
 
16
"""Tests for the test framework."""
 
17
 
 
18
import os
 
19
from StringIO import StringIO
 
20
import sys
 
21
import time
 
22
import unittest
 
23
import warnings
 
24
 
 
25
from bzrlib import osutils
 
26
import bzrlib
 
27
from bzrlib.progress import _BaseProgressBar
 
28
from bzrlib.tests import (
 
29
                          ChrootedTestCase,
 
30
                          TestCase,
 
31
                          TestCaseInTempDir,
 
32
                          TestCaseWithTransport,
 
33
                          TestSkipped,
 
34
                          TestSuite,
 
35
                          TextTestRunner,
 
36
                          )
 
37
from bzrlib.tests.TestUtil import _load_module_by_name
 
38
import bzrlib.errors as errors
 
39
from bzrlib.trace import note
 
40
 
 
41
 
 
42
class SelftestTests(TestCase):
 
43
 
 
44
    def test_import_tests(self):
 
45
        mod = _load_module_by_name('bzrlib.tests.test_selftest')
 
46
        self.assertEqual(mod.SelftestTests, SelftestTests)
 
47
 
 
48
    def test_import_test_failure(self):
 
49
        self.assertRaises(ImportError,
 
50
                          _load_module_by_name,
 
51
                          'bzrlib.no-name-yet')
 
52
 
 
53
 
 
54
class MetaTestLog(TestCase):
 
55
 
 
56
    def test_logging(self):
 
57
        """Test logs are captured when a test fails."""
 
58
        self.log('a test message')
 
59
        self._log_file.flush()
 
60
        self.assertContainsRe(self._get_log(), 'a test message\n')
 
61
 
 
62
 
 
63
class TestTreeShape(TestCaseInTempDir):
 
64
 
 
65
    def test_unicode_paths(self):
 
66
        filename = u'hell\u00d8'
 
67
        try:
 
68
            self.build_tree_contents([(filename, 'contents of hello')])
 
69
        except UnicodeEncodeError:
 
70
            raise TestSkipped("can't build unicode working tree in "
 
71
                "filesystem encoding %s" % sys.getfilesystemencoding())
 
72
        self.failUnlessExists(filename)
 
73
 
 
74
 
 
75
class TestTransportProviderAdapter(TestCase):
 
76
    """A group of tests that test the transport implementation adaption core.
 
77
 
 
78
    This is a meta test that the tests are applied to all available 
 
79
    transports.
 
80
 
 
81
    This will be generalised in the future which is why it is in this 
 
82
    test file even though it is specific to transport tests at the moment.
 
83
    """
 
84
 
 
85
    def test_get_transport_permutations(self):
 
86
        # this checks that we the module get_test_permutations call
 
87
        # is made by the adapter get_transport_test_permitations method.
 
88
        class MockModule(object):
 
89
            def get_test_permutations(self):
 
90
                return sample_permutation
 
91
        sample_permutation = [(1,2), (3,4)]
 
92
        from bzrlib.transport import TransportTestProviderAdapter
 
93
        adapter = TransportTestProviderAdapter()
 
94
        self.assertEqual(sample_permutation,
 
95
                         adapter.get_transport_test_permutations(MockModule()))
 
96
 
 
97
    def test_adapter_checks_all_modules(self):
 
98
        # this checks that the adapter returns as many permurtations as
 
99
        # there are in all the registered# transport modules for there
 
100
        # - we assume if this matches its probably doing the right thing
 
101
        # especially in combination with the tests for setting the right
 
102
        # classes below.
 
103
        from bzrlib.transport import (TransportTestProviderAdapter,
 
104
                                      _get_transport_modules
 
105
                                      )
 
106
        modules = _get_transport_modules()
 
107
        permutation_count = 0
 
108
        for module in modules:
 
109
            try:
 
110
                permutation_count += len(reduce(getattr, 
 
111
                    (module + ".get_test_permutations").split('.')[1:],
 
112
                     __import__(module))())
 
113
            except errors.DependencyNotPresent:
 
114
                pass
 
115
        input_test = TestTransportProviderAdapter(
 
116
            "test_adapter_sets_transport_class")
 
117
        adapter = TransportTestProviderAdapter()
 
118
        self.assertEqual(permutation_count,
 
119
                         len(list(iter(adapter.adapt(input_test)))))
 
120
 
 
121
    def test_adapter_sets_transport_class(self):
 
122
        # Check that the test adapter inserts a transport and server into the
 
123
        # generated test.
 
124
        #
 
125
        # This test used to know about all the possible transports and the
 
126
        # order they were returned but that seems overly brittle (mbp
 
127
        # 20060307)
 
128
        input_test = TestTransportProviderAdapter(
 
129
            "test_adapter_sets_transport_class")
 
130
        from bzrlib.transport import TransportTestProviderAdapter
 
131
        suite = TransportTestProviderAdapter().adapt(input_test)
 
132
        tests = list(iter(suite))
 
133
        self.assertTrue(len(tests) > 6)
 
134
        # there are at least that many builtin transports
 
135
        one_test = tests[0]
 
136
        self.assertTrue(issubclass(one_test.transport_class, 
 
137
                                   bzrlib.transport.Transport))
 
138
        self.assertTrue(issubclass(one_test.transport_server, 
 
139
                                   bzrlib.transport.Server))
 
140
 
 
141
 
 
142
class TestBranchProviderAdapter(TestCase):
 
143
    """A group of tests that test the branch implementation test adapter."""
 
144
 
 
145
    def test_adapted_tests(self):
 
146
        # check that constructor parameters are passed through to the adapted
 
147
        # test.
 
148
        from bzrlib.branch import BranchTestProviderAdapter
 
149
        input_test = TestBranchProviderAdapter(
 
150
            "test_adapted_tests")
 
151
        server1 = "a"
 
152
        server2 = "b"
 
153
        formats = [("c", "C"), ("d", "D")]
 
154
        adapter = BranchTestProviderAdapter(server1, server2, formats)
 
155
        suite = adapter.adapt(input_test)
 
156
        tests = list(iter(suite))
 
157
        self.assertEqual(2, len(tests))
 
158
        self.assertEqual(tests[0].branch_format, formats[0][0])
 
159
        self.assertEqual(tests[0].bzrdir_format, formats[0][1])
 
160
        self.assertEqual(tests[0].transport_server, server1)
 
161
        self.assertEqual(tests[0].transport_readonly_server, server2)
 
162
        self.assertEqual(tests[1].branch_format, formats[1][0])
 
163
        self.assertEqual(tests[1].bzrdir_format, formats[1][1])
 
164
        self.assertEqual(tests[1].transport_server, server1)
 
165
        self.assertEqual(tests[1].transport_readonly_server, server2)
 
166
 
 
167
 
 
168
class TestBzrDirProviderAdapter(TestCase):
 
169
    """A group of tests that test the bzr dir implementation test adapter."""
 
170
 
 
171
    def test_adapted_tests(self):
 
172
        # check that constructor parameters are passed through to the adapted
 
173
        # test.
 
174
        from bzrlib.bzrdir import BzrDirTestProviderAdapter
 
175
        input_test = TestBzrDirProviderAdapter(
 
176
            "test_adapted_tests")
 
177
        server1 = "a"
 
178
        server2 = "b"
 
179
        formats = ["c", "d"]
 
180
        adapter = BzrDirTestProviderAdapter(server1, server2, formats)
 
181
        suite = adapter.adapt(input_test)
 
182
        tests = list(iter(suite))
 
183
        self.assertEqual(2, len(tests))
 
184
        self.assertEqual(tests[0].bzrdir_format, formats[0])
 
185
        self.assertEqual(tests[0].transport_server, server1)
 
186
        self.assertEqual(tests[0].transport_readonly_server, server2)
 
187
        self.assertEqual(tests[1].bzrdir_format, formats[1])
 
188
        self.assertEqual(tests[1].transport_server, server1)
 
189
        self.assertEqual(tests[1].transport_readonly_server, server2)
 
190
 
 
191
 
 
192
class TestRepositoryProviderAdapter(TestCase):
 
193
    """A group of tests that test the repository implementation test adapter."""
 
194
 
 
195
    def test_adapted_tests(self):
 
196
        # check that constructor parameters are passed through to the adapted
 
197
        # test.
 
198
        from bzrlib.repository import RepositoryTestProviderAdapter
 
199
        input_test = TestRepositoryProviderAdapter(
 
200
            "test_adapted_tests")
 
201
        server1 = "a"
 
202
        server2 = "b"
 
203
        formats = [("c", "C"), ("d", "D")]
 
204
        adapter = RepositoryTestProviderAdapter(server1, server2, formats)
 
205
        suite = adapter.adapt(input_test)
 
206
        tests = list(iter(suite))
 
207
        self.assertEqual(2, len(tests))
 
208
        self.assertEqual(tests[0].bzrdir_format, formats[0][1])
 
209
        self.assertEqual(tests[0].repository_format, formats[0][0])
 
210
        self.assertEqual(tests[0].transport_server, server1)
 
211
        self.assertEqual(tests[0].transport_readonly_server, server2)
 
212
        self.assertEqual(tests[1].bzrdir_format, formats[1][1])
 
213
        self.assertEqual(tests[1].repository_format, formats[1][0])
 
214
        self.assertEqual(tests[1].transport_server, server1)
 
215
        self.assertEqual(tests[1].transport_readonly_server, server2)
 
216
 
 
217
 
 
218
class TestInterRepositoryProviderAdapter(TestCase):
 
219
    """A group of tests that test the InterRepository test adapter."""
 
220
 
 
221
    def test_adapted_tests(self):
 
222
        # check that constructor parameters are passed through to the adapted
 
223
        # test.
 
224
        from bzrlib.repository import InterRepositoryTestProviderAdapter
 
225
        input_test = TestInterRepositoryProviderAdapter(
 
226
            "test_adapted_tests")
 
227
        server1 = "a"
 
228
        server2 = "b"
 
229
        formats = [(str, "C1", "C2"), (int, "D1", "D2")]
 
230
        adapter = InterRepositoryTestProviderAdapter(server1, server2, formats)
 
231
        suite = adapter.adapt(input_test)
 
232
        tests = list(iter(suite))
 
233
        self.assertEqual(2, len(tests))
 
234
        self.assertEqual(tests[0].interrepo_class, formats[0][0])
 
235
        self.assertEqual(tests[0].repository_format, formats[0][1])
 
236
        self.assertEqual(tests[0].repository_format_to, formats[0][2])
 
237
        self.assertEqual(tests[0].transport_server, server1)
 
238
        self.assertEqual(tests[0].transport_readonly_server, server2)
 
239
        self.assertEqual(tests[1].interrepo_class, formats[1][0])
 
240
        self.assertEqual(tests[1].repository_format, formats[1][1])
 
241
        self.assertEqual(tests[1].repository_format_to, formats[1][2])
 
242
        self.assertEqual(tests[1].transport_server, server1)
 
243
        self.assertEqual(tests[1].transport_readonly_server, server2)
 
244
 
 
245
 
 
246
class TestInterVersionedFileProviderAdapter(TestCase):
 
247
    """A group of tests that test the InterVersionedFile test adapter."""
 
248
 
 
249
    def test_adapted_tests(self):
 
250
        # check that constructor parameters are passed through to the adapted
 
251
        # test.
 
252
        from bzrlib.versionedfile import InterVersionedFileTestProviderAdapter
 
253
        input_test = TestInterRepositoryProviderAdapter(
 
254
            "test_adapted_tests")
 
255
        server1 = "a"
 
256
        server2 = "b"
 
257
        formats = [(str, "C1", "C2"), (int, "D1", "D2")]
 
258
        adapter = InterVersionedFileTestProviderAdapter(server1, server2, formats)
 
259
        suite = adapter.adapt(input_test)
 
260
        tests = list(iter(suite))
 
261
        self.assertEqual(2, len(tests))
 
262
        self.assertEqual(tests[0].interversionedfile_class, formats[0][0])
 
263
        self.assertEqual(tests[0].versionedfile_factory, formats[0][1])
 
264
        self.assertEqual(tests[0].versionedfile_factory_to, formats[0][2])
 
265
        self.assertEqual(tests[0].transport_server, server1)
 
266
        self.assertEqual(tests[0].transport_readonly_server, server2)
 
267
        self.assertEqual(tests[1].interversionedfile_class, formats[1][0])
 
268
        self.assertEqual(tests[1].versionedfile_factory, formats[1][1])
 
269
        self.assertEqual(tests[1].versionedfile_factory_to, formats[1][2])
 
270
        self.assertEqual(tests[1].transport_server, server1)
 
271
        self.assertEqual(tests[1].transport_readonly_server, server2)
 
272
 
 
273
 
 
274
class TestRevisionStoreProviderAdapter(TestCase):
 
275
    """A group of tests that test the RevisionStore test adapter."""
 
276
 
 
277
    def test_adapted_tests(self):
 
278
        # check that constructor parameters are passed through to the adapted
 
279
        # test.
 
280
        from bzrlib.store.revision import RevisionStoreTestProviderAdapter
 
281
        input_test = TestRevisionStoreProviderAdapter(
 
282
            "test_adapted_tests")
 
283
        # revision stores need a store factory - i.e. RevisionKnit
 
284
        #, a readonly and rw transport 
 
285
        # transport servers:
 
286
        server1 = "a"
 
287
        server2 = "b"
 
288
        store_factories = ["c", "d"]
 
289
        adapter = RevisionStoreTestProviderAdapter(server1, server2, store_factories)
 
290
        suite = adapter.adapt(input_test)
 
291
        tests = list(iter(suite))
 
292
        self.assertEqual(2, len(tests))
 
293
        self.assertEqual(tests[0].store_factory, store_factories[0][0])
 
294
        self.assertEqual(tests[0].transport_server, server1)
 
295
        self.assertEqual(tests[0].transport_readonly_server, server2)
 
296
        self.assertEqual(tests[1].store_factory, store_factories[1][0])
 
297
        self.assertEqual(tests[1].transport_server, server1)
 
298
        self.assertEqual(tests[1].transport_readonly_server, server2)
 
299
 
 
300
 
 
301
class TestWorkingTreeProviderAdapter(TestCase):
 
302
    """A group of tests that test the workingtree implementation test adapter."""
 
303
 
 
304
    def test_adapted_tests(self):
 
305
        # check that constructor parameters are passed through to the adapted
 
306
        # test.
 
307
        from bzrlib.workingtree import WorkingTreeTestProviderAdapter
 
308
        input_test = TestWorkingTreeProviderAdapter(
 
309
            "test_adapted_tests")
 
310
        server1 = "a"
 
311
        server2 = "b"
 
312
        formats = [("c", "C"), ("d", "D")]
 
313
        adapter = WorkingTreeTestProviderAdapter(server1, server2, formats)
 
314
        suite = adapter.adapt(input_test)
 
315
        tests = list(iter(suite))
 
316
        self.assertEqual(2, len(tests))
 
317
        self.assertEqual(tests[0].workingtree_format, formats[0][0])
 
318
        self.assertEqual(tests[0].bzrdir_format, formats[0][1])
 
319
        self.assertEqual(tests[0].transport_server, server1)
 
320
        self.assertEqual(tests[0].transport_readonly_server, server2)
 
321
        self.assertEqual(tests[1].workingtree_format, formats[1][0])
 
322
        self.assertEqual(tests[1].bzrdir_format, formats[1][1])
 
323
        self.assertEqual(tests[1].transport_server, server1)
 
324
        self.assertEqual(tests[1].transport_readonly_server, server2)
 
325
 
 
326
 
 
327
class TestTestCaseWithTransport(TestCaseWithTransport):
 
328
    """Tests for the convenience functions TestCaseWithTransport introduces."""
 
329
 
 
330
    def test_get_readonly_url_none(self):
 
331
        from bzrlib.transport import get_transport
 
332
        from bzrlib.transport.memory import MemoryServer
 
333
        from bzrlib.transport.readonly import ReadonlyTransportDecorator
 
334
        self.transport_server = MemoryServer
 
335
        self.transport_readonly_server = None
 
336
        # calling get_readonly_transport() constructs a decorator on the url
 
337
        # for the server
 
338
        url = self.get_readonly_url()
 
339
        url2 = self.get_readonly_url('foo/bar')
 
340
        t = get_transport(url)
 
341
        t2 = get_transport(url2)
 
342
        self.failUnless(isinstance(t, ReadonlyTransportDecorator))
 
343
        self.failUnless(isinstance(t2, ReadonlyTransportDecorator))
 
344
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
 
345
 
 
346
    def test_get_readonly_url_http(self):
 
347
        from bzrlib.transport import get_transport
 
348
        from bzrlib.transport.local import LocalRelpathServer
 
349
        from bzrlib.transport.http import HttpServer, HttpTransportBase
 
350
        self.transport_server = LocalRelpathServer
 
351
        self.transport_readonly_server = HttpServer
 
352
        # calling get_readonly_transport() gives us a HTTP server instance.
 
353
        url = self.get_readonly_url()
 
354
        url2 = self.get_readonly_url('foo/bar')
 
355
        # the transport returned may be any HttpTransportBase subclass
 
356
        t = get_transport(url)
 
357
        t2 = get_transport(url2)
 
358
        self.failUnless(isinstance(t, HttpTransportBase))
 
359
        self.failUnless(isinstance(t2, HttpTransportBase))
 
360
        self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
 
361
 
 
362
    def test_is_directory(self):
 
363
        """Test assertIsDirectory assertion"""
 
364
        t = self.get_transport()
 
365
        self.build_tree(['a_dir/', 'a_file'], transport=t)
 
366
        self.assertIsDirectory('a_dir', t)
 
367
        self.assertRaises(AssertionError, self.assertIsDirectory, 'a_file', t)
 
368
        self.assertRaises(AssertionError, self.assertIsDirectory, 'not_here', t)
 
369
 
 
370
 
 
371
class TestChrootedTest(ChrootedTestCase):
 
372
 
 
373
    def test_root_is_root(self):
 
374
        from bzrlib.transport import get_transport
 
375
        t = get_transport(self.get_readonly_url())
 
376
        url = t.base
 
377
        self.assertEqual(url, t.clone('..').base)
 
378
 
 
379
 
 
380
class MockProgress(_BaseProgressBar):
 
381
    """Progress-bar standin that records calls.
 
382
 
 
383
    Useful for testing pb using code.
 
384
    """
 
385
 
 
386
    def __init__(self):
 
387
        _BaseProgressBar.__init__(self)
 
388
        self.calls = []
 
389
 
 
390
    def tick(self):
 
391
        self.calls.append(('tick',))
 
392
 
 
393
    def update(self, msg=None, current=None, total=None):
 
394
        self.calls.append(('update', msg, current, total))
 
395
 
 
396
    def clear(self):
 
397
        self.calls.append(('clear',))
 
398
 
 
399
    def note(self, msg, *args):
 
400
        self.calls.append(('note', msg, args))
 
401
 
 
402
 
 
403
class TestTestResult(TestCase):
 
404
 
 
405
    def test_progress_bar_style_quiet(self):
 
406
        # test using a progress bar.
 
407
        dummy_test = TestTestResult('test_progress_bar_style_quiet')
 
408
        dummy_error = (Exception, None, [])
 
409
        mypb = MockProgress()
 
410
        mypb.update('Running tests', 0, 4)
 
411
        last_calls = mypb.calls[:]
 
412
 
 
413
        result = bzrlib.tests._MyResult(self._log_file,
 
414
                                        descriptions=0,
 
415
                                        verbosity=1,
 
416
                                        pb=mypb)
 
417
        self.assertEqual(last_calls, mypb.calls)
 
418
 
 
419
        def shorten(s):
 
420
            """Shorten a string based on the terminal width"""
 
421
            return result._ellipsise_unimportant_words(s,
 
422
                                 osutils.terminal_width())
 
423
 
 
424
        # an error 
 
425
        result.startTest(dummy_test)
 
426
        # starting a test prints the test name
 
427
        last_calls += [('update', '...tyle_quiet', 0, None)]
 
428
        self.assertEqual(last_calls, mypb.calls)
 
429
        result.addError(dummy_test, dummy_error)
 
430
        last_calls += [('update', 'ERROR        ', 1, None),
 
431
                       ('note', shorten(dummy_test.id() + ': ERROR'), ())
 
432
                      ]
 
433
        self.assertEqual(last_calls, mypb.calls)
 
434
 
 
435
        # a failure
 
436
        result.startTest(dummy_test)
 
437
        last_calls += [('update', '...tyle_quiet', 1, None)]
 
438
        self.assertEqual(last_calls, mypb.calls)
 
439
        last_calls += [('update', 'FAIL         ', 2, None),
 
440
                       ('note', shorten(dummy_test.id() + ': FAIL'), ())
 
441
                      ]
 
442
        result.addFailure(dummy_test, dummy_error)
 
443
        self.assertEqual(last_calls, mypb.calls)
 
444
 
 
445
        # a success
 
446
        result.startTest(dummy_test)
 
447
        last_calls += [('update', '...tyle_quiet', 2, None)]
 
448
        self.assertEqual(last_calls, mypb.calls)
 
449
        result.addSuccess(dummy_test)
 
450
        last_calls += [('update', 'OK           ', 3, None)]
 
451
        self.assertEqual(last_calls, mypb.calls)
 
452
 
 
453
        # a skip
 
454
        result.startTest(dummy_test)
 
455
        last_calls += [('update', '...tyle_quiet', 3, None)]
 
456
        self.assertEqual(last_calls, mypb.calls)
 
457
        result.addSkipped(dummy_test, dummy_error)
 
458
        last_calls += [('update', 'SKIP         ', 4, None)]
 
459
        self.assertEqual(last_calls, mypb.calls)
 
460
 
 
461
    def test_elapsed_time_with_benchmarking(self):
 
462
        result = bzrlib.tests._MyResult(self._log_file,
 
463
                                        descriptions=0,
 
464
                                        verbosity=1,
 
465
                                        )
 
466
        result._recordTestStartTime()
 
467
        time.sleep(0.003)
 
468
        result.extractBenchmarkTime(self)
 
469
        timed_string = result._testTimeString()
 
470
        # without explicit benchmarking, we should get a simple time.
 
471
        self.assertContainsRe(timed_string, "^         [ 1-9][0-9]ms$")
 
472
        # if a benchmark time is given, we want a x of y style result.
 
473
        self.time(time.sleep, 0.001)
 
474
        result.extractBenchmarkTime(self)
 
475
        timed_string = result._testTimeString()
 
476
        self.assertContainsRe(timed_string, "^   [ 1-9][0-9]ms/   [ 1-9][0-9]ms$")
 
477
        # extracting the time from a non-bzrlib testcase sets to None
 
478
        result._recordTestStartTime()
 
479
        result.extractBenchmarkTime(
 
480
            unittest.FunctionTestCase(self.test_elapsed_time_with_benchmarking))
 
481
        timed_string = result._testTimeString()
 
482
        self.assertContainsRe(timed_string, "^         [ 1-9][0-9]ms$")
 
483
        # cheat. Yes, wash thy mouth out with soap.
 
484
        self._benchtime = None
 
485
 
 
486
    def _time_hello_world_encoding(self):
 
487
        """Profile two sleep calls
 
488
        
 
489
        This is used to exercise the test framework.
 
490
        """
 
491
        self.time(unicode, 'hello', errors='replace')
 
492
        self.time(unicode, 'world', errors='replace')
 
493
 
 
494
    def test_lsprofiling(self):
 
495
        """Verbose test result prints lsprof statistics from test cases."""
 
496
        try:
 
497
            import bzrlib.lsprof
 
498
        except ImportError:
 
499
            raise TestSkipped("lsprof not installed.")
 
500
        result_stream = StringIO()
 
501
        result = bzrlib.tests._MyResult(
 
502
            unittest._WritelnDecorator(result_stream),
 
503
            descriptions=0,
 
504
            verbosity=2,
 
505
            )
 
506
        # we want profile a call of some sort and check it is output by
 
507
        # addSuccess. We dont care about addError or addFailure as they
 
508
        # are not that interesting for performance tuning.
 
509
        # make a new test instance that when run will generate a profile
 
510
        example_test_case = TestTestResult("_time_hello_world_encoding")
 
511
        example_test_case._gather_lsprof_in_benchmarks = True
 
512
        # execute the test, which should succeed and record profiles
 
513
        example_test_case.run(result)
 
514
        # lsprofile_something()
 
515
        # if this worked we want 
 
516
        # LSProf output for <built in function unicode> (['hello'], {'errors': 'replace'})
 
517
        #    CallCount    Recursive    Total(ms)   Inline(ms) module:lineno(function)
 
518
        # (the lsprof header)
 
519
        # ... an arbitrary number of lines
 
520
        # and the function call which is time.sleep.
 
521
        #           1        0            ???         ???       ???(sleep) 
 
522
        # and then repeated but with 'world', rather than 'hello'.
 
523
        # this should appear in the output stream of our test result.
 
524
        output = result_stream.getvalue()
 
525
        self.assertContainsRe(output,
 
526
            r"LSProf output for <type 'unicode'>\(\('hello',\), {'errors': 'replace'}\)")
 
527
        self.assertContainsRe(output,
 
528
            r" *CallCount *Recursive *Total\(ms\) *Inline\(ms\) *module:lineno\(function\)\n")
 
529
        self.assertContainsRe(output,
 
530
            r"( +1 +0 +0\.\d+ +0\.\d+ +<method 'disable' of '_lsprof\.Profiler' objects>\n)?")
 
531
        self.assertContainsRe(output,
 
532
            r"LSProf output for <type 'unicode'>\(\('world',\), {'errors': 'replace'}\)\n")
 
533
 
 
534
 
 
535
class TestRunner(TestCase):
 
536
 
 
537
    def dummy_test(self):
 
538
        pass
 
539
 
 
540
    def run_test_runner(self, testrunner, test):
 
541
        """Run suite in testrunner, saving global state and restoring it.
 
542
 
 
543
        This current saves and restores:
 
544
        TestCaseInTempDir.TEST_ROOT
 
545
        
 
546
        There should be no tests in this file that use bzrlib.tests.TextTestRunner
 
547
        without using this convenience method, because of our use of global state.
 
548
        """
 
549
        old_root = TestCaseInTempDir.TEST_ROOT
 
550
        try:
 
551
            TestCaseInTempDir.TEST_ROOT = None
 
552
            return testrunner.run(test)
 
553
        finally:
 
554
            TestCaseInTempDir.TEST_ROOT = old_root
 
555
 
 
556
    def test_accepts_and_uses_pb_parameter(self):
 
557
        test = TestRunner('dummy_test')
 
558
        mypb = MockProgress()
 
559
        self.assertEqual([], mypb.calls)
 
560
        runner = TextTestRunner(stream=self._log_file, pb=mypb)
 
561
        result = self.run_test_runner(runner, test)
 
562
        self.assertEqual(1, result.testsRun)
 
563
        self.assertEqual(('update', 'Running tests', 0, 1), mypb.calls[0])
 
564
        self.assertEqual(('update', '...dummy_test', 0, None), mypb.calls[1])
 
565
        self.assertEqual(('update', 'OK           ', 1, None), mypb.calls[2])
 
566
        self.assertEqual(('update', 'Cleaning up', 0, 1), mypb.calls[3])
 
567
        self.assertEqual(('clear',), mypb.calls[4])
 
568
        self.assertEqual(5, len(mypb.calls))
 
569
 
 
570
    def test_skipped_test(self):
 
571
        # run a test that is skipped, and check the suite as a whole still
 
572
        # succeeds.
 
573
        # skipping_test must be hidden in here so it's not run as a real test
 
574
        def skipping_test():
 
575
            raise TestSkipped('test intentionally skipped')
 
576
        runner = TextTestRunner(stream=self._log_file, keep_output=True)
 
577
        test = unittest.FunctionTestCase(skipping_test)
 
578
        result = self.run_test_runner(runner, test)
 
579
        self.assertTrue(result.wasSuccessful())
 
580
 
 
581
 
 
582
class TestTestCase(TestCase):
 
583
    """Tests that test the core bzrlib TestCase."""
 
584
 
 
585
    def inner_test(self):
 
586
        # the inner child test
 
587
        note("inner_test")
 
588
 
 
589
    def outer_child(self):
 
590
        # the outer child test
 
591
        note("outer_start")
 
592
        self.inner_test = TestTestCase("inner_child")
 
593
        result = bzrlib.tests._MyResult(self._log_file,
 
594
                                        descriptions=0,
 
595
                                        verbosity=1)
 
596
        self.inner_test.run(result)
 
597
        note("outer finish")
 
598
 
 
599
    def test_trace_nesting(self):
 
600
        # this tests that each test case nests its trace facility correctly.
 
601
        # we do this by running a test case manually. That test case (A)
 
602
        # should setup a new log, log content to it, setup a child case (B),
 
603
        # which should log independently, then case (A) should log a trailer
 
604
        # and return.
 
605
        # we do two nested children so that we can verify the state of the 
 
606
        # logs after the outer child finishes is correct, which a bad clean
 
607
        # up routine in tearDown might trigger a fault in our test with only
 
608
        # one child, we should instead see the bad result inside our test with
 
609
        # the two children.
 
610
        # the outer child test
 
611
        original_trace = bzrlib.trace._trace_file
 
612
        outer_test = TestTestCase("outer_child")
 
613
        result = bzrlib.tests._MyResult(self._log_file,
 
614
                                        descriptions=0,
 
615
                                        verbosity=1)
 
616
        outer_test.run(result)
 
617
        self.assertEqual(original_trace, bzrlib.trace._trace_file)
 
618
 
 
619
    def method_that_times_a_bit_twice(self):
 
620
        # call self.time twice to ensure it aggregates
 
621
        self.time(time.sleep, 0.007)
 
622
        self.time(time.sleep, 0.007)
 
623
 
 
624
    def test_time_creates_benchmark_in_result(self):
 
625
        """Test that the TestCase.time() method accumulates a benchmark time."""
 
626
        sample_test = TestTestCase("method_that_times_a_bit_twice")
 
627
        output_stream = StringIO()
 
628
        result = bzrlib.tests._MyResult(
 
629
            unittest._WritelnDecorator(output_stream),
 
630
            descriptions=0,
 
631
            verbosity=2)
 
632
        sample_test.run(result)
 
633
        self.assertContainsRe(
 
634
            output_stream.getvalue(),
 
635
            "[1-9][0-9]ms/   [1-9][0-9]ms\n$")
 
636
        
 
637
    def test__gather_lsprof_in_benchmarks(self):
 
638
        """When _gather_lsprof_in_benchmarks is on, accumulate profile data.
 
639
        
 
640
        Each self.time() call is individually and separately profiled.
 
641
        """
 
642
        try:
 
643
            import bzrlib.lsprof
 
644
        except ImportError:
 
645
            raise TestSkipped("lsprof not installed.")
 
646
        # overrides the class member with an instance member so no cleanup 
 
647
        # needed.
 
648
        self._gather_lsprof_in_benchmarks = True
 
649
        self.time(time.sleep, 0.000)
 
650
        self.time(time.sleep, 0.003)
 
651
        self.assertEqual(2, len(self._benchcalls))
 
652
        self.assertEqual((time.sleep, (0.000,), {}), self._benchcalls[0][0])
 
653
        self.assertEqual((time.sleep, (0.003,), {}), self._benchcalls[1][0])
 
654
        self.assertIsInstance(self._benchcalls[0][1], bzrlib.lsprof.Stats)
 
655
        self.assertIsInstance(self._benchcalls[1][1], bzrlib.lsprof.Stats)
 
656
 
 
657
 
 
658
class TestExtraAssertions(TestCase):
 
659
    """Tests for new test assertions in bzrlib test suite"""
 
660
 
 
661
    def test_assert_isinstance(self):
 
662
        self.assertIsInstance(2, int)
 
663
        self.assertIsInstance(u'', basestring)
 
664
        self.assertRaises(AssertionError, self.assertIsInstance, None, int)
 
665
        self.assertRaises(AssertionError, self.assertIsInstance, 23.3, int)
 
666
 
 
667
    def test_assertEndsWith(self):
 
668
        self.assertEndsWith('foo', 'oo')
 
669
        self.assertRaises(AssertionError, self.assertEndsWith, 'o', 'oo')
 
670
 
 
671
 
 
672
class TestConvenienceMakers(TestCaseWithTransport):
 
673
    """Test for the make_* convenience functions."""
 
674
 
 
675
    def test_make_branch_and_tree_with_format(self):
 
676
        # we should be able to supply a format to make_branch_and_tree
 
677
        self.make_branch_and_tree('a', format=bzrlib.bzrdir.BzrDirMetaFormat1())
 
678
        self.make_branch_and_tree('b', format=bzrlib.bzrdir.BzrDirFormat6())
 
679
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('a')._format,
 
680
                              bzrlib.bzrdir.BzrDirMetaFormat1)
 
681
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('b')._format,
 
682
                              bzrlib.bzrdir.BzrDirFormat6)
 
683
 
 
684
 
 
685
class TestSelftest(TestCase):
 
686
    """Tests of bzrlib.tests.selftest."""
 
687
 
 
688
    def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
 
689
        factory_called = []
 
690
        def factory():
 
691
            factory_called.append(True)
 
692
            return TestSuite()
 
693
        out = StringIO()
 
694
        err = StringIO()
 
695
        self.apply_redirected(out, err, None, bzrlib.tests.selftest, 
 
696
            test_suite_factory=factory)
 
697
        self.assertEqual([True], factory_called)
 
698
 
 
699
    def test_run_bzr_subprocess(self):
 
700
        """The run_bzr_helper_external comand behaves nicely."""
 
701
        result = self.run_bzr_subprocess('--version')
 
702
        result = self.run_bzr_subprocess('--version', retcode=None)
 
703
        self.assertContainsRe(result[0], 'is free software')
 
704
        self.assertRaises(AssertionError, self.run_bzr_subprocess, 
 
705
                          '--versionn')
 
706
        result = self.run_bzr_subprocess('--versionn', retcode=3)
 
707
        result = self.run_bzr_subprocess('--versionn', retcode=None)
 
708
        self.assertContainsRe(result[1], 'unknown command')
 
709
        err = self.run_bzr_subprocess('merge', '--merge-type', 'magic merge', 
 
710
                                      retcode=3)[1]
 
711
        self.assertContainsRe(err, 'No known merge type magic merge')
 
712
 
 
713
    def test_run_bzr_error(self):
 
714
        out, err = self.run_bzr_error(['^$'], 'rocks', retcode=0)
 
715
        self.assertEqual(out, 'it sure does!\n')
 
716
 
 
717
        out, err = self.run_bzr_error(["'foobarbaz' is not a versioned file"],
 
718
                                      'file-id', 'foobarbaz')