~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_selftest.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2006-09-17 21:19:56 UTC
  • mfrom: (1997.1.6 bind-does-not-push-or-pull)
  • Revision ID: pqm@pqm.ubuntu.com-20060917211956-6e30d07da410fd1a
(Robert Collins) Change the Branch bind method to just bind rather than binding and pushing (fixes #43744 and #39542)

Show diffs side-by-side

added added

removed removed

Lines of Context:
22
22
import unittest
23
23
import warnings
24
24
 
 
25
from bzrlib import osutils
25
26
import bzrlib
26
27
from bzrlib.progress import _BaseProgressBar
27
28
from bzrlib.tests import (
33
34
                          TestSuite,
34
35
                          TextTestRunner,
35
36
                          )
 
37
from bzrlib.tests.test_sftp_transport import TestCaseWithSFTPServer
36
38
from bzrlib.tests.TestUtil import _load_module_by_name
37
39
import bzrlib.errors as errors
 
40
from bzrlib import symbol_versioning
 
41
from bzrlib.symbol_versioning import zero_ten, zero_eleven
 
42
from bzrlib.trace import note
 
43
from bzrlib.transport.memory import MemoryServer, MemoryTransport
 
44
from bzrlib.version import _get_bzr_source_tree
38
45
 
39
46
 
40
47
class SelftestTests(TestCase):
322
329
        self.assertEqual(tests[1].transport_readonly_server, server2)
323
330
 
324
331
 
 
332
class TestTreeProviderAdapter(TestCase):
 
333
    """Test the setup of tree_implementation tests."""
 
334
 
 
335
    def test_adapted_tests(self):
 
336
        # the tree implementation adapter is meant to setup one instance for
 
337
        # each working tree format, and one additional instance that will
 
338
        # use the default wt format, but create a revision tree for the tests.
 
339
        # this means that the wt ones should have the workingtree_to_test_tree
 
340
        # attribute set to 'return_parameter' and the revision one set to
 
341
        # revision_tree_from_workingtree.
 
342
 
 
343
        from bzrlib.tests.tree_implementations import (
 
344
            TreeTestProviderAdapter,
 
345
            return_parameter,
 
346
            revision_tree_from_workingtree
 
347
            )
 
348
        from bzrlib.workingtree import WorkingTreeFormat
 
349
        input_test = TestTreeProviderAdapter(
 
350
            "test_adapted_tests")
 
351
        server1 = "a"
 
352
        server2 = "b"
 
353
        formats = [("c", "C"), ("d", "D")]
 
354
        adapter = TreeTestProviderAdapter(server1, server2, formats)
 
355
        suite = adapter.adapt(input_test)
 
356
        tests = list(iter(suite))
 
357
        self.assertEqual(3, len(tests))
 
358
        default_format = WorkingTreeFormat.get_default_format()
 
359
        self.assertEqual(tests[0].workingtree_format, formats[0][0])
 
360
        self.assertEqual(tests[0].bzrdir_format, formats[0][1])
 
361
        self.assertEqual(tests[0].transport_server, server1)
 
362
        self.assertEqual(tests[0].transport_readonly_server, server2)
 
363
        self.assertEqual(tests[0].workingtree_to_test_tree, return_parameter)
 
364
        self.assertEqual(tests[1].workingtree_format, formats[1][0])
 
365
        self.assertEqual(tests[1].bzrdir_format, formats[1][1])
 
366
        self.assertEqual(tests[1].transport_server, server1)
 
367
        self.assertEqual(tests[1].transport_readonly_server, server2)
 
368
        self.assertEqual(tests[1].workingtree_to_test_tree, return_parameter)
 
369
        self.assertEqual(tests[2].workingtree_format, default_format)
 
370
        self.assertEqual(tests[2].bzrdir_format, default_format._matchingbzrdir)
 
371
        self.assertEqual(tests[2].transport_server, server1)
 
372
        self.assertEqual(tests[2].transport_readonly_server, server2)
 
373
        self.assertEqual(tests[2].workingtree_to_test_tree,
 
374
            revision_tree_from_workingtree)
 
375
 
 
376
 
 
377
class TestInterTreeProviderAdapter(TestCase):
 
378
    """A group of tests that test the InterTreeTestAdapter."""
 
379
 
 
380
    def test_adapted_tests(self):
 
381
        # check that constructor parameters are passed through to the adapted
 
382
        # test.
 
383
        # for InterTree tests we want the machinery to bring up two trees in
 
384
        # each instance: the base one, and the one we are interacting with.
 
385
        # because each optimiser can be direction specific, we need to test
 
386
        # each optimiser in its chosen direction.
 
387
        # unlike the TestProviderAdapter we dont want to automatically add a
 
388
        # parameterised one for WorkingTree - the optimisers will tell us what
 
389
        # ones to add.
 
390
        from bzrlib.tests.tree_implementations import (
 
391
            return_parameter,
 
392
            revision_tree_from_workingtree
 
393
            )
 
394
        from bzrlib.tests.intertree_implementations import (
 
395
            InterTreeTestProviderAdapter,
 
396
            )
 
397
        from bzrlib.workingtree import WorkingTreeFormat2, WorkingTreeFormat3
 
398
        input_test = TestInterTreeProviderAdapter(
 
399
            "test_adapted_tests")
 
400
        server1 = "a"
 
401
        server2 = "b"
 
402
        format1 = WorkingTreeFormat2()
 
403
        format2 = WorkingTreeFormat3()
 
404
        formats = [(str, format1, format2, False, True),
 
405
            (int, format2, format1, False, True)]
 
406
        adapter = InterTreeTestProviderAdapter(server1, server2, formats)
 
407
        suite = adapter.adapt(input_test)
 
408
        tests = list(iter(suite))
 
409
        self.assertEqual(2, len(tests))
 
410
        self.assertEqual(tests[0].intertree_class, formats[0][0])
 
411
        self.assertEqual(tests[0].workingtree_format, formats[0][1])
 
412
        self.assertEqual(tests[0].workingtree_to_test_tree, formats[0][2])
 
413
        self.assertEqual(tests[0].workingtree_format_to, formats[0][3])
 
414
        self.assertEqual(tests[0].workingtree_to_test_tree_to, formats[0][4])
 
415
        self.assertEqual(tests[0].transport_server, server1)
 
416
        self.assertEqual(tests[0].transport_readonly_server, server2)
 
417
        self.assertEqual(tests[1].intertree_class, formats[1][0])
 
418
        self.assertEqual(tests[1].workingtree_format, formats[1][1])
 
419
        self.assertEqual(tests[1].workingtree_to_test_tree, formats[1][2])
 
420
        self.assertEqual(tests[1].workingtree_format_to, formats[1][3])
 
421
        self.assertEqual(tests[1].workingtree_to_test_tree_to, formats[1][4])
 
422
        self.assertEqual(tests[1].transport_server, server1)
 
423
        self.assertEqual(tests[1].transport_readonly_server, server2)
 
424
 
 
425
 
 
426
class TestTestCaseInTempDir(TestCaseInTempDir):
 
427
 
 
428
    def test_home_is_not_working(self):
 
429
        self.assertNotEqual(self.test_dir, self.test_home_dir)
 
430
        cwd = osutils.getcwd()
 
431
        self.assertEqual(self.test_dir, cwd)
 
432
        self.assertEqual(self.test_home_dir, os.environ['HOME'])
 
433
 
 
434
 
325
435
class TestTestCaseWithTransport(TestCaseWithTransport):
326
436
    """Tests for the convenience functions TestCaseWithTransport introduces."""
327
437
 
366
476
        self.assertRaises(AssertionError, self.assertIsDirectory, 'not_here', t)
367
477
 
368
478
 
 
479
class TestTestCaseTransports(TestCaseWithTransport):
 
480
 
 
481
    def setUp(self):
 
482
        super(TestTestCaseTransports, self).setUp()
 
483
        self.transport_server = MemoryServer
 
484
 
 
485
    def test_make_bzrdir_preserves_transport(self):
 
486
        t = self.get_transport()
 
487
        result_bzrdir = self.make_bzrdir('subdir')
 
488
        self.assertIsInstance(result_bzrdir.transport, 
 
489
                              MemoryTransport)
 
490
        # should not be on disk, should only be in memory
 
491
        self.failIfExists('subdir')
 
492
 
 
493
 
369
494
class TestChrootedTest(ChrootedTestCase):
370
495
 
371
496
    def test_root_is_root(self):
394
519
    def clear(self):
395
520
        self.calls.append(('clear',))
396
521
 
 
522
    def note(self, msg, *args):
 
523
        self.calls.append(('note', msg, args))
 
524
 
397
525
 
398
526
class TestTestResult(TestCase):
399
527
 
404
532
        mypb = MockProgress()
405
533
        mypb.update('Running tests', 0, 4)
406
534
        last_calls = mypb.calls[:]
 
535
 
407
536
        result = bzrlib.tests._MyResult(self._log_file,
408
537
                                        descriptions=0,
409
538
                                        verbosity=1,
410
539
                                        pb=mypb)
411
540
        self.assertEqual(last_calls, mypb.calls)
412
541
 
 
542
        def shorten(s):
 
543
            """Shorten a string based on the terminal width"""
 
544
            return result._ellipsise_unimportant_words(s,
 
545
                                 osutils.terminal_width())
 
546
 
413
547
        # an error 
414
548
        result.startTest(dummy_test)
415
549
        # starting a test prints the test name
416
 
        self.assertEqual(last_calls + [('update', '...tyle_quiet', 0, None)], mypb.calls)
417
 
        last_calls = mypb.calls[:]
 
550
        last_calls += [('update', '...tyle_quiet', 0, None)]
 
551
        self.assertEqual(last_calls, mypb.calls)
418
552
        result.addError(dummy_test, dummy_error)
419
 
        self.assertEqual(last_calls + [('update', 'ERROR        ', 1, None)], mypb.calls)
420
 
        last_calls = mypb.calls[:]
 
553
        last_calls += [('update', 'ERROR        ', 1, None),
 
554
                       ('note', shorten(dummy_test.id() + ': ERROR'), ())
 
555
                      ]
 
556
        self.assertEqual(last_calls, mypb.calls)
421
557
 
422
558
        # a failure
423
559
        result.startTest(dummy_test)
424
 
        self.assertEqual(last_calls + [('update', '...tyle_quiet', 1, None)], mypb.calls)
425
 
        last_calls = mypb.calls[:]
 
560
        last_calls += [('update', '...tyle_quiet', 1, None)]
 
561
        self.assertEqual(last_calls, mypb.calls)
 
562
        last_calls += [('update', 'FAIL         ', 2, None),
 
563
                       ('note', shorten(dummy_test.id() + ': FAIL'), ())
 
564
                      ]
426
565
        result.addFailure(dummy_test, dummy_error)
427
 
        self.assertEqual(last_calls + [('update', 'FAIL         ', 2, None)], mypb.calls)
428
 
        last_calls = mypb.calls[:]
 
566
        self.assertEqual(last_calls, mypb.calls)
429
567
 
430
568
        # a success
431
569
        result.startTest(dummy_test)
432
 
        self.assertEqual(last_calls + [('update', '...tyle_quiet', 2, None)], mypb.calls)
433
 
        last_calls = mypb.calls[:]
 
570
        last_calls += [('update', '...tyle_quiet', 2, None)]
 
571
        self.assertEqual(last_calls, mypb.calls)
434
572
        result.addSuccess(dummy_test)
435
 
        self.assertEqual(last_calls + [('update', 'OK           ', 3, None)], mypb.calls)
436
 
        last_calls = mypb.calls[:]
 
573
        last_calls += [('update', 'OK           ', 3, None)]
 
574
        self.assertEqual(last_calls, mypb.calls)
437
575
 
438
576
        # a skip
439
577
        result.startTest(dummy_test)
440
 
        self.assertEqual(last_calls + [('update', '...tyle_quiet', 3, None)], mypb.calls)
441
 
        last_calls = mypb.calls[:]
 
578
        last_calls += [('update', '...tyle_quiet', 3, None)]
 
579
        self.assertEqual(last_calls, mypb.calls)
442
580
        result.addSkipped(dummy_test, dummy_error)
443
 
        self.assertEqual(last_calls + [('update', 'SKIP         ', 4, None)], mypb.calls)
444
 
        last_calls = mypb.calls[:]
 
581
        last_calls += [('update', 'SKIP         ', 4, None)]
 
582
        self.assertEqual(last_calls, mypb.calls)
445
583
 
446
584
    def test_elapsed_time_with_benchmarking(self):
447
585
        result = bzrlib.tests._MyResult(self._log_file,
468
606
        # cheat. Yes, wash thy mouth out with soap.
469
607
        self._benchtime = None
470
608
 
 
609
    def test_assigned_benchmark_file_stores_date(self):
 
610
        output = StringIO()
 
611
        result = bzrlib.tests._MyResult(self._log_file,
 
612
                                        descriptions=0,
 
613
                                        verbosity=1,
 
614
                                        bench_history=output
 
615
                                        )
 
616
        output_string = output.getvalue()
 
617
        # if you are wondering about the regexp please read the comment in
 
618
        # test_bench_history (bzrlib.tests.test_selftest.TestRunner)
 
619
        # XXX: what comment?  -- Andrew Bennetts
 
620
        self.assertContainsRe(output_string, "--date [0-9.]+")
 
621
 
 
622
    def test_benchhistory_records_test_times(self):
 
623
        result_stream = StringIO()
 
624
        result = bzrlib.tests._MyResult(
 
625
            self._log_file,
 
626
            descriptions=0,
 
627
            verbosity=1,
 
628
            bench_history=result_stream
 
629
            )
 
630
 
 
631
        # we want profile a call and check that its test duration is recorded
 
632
        # make a new test instance that when run will generate a benchmark
 
633
        example_test_case = TestTestResult("_time_hello_world_encoding")
 
634
        # execute the test, which should succeed and record times
 
635
        example_test_case.run(result)
 
636
        lines = result_stream.getvalue().splitlines()
 
637
        self.assertEqual(2, len(lines))
 
638
        self.assertContainsRe(lines[1],
 
639
            " *[0-9]+ms bzrlib.tests.test_selftest.TestTestResult"
 
640
            "._time_hello_world_encoding")
 
641
 
471
642
    def _time_hello_world_encoding(self):
472
643
        """Profile two sleep calls
473
644
        
506
677
        #           1        0            ???         ???       ???(sleep) 
507
678
        # and then repeated but with 'world', rather than 'hello'.
508
679
        # this should appear in the output stream of our test result.
509
 
        self.assertContainsRe(result_stream.getvalue(), 
510
 
            r"LSProf output for <type 'unicode'>\(\('hello',\), {'errors': 'replace'}\)\n"
511
 
            r" *CallCount *Recursive *Total\(ms\) *Inline\(ms\) *module:lineno\(function\)\n"
512
 
            r"( +1 +0 +0\.\d+ +0\.\d+ +<method 'disable' of '_lsprof\.Profiler' objects>\n)?"
513
 
            r"LSProf output for <type 'unicode'>\(\('world',\), {'errors': 'replace'}\)\n"
514
 
            r" *CallCount *Recursive *Total\(ms\) *Inline\(ms\) *module:lineno\(function\)\n"
515
 
            r"( +1 +0 +0\.\d+ +0\.\d+ +<method 'disable' of '_lsprof\.Profiler' objects>\n)?"
516
 
            )
 
680
        output = result_stream.getvalue()
 
681
        self.assertContainsRe(output,
 
682
            r"LSProf output for <type 'unicode'>\(\('hello',\), {'errors': 'replace'}\)")
 
683
        self.assertContainsRe(output,
 
684
            r" *CallCount *Recursive *Total\(ms\) *Inline\(ms\) *module:lineno\(function\)\n")
 
685
        self.assertContainsRe(output,
 
686
            r"( +1 +0 +0\.\d+ +0\.\d+ +<method 'disable' of '_lsprof\.Profiler' objects>\n)?")
 
687
        self.assertContainsRe(output,
 
688
            r"LSProf output for <type 'unicode'>\(\('world',\), {'errors': 'replace'}\)\n")
517
689
 
518
690
 
519
691
class TestRunner(TestCase):
562
734
        result = self.run_test_runner(runner, test)
563
735
        self.assertTrue(result.wasSuccessful())
564
736
 
 
737
    def test_bench_history(self):
 
738
        # tests that the running the benchmark produces a history file
 
739
        # containing a timestamp and the revision id of the bzrlib source which
 
740
        # was tested.
 
741
        workingtree = _get_bzr_source_tree()
 
742
        test = TestRunner('dummy_test')
 
743
        output = StringIO()
 
744
        runner = TextTestRunner(stream=self._log_file, bench_history=output)
 
745
        result = self.run_test_runner(runner, test)
 
746
        output_string = output.getvalue()
 
747
        self.assertContainsRe(output_string, "--date [0-9.]+")
 
748
        if workingtree is not None:
 
749
            revision_id = workingtree.get_parent_ids()[0]
 
750
            self.assertEndsWith(output_string.rstrip(), revision_id)
 
751
 
565
752
 
566
753
class TestTestCase(TestCase):
567
754
    """Tests that test the core bzrlib TestCase."""
639
826
        self.assertIsInstance(self._benchcalls[1][1], bzrlib.lsprof.Stats)
640
827
 
641
828
 
 
829
@symbol_versioning.deprecated_function(zero_eleven)
 
830
def sample_deprecated_function():
 
831
    """A deprecated function to test applyDeprecated with."""
 
832
    return 2
 
833
 
 
834
 
 
835
def sample_undeprecated_function(a_param):
 
836
    """A undeprecated function to test applyDeprecated with."""
 
837
 
 
838
 
 
839
class ApplyDeprecatedHelper(object):
 
840
    """A helper class for ApplyDeprecated tests."""
 
841
 
 
842
    @symbol_versioning.deprecated_method(zero_eleven)
 
843
    def sample_deprecated_method(self, param_one):
 
844
        """A deprecated method for testing with."""
 
845
        return param_one
 
846
 
 
847
    def sample_normal_method(self):
 
848
        """A undeprecated method."""
 
849
 
 
850
    @symbol_versioning.deprecated_method(zero_ten)
 
851
    def sample_nested_deprecation(self):
 
852
        return sample_deprecated_function()
 
853
 
 
854
 
642
855
class TestExtraAssertions(TestCase):
643
856
    """Tests for new test assertions in bzrlib test suite"""
644
857
 
652
865
        self.assertEndsWith('foo', 'oo')
653
866
        self.assertRaises(AssertionError, self.assertEndsWith, 'o', 'oo')
654
867
 
 
868
    def test_applyDeprecated_not_deprecated(self):
 
869
        sample_object = ApplyDeprecatedHelper()
 
870
        # calling an undeprecated callable raises an assertion
 
871
        self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
 
872
            sample_object.sample_normal_method)
 
873
        self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
 
874
            sample_undeprecated_function, "a param value")
 
875
        # calling a deprecated callable (function or method) with the wrong
 
876
        # expected deprecation fails.
 
877
        self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
 
878
            sample_object.sample_deprecated_method, "a param value")
 
879
        self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
 
880
            sample_deprecated_function)
 
881
        # calling a deprecated callable (function or method) with the right
 
882
        # expected deprecation returns the functions result.
 
883
        self.assertEqual("a param value", self.applyDeprecated(zero_eleven,
 
884
            sample_object.sample_deprecated_method, "a param value"))
 
885
        self.assertEqual(2, self.applyDeprecated(zero_eleven,
 
886
            sample_deprecated_function))
 
887
        # calling a nested deprecation with the wrong deprecation version
 
888
        # fails even if a deeper nested function was deprecated with the 
 
889
        # supplied version.
 
890
        self.assertRaises(AssertionError, self.applyDeprecated,
 
891
            zero_eleven, sample_object.sample_nested_deprecation)
 
892
        # calling a nested deprecation with the right deprecation value
 
893
        # returns the calls result.
 
894
        self.assertEqual(2, self.applyDeprecated(zero_ten,
 
895
            sample_object.sample_nested_deprecation))
 
896
 
 
897
    def test_callDeprecated(self):
 
898
        def testfunc(be_deprecated, result=None):
 
899
            if be_deprecated is True:
 
900
                symbol_versioning.warn('i am deprecated', DeprecationWarning, 
 
901
                                       stacklevel=1)
 
902
            return result
 
903
        result = self.callDeprecated(['i am deprecated'], testfunc, True)
 
904
        self.assertIs(None, result)
 
905
        result = self.callDeprecated([], testfunc, False, 'result')
 
906
        self.assertEqual('result', result)
 
907
        self.callDeprecated(['i am deprecated'], testfunc, be_deprecated=True)
 
908
        self.callDeprecated([], testfunc, be_deprecated=False)
 
909
 
655
910
 
656
911
class TestConvenienceMakers(TestCaseWithTransport):
657
912
    """Test for the make_* convenience functions."""
665
920
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('b')._format,
666
921
                              bzrlib.bzrdir.BzrDirFormat6)
667
922
 
 
923
    def test_make_branch_and_mutable_tree(self):
 
924
        # we should be able to get a new branch and a mutable tree from
 
925
        # TestCaseWithTransport
 
926
        tree = self.make_branch_and_memory_tree('a')
 
927
        self.assertIsInstance(tree, bzrlib.memorytree.MemoryTree)
 
928
 
 
929
 
 
930
class TestSFTPMakeBranchAndTree(TestCaseWithSFTPServer):
 
931
 
 
932
    def test_make_tree_for_sftp_branch(self):
 
933
        """Transports backed by local directories create local trees."""
 
934
 
 
935
        tree = self.make_branch_and_tree('t1')
 
936
        base = tree.bzrdir.root_transport.base
 
937
        self.failIf(base.startswith('sftp'),
 
938
                'base %r is on sftp but should be local' % base)
 
939
        self.assertEquals(tree.bzrdir.root_transport,
 
940
                tree.branch.bzrdir.root_transport)
 
941
        self.assertEquals(tree.bzrdir.root_transport,
 
942
                tree.branch.repository.bzrdir.root_transport)
 
943
 
668
944
 
669
945
class TestSelftest(TestCase):
670
946
    """Tests of bzrlib.tests.selftest."""
679
955
        self.apply_redirected(out, err, None, bzrlib.tests.selftest, 
680
956
            test_suite_factory=factory)
681
957
        self.assertEqual([True], factory_called)
682
 
 
683
 
    def test_run_bzr_subprocess(self):
684
 
        """The run_bzr_helper_external comand behaves nicely."""
685
 
        result = self.run_bzr_subprocess('--version')
686
 
        result = self.run_bzr_subprocess('--version', retcode=None)
687
 
        self.assertContainsRe(result[0], 'is free software')
688
 
        self.assertRaises(AssertionError, self.run_bzr_subprocess, 
689
 
                          '--versionn')
690
 
        result = self.run_bzr_subprocess('--versionn', retcode=3)
691
 
        result = self.run_bzr_subprocess('--versionn', retcode=None)
692
 
        self.assertContainsRe(result[1], 'unknown command')
693
 
        err = self.run_bzr_subprocess('merge', '--merge-type', 'magic merge', 
694
 
                                      retcode=3)[1]
695
 
        self.assertContainsRe(err, 'No known merge type magic merge')