~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_versionedfile.py

  • Committer: Andrew Bennetts
  • Date: 2009-03-04 07:10:07 UTC
  • mto: (4086.1.2 hpss-integration)
  • mto: This revision was merged to the branch mainline in revision 4087.
  • Revision ID: andrew.bennetts@canonical.com-20090304071007-8iqoi1m44ypmzg2a
Rough prototype of allowing a SearchResult to be passed to fetch, and using that to improve network conversations.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2010 Canonical Ltd
 
1
# Copyright (C) 2005 Canonical Ltd
2
2
#
3
3
# Authors:
4
4
#   Johan Rydberg <jrydberg@gnu.org>
15
15
#
16
16
# You should have received a copy of the GNU General Public License
17
17
# along with this program; if not, write to the Free Software
18
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
18
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
19
 
20
20
 
21
21
# TODO: might be nice to create a versionedfile with some type of corruption
24
24
from itertools import chain, izip
25
25
from StringIO import StringIO
26
26
 
 
27
import bzrlib
27
28
from bzrlib import (
28
29
    errors,
29
 
    graph as _mod_graph,
30
 
    groupcompress,
31
 
    knit as _mod_knit,
32
30
    osutils,
33
31
    progress,
34
 
    transport,
35
 
    ui,
36
32
    )
37
33
from bzrlib.errors import (
38
34
                           RevisionNotPresent,
39
35
                           RevisionAlreadyPresent,
40
36
                           WeaveParentMismatch
41
37
                           )
 
38
from bzrlib import knit as _mod_knit
42
39
from bzrlib.knit import (
43
40
    cleanup_pack_knit,
44
41
    make_file_factory,
46
43
    KnitAnnotateFactory,
47
44
    KnitPlainFactory,
48
45
    )
 
46
from bzrlib.symbol_versioning import one_four, one_five
49
47
from bzrlib.tests import (
50
48
    TestCase,
51
49
    TestCaseWithMemoryTransport,
52
50
    TestNotApplicable,
 
51
    TestScenarioApplier,
53
52
    TestSkipped,
54
53
    condition_isinstance,
55
54
    split_suite_by_condition,
56
 
    multiply_tests,
 
55
    iter_suite_tests,
57
56
    )
58
57
from bzrlib.tests.http_utils import TestCaseWithWebserver
59
58
from bzrlib.trace import mutter
 
59
from bzrlib.transport import get_transport
60
60
from bzrlib.transport.memory import MemoryTransport
61
61
from bzrlib.tsort import topo_sort
62
62
from bzrlib.tuned_gzip import GzipFile
76
76
    """Parameterize VersionedFiles tests for different implementations."""
77
77
    to_adapt, result = split_suite_by_condition(
78
78
        standard_tests, condition_isinstance(TestVersionedFiles))
 
79
    len_one_adapter = TestScenarioApplier()
 
80
    len_two_adapter = TestScenarioApplier()
79
81
    # We want to be sure of behaviour for:
80
82
    # weaves prefix layout (weave texts)
81
83
    # individually named weaves (weave inventories)
86
88
    # individual graph knits in packs (inventories)
87
89
    # individual graph nocompression knits in packs (revisions)
88
90
    # plain text knits in packs (texts)
89
 
    len_one_scenarios = [
 
91
    len_one_adapter.scenarios = [
90
92
        ('weave-named', {
91
93
            'cleanup':None,
92
94
            'factory':make_versioned_files_factory(WeaveFile,
123
125
            'key_length':1,
124
126
            'support_partial_insertion': False,
125
127
            }),
126
 
        ('groupcompress-nograph', {
127
 
            'cleanup':groupcompress.cleanup_pack_group,
128
 
            'factory':groupcompress.make_pack_factory(False, False, 1),
129
 
            'graph': False,
130
 
            'key_length':1,
131
 
            'support_partial_insertion':False,
132
 
            }),
133
128
        ]
134
 
    len_two_scenarios = [
 
129
    len_two_adapter.scenarios = [
135
130
        ('weave-prefix', {
136
131
            'cleanup':None,
137
132
            'factory':make_versioned_files_factory(WeaveFile,
154
149
            'key_length':2,
155
150
            'support_partial_insertion': True,
156
151
            }),
157
 
        ('groupcompress', {
158
 
            'cleanup':groupcompress.cleanup_pack_group,
159
 
            'factory':groupcompress.make_pack_factory(True, False, 1),
160
 
            'graph': True,
161
 
            'key_length':1,
162
 
            'support_partial_insertion':False,
163
 
            }),
164
152
        ]
165
 
    scenarios = len_one_scenarios + len_two_scenarios
166
 
    return multiply_tests(to_adapt, scenarios, result)
 
153
    for test in iter_suite_tests(to_adapt):
 
154
        result.addTests(len_one_adapter.adapt(test))
 
155
        result.addTests(len_two_adapter.adapt(test))
 
156
    return result
167
157
 
168
158
 
169
159
def get_diamond_vf(f, trailing_eol=True, left_only=False):
195
185
 
196
186
 
197
187
def get_diamond_files(files, key_length, trailing_eol=True, left_only=False,
198
 
    nograph=False, nokeys=False):
 
188
    nograph=False):
199
189
    """Get a diamond graph to exercise deltas and merges.
200
190
 
201
191
    This creates a 5-node graph in files. If files supports 2-length keys two
208
198
    :param nograph: If True, do not provide parents to the add_lines calls;
209
199
        this is useful for tests that need inserted data but have graphless
210
200
        stores.
211
 
    :param nokeys: If True, pass None is as the key for all insertions.
212
 
        Currently implies nograph.
213
201
    :return: The results of the add_lines calls.
214
202
    """
215
 
    if nokeys:
216
 
        nograph = True
217
203
    if key_length == 1:
218
204
        prefixes = [()]
219
205
    else:
230
216
        else:
231
217
            result = [prefix + suffix for suffix in suffix_list]
232
218
            return result
233
 
    def get_key(suffix):
234
 
        if nokeys:
235
 
            return (None, )
236
 
        else:
237
 
            return (suffix,)
238
219
    # we loop over each key because that spreads the inserts across prefixes,
239
220
    # which is how commit operates.
240
221
    for prefix in prefixes:
241
 
        result.append(files.add_lines(prefix + get_key('origin'), (),
 
222
        result.append(files.add_lines(prefix + ('origin',), (),
242
223
            ['origin' + last_char]))
243
224
    for prefix in prefixes:
244
 
        result.append(files.add_lines(prefix + get_key('base'),
 
225
        result.append(files.add_lines(prefix + ('base',),
245
226
            get_parents([('origin',)]), ['base' + last_char]))
246
227
    for prefix in prefixes:
247
 
        result.append(files.add_lines(prefix + get_key('left'),
 
228
        result.append(files.add_lines(prefix + ('left',),
248
229
            get_parents([('base',)]),
249
230
            ['base\n', 'left' + last_char]))
250
231
    if not left_only:
251
232
        for prefix in prefixes:
252
 
            result.append(files.add_lines(prefix + get_key('right'),
 
233
            result.append(files.add_lines(prefix + ('right',),
253
234
                get_parents([('base',)]),
254
235
                ['base\n', 'right' + last_char]))
255
236
        for prefix in prefixes:
256
 
            result.append(files.add_lines(prefix + get_key('merged'),
 
237
            result.append(files.add_lines(prefix + ('merged',),
257
238
                get_parents([('left',), ('right',)]),
258
239
                ['base\n', 'left\n', 'right\n', 'merged' + last_char]))
259
240
    return result
734
715
        # the ordering here is to make a tree so that dumb searches have
735
716
        # more changes to muck up.
736
717
 
737
 
        class InstrumentedProgress(progress.ProgressTask):
 
718
        class InstrumentedProgress(progress.DummyProgress):
738
719
 
739
720
            def __init__(self):
740
 
                progress.ProgressTask.__init__(self)
 
721
 
 
722
                progress.DummyProgress.__init__(self)
741
723
                self.updates = []
742
724
 
743
725
            def update(self, msg=None, current=None, total=None):
769
751
                self.assertEqual(expected, progress.updates)
770
752
            return lines
771
753
        lines = iter_with_versions(['child', 'otherchild'],
772
 
                                   [('Walking content', 0, 2),
773
 
                                    ('Walking content', 1, 2),
774
 
                                    ('Walking content', 2, 2)])
 
754
                                   [('Walking content.', 0, 2),
 
755
                                    ('Walking content.', 1, 2),
 
756
                                    ('Walking content.', 2, 2)])
775
757
        # we must see child and otherchild
776
758
        self.assertTrue(lines[('child\n', 'child')] > 0)
777
759
        self.assertTrue(lines[('otherchild\n', 'otherchild')] > 0)
778
760
        # we dont care if we got more than that.
779
761
 
780
762
        # test all lines
781
 
        lines = iter_with_versions(None, [('Walking content', 0, 5),
782
 
                                          ('Walking content', 1, 5),
783
 
                                          ('Walking content', 2, 5),
784
 
                                          ('Walking content', 3, 5),
785
 
                                          ('Walking content', 4, 5),
786
 
                                          ('Walking content', 5, 5)])
 
763
        lines = iter_with_versions(None, [('Walking content.', 0, 5),
 
764
                                          ('Walking content.', 1, 5),
 
765
                                          ('Walking content.', 2, 5),
 
766
                                          ('Walking content.', 3, 5),
 
767
                                          ('Walking content.', 4, 5),
 
768
                                          ('Walking content.', 5, 5)])
787
769
        # all lines must be seen at least once
788
770
        self.assertTrue(lines[('base\n', 'base')] > 0)
789
771
        self.assertTrue(lines[('lancestor\n', 'lancestor')] > 0)
849
831
        self.assertEquals(('references_ghost', 'line_c\n'), origins[2])
850
832
 
851
833
    def test_readonly_mode(self):
852
 
        t = transport.get_transport(self.get_url('.'))
 
834
        transport = get_transport(self.get_url('.'))
853
835
        factory = self.get_factory()
854
 
        vf = factory('id', t, 0777, create=True, access_mode='w')
855
 
        vf = factory('id', t, access_mode='r')
 
836
        vf = factory('id', transport, 0777, create=True, access_mode='w')
 
837
        vf = factory('id', transport, access_mode='r')
856
838
        self.assertRaises(errors.ReadOnlyError, vf.add_lines, 'base', [], [])
857
839
        self.assertRaises(errors.ReadOnlyError,
858
840
                          vf.add_lines_with_ghosts,
880
862
class TestWeave(TestCaseWithMemoryTransport, VersionedFileTestMixIn):
881
863
 
882
864
    def get_file(self, name='foo'):
883
 
        return WeaveFile(name, transport.get_transport(self.get_url('.')),
884
 
                         create=True,
885
 
                         get_scope=self.get_transaction)
 
865
        return WeaveFile(name, get_transport(self.get_url('.')), create=True,
 
866
            get_scope=self.get_transaction)
886
867
 
887
868
    def get_file_corrupted_text(self):
888
 
        w = WeaveFile('foo', transport.get_transport(self.get_url('.')),
889
 
                      create=True,
890
 
                      get_scope=self.get_transaction)
 
869
        w = WeaveFile('foo', get_transport(self.get_url('.')), create=True,
 
870
            get_scope=self.get_transaction)
891
871
        w.add_lines('v1', [], ['hello\n'])
892
872
        w.add_lines('v2', ['v1'], ['hello\n', 'there\n'])
893
873
 
921
901
        return w
922
902
 
923
903
    def reopen_file(self, name='foo', create=False):
924
 
        return WeaveFile(name, transport.get_transport(self.get_url('.')),
925
 
                         create=create,
926
 
                         get_scope=self.get_transaction)
 
904
        return WeaveFile(name, get_transport(self.get_url('.')), create=create,
 
905
            get_scope=self.get_transaction)
927
906
 
928
907
    def test_no_implicit_create(self):
929
908
        self.assertRaises(errors.NoSuchFile,
930
909
                          WeaveFile,
931
910
                          'foo',
932
 
                          transport.get_transport(self.get_url('.')),
 
911
                          get_transport(self.get_url('.')),
933
912
                          get_scope=self.get_transaction)
934
913
 
935
914
    def get_factory(self):
1002
981
        # we should be able to read from http with a versioned file.
1003
982
        vf = self.get_file()
1004
983
        # try an empty file access
1005
 
        readonly_vf = self.get_factory()('foo', transport.get_transport(
1006
 
                self.get_readonly_url('.')))
 
984
        readonly_vf = self.get_factory()('foo', get_transport(self.get_readonly_url('.')))
1007
985
        self.assertEqual([], readonly_vf.versions())
1008
 
 
1009
 
    def test_readonly_http_works_with_feeling(self):
1010
 
        # we should be able to read from http with a versioned file.
1011
 
        vf = self.get_file()
1012
986
        # now with feeling.
1013
987
        vf.add_lines('1', [], ['a\n'])
1014
988
        vf.add_lines('2', ['1'], ['b\n', 'a\n'])
1015
 
        readonly_vf = self.get_factory()('foo', transport.get_transport(
1016
 
                self.get_readonly_url('.')))
 
989
        readonly_vf = self.get_factory()('foo', get_transport(self.get_readonly_url('.')))
1017
990
        self.assertEqual(['1', '2'], vf.versions())
1018
 
        self.assertEqual(['1', '2'], readonly_vf.versions())
1019
991
        for version in readonly_vf.versions():
1020
992
            readonly_vf.get_lines(version)
1021
993
 
1023
995
class TestWeaveHTTP(TestCaseWithWebserver, TestReadonlyHttpMixin):
1024
996
 
1025
997
    def get_file(self):
1026
 
        return WeaveFile('foo', transport.get_transport(self.get_url('.')),
1027
 
                         create=True,
1028
 
                         get_scope=self.get_transaction)
 
998
        return WeaveFile('foo', get_transport(self.get_url('.')), create=True,
 
999
            get_scope=self.get_transaction)
1029
1000
 
1030
1001
    def get_factory(self):
1031
1002
        return WeaveFile
1164
1135
            """
1165
1136
        result = """\
1166
1137
            line 1
1167
 
<<<<<<<\x20
1168
 
            line 2
1169
 
=======
1170
 
>>>>>>>\x20
1171
1138
            """
1172
1139
        self._test_merge_from_strings(base, a, b, result)
1173
1140
 
1275
1242
class TestWeaveMerge(TestCaseWithMemoryTransport, MergeCasesMixin):
1276
1243
 
1277
1244
    def get_file(self, name='foo'):
1278
 
        return WeaveFile(name, transport.get_transport(self.get_url('.')),
1279
 
                         create=True)
 
1245
        return WeaveFile(name, get_transport(self.get_url('.')), create=True)
1280
1246
 
1281
1247
    def log_contents(self, w):
1282
1248
        self.log('weave is:')
1481
1447
            transport.mkdir('.')
1482
1448
        files = self.factory(transport)
1483
1449
        if self.cleanup is not None:
1484
 
            self.addCleanup(self.cleanup, files)
 
1450
            self.addCleanup(lambda:self.cleanup(files))
1485
1451
        return files
1486
1452
 
1487
 
    def get_simple_key(self, suffix):
1488
 
        """Return a key for the object under test."""
1489
 
        if self.key_length == 1:
1490
 
            return (suffix,)
1491
 
        else:
1492
 
            return ('FileA',) + (suffix,)
1493
 
 
1494
 
    def test_add_lines(self):
1495
 
        f = self.get_versionedfiles()
1496
 
        key0 = self.get_simple_key('r0')
1497
 
        key1 = self.get_simple_key('r1')
1498
 
        key2 = self.get_simple_key('r2')
1499
 
        keyf = self.get_simple_key('foo')
1500
 
        f.add_lines(key0, [], ['a\n', 'b\n'])
1501
 
        if self.graph:
1502
 
            f.add_lines(key1, [key0], ['b\n', 'c\n'])
1503
 
        else:
1504
 
            f.add_lines(key1, [], ['b\n', 'c\n'])
1505
 
        keys = f.keys()
1506
 
        self.assertTrue(key0 in keys)
1507
 
        self.assertTrue(key1 in keys)
1508
 
        records = []
1509
 
        for record in f.get_record_stream([key0, key1], 'unordered', True):
1510
 
            records.append((record.key, record.get_bytes_as('fulltext')))
1511
 
        records.sort()
1512
 
        self.assertEqual([(key0, 'a\nb\n'), (key1, 'b\nc\n')], records)
1513
 
 
1514
 
    def test__add_text(self):
1515
 
        f = self.get_versionedfiles()
1516
 
        key0 = self.get_simple_key('r0')
1517
 
        key1 = self.get_simple_key('r1')
1518
 
        key2 = self.get_simple_key('r2')
1519
 
        keyf = self.get_simple_key('foo')
1520
 
        f._add_text(key0, [], 'a\nb\n')
1521
 
        if self.graph:
1522
 
            f._add_text(key1, [key0], 'b\nc\n')
1523
 
        else:
1524
 
            f._add_text(key1, [], 'b\nc\n')
1525
 
        keys = f.keys()
1526
 
        self.assertTrue(key0 in keys)
1527
 
        self.assertTrue(key1 in keys)
1528
 
        records = []
1529
 
        for record in f.get_record_stream([key0, key1], 'unordered', True):
1530
 
            records.append((record.key, record.get_bytes_as('fulltext')))
1531
 
        records.sort()
1532
 
        self.assertEqual([(key0, 'a\nb\n'), (key1, 'b\nc\n')], records)
1533
 
 
1534
1453
    def test_annotate(self):
1535
1454
        files = self.get_versionedfiles()
1536
1455
        self.get_diamond_files(files)
1570
1489
        self.assertRaises(RevisionNotPresent,
1571
1490
            files.annotate, prefix + ('missing-key',))
1572
1491
 
1573
 
    def test_check_no_parameters(self):
1574
 
        files = self.get_versionedfiles()
1575
 
 
1576
 
    def test_check_progressbar_parameter(self):
1577
 
        """A progress bar can be supplied because check can be a generator."""
1578
 
        pb = ui.ui_factory.nested_progress_bar()
1579
 
        self.addCleanup(pb.finished)
1580
 
        files = self.get_versionedfiles()
1581
 
        files.check(progress_bar=pb)
1582
 
 
1583
 
    def test_check_with_keys_becomes_generator(self):
1584
 
        files = self.get_versionedfiles()
1585
 
        self.get_diamond_files(files)
1586
 
        keys = files.keys()
1587
 
        entries = files.check(keys=keys)
1588
 
        seen = set()
1589
 
        # Texts output should be fulltexts.
1590
 
        self.capture_stream(files, entries, seen.add,
1591
 
            files.get_parent_map(keys), require_fulltext=True)
1592
 
        # All texts should be output.
1593
 
        self.assertEqual(set(keys), seen)
1594
 
 
1595
 
    def test_clear_cache(self):
1596
 
        files = self.get_versionedfiles()
1597
 
        files.clear_cache()
1598
 
 
1599
1492
    def test_construct(self):
1600
1493
        """Each parameterised test can be constructed on a transport."""
1601
1494
        files = self.get_versionedfiles()
1602
1495
 
1603
 
    def get_diamond_files(self, files, trailing_eol=True, left_only=False,
1604
 
        nokeys=False):
 
1496
    def get_diamond_files(self, files, trailing_eol=True, left_only=False):
1605
1497
        return get_diamond_files(files, self.key_length,
1606
1498
            trailing_eol=trailing_eol, nograph=not self.graph,
1607
 
            left_only=left_only, nokeys=nokeys)
1608
 
 
1609
 
    def _add_content_nostoresha(self, add_lines):
1610
 
        """When nostore_sha is supplied using old content raises."""
1611
 
        vf = self.get_versionedfiles()
1612
 
        empty_text = ('a', [])
1613
 
        sample_text_nl = ('b', ["foo\n", "bar\n"])
1614
 
        sample_text_no_nl = ('c', ["foo\n", "bar"])
1615
 
        shas = []
1616
 
        for version, lines in (empty_text, sample_text_nl, sample_text_no_nl):
1617
 
            if add_lines:
1618
 
                sha, _, _ = vf.add_lines(self.get_simple_key(version), [],
1619
 
                                         lines)
1620
 
            else:
1621
 
                sha, _, _ = vf._add_text(self.get_simple_key(version), [],
1622
 
                                         ''.join(lines))
1623
 
            shas.append(sha)
1624
 
        # we now have a copy of all the lines in the vf.
1625
 
        for sha, (version, lines) in zip(
1626
 
            shas, (empty_text, sample_text_nl, sample_text_no_nl)):
1627
 
            new_key = self.get_simple_key(version + "2")
1628
 
            self.assertRaises(errors.ExistingContent,
1629
 
                vf.add_lines, new_key, [], lines,
1630
 
                nostore_sha=sha)
1631
 
            self.assertRaises(errors.ExistingContent,
1632
 
                vf._add_text, new_key, [], ''.join(lines),
1633
 
                nostore_sha=sha)
1634
 
            # and no new version should have been added.
1635
 
            record = vf.get_record_stream([new_key], 'unordered', True).next()
1636
 
            self.assertEqual('absent', record.storage_kind)
1637
 
 
1638
 
    def test_add_lines_nostoresha(self):
1639
 
        self._add_content_nostoresha(add_lines=True)
1640
 
 
1641
 
    def test__add_text_nostoresha(self):
1642
 
        self._add_content_nostoresha(add_lines=False)
 
1499
            left_only=left_only)
1643
1500
 
1644
1501
    def test_add_lines_return(self):
1645
1502
        files = self.get_versionedfiles()
1672
1529
                ('ed8bce375198ea62444dc71952b22cfc2b09226d', 23)],
1673
1530
                results)
1674
1531
 
1675
 
    def test_add_lines_no_key_generates_chk_key(self):
1676
 
        files = self.get_versionedfiles()
1677
 
        # save code by using the stock data insertion helper.
1678
 
        adds = self.get_diamond_files(files, nokeys=True)
1679
 
        results = []
1680
 
        # We can only validate the first 2 elements returned from add_lines.
1681
 
        for add in adds:
1682
 
            self.assertEqual(3, len(add))
1683
 
            results.append(add[:2])
1684
 
        if self.key_length == 1:
1685
 
            self.assertEqual([
1686
 
                ('00e364d235126be43292ab09cb4686cf703ddc17', 7),
1687
 
                ('51c64a6f4fc375daf0d24aafbabe4d91b6f4bb44', 5),
1688
 
                ('a8478686da38e370e32e42e8a0c220e33ee9132f', 10),
1689
 
                ('9ef09dfa9d86780bdec9219a22560c6ece8e0ef1', 11),
1690
 
                ('ed8bce375198ea62444dc71952b22cfc2b09226d', 23)],
1691
 
                results)
1692
 
            # Check the added items got CHK keys.
1693
 
            self.assertEqual(set([
1694
 
                ('sha1:00e364d235126be43292ab09cb4686cf703ddc17',),
1695
 
                ('sha1:51c64a6f4fc375daf0d24aafbabe4d91b6f4bb44',),
1696
 
                ('sha1:9ef09dfa9d86780bdec9219a22560c6ece8e0ef1',),
1697
 
                ('sha1:a8478686da38e370e32e42e8a0c220e33ee9132f',),
1698
 
                ('sha1:ed8bce375198ea62444dc71952b22cfc2b09226d',),
1699
 
                ]),
1700
 
                files.keys())
1701
 
        elif self.key_length == 2:
1702
 
            self.assertEqual([
1703
 
                ('00e364d235126be43292ab09cb4686cf703ddc17', 7),
1704
 
                ('00e364d235126be43292ab09cb4686cf703ddc17', 7),
1705
 
                ('51c64a6f4fc375daf0d24aafbabe4d91b6f4bb44', 5),
1706
 
                ('51c64a6f4fc375daf0d24aafbabe4d91b6f4bb44', 5),
1707
 
                ('a8478686da38e370e32e42e8a0c220e33ee9132f', 10),
1708
 
                ('a8478686da38e370e32e42e8a0c220e33ee9132f', 10),
1709
 
                ('9ef09dfa9d86780bdec9219a22560c6ece8e0ef1', 11),
1710
 
                ('9ef09dfa9d86780bdec9219a22560c6ece8e0ef1', 11),
1711
 
                ('ed8bce375198ea62444dc71952b22cfc2b09226d', 23),
1712
 
                ('ed8bce375198ea62444dc71952b22cfc2b09226d', 23)],
1713
 
                results)
1714
 
            # Check the added items got CHK keys.
1715
 
            self.assertEqual(set([
1716
 
                ('FileA', 'sha1:00e364d235126be43292ab09cb4686cf703ddc17'),
1717
 
                ('FileA', 'sha1:51c64a6f4fc375daf0d24aafbabe4d91b6f4bb44'),
1718
 
                ('FileA', 'sha1:9ef09dfa9d86780bdec9219a22560c6ece8e0ef1'),
1719
 
                ('FileA', 'sha1:a8478686da38e370e32e42e8a0c220e33ee9132f'),
1720
 
                ('FileA', 'sha1:ed8bce375198ea62444dc71952b22cfc2b09226d'),
1721
 
                ('FileB', 'sha1:00e364d235126be43292ab09cb4686cf703ddc17'),
1722
 
                ('FileB', 'sha1:51c64a6f4fc375daf0d24aafbabe4d91b6f4bb44'),
1723
 
                ('FileB', 'sha1:9ef09dfa9d86780bdec9219a22560c6ece8e0ef1'),
1724
 
                ('FileB', 'sha1:a8478686da38e370e32e42e8a0c220e33ee9132f'),
1725
 
                ('FileB', 'sha1:ed8bce375198ea62444dc71952b22cfc2b09226d'),
1726
 
                ]),
1727
 
                files.keys())
1728
 
 
1729
1532
    def test_empty_lines(self):
1730
1533
        """Empty files can be stored."""
1731
1534
        f = self.get_versionedfiles()
1753
1556
            f.get_record_stream([key_b], 'unordered', True
1754
1557
                ).next().get_bytes_as('fulltext'))
1755
1558
 
1756
 
    def test_get_known_graph_ancestry(self):
1757
 
        f = self.get_versionedfiles()
1758
 
        if not self.graph:
1759
 
            raise TestNotApplicable('ancestry info only relevant with graph.')
1760
 
        key_a = self.get_simple_key('a')
1761
 
        key_b = self.get_simple_key('b')
1762
 
        key_c = self.get_simple_key('c')
1763
 
        # A
1764
 
        # |\
1765
 
        # | B
1766
 
        # |/
1767
 
        # C
1768
 
        f.add_lines(key_a, [], ['\n'])
1769
 
        f.add_lines(key_b, [key_a], ['\n'])
1770
 
        f.add_lines(key_c, [key_a, key_b], ['\n'])
1771
 
        kg = f.get_known_graph_ancestry([key_c])
1772
 
        self.assertIsInstance(kg, _mod_graph.KnownGraph)
1773
 
        self.assertEqual([key_a, key_b, key_c], list(kg.topo_sort()))
1774
 
 
1775
 
    def test_known_graph_with_fallbacks(self):
1776
 
        f = self.get_versionedfiles('files')
1777
 
        if not self.graph:
1778
 
            raise TestNotApplicable('ancestry info only relevant with graph.')
1779
 
        if getattr(f, 'add_fallback_versioned_files', None) is None:
1780
 
            raise TestNotApplicable("%s doesn't support fallbacks"
1781
 
                                    % (f.__class__.__name__,))
1782
 
        key_a = self.get_simple_key('a')
1783
 
        key_b = self.get_simple_key('b')
1784
 
        key_c = self.get_simple_key('c')
1785
 
        # A     only in fallback
1786
 
        # |\
1787
 
        # | B
1788
 
        # |/
1789
 
        # C
1790
 
        g = self.get_versionedfiles('fallback')
1791
 
        g.add_lines(key_a, [], ['\n'])
1792
 
        f.add_fallback_versioned_files(g)
1793
 
        f.add_lines(key_b, [key_a], ['\n'])
1794
 
        f.add_lines(key_c, [key_a, key_b], ['\n'])
1795
 
        kg = f.get_known_graph_ancestry([key_c])
1796
 
        self.assertEqual([key_a, key_b, key_c], list(kg.topo_sort()))
1797
 
 
1798
1559
    def test_get_record_stream_empty(self):
1799
1560
        """An empty stream can be requested without error."""
1800
1561
        f = self.get_versionedfiles()
1808
1569
             'knit-ft', 'knit-delta', 'chunked', 'fulltext',
1809
1570
             'knit-annotated-ft-gz', 'knit-annotated-delta-gz', 'knit-ft-gz',
1810
1571
             'knit-delta-gz',
1811
 
             'knit-delta-closure', 'knit-delta-closure-ref',
1812
 
             'groupcompress-block', 'groupcompress-block-ref'])
 
1572
             'knit-delta-closure', 'knit-delta-closure-ref'])
1813
1573
 
1814
 
    def capture_stream(self, f, entries, on_seen, parents,
1815
 
        require_fulltext=False):
 
1574
    def capture_stream(self, f, entries, on_seen, parents):
1816
1575
        """Capture a stream for testing."""
1817
1576
        for factory in entries:
1818
1577
            on_seen(factory.key)
1819
1578
            self.assertValidStorageKind(factory.storage_kind)
1820
 
            if factory.sha1 is not None:
1821
 
                self.assertEqual(f.get_sha1s([factory.key])[factory.key],
1822
 
                    factory.sha1)
 
1579
            self.assertEqual(f.get_sha1s([factory.key])[factory.key],
 
1580
                factory.sha1)
1823
1581
            self.assertEqual(parents[factory.key], factory.parents)
1824
1582
            self.assertIsInstance(factory.get_bytes_as(factory.storage_kind),
1825
1583
                str)
1826
 
            if require_fulltext:
1827
 
                factory.get_bytes_as('fulltext')
1828
1584
 
1829
1585
    def test_get_record_stream_interface(self):
1830
1586
        """each item in a stream has to provide a regular interface."""
1837
1593
        self.capture_stream(files, entries, seen.add, parent_map)
1838
1594
        self.assertEqual(set(keys), seen)
1839
1595
 
 
1596
    def get_simple_key(self, suffix):
 
1597
        """Return a key for the object under test."""
 
1598
        if self.key_length == 1:
 
1599
            return (suffix,)
 
1600
        else:
 
1601
            return ('FileA',) + (suffix,)
 
1602
 
1840
1603
    def get_keys_and_sort_order(self):
1841
1604
        """Get diamond test keys list, and their sort ordering."""
1842
1605
        if self.key_length == 1:
1857
1620
                }
1858
1621
        return keys, sort_order
1859
1622
 
1860
 
    def get_keys_and_groupcompress_sort_order(self):
1861
 
        """Get diamond test keys list, and their groupcompress sort ordering."""
1862
 
        if self.key_length == 1:
1863
 
            keys = [('merged',), ('left',), ('right',), ('base',)]
1864
 
            sort_order = {('merged',):0, ('left',):1, ('right',):1, ('base',):2}
1865
 
        else:
1866
 
            keys = [
1867
 
                ('FileA', 'merged'), ('FileA', 'left'), ('FileA', 'right'),
1868
 
                ('FileA', 'base'),
1869
 
                ('FileB', 'merged'), ('FileB', 'left'), ('FileB', 'right'),
1870
 
                ('FileB', 'base'),
1871
 
                ]
1872
 
            sort_order = {
1873
 
                ('FileA', 'merged'):0, ('FileA', 'left'):1, ('FileA', 'right'):1,
1874
 
                ('FileA', 'base'):2,
1875
 
                ('FileB', 'merged'):3, ('FileB', 'left'):4, ('FileB', 'right'):4,
1876
 
                ('FileB', 'base'):5,
1877
 
                }
1878
 
        return keys, sort_order
1879
 
 
1880
1623
    def test_get_record_stream_interface_ordered(self):
1881
1624
        """each item in a stream has to provide a regular interface."""
1882
1625
        files = self.get_versionedfiles()
1910
1653
 
1911
1654
        self.assertStreamOrder(sort_order, seen, keys)
1912
1655
 
1913
 
    def test_get_record_stream_interface_groupcompress(self):
1914
 
        """each item in a stream has to provide a regular interface."""
1915
 
        files = self.get_versionedfiles()
1916
 
        self.get_diamond_files(files)
1917
 
        keys, sort_order = self.get_keys_and_groupcompress_sort_order()
1918
 
        parent_map = files.get_parent_map(keys)
1919
 
        entries = files.get_record_stream(keys, 'groupcompress', False)
1920
 
        seen = []
1921
 
        self.capture_stream(files, entries, seen.append, parent_map)
1922
 
        self.assertStreamOrder(sort_order, seen, keys)
1923
 
 
1924
1656
    def assertStreamOrder(self, sort_order, seen, keys):
1925
1657
        self.assertEqual(len(set(seen)), len(keys))
1926
1658
        if self.key_length == 1:
1957
1689
        for factory in entries:
1958
1690
            seen.add(factory.key)
1959
1691
            self.assertValidStorageKind(factory.storage_kind)
1960
 
            if factory.sha1 is not None:
1961
 
                self.assertEqual(files.get_sha1s([factory.key])[factory.key],
1962
 
                                 factory.sha1)
 
1692
            self.assertEqual(files.get_sha1s([factory.key])[factory.key],
 
1693
                factory.sha1)
1963
1694
            self.assertEqual(parent_map[factory.key], factory.parents)
1964
1695
            # currently no stream emits mpdiff
1965
1696
            self.assertRaises(errors.UnavailableRepresentation,
2163
1894
                self.assertEqual(None, factory.parents)
2164
1895
            else:
2165
1896
                self.assertValidStorageKind(factory.storage_kind)
2166
 
                if factory.sha1 is not None:
2167
 
                    sha1 = files.get_sha1s([factory.key])[factory.key]
2168
 
                    self.assertEqual(sha1, factory.sha1)
 
1897
                self.assertEqual(files.get_sha1s([factory.key])[factory.key],
 
1898
                    factory.sha1)
2169
1899
                self.assertEqual(parents[factory.key], factory.parents)
2170
1900
                self.assertIsInstance(factory.get_bytes_as(factory.storage_kind),
2171
1901
                    str)
2205
1935
        else:
2206
1936
            return None
2207
1937
 
2208
 
    def test_get_annotator(self):
2209
 
        files = self.get_versionedfiles()
2210
 
        self.get_diamond_files(files)
2211
 
        origin_key = self.get_simple_key('origin')
2212
 
        base_key = self.get_simple_key('base')
2213
 
        left_key = self.get_simple_key('left')
2214
 
        right_key = self.get_simple_key('right')
2215
 
        merged_key = self.get_simple_key('merged')
2216
 
        # annotator = files.get_annotator()
2217
 
        # introduced full text
2218
 
        origins, lines = files.get_annotator().annotate(origin_key)
2219
 
        self.assertEqual([(origin_key,)], origins)
2220
 
        self.assertEqual(['origin\n'], lines)
2221
 
        # a delta
2222
 
        origins, lines = files.get_annotator().annotate(base_key)
2223
 
        self.assertEqual([(base_key,)], origins)
2224
 
        # a merge
2225
 
        origins, lines = files.get_annotator().annotate(merged_key)
2226
 
        if self.graph:
2227
 
            self.assertEqual([
2228
 
                (base_key,),
2229
 
                (left_key,),
2230
 
                (right_key,),
2231
 
                (merged_key,),
2232
 
                ], origins)
2233
 
        else:
2234
 
            # Without a graph everything is new.
2235
 
            self.assertEqual([
2236
 
                (merged_key,),
2237
 
                (merged_key,),
2238
 
                (merged_key,),
2239
 
                (merged_key,),
2240
 
                ], origins)
2241
 
        self.assertRaises(RevisionNotPresent,
2242
 
            files.get_annotator().annotate, self.get_simple_key('missing-key'))
2243
 
 
2244
1938
    def test_get_parent_map(self):
2245
1939
        files = self.get_versionedfiles()
2246
1940
        if self.key_length == 1:
2449
2143
        else:
2450
2144
            self.assertIdenticalVersionedFile(source, files)
2451
2145
 
2452
 
    def test_insert_record_stream_long_parent_chain_out_of_order(self):
2453
 
        """An out of order stream can either error or work."""
2454
 
        if not self.graph:
2455
 
            raise TestNotApplicable('ancestry info only relevant with graph.')
2456
 
        # Create a reasonably long chain of records based on each other, where
2457
 
        # most will be deltas.
2458
 
        source = self.get_versionedfiles('source')
2459
 
        parents = ()
2460
 
        keys = []
2461
 
        content = [('same same %d\n' % n) for n in range(500)]
2462
 
        for letter in 'abcdefghijklmnopqrstuvwxyz':
2463
 
            key = ('key-' + letter,)
2464
 
            if self.key_length == 2:
2465
 
                key = ('prefix',) + key
2466
 
            content.append('content for ' + letter + '\n')
2467
 
            source.add_lines(key, parents, content)
2468
 
            keys.append(key)
2469
 
            parents = (key,)
2470
 
        # Create a stream of these records, excluding the first record that the
2471
 
        # rest ultimately depend upon, and insert it into a new vf.
2472
 
        streams = []
2473
 
        for key in reversed(keys):
2474
 
            streams.append(source.get_record_stream([key], 'unordered', False))
2475
 
        deltas = chain(*streams[:-1])
2476
 
        files = self.get_versionedfiles()
2477
 
        try:
2478
 
            files.insert_record_stream(deltas)
2479
 
        except RevisionNotPresent:
2480
 
            # Must not have corrupted the file.
2481
 
            files.check()
2482
 
        else:
2483
 
            # Must only report either just the first key as a missing parent,
2484
 
            # no key as missing (for nodelta scenarios).
2485
 
            missing = set(files.get_missing_compression_parent_keys())
2486
 
            missing.discard(keys[0])
2487
 
            self.assertEqual(set(), missing)
2488
 
 
2489
2146
    def get_knit_delta_source(self):
2490
2147
        """Get a source that can produce a stream with knit delta records,
2491
2148
        regardless of this test's scenario.
2559
2216
        # the ordering here is to make a tree so that dumb searches have
2560
2217
        # more changes to muck up.
2561
2218
 
2562
 
        class InstrumentedProgress(progress.ProgressTask):
 
2219
        class InstrumentedProgress(progress.DummyProgress):
2563
2220
 
2564
2221
            def __init__(self):
2565
 
                progress.ProgressTask.__init__(self)
 
2222
 
 
2223
                progress.DummyProgress.__init__(self)
2566
2224
                self.updates = []
2567
2225
 
2568
2226
            def update(self, msg=None, current=None, total=None):
2599
2257
            return lines
2600
2258
        lines = iter_with_keys(
2601
2259
            [self.get_simple_key('child'), self.get_simple_key('otherchild')],
2602
 
            [('Walking content', 0, 2),
2603
 
             ('Walking content', 1, 2),
2604
 
             ('Walking content', 2, 2)])
 
2260
            [('Walking content.', 0, 2),
 
2261
             ('Walking content.', 1, 2),
 
2262
             ('Walking content.', 2, 2)])
2605
2263
        # we must see child and otherchild
2606
2264
        self.assertTrue(lines[('child\n', self.get_simple_key('child'))] > 0)
2607
2265
        self.assertTrue(
2610
2268
 
2611
2269
        # test all lines
2612
2270
        lines = iter_with_keys(files.keys(),
2613
 
            [('Walking content', 0, 5),
2614
 
             ('Walking content', 1, 5),
2615
 
             ('Walking content', 2, 5),
2616
 
             ('Walking content', 3, 5),
2617
 
             ('Walking content', 4, 5),
2618
 
             ('Walking content', 5, 5)])
 
2271
            [('Walking content.', 0, 5),
 
2272
             ('Walking content.', 1, 5),
 
2273
             ('Walking content.', 2, 5),
 
2274
             ('Walking content.', 3, 5),
 
2275
             ('Walking content.', 4, 5),
 
2276
             ('Walking content.', 5, 5)])
2619
2277
        # all lines must be seen at least once
2620
2278
        self.assertTrue(lines[('base\n', self.get_simple_key('base'))] > 0)
2621
2279
        self.assertTrue(
2757
2415
        self.assertRaises(NotImplementedError,
2758
2416
                self.texts.add_mpdiffs, [])
2759
2417
 
2760
 
    def test_check_noerrors(self):
2761
 
        self.texts.check()
 
2418
    def test_check(self):
 
2419
        self.assertTrue(self.texts.check())
2762
2420
 
2763
2421
    def test_insert_record_stream(self):
2764
2422
        self.assertRaises(NotImplementedError, self.texts.insert_record_stream,