/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_index.py

  • Committer: Aaron Bentley
  • Date: 2008-10-28 10:31:32 UTC
  • mto: (0.14.36 prepare-shelf)
  • mto: This revision was merged to the branch mainline in revision 3820.
  • Revision ID: aaron@aaronbentley.com-20081028103132-syota6mcye41kvqh
Update to use Tree.readlines, if possible.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2007 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
"""Tests for indices."""
 
18
 
 
19
from bzrlib import errors
 
20
from bzrlib.index import *
 
21
from bzrlib.tests import TestCaseWithMemoryTransport
 
22
from bzrlib.transport import get_transport
 
23
 
 
24
 
 
25
class TestGraphIndexBuilder(TestCaseWithMemoryTransport):
 
26
 
 
27
    def test_build_index_empty(self):
 
28
        builder = GraphIndexBuilder()
 
29
        stream = builder.finish()
 
30
        contents = stream.read()
 
31
        self.assertEqual(
 
32
            "Bazaar Graph Index 1\nnode_ref_lists=0\nkey_elements=1\nlen=0\n\n",
 
33
            contents)
 
34
 
 
35
    def test_build_index_empty_two_element_keys(self):
 
36
        builder = GraphIndexBuilder(key_elements=2)
 
37
        stream = builder.finish()
 
38
        contents = stream.read()
 
39
        self.assertEqual(
 
40
            "Bazaar Graph Index 1\nnode_ref_lists=0\nkey_elements=2\nlen=0\n\n",
 
41
            contents)
 
42
 
 
43
    def test_build_index_one_reference_list_empty(self):
 
44
        builder = GraphIndexBuilder(reference_lists=1)
 
45
        stream = builder.finish()
 
46
        contents = stream.read()
 
47
        self.assertEqual(
 
48
            "Bazaar Graph Index 1\nnode_ref_lists=1\nkey_elements=1\nlen=0\n\n",
 
49
            contents)
 
50
 
 
51
    def test_build_index_two_reference_list_empty(self):
 
52
        builder = GraphIndexBuilder(reference_lists=2)
 
53
        stream = builder.finish()
 
54
        contents = stream.read()
 
55
        self.assertEqual(
 
56
            "Bazaar Graph Index 1\nnode_ref_lists=2\nkey_elements=1\nlen=0\n\n",
 
57
            contents)
 
58
 
 
59
    def test_build_index_one_node_no_refs(self):
 
60
        builder = GraphIndexBuilder()
 
61
        builder.add_node(('akey', ), 'data')
 
62
        stream = builder.finish()
 
63
        contents = stream.read()
 
64
        self.assertEqual(
 
65
            "Bazaar Graph Index 1\nnode_ref_lists=0\nkey_elements=1\nlen=1\n"
 
66
            "akey\x00\x00\x00data\n\n", contents)
 
67
 
 
68
    def test_build_index_one_node_no_refs_accepts_empty_reflist(self):
 
69
        builder = GraphIndexBuilder()
 
70
        builder.add_node(('akey', ), 'data', ())
 
71
        stream = builder.finish()
 
72
        contents = stream.read()
 
73
        self.assertEqual(
 
74
            "Bazaar Graph Index 1\nnode_ref_lists=0\nkey_elements=1\nlen=1\n"
 
75
            "akey\x00\x00\x00data\n\n", contents)
 
76
 
 
77
    def test_build_index_one_node_2_element_keys(self):
 
78
        # multipart keys are separated by \x00 - because they are fixed length,
 
79
        # not variable this does not cause any issues, and seems clearer to the
 
80
        # author.
 
81
        builder = GraphIndexBuilder(key_elements=2)
 
82
        builder.add_node(('akey', 'secondpart'), 'data')
 
83
        stream = builder.finish()
 
84
        contents = stream.read()
 
85
        self.assertEqual(
 
86
            "Bazaar Graph Index 1\nnode_ref_lists=0\nkey_elements=2\nlen=1\n"
 
87
            "akey\x00secondpart\x00\x00\x00data\n\n", contents)
 
88
 
 
89
    def test_add_node_empty_value(self):
 
90
        builder = GraphIndexBuilder()
 
91
        builder.add_node(('akey', ), '')
 
92
        stream = builder.finish()
 
93
        contents = stream.read()
 
94
        self.assertEqual(
 
95
            "Bazaar Graph Index 1\nnode_ref_lists=0\nkey_elements=1\nlen=1\n"
 
96
            "akey\x00\x00\x00\n\n", contents)
 
97
 
 
98
    def test_build_index_nodes_sorted(self):
 
99
        # the highest sorted node comes first.
 
100
        builder = GraphIndexBuilder()
 
101
        # use three to have a good chance of glitching dictionary hash
 
102
        # lookups etc. Insert in randomish order that is not correct
 
103
        # and not the reverse of the correct order.
 
104
        builder.add_node(('2002', ), 'data')
 
105
        builder.add_node(('2000', ), 'data')
 
106
        builder.add_node(('2001', ), 'data')
 
107
        stream = builder.finish()
 
108
        contents = stream.read()
 
109
        self.assertEqual(
 
110
            "Bazaar Graph Index 1\nnode_ref_lists=0\nkey_elements=1\nlen=3\n"
 
111
            "2000\x00\x00\x00data\n"
 
112
            "2001\x00\x00\x00data\n"
 
113
            "2002\x00\x00\x00data\n"
 
114
            "\n", contents)
 
115
 
 
116
    def test_build_index_2_element_key_nodes_sorted(self):
 
117
        # multiple element keys are sorted first-key, second-key.
 
118
        builder = GraphIndexBuilder(key_elements=2)
 
119
        # use three values of each key element, to have a good chance of
 
120
        # glitching dictionary hash lookups etc. Insert in randomish order that
 
121
        # is not correct and not the reverse of the correct order.
 
122
        builder.add_node(('2002', '2002'), 'data')
 
123
        builder.add_node(('2002', '2000'), 'data')
 
124
        builder.add_node(('2002', '2001'), 'data')
 
125
        builder.add_node(('2000', '2002'), 'data')
 
126
        builder.add_node(('2000', '2000'), 'data')
 
127
        builder.add_node(('2000', '2001'), 'data')
 
128
        builder.add_node(('2001', '2002'), 'data')
 
129
        builder.add_node(('2001', '2000'), 'data')
 
130
        builder.add_node(('2001', '2001'), 'data')
 
131
        stream = builder.finish()
 
132
        contents = stream.read()
 
133
        self.assertEqual(
 
134
            "Bazaar Graph Index 1\nnode_ref_lists=0\nkey_elements=2\nlen=9\n"
 
135
            "2000\x002000\x00\x00\x00data\n"
 
136
            "2000\x002001\x00\x00\x00data\n"
 
137
            "2000\x002002\x00\x00\x00data\n"
 
138
            "2001\x002000\x00\x00\x00data\n"
 
139
            "2001\x002001\x00\x00\x00data\n"
 
140
            "2001\x002002\x00\x00\x00data\n"
 
141
            "2002\x002000\x00\x00\x00data\n"
 
142
            "2002\x002001\x00\x00\x00data\n"
 
143
            "2002\x002002\x00\x00\x00data\n"
 
144
            "\n", contents)
 
145
 
 
146
    def test_build_index_reference_lists_are_included_one(self):
 
147
        builder = GraphIndexBuilder(reference_lists=1)
 
148
        builder.add_node(('key', ), 'data', ([], ))
 
149
        stream = builder.finish()
 
150
        contents = stream.read()
 
151
        self.assertEqual(
 
152
            "Bazaar Graph Index 1\nnode_ref_lists=1\nkey_elements=1\nlen=1\n"
 
153
            "key\x00\x00\x00data\n"
 
154
            "\n", contents)
 
155
 
 
156
    def test_build_index_reference_lists_with_2_element_keys(self):
 
157
        builder = GraphIndexBuilder(reference_lists=1, key_elements=2)
 
158
        builder.add_node(('key', 'key2'), 'data', ([], ))
 
159
        stream = builder.finish()
 
160
        contents = stream.read()
 
161
        self.assertEqual(
 
162
            "Bazaar Graph Index 1\nnode_ref_lists=1\nkey_elements=2\nlen=1\n"
 
163
            "key\x00key2\x00\x00\x00data\n"
 
164
            "\n", contents)
 
165
 
 
166
    def test_build_index_reference_lists_are_included_two(self):
 
167
        builder = GraphIndexBuilder(reference_lists=2)
 
168
        builder.add_node(('key', ), 'data', ([], []))
 
169
        stream = builder.finish()
 
170
        contents = stream.read()
 
171
        self.assertEqual(
 
172
            "Bazaar Graph Index 1\nnode_ref_lists=2\nkey_elements=1\nlen=1\n"
 
173
            "key\x00\x00\t\x00data\n"
 
174
            "\n", contents)
 
175
 
 
176
    def test_node_references_are_byte_offsets(self):
 
177
        builder = GraphIndexBuilder(reference_lists=1)
 
178
        builder.add_node(('reference', ), 'data', ([], ))
 
179
        builder.add_node(('key', ), 'data', ([('reference', )], ))
 
180
        stream = builder.finish()
 
181
        contents = stream.read()
 
182
        self.assertEqual(
 
183
            "Bazaar Graph Index 1\nnode_ref_lists=1\nkey_elements=1\nlen=2\n"
 
184
            "key\x00\x0072\x00data\n"
 
185
            "reference\x00\x00\x00data\n"
 
186
            "\n", contents)
 
187
 
 
188
    def test_node_references_are_cr_delimited(self):
 
189
        builder = GraphIndexBuilder(reference_lists=1)
 
190
        builder.add_node(('reference', ), 'data', ([], ))
 
191
        builder.add_node(('reference2', ), 'data', ([], ))
 
192
        builder.add_node(('key', ), 'data', ([('reference', ), ('reference2', )], ))
 
193
        stream = builder.finish()
 
194
        contents = stream.read()
 
195
        self.assertEqual(
 
196
            "Bazaar Graph Index 1\nnode_ref_lists=1\nkey_elements=1\nlen=3\n"
 
197
            "key\x00\x00077\r094\x00data\n"
 
198
            "reference\x00\x00\x00data\n"
 
199
            "reference2\x00\x00\x00data\n"
 
200
            "\n", contents)
 
201
 
 
202
    def test_multiple_reference_lists_are_tab_delimited(self):
 
203
        builder = GraphIndexBuilder(reference_lists=2)
 
204
        builder.add_node(('keference', ), 'data', ([], []))
 
205
        builder.add_node(('rey', ), 'data', ([('keference', )], [('keference', )]))
 
206
        stream = builder.finish()
 
207
        contents = stream.read()
 
208
        self.assertEqual(
 
209
            "Bazaar Graph Index 1\nnode_ref_lists=2\nkey_elements=1\nlen=2\n"
 
210
            "keference\x00\x00\t\x00data\n"
 
211
            "rey\x00\x0059\t59\x00data\n"
 
212
            "\n", contents)
 
213
 
 
214
    def test_add_node_referencing_missing_key_makes_absent(self):
 
215
        builder = GraphIndexBuilder(reference_lists=1)
 
216
        builder.add_node(('rey', ), 'data', ([('beference', ), ('aeference2', )], ))
 
217
        stream = builder.finish()
 
218
        contents = stream.read()
 
219
        self.assertEqual(
 
220
            "Bazaar Graph Index 1\nnode_ref_lists=1\nkey_elements=1\nlen=1\n"
 
221
            "aeference2\x00a\x00\x00\n"
 
222
            "beference\x00a\x00\x00\n"
 
223
            "rey\x00\x00074\r059\x00data\n"
 
224
            "\n", contents)
 
225
 
 
226
    def test_node_references_three_digits(self):
 
227
        # test the node digit expands as needed.
 
228
        builder = GraphIndexBuilder(reference_lists=1)
 
229
        references = [(str(val), ) for val in reversed(range(9))]
 
230
        builder.add_node(('2-key', ), '', (references, ))
 
231
        stream = builder.finish()
 
232
        contents = stream.read()
 
233
        self.assertEqual(
 
234
            "Bazaar Graph Index 1\nnode_ref_lists=1\nkey_elements=1\nlen=1\n"
 
235
            "0\x00a\x00\x00\n"
 
236
            "1\x00a\x00\x00\n"
 
237
            "2\x00a\x00\x00\n"
 
238
            "2-key\x00\x00151\r145\r139\r133\r127\r121\r071\r065\r059\x00\n"
 
239
            "3\x00a\x00\x00\n"
 
240
            "4\x00a\x00\x00\n"
 
241
            "5\x00a\x00\x00\n"
 
242
            "6\x00a\x00\x00\n"
 
243
            "7\x00a\x00\x00\n"
 
244
            "8\x00a\x00\x00\n"
 
245
            "\n", contents)
 
246
 
 
247
    def test_absent_has_no_reference_overhead(self):
 
248
        # the offsets after an absent record should be correct when there are
 
249
        # >1 reference lists.
 
250
        builder = GraphIndexBuilder(reference_lists=2)
 
251
        builder.add_node(('parent', ), '', ([('aail', ), ('zther', )], []))
 
252
        stream = builder.finish()
 
253
        contents = stream.read()
 
254
        self.assertEqual(
 
255
            "Bazaar Graph Index 1\nnode_ref_lists=2\nkey_elements=1\nlen=1\n"
 
256
            "aail\x00a\x00\x00\n"
 
257
            "parent\x00\x0059\r84\t\x00\n"
 
258
            "zther\x00a\x00\x00\n"
 
259
            "\n", contents)
 
260
 
 
261
    def test_add_node_bad_key(self):
 
262
        builder = GraphIndexBuilder()
 
263
        for bad_char in '\t\n\x0b\x0c\r\x00 ':
 
264
            self.assertRaises(errors.BadIndexKey, builder.add_node,
 
265
                ('a%skey' % bad_char, ), 'data')
 
266
        self.assertRaises(errors.BadIndexKey, builder.add_node,
 
267
                ('', ), 'data')
 
268
        self.assertRaises(errors.BadIndexKey, builder.add_node,
 
269
                'not-a-tuple', 'data')
 
270
        # not enough length
 
271
        self.assertRaises(errors.BadIndexKey, builder.add_node,
 
272
                (), 'data')
 
273
        # too long
 
274
        self.assertRaises(errors.BadIndexKey, builder.add_node,
 
275
                ('primary', 'secondary'), 'data')
 
276
        # secondary key elements get checked too:
 
277
        builder = GraphIndexBuilder(key_elements=2)
 
278
        for bad_char in '\t\n\x0b\x0c\r\x00 ':
 
279
            self.assertRaises(errors.BadIndexKey, builder.add_node,
 
280
                ('prefix', 'a%skey' % bad_char), 'data')
 
281
 
 
282
    def test_add_node_bad_data(self):
 
283
        builder = GraphIndexBuilder()
 
284
        self.assertRaises(errors.BadIndexValue, builder.add_node, ('akey', ),
 
285
            'data\naa')
 
286
        self.assertRaises(errors.BadIndexValue, builder.add_node, ('akey', ),
 
287
            'data\x00aa')
 
288
 
 
289
    def test_add_node_bad_mismatched_ref_lists_length(self):
 
290
        builder = GraphIndexBuilder()
 
291
        self.assertRaises(errors.BadIndexValue, builder.add_node, ('akey', ),
 
292
            'data aa', ([], ))
 
293
        builder = GraphIndexBuilder(reference_lists=1)
 
294
        self.assertRaises(errors.BadIndexValue, builder.add_node, ('akey', ),
 
295
            'data aa')
 
296
        self.assertRaises(errors.BadIndexValue, builder.add_node, ('akey', ),
 
297
            'data aa', (), )
 
298
        self.assertRaises(errors.BadIndexValue, builder.add_node, ('akey', ),
 
299
            'data aa', ([], []))
 
300
        builder = GraphIndexBuilder(reference_lists=2)
 
301
        self.assertRaises(errors.BadIndexValue, builder.add_node, ('akey', ),
 
302
            'data aa')
 
303
        self.assertRaises(errors.BadIndexValue, builder.add_node, ('akey', ),
 
304
            'data aa', ([], ))
 
305
        self.assertRaises(errors.BadIndexValue, builder.add_node, ('akey', ),
 
306
            'data aa', ([], [], []))
 
307
 
 
308
    def test_add_node_bad_key_in_reference_lists(self):
 
309
        # first list, first key - trivial
 
310
        builder = GraphIndexBuilder(reference_lists=1)
 
311
        self.assertRaises(errors.BadIndexKey, builder.add_node, ('akey', ),
 
312
            'data aa', ([('a key', )], ))
 
313
        # references keys must be tuples too
 
314
        self.assertRaises(errors.BadIndexKey, builder.add_node, ('akey', ),
 
315
            'data aa', (['not-a-tuple'], ))
 
316
        # not enough length
 
317
        self.assertRaises(errors.BadIndexKey, builder.add_node, ('akey', ),
 
318
            'data aa', ([()], ))
 
319
        # too long
 
320
        self.assertRaises(errors.BadIndexKey, builder.add_node, ('akey', ),
 
321
            'data aa', ([('primary', 'secondary')], ))
 
322
        # need to check more than the first key in the list
 
323
        self.assertRaises(errors.BadIndexKey, builder.add_node, ('akey', ),
 
324
            'data aa', ([('agoodkey', ), ('that is a bad key', )], ))
 
325
        # and if there is more than one list it should be getting checked
 
326
        # too
 
327
        builder = GraphIndexBuilder(reference_lists=2)
 
328
        self.assertRaises(errors.BadIndexKey, builder.add_node, ('akey', ),
 
329
            'data aa', ([], ['a bad key']))
 
330
 
 
331
    def test_add_duplicate_key(self):
 
332
        builder = GraphIndexBuilder()
 
333
        builder.add_node(('key', ), 'data')
 
334
        self.assertRaises(errors.BadIndexDuplicateKey, builder.add_node, ('key', ),
 
335
            'data')
 
336
 
 
337
    def test_add_duplicate_key_2_elements(self):
 
338
        builder = GraphIndexBuilder(key_elements=2)
 
339
        builder.add_node(('key', 'key'), 'data')
 
340
        self.assertRaises(errors.BadIndexDuplicateKey, builder.add_node,
 
341
            ('key', 'key'), 'data')
 
342
 
 
343
    def test_add_key_after_referencing_key(self):
 
344
        builder = GraphIndexBuilder(reference_lists=1)
 
345
        builder.add_node(('key', ), 'data', ([('reference', )], ))
 
346
        builder.add_node(('reference', ), 'data', ([],))
 
347
 
 
348
    def test_add_key_after_referencing_key_2_elements(self):
 
349
        builder = GraphIndexBuilder(reference_lists=1, key_elements=2)
 
350
        builder.add_node(('k', 'ey'), 'data', ([('reference', 'tokey')], ))
 
351
        builder.add_node(('reference', 'tokey'), 'data', ([],))
 
352
 
 
353
    def test_set_optimize(self):
 
354
        builder = GraphIndexBuilder(reference_lists=1, key_elements=2)
 
355
        builder.set_optimize(for_size=True)
 
356
        self.assertTrue(builder._optimize_for_size)
 
357
        builder.set_optimize(for_size=False)
 
358
        self.assertFalse(builder._optimize_for_size)
 
359
 
 
360
 
 
361
class TestGraphIndex(TestCaseWithMemoryTransport):
 
362
 
 
363
    def make_key(self, number):
 
364
        return (str(number) + 'X'*100,)
 
365
 
 
366
    def make_value(self, number):
 
367
            return str(number) + 'Y'*100
 
368
 
 
369
    def make_nodes(self, count=64):
 
370
        # generate a big enough index that we only read some of it on a typical
 
371
        # bisection lookup.
 
372
        nodes = []
 
373
        for counter in range(count):
 
374
            nodes.append((self.make_key(counter), self.make_value(counter), ()))
 
375
        return nodes
 
376
 
 
377
    def make_index(self, ref_lists=0, key_elements=1, nodes=[]):
 
378
        builder = GraphIndexBuilder(ref_lists, key_elements=key_elements)
 
379
        for key, value, references in nodes:
 
380
            builder.add_node(key, value, references)
 
381
        stream = builder.finish()
 
382
        trans = get_transport('trace+' + self.get_url())
 
383
        size = trans.put_file('index', stream)
 
384
        return GraphIndex(trans, 'index', size)
 
385
 
 
386
    def test_open_bad_index_no_error(self):
 
387
        trans = self.get_transport()
 
388
        trans.put_bytes('name', "not an index\n")
 
389
        index = GraphIndex(trans, 'name', 13)
 
390
 
 
391
    def test_open_sets_parsed_map_empty(self):
 
392
        index = self.make_index()
 
393
        self.assertEqual([], index._parsed_byte_map)
 
394
        self.assertEqual([], index._parsed_key_map)
 
395
 
 
396
    def test_key_count_buffers(self):
 
397
        index = self.make_index(nodes=self.make_nodes(2))
 
398
        # reset the transport log
 
399
        del index._transport._activity[:]
 
400
        self.assertEqual(2, index.key_count())
 
401
        # We should have requested reading the header bytes
 
402
        self.assertEqual([
 
403
            ('readv', 'index', [(0, 200)], True, index._size),
 
404
            ],
 
405
            index._transport._activity)
 
406
        # And that should have been enough to trigger reading the whole index
 
407
        # with buffering
 
408
        self.assertIsNot(None, index._nodes)
 
409
 
 
410
    def test_lookup_key_via_location_buffers(self):
 
411
        index = self.make_index()
 
412
        # reset the transport log
 
413
        del index._transport._activity[:]
 
414
        # do a _lookup_keys_via_location call for the middle of the file, which
 
415
        # is what bisection uses.
 
416
        result = index._lookup_keys_via_location(
 
417
            [(index._size // 2, ('missing', ))])
 
418
        # this should have asked for a readv request, with adjust_for_latency,
 
419
        # and two regions: the header, and half-way into the file.
 
420
        self.assertEqual([
 
421
            ('readv', 'index', [(30, 30), (0, 200)], True, 60),
 
422
            ],
 
423
            index._transport._activity)
 
424
        # and the result should be that the key cannot be present, because this
 
425
        # is a trivial index.
 
426
        self.assertEqual([((index._size // 2, ('missing', )), False)],
 
427
            result)
 
428
        # And this should have caused the file to be fully buffered
 
429
        self.assertIsNot(None, index._nodes)
 
430
        self.assertEqual([], index._parsed_byte_map)
 
431
 
 
432
    def test_first_lookup_key_via_location(self):
 
433
        # We need enough data so that the _HEADER_READV doesn't consume the
 
434
        # whole file. We always read 800 bytes for every key, and the local
 
435
        # transport natural expansion is 4096 bytes. So we have to have >8192
 
436
        # bytes or we will trigger "buffer_all".
 
437
        # We also want the 'missing' key to fall within the range that *did*
 
438
        # read
 
439
        nodes = []
 
440
        index = self.make_index(nodes=self.make_nodes(64))
 
441
        # reset the transport log
 
442
        del index._transport._activity[:]
 
443
        # do a _lookup_keys_via_location call for the middle of the file, which
 
444
        # is what bisection uses.
 
445
        start_lookup = index._size // 2
 
446
        result = index._lookup_keys_via_location(
 
447
            [(start_lookup, ('40missing', ))])
 
448
        # this should have asked for a readv request, with adjust_for_latency,
 
449
        # and two regions: the header, and half-way into the file.
 
450
        self.assertEqual([
 
451
            ('readv', 'index',
 
452
             [(start_lookup, 800), (0, 200)], True, index._size),
 
453
            ],
 
454
            index._transport._activity)
 
455
        # and the result should be that the key cannot be present, because this
 
456
        # is a trivial index.
 
457
        self.assertEqual([((start_lookup, ('40missing', )), False)],
 
458
            result)
 
459
        # And this should not have caused the file to be fully buffered
 
460
        self.assertIs(None, index._nodes)
 
461
        # And the regions of the file that have been parsed should be in the
 
462
        # parsed_byte_map and the parsed_key_map
 
463
        self.assertEqual([(0, 4008), (5046, 8996)], index._parsed_byte_map)
 
464
        self.assertEqual([(None, self.make_key(26)),
 
465
                          (self.make_key(31), self.make_key(48))],
 
466
                         index._parsed_key_map)
 
467
 
 
468
    def test_parsing_non_adjacent_data_trims(self):
 
469
        index = self.make_index(nodes=self.make_nodes(64))
 
470
        result = index._lookup_keys_via_location(
 
471
            [(index._size // 2, ('40', ))])
 
472
        # and the result should be that the key cannot be present, because key is
 
473
        # in the middle of the observed data from a 4K read - the smallest transport
 
474
        # will do today with this api.
 
475
        self.assertEqual([((index._size // 2, ('40', )), False)],
 
476
            result)
 
477
        # and we should have a parse map that includes the header and the
 
478
        # region that was parsed after trimming.
 
479
        self.assertEqual([(0, 4008), (5046, 8996)], index._parsed_byte_map)
 
480
        self.assertEqual([(None, self.make_key(26)),
 
481
                          (self.make_key(31), self.make_key(48))],
 
482
            index._parsed_key_map)
 
483
 
 
484
    def test_parsing_data_handles_parsed_contained_regions(self):
 
485
        # the following patten creates a parsed region that is wholly within a
 
486
        # single result from the readv layer:
 
487
        # .... single-read (readv-minimum-size) ...
 
488
        # which then trims the start and end so the parsed size is < readv
 
489
        # miniumum.
 
490
        # then a dual lookup (or a reference lookup for that matter) which
 
491
        # abuts or overlaps the parsed region on both sides will need to
 
492
        # discard the data in the middle, but parse the end as well.
 
493
        #
 
494
        # we test this by doing a single lookup to seed the data, then
 
495
        # a lookup for two keys that are present, and adjacent -
 
496
        # we except both to be found, and the parsed byte map to include the
 
497
        # locations of both keys.
 
498
        index = self.make_index(nodes=self.make_nodes(128))
 
499
        result = index._lookup_keys_via_location(
 
500
            [(index._size // 2, ('40', ))])
 
501
        # and we should have a parse map that includes the header and the
 
502
        # region that was parsed after trimming.
 
503
        self.assertEqual([(0, 4045), (11759, 15707)], index._parsed_byte_map)
 
504
        self.assertEqual([(None, self.make_key(116)),
 
505
                          (self.make_key(35), self.make_key(51))],
 
506
            index._parsed_key_map)
 
507
        # now ask for two keys, right before and after the parsed region
 
508
        result = index._lookup_keys_via_location(
 
509
            [(11450, self.make_key(34)), (15707, self.make_key(52))])
 
510
        self.assertEqual([
 
511
            ((11450, self.make_key(34)),
 
512
             (index, self.make_key(34), self.make_value(34))),
 
513
            ((15707, self.make_key(52)),
 
514
             (index, self.make_key(52), self.make_value(52))),
 
515
            ],
 
516
            result)
 
517
        self.assertEqual([(0, 4045), (9889, 17993)], index._parsed_byte_map)
 
518
 
 
519
    def test_lookup_missing_key_answers_without_io_when_map_permits(self):
 
520
        # generate a big enough index that we only read some of it on a typical
 
521
        # bisection lookup.
 
522
        index = self.make_index(nodes=self.make_nodes(64))
 
523
        # lookup the keys in the middle of the file
 
524
        result =index._lookup_keys_via_location(
 
525
            [(index._size // 2, ('40', ))])
 
526
        # check the parse map, this determines the test validity
 
527
        self.assertEqual([(0, 4008), (5046, 8996)], index._parsed_byte_map)
 
528
        self.assertEqual([(None, self.make_key(26)),
 
529
                          (self.make_key(31), self.make_key(48))],
 
530
            index._parsed_key_map)
 
531
        # reset the transport log
 
532
        del index._transport._activity[:]
 
533
        # now looking up a key in the portion of the file already parsed should
 
534
        # not create a new transport request, and should return False (cannot
 
535
        # be in the index) - even when the byte location we ask for is outside
 
536
        # the parsed region
 
537
        result = index._lookup_keys_via_location(
 
538
            [(4000, ('40', ))])
 
539
        self.assertEqual([((4000, ('40', )), False)],
 
540
            result)
 
541
        self.assertEqual([], index._transport._activity)
 
542
 
 
543
    def test_lookup_present_key_answers_without_io_when_map_permits(self):
 
544
        # generate a big enough index that we only read some of it on a typical
 
545
        # bisection lookup.
 
546
        index = self.make_index(nodes=self.make_nodes(64))
 
547
        # lookup the keys in the middle of the file
 
548
        result =index._lookup_keys_via_location(
 
549
            [(index._size // 2, ('40', ))])
 
550
        # check the parse map, this determines the test validity
 
551
        self.assertEqual([(0, 4008), (5046, 8996)], index._parsed_byte_map)
 
552
        self.assertEqual([(None, self.make_key(26)),
 
553
                          (self.make_key(31), self.make_key(48))],
 
554
            index._parsed_key_map)
 
555
        # reset the transport log
 
556
        del index._transport._activity[:]
 
557
        # now looking up a key in the portion of the file already parsed should
 
558
        # not create a new transport request, and should return False (cannot
 
559
        # be in the index) - even when the byte location we ask for is outside
 
560
        # the parsed region
 
561
        # 
 
562
        result = index._lookup_keys_via_location([(4000, self.make_key(40))])
 
563
        self.assertEqual(
 
564
            [((4000, self.make_key(40)),
 
565
              (index, self.make_key(40), self.make_value(40)))],
 
566
            result)
 
567
        self.assertEqual([], index._transport._activity)
 
568
 
 
569
    def test_lookup_key_below_probed_area(self):
 
570
        # generate a big enough index that we only read some of it on a typical
 
571
        # bisection lookup.
 
572
        index = self.make_index(nodes=self.make_nodes(64))
 
573
        # ask for the key in the middle, but a key that is located in the
 
574
        # unparsed region before the middle.
 
575
        result =index._lookup_keys_via_location(
 
576
            [(index._size // 2, ('30', ))])
 
577
        # check the parse map, this determines the test validity
 
578
        self.assertEqual([(0, 4008), (5046, 8996)], index._parsed_byte_map)
 
579
        self.assertEqual([(None, self.make_key(26)),
 
580
                          (self.make_key(31), self.make_key(48))],
 
581
            index._parsed_key_map)
 
582
        self.assertEqual([((index._size // 2, ('30', )), -1)],
 
583
            result)
 
584
 
 
585
    def test_lookup_key_above_probed_area(self):
 
586
        # generate a big enough index that we only read some of it on a typical
 
587
        # bisection lookup.
 
588
        index = self.make_index(nodes=self.make_nodes(64))
 
589
        # ask for the key in the middle, but a key that is located in the
 
590
        # unparsed region after the middle.
 
591
        result =index._lookup_keys_via_location(
 
592
            [(index._size // 2, ('50', ))])
 
593
        # check the parse map, this determines the test validity
 
594
        self.assertEqual([(0, 4008), (5046, 8996)], index._parsed_byte_map)
 
595
        self.assertEqual([(None, self.make_key(26)),
 
596
                          (self.make_key(31), self.make_key(48))],
 
597
            index._parsed_key_map)
 
598
        self.assertEqual([((index._size // 2, ('50', )), +1)],
 
599
            result)
 
600
 
 
601
    def test_lookup_key_resolves_references(self):
 
602
        # generate a big enough index that we only read some of it on a typical
 
603
        # bisection lookup.
 
604
        nodes = []
 
605
        for counter in range(99):
 
606
            nodes.append((self.make_key(counter), self.make_value(counter),
 
607
                ((self.make_key(counter + 20),),)  ))
 
608
        index = self.make_index(ref_lists=1, nodes=nodes)
 
609
        # lookup a key in the middle that does not exist, so that when we can
 
610
        # check that the referred-to-keys are not accessed automatically.
 
611
        index_size = index._size
 
612
        index_center = index_size // 2
 
613
        result = index._lookup_keys_via_location(
 
614
            [(index_center, ('40', ))])
 
615
        # check the parse map - only the start and middle should have been
 
616
        # parsed.
 
617
        self.assertEqual([(0, 4027), (10198, 14028)], index._parsed_byte_map)
 
618
        self.assertEqual([(None, self.make_key(17)),
 
619
                          (self.make_key(44), self.make_key(5))],
 
620
            index._parsed_key_map)
 
621
        # and check the transport activity likewise.
 
622
        self.assertEqual(
 
623
            [('readv', 'index', [(index_center, 800), (0, 200)], True,
 
624
                                  index_size)],
 
625
            index._transport._activity)
 
626
        # reset the transport log for testing the reference lookup
 
627
        del index._transport._activity[:]
 
628
        # now looking up a key in the portion of the file already parsed should
 
629
        # only perform IO to resolve its key references.
 
630
        result = index._lookup_keys_via_location([(11000, self.make_key(45))])
 
631
        self.assertEqual(
 
632
            [((11000, self.make_key(45)),
 
633
              (index, self.make_key(45), self.make_value(45),
 
634
               ((self.make_key(65),),)))],
 
635
            result)
 
636
        self.assertEqual([('readv', 'index', [(15093, 800)], True, index_size)],
 
637
            index._transport._activity)
 
638
 
 
639
    def test_lookup_key_can_buffer_all(self):
 
640
        nodes = []
 
641
        for counter in range(64):
 
642
            nodes.append((self.make_key(counter), self.make_value(counter),
 
643
                ((self.make_key(counter + 20),),)  ))
 
644
        index = self.make_index(ref_lists=1, nodes=nodes)
 
645
        # lookup a key in the middle that does not exist, so that when we can
 
646
        # check that the referred-to-keys are not accessed automatically.
 
647
        index_size = index._size
 
648
        index_center = index_size // 2
 
649
        result = index._lookup_keys_via_location([(index_center, ('40', ))])
 
650
        # check the parse map - only the start and middle should have been
 
651
        # parsed.
 
652
        self.assertEqual([(0, 3890), (6444, 10274)], index._parsed_byte_map)
 
653
        self.assertEqual([(None, self.make_key(25)),
 
654
                          (self.make_key(37), self.make_key(52))],
 
655
            index._parsed_key_map)
 
656
        # and check the transport activity likewise.
 
657
        self.assertEqual(
 
658
            [('readv', 'index', [(index_center, 800), (0, 200)], True,
 
659
                                  index_size)],
 
660
            index._transport._activity)
 
661
        # reset the transport log for testing the reference lookup
 
662
        del index._transport._activity[:]
 
663
        # now looking up a key in the portion of the file already parsed should
 
664
        # only perform IO to resolve its key references.
 
665
        result = index._lookup_keys_via_location([(7000, self.make_key(40))])
 
666
        self.assertEqual(
 
667
            [((7000, self.make_key(40)),
 
668
              (index, self.make_key(40), self.make_value(40),
 
669
               ((self.make_key(60),),)))],
 
670
            result)
 
671
        # Resolving the references would have required more data read, and we
 
672
        # are already above the 50% threshold, so it triggered a _buffer_all
 
673
        self.assertEqual([('get', 'index')], index._transport._activity)
 
674
 
 
675
    def test_iter_all_entries_empty(self):
 
676
        index = self.make_index()
 
677
        self.assertEqual([], list(index.iter_all_entries()))
 
678
 
 
679
    def test_iter_all_entries_simple(self):
 
680
        index = self.make_index(nodes=[(('name', ), 'data', ())])
 
681
        self.assertEqual([(index, ('name', ), 'data')],
 
682
            list(index.iter_all_entries()))
 
683
 
 
684
    def test_iter_all_entries_simple_2_elements(self):
 
685
        index = self.make_index(key_elements=2,
 
686
            nodes=[(('name', 'surname'), 'data', ())])
 
687
        self.assertEqual([(index, ('name', 'surname'), 'data')],
 
688
            list(index.iter_all_entries()))
 
689
 
 
690
    def test_iter_all_entries_references_resolved(self):
 
691
        index = self.make_index(1, nodes=[
 
692
            (('name', ), 'data', ([('ref', )], )),
 
693
            (('ref', ), 'refdata', ([], ))])
 
694
        self.assertEqual(set([(index, ('name', ), 'data', ((('ref',),),)),
 
695
            (index, ('ref', ), 'refdata', ((), ))]),
 
696
            set(index.iter_all_entries()))
 
697
 
 
698
    def test_iter_entries_buffers_once(self):
 
699
        index = self.make_index(nodes=self.make_nodes(2))
 
700
        # reset the transport log
 
701
        del index._transport._activity[:]
 
702
        self.assertEqual(set([(index, self.make_key(1), self.make_value(1))]),
 
703
                         set(index.iter_entries([self.make_key(1)])))
 
704
        # We should have requested reading the header bytes
 
705
        # But not needed any more than that because it would have triggered a
 
706
        # buffer all
 
707
        self.assertEqual([
 
708
            ('readv', 'index', [(0, 200)], True, index._size),
 
709
            ],
 
710
            index._transport._activity)
 
711
        # And that should have been enough to trigger reading the whole index
 
712
        # with buffering
 
713
        self.assertIsNot(None, index._nodes)
 
714
 
 
715
    def test_iter_entries_buffers_by_bytes_read(self):
 
716
        index = self.make_index(nodes=self.make_nodes(64))
 
717
        list(index.iter_entries([self.make_key(10)]))
 
718
        # The first time through isn't enough to trigger a buffer all
 
719
        self.assertIs(None, index._nodes)
 
720
        self.assertEqual(4096, index._bytes_read)
 
721
        # Grabbing a key in that same page won't trigger a buffer all, as we
 
722
        # still haven't read 50% of the file
 
723
        list(index.iter_entries([self.make_key(11)]))
 
724
        self.assertIs(None, index._nodes)
 
725
        self.assertEqual(4096, index._bytes_read)
 
726
        # We haven't read more data, so reading outside the range won't trigger
 
727
        # a buffer all right away
 
728
        list(index.iter_entries([self.make_key(40)]))
 
729
        self.assertIs(None, index._nodes)
 
730
        self.assertEqual(8192, index._bytes_read)
 
731
        # On the next pass, we will not trigger buffer all if the key is
 
732
        # available without reading more
 
733
        list(index.iter_entries([self.make_key(32)]))
 
734
        self.assertIs(None, index._nodes)
 
735
        # But if we *would* need to read more to resolve it, then we will
 
736
        # buffer all.
 
737
        list(index.iter_entries([self.make_key(60)]))
 
738
        self.assertIsNot(None, index._nodes)
 
739
 
 
740
    def test_iter_entries_references_resolved(self):
 
741
        index = self.make_index(1, nodes=[
 
742
            (('name', ), 'data', ([('ref', ), ('ref', )], )),
 
743
            (('ref', ), 'refdata', ([], ))])
 
744
        self.assertEqual(set([(index, ('name', ), 'data', ((('ref',),('ref',)),)),
 
745
            (index, ('ref', ), 'refdata', ((), ))]),
 
746
            set(index.iter_entries([('name',), ('ref',)])))
 
747
 
 
748
    def test_iter_entries_references_2_refs_resolved(self):
 
749
        index = self.make_index(2, nodes=[
 
750
            (('name', ), 'data', ([('ref', )], [('ref', )])),
 
751
            (('ref', ), 'refdata', ([], []))])
 
752
        self.assertEqual(set([(index, ('name', ), 'data', ((('ref',),), (('ref',),))),
 
753
            (index, ('ref', ), 'refdata', ((), ()))]),
 
754
            set(index.iter_entries([('name',), ('ref',)])))
 
755
 
 
756
    def test_iteration_absent_skipped(self):
 
757
        index = self.make_index(1, nodes=[
 
758
            (('name', ), 'data', ([('ref', )], ))])
 
759
        self.assertEqual(set([(index, ('name', ), 'data', ((('ref',),),))]),
 
760
            set(index.iter_all_entries()))
 
761
        self.assertEqual(set([(index, ('name', ), 'data', ((('ref',),),))]),
 
762
            set(index.iter_entries([('name', )])))
 
763
        self.assertEqual([], list(index.iter_entries([('ref', )])))
 
764
 
 
765
    def test_iteration_absent_skipped_2_element_keys(self):
 
766
        index = self.make_index(1, key_elements=2, nodes=[
 
767
            (('name', 'fin'), 'data', ([('ref', 'erence')], ))])
 
768
        self.assertEqual(set([(index, ('name', 'fin'), 'data', ((('ref', 'erence'),),))]),
 
769
            set(index.iter_all_entries()))
 
770
        self.assertEqual(set([(index, ('name', 'fin'), 'data', ((('ref', 'erence'),),))]),
 
771
            set(index.iter_entries([('name', 'fin')])))
 
772
        self.assertEqual([], list(index.iter_entries([('ref', 'erence')])))
 
773
 
 
774
    def test_iter_all_keys(self):
 
775
        index = self.make_index(1, nodes=[
 
776
            (('name', ), 'data', ([('ref', )], )),
 
777
            (('ref', ), 'refdata', ([], ))])
 
778
        self.assertEqual(set([(index, ('name', ), 'data', ((('ref',),),)),
 
779
            (index, ('ref', ), 'refdata', ((), ))]),
 
780
            set(index.iter_entries([('name', ), ('ref', )])))
 
781
 
 
782
    def test_iter_nothing_empty(self):
 
783
        index = self.make_index()
 
784
        self.assertEqual([], list(index.iter_entries([])))
 
785
 
 
786
    def test_iter_missing_entry_empty(self):
 
787
        index = self.make_index()
 
788
        self.assertEqual([], list(index.iter_entries([('a', )])))
 
789
 
 
790
    def test_iter_missing_entry_empty_no_size(self):
 
791
        index = self.make_index()
 
792
        index = GraphIndex(index._transport, 'index', None)
 
793
        self.assertEqual([], list(index.iter_entries([('a', )])))
 
794
 
 
795
    def test_iter_key_prefix_1_element_key_None(self):
 
796
        index = self.make_index()
 
797
        self.assertRaises(errors.BadIndexKey, list,
 
798
            index.iter_entries_prefix([(None, )]))
 
799
 
 
800
    def test_iter_key_prefix_wrong_length(self):
 
801
        index = self.make_index()
 
802
        self.assertRaises(errors.BadIndexKey, list,
 
803
            index.iter_entries_prefix([('foo', None)]))
 
804
        index = self.make_index(key_elements=2)
 
805
        self.assertRaises(errors.BadIndexKey, list,
 
806
            index.iter_entries_prefix([('foo', )]))
 
807
        self.assertRaises(errors.BadIndexKey, list,
 
808
            index.iter_entries_prefix([('foo', None, None)]))
 
809
 
 
810
    def test_iter_key_prefix_1_key_element_no_refs(self):
 
811
        index = self.make_index( nodes=[
 
812
            (('name', ), 'data', ()),
 
813
            (('ref', ), 'refdata', ())])
 
814
        self.assertEqual(set([(index, ('name', ), 'data'),
 
815
            (index, ('ref', ), 'refdata')]),
 
816
            set(index.iter_entries_prefix([('name', ), ('ref', )])))
 
817
 
 
818
    def test_iter_key_prefix_1_key_element_refs(self):
 
819
        index = self.make_index(1, nodes=[
 
820
            (('name', ), 'data', ([('ref', )], )),
 
821
            (('ref', ), 'refdata', ([], ))])
 
822
        self.assertEqual(set([(index, ('name', ), 'data', ((('ref',),),)),
 
823
            (index, ('ref', ), 'refdata', ((), ))]),
 
824
            set(index.iter_entries_prefix([('name', ), ('ref', )])))
 
825
 
 
826
    def test_iter_key_prefix_2_key_element_no_refs(self):
 
827
        index = self.make_index(key_elements=2, nodes=[
 
828
            (('name', 'fin1'), 'data', ()),
 
829
            (('name', 'fin2'), 'beta', ()),
 
830
            (('ref', 'erence'), 'refdata', ())])
 
831
        self.assertEqual(set([(index, ('name', 'fin1'), 'data'),
 
832
            (index, ('ref', 'erence'), 'refdata')]),
 
833
            set(index.iter_entries_prefix([('name', 'fin1'), ('ref', 'erence')])))
 
834
        self.assertEqual(set([(index, ('name', 'fin1'), 'data'),
 
835
            (index, ('name', 'fin2'), 'beta')]),
 
836
            set(index.iter_entries_prefix([('name', None)])))
 
837
 
 
838
    def test_iter_key_prefix_2_key_element_refs(self):
 
839
        index = self.make_index(1, key_elements=2, nodes=[
 
840
            (('name', 'fin1'), 'data', ([('ref', 'erence')], )),
 
841
            (('name', 'fin2'), 'beta', ([], )),
 
842
            (('ref', 'erence'), 'refdata', ([], ))])
 
843
        self.assertEqual(set([(index, ('name', 'fin1'), 'data', ((('ref', 'erence'),),)),
 
844
            (index, ('ref', 'erence'), 'refdata', ((), ))]),
 
845
            set(index.iter_entries_prefix([('name', 'fin1'), ('ref', 'erence')])))
 
846
        self.assertEqual(set([(index, ('name', 'fin1'), 'data', ((('ref', 'erence'),),)),
 
847
            (index, ('name', 'fin2'), 'beta', ((), ))]),
 
848
            set(index.iter_entries_prefix([('name', None)])))
 
849
 
 
850
    def test_key_count_empty(self):
 
851
        index = self.make_index()
 
852
        self.assertEqual(0, index.key_count())
 
853
 
 
854
    def test_key_count_one(self):
 
855
        index = self.make_index(nodes=[(('name', ), '', ())])
 
856
        self.assertEqual(1, index.key_count())
 
857
 
 
858
    def test_key_count_two(self):
 
859
        index = self.make_index(nodes=[
 
860
            (('name', ), '', ()), (('foo', ), '', ())])
 
861
        self.assertEqual(2, index.key_count())
 
862
 
 
863
    def test_read_and_parse_tracks_real_read_value(self):
 
864
        index = self.make_index(nodes=self.make_nodes(10))
 
865
        del index._transport._activity[:]
 
866
        index._read_and_parse([(0, 200)])
 
867
        self.assertEqual([
 
868
            ('readv', 'index', [(0, 200)], True, index._size),
 
869
            ],
 
870
            index._transport._activity)
 
871
        # The readv expansion code will expand the initial request to 4096
 
872
        # bytes, which is more than enough to read the entire index, and we
 
873
        # will track the fact that we read that many bytes.
 
874
        self.assertEqual(index._size, index._bytes_read)
 
875
 
 
876
    def test_read_and_parse_triggers_buffer_all(self):
 
877
        index = self.make_index(key_elements=2, nodes=[
 
878
            (('name', 'fin1'), 'data', ()),
 
879
            (('name', 'fin2'), 'beta', ()),
 
880
            (('ref', 'erence'), 'refdata', ())])
 
881
        self.assertTrue(index._size > 0)
 
882
        self.assertIs(None, index._nodes)
 
883
        index._read_and_parse([(0, index._size)])
 
884
        self.assertIsNot(None, index._nodes)
 
885
 
 
886
    def test_validate_bad_index_errors(self):
 
887
        trans = self.get_transport()
 
888
        trans.put_bytes('name', "not an index\n")
 
889
        index = GraphIndex(trans, 'name', 13)
 
890
        self.assertRaises(errors.BadIndexFormatSignature, index.validate)
 
891
 
 
892
    def test_validate_bad_node_refs(self):
 
893
        index = self.make_index(2)
 
894
        trans = self.get_transport()
 
895
        content = trans.get_bytes('index')
 
896
        # change the options line to end with a rather than a parseable number
 
897
        new_content = content[:-2] + 'a\n\n'
 
898
        trans.put_bytes('index', new_content)
 
899
        self.assertRaises(errors.BadIndexOptions, index.validate)
 
900
 
 
901
    def test_validate_missing_end_line_empty(self):
 
902
        index = self.make_index(2)
 
903
        trans = self.get_transport()
 
904
        content = trans.get_bytes('index')
 
905
        # truncate the last byte
 
906
        trans.put_bytes('index', content[:-1])
 
907
        self.assertRaises(errors.BadIndexData, index.validate)
 
908
 
 
909
    def test_validate_missing_end_line_nonempty(self):
 
910
        index = self.make_index(2, nodes=[(('key', ), '', ([], []))])
 
911
        trans = self.get_transport()
 
912
        content = trans.get_bytes('index')
 
913
        # truncate the last byte
 
914
        trans.put_bytes('index', content[:-1])
 
915
        self.assertRaises(errors.BadIndexData, index.validate)
 
916
 
 
917
    def test_validate_empty(self):
 
918
        index = self.make_index()
 
919
        index.validate()
 
920
 
 
921
    def test_validate_no_refs_content(self):
 
922
        index = self.make_index(nodes=[(('key', ), 'value', ())])
 
923
        index.validate()
 
924
 
 
925
 
 
926
class TestCombinedGraphIndex(TestCaseWithMemoryTransport):
 
927
 
 
928
    def make_index(self, name, ref_lists=0, key_elements=1, nodes=[]):
 
929
        builder = GraphIndexBuilder(ref_lists, key_elements=key_elements)
 
930
        for key, value, references in nodes:
 
931
            builder.add_node(key, value, references)
 
932
        stream = builder.finish()
 
933
        trans = self.get_transport()
 
934
        size = trans.put_file(name, stream)
 
935
        return GraphIndex(trans, name, size)
 
936
 
 
937
    def test_open_missing_index_no_error(self):
 
938
        trans = self.get_transport()
 
939
        index1 = GraphIndex(trans, 'missing', 100)
 
940
        index = CombinedGraphIndex([index1])
 
941
 
 
942
    def test_add_index(self):
 
943
        index = CombinedGraphIndex([])
 
944
        index1 = self.make_index('name', 0, nodes=[(('key', ), '', ())])
 
945
        index.insert_index(0, index1)
 
946
        self.assertEqual([(index1, ('key', ), '')], list(index.iter_all_entries()))
 
947
 
 
948
    def test_iter_all_entries_empty(self):
 
949
        index = CombinedGraphIndex([])
 
950
        self.assertEqual([], list(index.iter_all_entries()))
 
951
 
 
952
    def test_iter_all_entries_children_empty(self):
 
953
        index1 = self.make_index('name')
 
954
        index = CombinedGraphIndex([index1])
 
955
        self.assertEqual([], list(index.iter_all_entries()))
 
956
 
 
957
    def test_iter_all_entries_simple(self):
 
958
        index1 = self.make_index('name', nodes=[(('name', ), 'data', ())])
 
959
        index = CombinedGraphIndex([index1])
 
960
        self.assertEqual([(index1, ('name', ), 'data')],
 
961
            list(index.iter_all_entries()))
 
962
 
 
963
    def test_iter_all_entries_two_indices(self):
 
964
        index1 = self.make_index('name1', nodes=[(('name', ), 'data', ())])
 
965
        index2 = self.make_index('name2', nodes=[(('2', ), '', ())])
 
966
        index = CombinedGraphIndex([index1, index2])
 
967
        self.assertEqual([(index1, ('name', ), 'data'),
 
968
            (index2, ('2', ), '')],
 
969
            list(index.iter_all_entries()))
 
970
 
 
971
    def test_iter_entries_two_indices_dup_key(self):
 
972
        index1 = self.make_index('name1', nodes=[(('name', ), 'data', ())])
 
973
        index2 = self.make_index('name2', nodes=[(('name', ), 'data', ())])
 
974
        index = CombinedGraphIndex([index1, index2])
 
975
        self.assertEqual([(index1, ('name', ), 'data')],
 
976
            list(index.iter_entries([('name', )])))
 
977
 
 
978
    def test_iter_all_entries_two_indices_dup_key(self):
 
979
        index1 = self.make_index('name1', nodes=[(('name', ), 'data', ())])
 
980
        index2 = self.make_index('name2', nodes=[(('name', ), 'data', ())])
 
981
        index = CombinedGraphIndex([index1, index2])
 
982
        self.assertEqual([(index1, ('name', ), 'data')],
 
983
            list(index.iter_all_entries()))
 
984
 
 
985
    def test_iter_key_prefix_2_key_element_refs(self):
 
986
        index1 = self.make_index('1', 1, key_elements=2, nodes=[
 
987
            (('name', 'fin1'), 'data', ([('ref', 'erence')], ))])
 
988
        index2 = self.make_index('2', 1, key_elements=2, nodes=[
 
989
            (('name', 'fin2'), 'beta', ([], )),
 
990
            (('ref', 'erence'), 'refdata', ([], ))])
 
991
        index = CombinedGraphIndex([index1, index2])
 
992
        self.assertEqual(set([(index1, ('name', 'fin1'), 'data', ((('ref', 'erence'),),)),
 
993
            (index2, ('ref', 'erence'), 'refdata', ((), ))]),
 
994
            set(index.iter_entries_prefix([('name', 'fin1'), ('ref', 'erence')])))
 
995
        self.assertEqual(set([(index1, ('name', 'fin1'), 'data', ((('ref', 'erence'),),)),
 
996
            (index2, ('name', 'fin2'), 'beta', ((), ))]),
 
997
            set(index.iter_entries_prefix([('name', None)])))
 
998
 
 
999
    def test_iter_nothing_empty(self):
 
1000
        index = CombinedGraphIndex([])
 
1001
        self.assertEqual([], list(index.iter_entries([])))
 
1002
 
 
1003
    def test_iter_nothing_children_empty(self):
 
1004
        index1 = self.make_index('name')
 
1005
        index = CombinedGraphIndex([index1])
 
1006
        self.assertEqual([], list(index.iter_entries([])))
 
1007
 
 
1008
    def test_iter_all_keys(self):
 
1009
        index1 = self.make_index('1', 1, nodes=[
 
1010
            (('name', ), 'data', ([('ref', )], ))])
 
1011
        index2 = self.make_index('2', 1, nodes=[
 
1012
            (('ref', ), 'refdata', ((), ))])
 
1013
        index = CombinedGraphIndex([index1, index2])
 
1014
        self.assertEqual(set([(index1, ('name', ), 'data', ((('ref', ), ), )),
 
1015
            (index2, ('ref', ), 'refdata', ((), ))]),
 
1016
            set(index.iter_entries([('name', ), ('ref', )])))
 
1017
 
 
1018
    def test_iter_all_keys_dup_entry(self):
 
1019
        index1 = self.make_index('1', 1, nodes=[
 
1020
            (('name', ), 'data', ([('ref', )], )),
 
1021
            (('ref', ), 'refdata', ([], ))])
 
1022
        index2 = self.make_index('2', 1, nodes=[
 
1023
            (('ref', ), 'refdata', ([], ))])
 
1024
        index = CombinedGraphIndex([index1, index2])
 
1025
        self.assertEqual(set([(index1, ('name', ), 'data', ((('ref',),),)),
 
1026
            (index1, ('ref', ), 'refdata', ((), ))]),
 
1027
            set(index.iter_entries([('name', ), ('ref', )])))
 
1028
 
 
1029
    def test_iter_missing_entry_empty(self):
 
1030
        index = CombinedGraphIndex([])
 
1031
        self.assertEqual([], list(index.iter_entries([('a', )])))
 
1032
 
 
1033
    def test_iter_missing_entry_one_index(self):
 
1034
        index1 = self.make_index('1')
 
1035
        index = CombinedGraphIndex([index1])
 
1036
        self.assertEqual([], list(index.iter_entries([('a', )])))
 
1037
 
 
1038
    def test_iter_missing_entry_two_index(self):
 
1039
        index1 = self.make_index('1')
 
1040
        index2 = self.make_index('2')
 
1041
        index = CombinedGraphIndex([index1, index2])
 
1042
        self.assertEqual([], list(index.iter_entries([('a', )])))
 
1043
 
 
1044
    def test_iter_entry_present_one_index_only(self):
 
1045
        index1 = self.make_index('1', nodes=[(('key', ), '', ())])
 
1046
        index2 = self.make_index('2', nodes=[])
 
1047
        index = CombinedGraphIndex([index1, index2])
 
1048
        self.assertEqual([(index1, ('key', ), '')],
 
1049
            list(index.iter_entries([('key', )])))
 
1050
        # and in the other direction
 
1051
        index = CombinedGraphIndex([index2, index1])
 
1052
        self.assertEqual([(index1, ('key', ), '')],
 
1053
            list(index.iter_entries([('key', )])))
 
1054
 
 
1055
    def test_key_count_empty(self):
 
1056
        index1 = self.make_index('1', nodes=[])
 
1057
        index2 = self.make_index('2', nodes=[])
 
1058
        index = CombinedGraphIndex([index1, index2])
 
1059
        self.assertEqual(0, index.key_count())
 
1060
 
 
1061
    def test_key_count_sums_index_keys(self):
 
1062
        index1 = self.make_index('1', nodes=[
 
1063
            (('1',), '', ()),
 
1064
            (('2',), '', ())])
 
1065
        index2 = self.make_index('2', nodes=[(('1',), '', ())])
 
1066
        index = CombinedGraphIndex([index1, index2])
 
1067
        self.assertEqual(3, index.key_count())
 
1068
 
 
1069
    def test_validate_bad_child_index_errors(self):
 
1070
        trans = self.get_transport()
 
1071
        trans.put_bytes('name', "not an index\n")
 
1072
        index1 = GraphIndex(trans, 'name', 13)
 
1073
        index = CombinedGraphIndex([index1])
 
1074
        self.assertRaises(errors.BadIndexFormatSignature, index.validate)
 
1075
 
 
1076
    def test_validate_empty(self):
 
1077
        index = CombinedGraphIndex([])
 
1078
        index.validate()
 
1079
 
 
1080
 
 
1081
class TestInMemoryGraphIndex(TestCaseWithMemoryTransport):
 
1082
 
 
1083
    def make_index(self, ref_lists=0, key_elements=1, nodes=[]):
 
1084
        result = InMemoryGraphIndex(ref_lists, key_elements=key_elements)
 
1085
        result.add_nodes(nodes)
 
1086
        return result
 
1087
 
 
1088
    def test_add_nodes_no_refs(self):
 
1089
        index = self.make_index(0)
 
1090
        index.add_nodes([(('name', ), 'data')])
 
1091
        index.add_nodes([(('name2', ), ''), (('name3', ), '')])
 
1092
        self.assertEqual(set([
 
1093
            (index, ('name', ), 'data'),
 
1094
            (index, ('name2', ), ''),
 
1095
            (index, ('name3', ), ''),
 
1096
            ]), set(index.iter_all_entries()))
 
1097
 
 
1098
    def test_add_nodes(self):
 
1099
        index = self.make_index(1)
 
1100
        index.add_nodes([(('name', ), 'data', ([],))])
 
1101
        index.add_nodes([(('name2', ), '', ([],)), (('name3', ), '', ([('r', )],))])
 
1102
        self.assertEqual(set([
 
1103
            (index, ('name', ), 'data', ((),)),
 
1104
            (index, ('name2', ), '', ((),)),
 
1105
            (index, ('name3', ), '', ((('r', ), ), )),
 
1106
            ]), set(index.iter_all_entries()))
 
1107
 
 
1108
    def test_iter_all_entries_empty(self):
 
1109
        index = self.make_index()
 
1110
        self.assertEqual([], list(index.iter_all_entries()))
 
1111
 
 
1112
    def test_iter_all_entries_simple(self):
 
1113
        index = self.make_index(nodes=[(('name', ), 'data')])
 
1114
        self.assertEqual([(index, ('name', ), 'data')],
 
1115
            list(index.iter_all_entries()))
 
1116
 
 
1117
    def test_iter_all_entries_references(self):
 
1118
        index = self.make_index(1, nodes=[
 
1119
            (('name', ), 'data', ([('ref', )], )),
 
1120
            (('ref', ), 'refdata', ([], ))])
 
1121
        self.assertEqual(set([(index, ('name', ), 'data', ((('ref', ),),)),
 
1122
            (index, ('ref', ), 'refdata', ((), ))]),
 
1123
            set(index.iter_all_entries()))
 
1124
 
 
1125
    def test_iteration_absent_skipped(self):
 
1126
        index = self.make_index(1, nodes=[
 
1127
            (('name', ), 'data', ([('ref', )], ))])
 
1128
        self.assertEqual(set([(index, ('name', ), 'data', ((('ref',),),))]),
 
1129
            set(index.iter_all_entries()))
 
1130
        self.assertEqual(set([(index, ('name', ), 'data', ((('ref',),),))]),
 
1131
            set(index.iter_entries([('name', )])))
 
1132
        self.assertEqual([], list(index.iter_entries([('ref', )])))
 
1133
 
 
1134
    def test_iter_all_keys(self):
 
1135
        index = self.make_index(1, nodes=[
 
1136
            (('name', ), 'data', ([('ref', )], )),
 
1137
            (('ref', ), 'refdata', ([], ))])
 
1138
        self.assertEqual(set([(index, ('name', ), 'data', ((('ref',),),)),
 
1139
            (index, ('ref', ), 'refdata', ((), ))]),
 
1140
            set(index.iter_entries([('name', ), ('ref', )])))
 
1141
 
 
1142
    def test_iter_key_prefix_1_key_element_no_refs(self):
 
1143
        index = self.make_index( nodes=[
 
1144
            (('name', ), 'data'),
 
1145
            (('ref', ), 'refdata')])
 
1146
        self.assertEqual(set([(index, ('name', ), 'data'),
 
1147
            (index, ('ref', ), 'refdata')]),
 
1148
            set(index.iter_entries_prefix([('name', ), ('ref', )])))
 
1149
 
 
1150
    def test_iter_key_prefix_1_key_element_refs(self):
 
1151
        index = self.make_index(1, nodes=[
 
1152
            (('name', ), 'data', ([('ref', )], )),
 
1153
            (('ref', ), 'refdata', ([], ))])
 
1154
        self.assertEqual(set([(index, ('name', ), 'data', ((('ref',),),)),
 
1155
            (index, ('ref', ), 'refdata', ((), ))]),
 
1156
            set(index.iter_entries_prefix([('name', ), ('ref', )])))
 
1157
 
 
1158
    def test_iter_key_prefix_2_key_element_no_refs(self):
 
1159
        index = self.make_index(key_elements=2, nodes=[
 
1160
            (('name', 'fin1'), 'data'),
 
1161
            (('name', 'fin2'), 'beta'),
 
1162
            (('ref', 'erence'), 'refdata')])
 
1163
        self.assertEqual(set([(index, ('name', 'fin1'), 'data'),
 
1164
            (index, ('ref', 'erence'), 'refdata')]),
 
1165
            set(index.iter_entries_prefix([('name', 'fin1'), ('ref', 'erence')])))
 
1166
        self.assertEqual(set([(index, ('name', 'fin1'), 'data'),
 
1167
            (index, ('name', 'fin2'), 'beta')]),
 
1168
            set(index.iter_entries_prefix([('name', None)])))
 
1169
 
 
1170
    def test_iter_key_prefix_2_key_element_refs(self):
 
1171
        index = self.make_index(1, key_elements=2, nodes=[
 
1172
            (('name', 'fin1'), 'data', ([('ref', 'erence')], )),
 
1173
            (('name', 'fin2'), 'beta', ([], )),
 
1174
            (('ref', 'erence'), 'refdata', ([], ))])
 
1175
        self.assertEqual(set([(index, ('name', 'fin1'), 'data', ((('ref', 'erence'),),)),
 
1176
            (index, ('ref', 'erence'), 'refdata', ((), ))]),
 
1177
            set(index.iter_entries_prefix([('name', 'fin1'), ('ref', 'erence')])))
 
1178
        self.assertEqual(set([(index, ('name', 'fin1'), 'data', ((('ref', 'erence'),),)),
 
1179
            (index, ('name', 'fin2'), 'beta', ((), ))]),
 
1180
            set(index.iter_entries_prefix([('name', None)])))
 
1181
 
 
1182
    def test_iter_nothing_empty(self):
 
1183
        index = self.make_index()
 
1184
        self.assertEqual([], list(index.iter_entries([])))
 
1185
 
 
1186
    def test_iter_missing_entry_empty(self):
 
1187
        index = self.make_index()
 
1188
        self.assertEqual([], list(index.iter_entries(['a'])))
 
1189
 
 
1190
    def test_key_count_empty(self):
 
1191
        index = self.make_index()
 
1192
        self.assertEqual(0, index.key_count())
 
1193
 
 
1194
    def test_key_count_one(self):
 
1195
        index = self.make_index(nodes=[(('name', ), '')])
 
1196
        self.assertEqual(1, index.key_count())
 
1197
 
 
1198
    def test_key_count_two(self):
 
1199
        index = self.make_index(nodes=[(('name', ), ''), (('foo', ), '')])
 
1200
        self.assertEqual(2, index.key_count())
 
1201
 
 
1202
    def test_validate_empty(self):
 
1203
        index = self.make_index()
 
1204
        index.validate()
 
1205
 
 
1206
    def test_validate_no_refs_content(self):
 
1207
        index = self.make_index(nodes=[(('key', ), 'value')])
 
1208
        index.validate()
 
1209
 
 
1210
 
 
1211
class TestGraphIndexPrefixAdapter(TestCaseWithMemoryTransport):
 
1212
 
 
1213
    def make_index(self, ref_lists=1, key_elements=2, nodes=[], add_callback=False):
 
1214
        result = InMemoryGraphIndex(ref_lists, key_elements=key_elements)
 
1215
        result.add_nodes(nodes)
 
1216
        if add_callback:
 
1217
            add_nodes_callback = result.add_nodes
 
1218
        else:
 
1219
            add_nodes_callback = None
 
1220
        adapter = GraphIndexPrefixAdapter(result, ('prefix', ), key_elements - 1,
 
1221
            add_nodes_callback=add_nodes_callback)
 
1222
        return result, adapter
 
1223
 
 
1224
    def test_add_node(self):
 
1225
        index, adapter = self.make_index(add_callback=True)
 
1226
        adapter.add_node(('key',), 'value', ((('ref',),),))
 
1227
        self.assertEqual(set([(index, ('prefix', 'key'), 'value', ((('prefix', 'ref'),),))]),
 
1228
            set(index.iter_all_entries()))
 
1229
 
 
1230
    def test_add_nodes(self):
 
1231
        index, adapter = self.make_index(add_callback=True)
 
1232
        adapter.add_nodes((
 
1233
            (('key',), 'value', ((('ref',),),)),
 
1234
            (('key2',), 'value2', ((),)),
 
1235
            ))
 
1236
        self.assertEqual(set([
 
1237
            (index, ('prefix', 'key2'), 'value2', ((),)),
 
1238
            (index, ('prefix', 'key'), 'value', ((('prefix', 'ref'),),))
 
1239
            ]),
 
1240
            set(index.iter_all_entries()))
 
1241
 
 
1242
    def test_construct(self):
 
1243
        index = InMemoryGraphIndex()
 
1244
        adapter = GraphIndexPrefixAdapter(index, ('prefix', ), 1)
 
1245
 
 
1246
    def test_construct_with_callback(self):
 
1247
        index = InMemoryGraphIndex()
 
1248
        adapter = GraphIndexPrefixAdapter(index, ('prefix', ), 1, index.add_nodes)
 
1249
 
 
1250
    def test_iter_all_entries_cross_prefix_map_errors(self):
 
1251
        index, adapter = self.make_index(nodes=[
 
1252
            (('prefix', 'key1'), 'data1', ((('prefixaltered', 'key2'),),))])
 
1253
        self.assertRaises(errors.BadIndexData, list, adapter.iter_all_entries())
 
1254
 
 
1255
    def test_iter_all_entries(self):
 
1256
        index, adapter = self.make_index(nodes=[
 
1257
            (('notprefix', 'key1'), 'data', ((), )),
 
1258
            (('prefix', 'key1'), 'data1', ((), )),
 
1259
            (('prefix', 'key2'), 'data2', ((('prefix', 'key1'),),))])
 
1260
        self.assertEqual(set([(index, ('key1', ), 'data1', ((),)),
 
1261
            (index, ('key2', ), 'data2', ((('key1',),),))]),
 
1262
            set(adapter.iter_all_entries()))
 
1263
 
 
1264
    def test_iter_entries(self):
 
1265
        index, adapter = self.make_index(nodes=[
 
1266
            (('notprefix', 'key1'), 'data', ((), )),
 
1267
            (('prefix', 'key1'), 'data1', ((), )),
 
1268
            (('prefix', 'key2'), 'data2', ((('prefix', 'key1'),),))])
 
1269
        # ask for many - get all
 
1270
        self.assertEqual(set([(index, ('key1', ), 'data1', ((),)),
 
1271
            (index, ('key2', ), 'data2', ((('key1', ),),))]),
 
1272
            set(adapter.iter_entries([('key1', ), ('key2', )])))
 
1273
        # ask for one, get one
 
1274
        self.assertEqual(set([(index, ('key1', ), 'data1', ((),))]),
 
1275
            set(adapter.iter_entries([('key1', )])))
 
1276
        # ask for missing, get none
 
1277
        self.assertEqual(set(),
 
1278
            set(adapter.iter_entries([('key3', )])))
 
1279
 
 
1280
    def test_iter_entries_prefix(self):
 
1281
        index, adapter = self.make_index(key_elements=3, nodes=[
 
1282
            (('notprefix', 'foo', 'key1'), 'data', ((), )),
 
1283
            (('prefix', 'prefix2', 'key1'), 'data1', ((), )),
 
1284
            (('prefix', 'prefix2', 'key2'), 'data2', ((('prefix', 'prefix2', 'key1'),),))])
 
1285
        # ask for a prefix, get the results for just that prefix, adjusted.
 
1286
        self.assertEqual(set([(index, ('prefix2', 'key1', ), 'data1', ((),)),
 
1287
            (index, ('prefix2', 'key2', ), 'data2', ((('prefix2', 'key1', ),),))]),
 
1288
            set(adapter.iter_entries_prefix([('prefix2', None)])))
 
1289
 
 
1290
    def test_key_count_no_matching_keys(self):
 
1291
        index, adapter = self.make_index(nodes=[
 
1292
            (('notprefix', 'key1'), 'data', ((), ))])
 
1293
        self.assertEqual(0, adapter.key_count())
 
1294
 
 
1295
    def test_key_count_some_keys(self):
 
1296
        index, adapter = self.make_index(nodes=[
 
1297
            (('notprefix', 'key1'), 'data', ((), )),
 
1298
            (('prefix', 'key1'), 'data1', ((), )),
 
1299
            (('prefix', 'key2'), 'data2', ((('prefix', 'key1'),),))])
 
1300
        self.assertEqual(2, adapter.key_count())
 
1301
 
 
1302
    def test_validate(self):
 
1303
        index, adapter = self.make_index()
 
1304
        calls = []
 
1305
        def validate():
 
1306
            calls.append('called')
 
1307
        index.validate = validate
 
1308
        adapter.validate()
 
1309
        self.assertEqual(['called'], calls)