/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
2490.2.5 by Aaron Bentley
Use GraphWalker.unique_ancestor to determine merge base
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
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2490.2.5 by Aaron Bentley
Use GraphWalker.unique_ancestor to determine merge base
16
2490.2.28 by Aaron Bentley
Fix handling of null revision
17
from bzrlib import (
18
    errors,
2653.2.1 by Aaron Bentley
Implement Graph.is_ancestor
19
    graph as _mod_graph,
3099.3.3 by John Arbash Meinel
Deprecate get_parents() in favor of get_parent_map()
20
    symbol_versioning,
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
21
    tests,
2490.2.28 by Aaron Bentley
Fix handling of null revision
22
    )
2490.2.1 by Aaron Bentley
Start work on GraphWalker
23
from bzrlib.revision import NULL_REVISION
24
from bzrlib.tests import TestCaseWithMemoryTransport
25
2490.2.25 by Aaron Bentley
Update from review
26
27
# Ancestry 1:
28
#
29
#  NULL_REVISION
30
#       |
31
#     rev1
32
#      /\
33
#  rev2a rev2b
34
#     |    |
35
#   rev3  /
36
#     |  /
37
#   rev4
2490.2.2 by Aaron Bentley
add minimal-common-ancestor calculation
38
ancestry_1 = {'rev1': [NULL_REVISION], 'rev2a': ['rev1'], 'rev2b': ['rev1'],
39
              'rev3': ['rev2a'], 'rev4': ['rev3', 'rev2b']}
2490.2.25 by Aaron Bentley
Update from review
40
41
42
# Ancestry 2:
43
#
44
#  NULL_REVISION
45
#    /    \
46
# rev1a  rev1b
47
#   |
48
# rev2a
49
#   |
50
# rev3a
51
#   |
52
# rev4a
2490.2.4 by Aaron Bentley
More tests for unique common ancestor
53
ancestry_2 = {'rev1a': [NULL_REVISION], 'rev2a': ['rev1a'],
54
              'rev1b': [NULL_REVISION], 'rev3a': ['rev2a'], 'rev4a': ['rev3a']}
2490.2.2 by Aaron Bentley
add minimal-common-ancestor calculation
55
2490.2.25 by Aaron Bentley
Update from review
56
57
# Criss cross ancestry
58
#
59
#     NULL_REVISION
60
#         |
61
#        rev1
62
#        /  \
63
#    rev2a  rev2b
64
#       |\  /|
65
#       |  X |
66
#       |/  \|
67
#    rev3a  rev3b
2490.2.3 by Aaron Bentley
Implement new merge base picker
68
criss_cross = {'rev1': [NULL_REVISION], 'rev2a': ['rev1'], 'rev2b': ['rev1'],
69
               'rev3a': ['rev2a', 'rev2b'], 'rev3b': ['rev2b', 'rev2a']}
70
2490.2.25 by Aaron Bentley
Update from review
71
72
# Criss-cross 2
73
#
74
#  NULL_REVISION
75
#    /   \
76
# rev1a  rev1b
77
#   |\   /|
78
#   | \ / |
79
#   |  X  |
80
#   | / \ |
81
#   |/   \|
82
# rev2a  rev2b
2490.2.4 by Aaron Bentley
More tests for unique common ancestor
83
criss_cross2 = {'rev1a': [NULL_REVISION], 'rev1b': [NULL_REVISION],
84
                'rev2a': ['rev1a', 'rev1b'], 'rev2b': ['rev1b', 'rev1a']}
85
2490.2.25 by Aaron Bentley
Update from review
86
87
# Mainline:
88
#
89
#  NULL_REVISION
90
#       |
91
#      rev1
92
#      /  \
93
#      | rev2b
94
#      |  /
95
#     rev2a
2490.2.6 by Aaron Bentley
Use new common-ancestor code everywhere
96
mainline = {'rev1': [NULL_REVISION], 'rev2a': ['rev1', 'rev2b'],
97
            'rev2b': ['rev1']}
98
2490.2.25 by Aaron Bentley
Update from review
99
100
# feature branch:
101
#
102
#  NULL_REVISION
103
#       |
104
#      rev1
105
#       |
106
#     rev2b
107
#       |
108
#     rev3b
2490.2.6 by Aaron Bentley
Use new common-ancestor code everywhere
109
feature_branch = {'rev1': [NULL_REVISION],
110
                  'rev2b': ['rev1'], 'rev3b': ['rev2b']}
111
2490.2.25 by Aaron Bentley
Update from review
112
113
# History shortcut
114
#  NULL_REVISION
115
#       |
116
#     rev1------
117
#     /  \      \
118
#  rev2a rev2b rev2c
119
#    |  /   \   /
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
120
#  rev3a    rev3b
2490.2.9 by Aaron Bentley
Fix minimal common ancestor algorithm for non-minimal perhipheral ancestors
121
history_shortcut = {'rev1': [NULL_REVISION], 'rev2a': ['rev1'],
122
                    'rev2b': ['rev1'], 'rev2c': ['rev1'],
123
                    'rev3a': ['rev2a', 'rev2b'], 'rev3b': ['rev2b', 'rev2c']}
124
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
125
# Extended history shortcut
126
#  NULL_REVISION
127
#       |
128
#       a
129
#       |\
130
#       b |
131
#       | |
132
#       c |
133
#       | |
134
#       d |
135
#       |\|
136
#       e f
137
extended_history_shortcut = {'a': [NULL_REVISION],
138
                             'b': ['a'],
139
                             'c': ['b'],
140
                             'd': ['c'],
141
                             'e': ['d'],
142
                             'f': ['a', 'd'],
143
                            }
144
145
# Double shortcut
146
# Both sides will see 'A' first, even though it is actually a decendent of a
147
# different common revision.
148
#
149
#  NULL_REVISION
150
#       |
151
#       a
152
#      /|\
153
#     / b \
154
#    /  |  \
155
#   |   c   |
156
#   |  / \  |
157
#   | d   e |
158
#   |/     \|
159
#   f       g
160
161
double_shortcut = {'a':[NULL_REVISION], 'b':['a'], 'c':['b'],
162
                   'd':['c'], 'e':['c'], 'f':['a', 'd'],
163
                   'g':['a', 'e']}
164
165
# Complex shortcut
166
# This has a failure mode in that a shortcut will find some nodes in common,
3377.3.37 by John Arbash Meinel
Ian's first review comments.
167
# but the common searcher won't have time to find that one branch is actually
3377.3.1 by John Arbash Meinel
Bring in some of the changes from graph_update and graph_optimization
168
# in common. The extra nodes at the beginning are because we want to avoid
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
169
# walking off the graph. Specifically, node G should be considered common, but
170
# is likely to be seen by M long before the common searcher finds it.
171
#
172
# NULL_REVISION
173
#     |
174
#     a
175
#     |
176
#     b
177
#     |
178
#     c
179
#     |
180
#     d
181
#     |\
182
#     e f
183
#     | |\
3377.3.1 by John Arbash Meinel
Bring in some of the changes from graph_update and graph_optimization
184
#     | g h
185
#     |/| |
186
#     i j |
187
#     | | |
188
#     | k |
189
#     | | |
190
#     | l |
191
#     |/|/
192
#     m n
193
complex_shortcut = {'a':[NULL_REVISION], 'b':['a'], 'c':['b'], 'd':['c'],
194
                    'e':['d'], 'f':['d'], 'g':['f'], 'h':['f'],
195
                    'i':['e', 'g'], 'j':['g'], 'k':['j'],
196
                    'l':['k'], 'm':['i', 'l'], 'n':['l', 'h']}
197
198
# NULL_REVISION
199
#     |
200
#     a
201
#     |
202
#     b
203
#     |
204
#     c
205
#     |
206
#     d
207
#     |\
3377.3.13 by John Arbash Meinel
Change _search_for_extra_common slightly.
208
#     e |
209
#     | |
210
#     f |
211
#     | |
212
#     g h
3377.3.1 by John Arbash Meinel
Bring in some of the changes from graph_update and graph_optimization
213
#     | |\
3377.3.13 by John Arbash Meinel
Change _search_for_extra_common slightly.
214
#     i | j
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
215
#     |\| |
216
#     | k |
217
#     | | |
218
#     | l |
3377.3.13 by John Arbash Meinel
Change _search_for_extra_common slightly.
219
#     | | |
220
#     | m |
221
#     | | |
222
#     | n |
223
#     | | |
224
#     | o |
225
#     | | |
226
#     | p |
227
#     | | |
228
#     | q |
229
#     | | |
230
#     | r |
231
#     | | |
232
#     | s |
233
#     | | |
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
234
#     |/|/
3377.3.13 by John Arbash Meinel
Change _search_for_extra_common slightly.
235
#     t u
236
complex_shortcut2 = {'a':[NULL_REVISION], 'b':['a'], 'c':['b'], 'd':['c'],
3377.3.43 by John Arbash Meinel
Ian's review feedback
237
                    'e':['d'], 'f':['e'], 'g':['f'], 'h':['d'], 'i':['g'],
238
                    'j':['h'], 'k':['h', 'i'], 'l':['k'], 'm':['l'], 'n':['m'],
239
                    'o':['n'], 'p':['o'], 'q':['p'], 'r':['q'], 's':['r'],
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
240
                    't':['i', 's'], 'u':['s', 'j'],
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
241
                    }
242
3377.3.36 by John Arbash Meinel
Small updates, try to write a test for the race condition.
243
# Graph where different walkers will race to find the common and uncommon
244
# nodes.
245
#
246
# NULL_REVISION
247
#     |
248
#     a
249
#     |
250
#     b
251
#     |
252
#     c
253
#     |
254
#     d
255
#     |\
256
#     e k
257
#     | |
258
#     f-+-p
259
#     | | |
260
#     | l |
261
#     | | |
262
#     | m |
263
#     | |\|
264
#     g n q
265
#     |\| |
266
#     h o |
267
#     |/| |
268
#     i r |
269
#     | | |
270
#     | s |
271
#     | | |
272
#     | t |
273
#     | | |
274
#     | u |
275
#     | | |
276
#     | v |
277
#     | | |
278
#     | w |
279
#     | | |
280
#     | x |
281
#     | |\|
282
#     | y z
283
#     |/
284
#     j
285
#
3377.4.2 by John Arbash Meinel
Merge in the bzr.dev changes
286
# x is found to be common right away, but is the start of a long series of
3377.3.36 by John Arbash Meinel
Small updates, try to write a test for the race condition.
287
# common commits.
288
# o is actually common, but the i-j shortcut makes it look like it is actually
3377.4.2 by John Arbash Meinel
Merge in the bzr.dev changes
289
# unique to j at first, you have to traverse all of x->o to find it.
290
# q,m gives the walker from j a common point to stop searching, as does p,f.
3377.3.36 by John Arbash Meinel
Small updates, try to write a test for the race condition.
291
# k-n exists so that the second pass still has nodes that are worth searching,
292
# rather than instantly cancelling the extra walker.
293
294
racing_shortcuts = {'a':[NULL_REVISION], 'b':['a'], 'c':['b'], 'd':['c'],
295
    'e':['d'], 'f':['e'], 'g':['f'], 'h':['g'], 'i':['h', 'o'], 'j':['i', 'y'],
296
    'k':['d'], 'l':['k'], 'm':['l'], 'n':['m'], 'o':['n', 'g'], 'p':['f'],
297
    'q':['p', 'm'], 'r':['o'], 's':['r'], 't':['s'], 'u':['t'], 'v':['u'],
298
    'w':['v'], 'x':['w'], 'y':['x'], 'z':['x', 'q']}
299
3377.3.35 by John Arbash Meinel
Add a test that exercises the multiple interesting unique code
300
301
# A graph with multiple nodes unique to one side.
302
#
303
# NULL_REVISION
304
#     |
305
#     a
306
#     |
307
#     b
308
#     |
309
#     c
310
#     |
311
#     d
312
#     |\
313
#     e f
314
#     |\ \
315
#     g h i
316
#     |\ \ \
317
#     j k l m
318
#     | |/ x|
319
#     | n o p
320
#     | |/  |
321
#     | q   |
322
#     | |   |
323
#     | r   |
324
#     | |   |
325
#     | s   |
326
#     | |   |
327
#     | t   |
328
#     | |   |
329
#     | u   |
330
#     | |   |
331
#     | v   |
332
#     | |   |
333
#     | w   |
334
#     | |   |
335
#     | x   |
336
#     |/ \ /
337
#     y   z
338
#
339
340
multiple_interesting_unique = {'a':[NULL_REVISION], 'b':['a'], 'c':['b'],
341
    'd':['c'], 'e':['d'], 'f':['d'], 'g':['e'], 'h':['e'], 'i':['f'],
342
    'j':['g'], 'k':['g'], 'l':['h'], 'm':['i'], 'n':['k', 'l'],
343
    'o':['m'], 'p':['m', 'l'], 'q':['n', 'o'], 'r':['q'], 's':['r'],
344
    't':['s'], 'u':['t'], 'v':['u'], 'w':['v'], 'x':['w'],
345
    'y':['j', 'x'], 'z':['x', 'p']}
346
347
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
348
# Shortcut with extra root
349
# We have a long history shortcut, and an extra root, which is why we can't
350
# stop searchers based on seeing NULL_REVISION
351
#  NULL_REVISION
352
#       |   |
353
#       a   |
354
#       |\  |
355
#       b | |
356
#       | | |
357
#       c | |
358
#       | | |
359
#       d | g
360
#       |\|/
361
#       e f
362
shortcut_extra_root = {'a': [NULL_REVISION],
363
                       'b': ['a'],
364
                       'c': ['b'],
365
                       'd': ['c'],
366
                       'e': ['d'],
367
                       'f': ['a', 'd', 'g'],
368
                       'g': [NULL_REVISION],
369
                      }
370
2653.2.1 by Aaron Bentley
Implement Graph.is_ancestor
371
#  NULL_REVISION
372
#       |
373
#       f
374
#       |
375
#       e
376
#      / \
377
#     b   d
378
#     | \ |
379
#     a   c
380
381
boundary = {'a': ['b'], 'c': ['b', 'd'], 'b':['e'], 'd':['e'], 'e': ['f'],
382
            'f':[NULL_REVISION]}
383
384
3228.4.2 by John Arbash Meinel
Add a Graph.iter_ancestry()
385
# A graph that contains a ghost
386
#  NULL_REVISION
387
#       |
388
#       f
389
#       |
390
#       e   g
391
#      / \ /
392
#     b   d
393
#     | \ |
394
#     a   c
395
396
with_ghost = {'a': ['b'], 'c': ['b', 'd'], 'b':['e'], 'd':['e', 'g'],
3228.4.10 by John Arbash Meinel
Respond to abentley's review comments.
397
              'e': ['f'], 'f':[NULL_REVISION], NULL_REVISION:()}
3228.4.2 by John Arbash Meinel
Add a Graph.iter_ancestry()
398
3445.1.3 by John Arbash Meinel
Search from all of the known revisions.
399
# A graph that shows we can shortcut finding revnos when reaching them from the
400
# side.
401
#  NULL_REVISION
402
#       |
403
#       a
404
#       |
405
#       b
406
#       |
407
#       c
408
#       |
409
#       d
410
#       |
411
#       e
412
#      / \
413
#     f   g
414
#     |
415
#     h
416
#     |
417
#     i
418
419
with_tail = {'a':[NULL_REVISION], 'b':['a'], 'c':['b'], 'd':['c'], 'e':['d'],
420
             'f':['e'], 'g':['e'], 'h':['f'], 'i':['h']}
3228.4.2 by John Arbash Meinel
Add a Graph.iter_ancestry()
421
422
2653.2.1 by Aaron Bentley
Implement Graph.is_ancestor
423
class InstrumentedParentsProvider(object):
424
425
    def __init__(self, parents_provider):
426
        self.calls = []
427
        self._real_parents_provider = parents_provider
428
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
429
    def get_parent_map(self, nodes):
430
        self.calls.extend(nodes)
431
        return self._real_parents_provider.get_parent_map(nodes)
432
2490.2.25 by Aaron Bentley
Update from review
433
3445.1.2 by John Arbash Meinel
Handle when a known revision is an ancestor.
434
class TestGraphBase(tests.TestCase):
435
436
    def make_graph(self, ancestors):
437
        return _mod_graph.Graph(_mod_graph.DictParentsProvider(ancestors))
438
439
    def make_breaking_graph(self, ancestors, break_on):
440
        """Make a Graph that raises an exception if we hit a node."""
441
        g = self.make_graph(ancestors)
442
        orig_parent_map = g.get_parent_map
443
        def get_parent_map(keys):
444
            bad_keys = set(keys).intersection(break_on)
445
            if bad_keys:
446
                self.fail('key(s) %s was accessed' % (sorted(bad_keys),))
447
            return orig_parent_map(keys)
448
        g.get_parent_map = get_parent_map
449
        return g
450
451
2490.2.31 by Aaron Bentley
Fix iter_topo_order to permit un-included parents
452
class TestGraph(TestCaseWithMemoryTransport):
2490.2.1 by Aaron Bentley
Start work on GraphWalker
453
2490.2.21 by Aaron Bentley
Rename graph to deprecated_graph
454
    def make_graph(self, ancestors):
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
455
        return _mod_graph.Graph(_mod_graph.DictParentsProvider(ancestors))
2490.2.3 by Aaron Bentley
Implement new merge base picker
456
2490.2.6 by Aaron Bentley
Use new common-ancestor code everywhere
457
    def prepare_memory_tree(self, location):
458
        tree = self.make_branch_and_memory_tree(location)
2490.2.1 by Aaron Bentley
Start work on GraphWalker
459
        tree.lock_write()
460
        tree.add('.')
2490.2.6 by Aaron Bentley
Use new common-ancestor code everywhere
461
        return tree
462
463
    def build_ancestry(self, tree, ancestors):
2490.2.25 by Aaron Bentley
Update from review
464
        """Create an ancestry as specified by a graph dict
465
466
        :param tree: A tree to use
467
        :param ancestors: a dict of {node: [node_parent, ...]}
468
        """
2490.2.1 by Aaron Bentley
Start work on GraphWalker
469
        pending = [NULL_REVISION]
470
        descendants = {}
471
        for descendant, parents in ancestors.iteritems():
472
            for parent in parents:
473
                descendants.setdefault(parent, []).append(descendant)
474
        while len(pending) > 0:
475
            cur_node = pending.pop()
476
            for descendant in descendants.get(cur_node, []):
2490.2.3 by Aaron Bentley
Implement new merge base picker
477
                if tree.branch.repository.has_revision(descendant):
478
                    continue
2490.2.1 by Aaron Bentley
Start work on GraphWalker
479
                parents = [p for p in ancestors[descendant] if p is not
480
                           NULL_REVISION]
481
                if len([p for p in parents if not
482
                    tree.branch.repository.has_revision(p)]) > 0:
483
                    continue
484
                tree.set_parent_ids(parents)
2490.2.3 by Aaron Bentley
Implement new merge base picker
485
                if len(parents) > 0:
486
                    left_parent = parents[0]
487
                else:
488
                    left_parent = NULL_REVISION
2490.2.1 by Aaron Bentley
Start work on GraphWalker
489
                tree.branch.set_last_revision_info(
2490.2.3 by Aaron Bentley
Implement new merge base picker
490
                    len(tree.branch._lefthand_history(left_parent)),
491
                    left_parent)
2490.2.1 by Aaron Bentley
Start work on GraphWalker
492
                tree.commit(descendant, rev_id=descendant)
493
                pending.append(descendant)
2490.2.2 by Aaron Bentley
add minimal-common-ancestor calculation
494
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
495
    def test_lca(self):
2490.2.25 by Aaron Bentley
Update from review
496
        """Test finding least common ancestor.
2490.2.3 by Aaron Bentley
Implement new merge base picker
497
498
        ancestry_1 should always have a single common ancestor
499
        """
2490.2.21 by Aaron Bentley
Rename graph to deprecated_graph
500
        graph = self.make_graph(ancestry_1)
2490.2.28 by Aaron Bentley
Fix handling of null revision
501
        self.assertRaises(errors.InvalidRevisionId, graph.find_lca, None)
2490.2.21 by Aaron Bentley
Rename graph to deprecated_graph
502
        self.assertEqual(set([NULL_REVISION]),
503
                         graph.find_lca(NULL_REVISION, NULL_REVISION))
504
        self.assertEqual(set([NULL_REVISION]),
505
                         graph.find_lca(NULL_REVISION, 'rev1'))
506
        self.assertEqual(set(['rev1']), graph.find_lca('rev1', 'rev1'))
507
        self.assertEqual(set(['rev1']), graph.find_lca('rev2a', 'rev2b'))
2490.2.3 by Aaron Bentley
Implement new merge base picker
508
2520.4.104 by Aaron Bentley
Avoid infinite loop when there is no unique lca
509
    def test_no_unique_lca(self):
510
        """Test error when one revision is not in the graph"""
511
        graph = self.make_graph(ancestry_1)
512
        self.assertRaises(errors.NoCommonAncestor, graph.find_unique_lca,
513
                          'rev1', '1rev')
514
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
515
    def test_lca_criss_cross(self):
2490.2.25 by Aaron Bentley
Update from review
516
        """Test least-common-ancestor after a criss-cross merge."""
2490.2.21 by Aaron Bentley
Rename graph to deprecated_graph
517
        graph = self.make_graph(criss_cross)
2490.2.3 by Aaron Bentley
Implement new merge base picker
518
        self.assertEqual(set(['rev2a', 'rev2b']),
2490.2.21 by Aaron Bentley
Rename graph to deprecated_graph
519
                         graph.find_lca('rev3a', 'rev3b'))
2490.2.3 by Aaron Bentley
Implement new merge base picker
520
        self.assertEqual(set(['rev2b']),
2490.2.25 by Aaron Bentley
Update from review
521
                         graph.find_lca('rev3a', 'rev3b', 'rev2b'))
2490.2.3 by Aaron Bentley
Implement new merge base picker
522
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
523
    def test_lca_shortcut(self):
2490.2.25 by Aaron Bentley
Update from review
524
        """Test least-common ancestor on this history shortcut"""
2490.2.21 by Aaron Bentley
Rename graph to deprecated_graph
525
        graph = self.make_graph(history_shortcut)
526
        self.assertEqual(set(['rev2b']), graph.find_lca('rev3a', 'rev3b'))
2490.2.9 by Aaron Bentley
Fix minimal common ancestor algorithm for non-minimal perhipheral ancestors
527
4332.3.4 by Robert Collins
Add a graph API for getting multiple distances to NULL at once.
528
    def test_lefthand_distance_smoke(self):
529
        """A simple does it work test for graph.lefthand_distance(keys)."""
530
        graph = self.make_graph(history_shortcut)
531
        distance_graph = graph.find_lefthand_distances(['rev3b', 'rev2a'])
532
        self.assertEqual({'rev2a': 2, 'rev3b': 3}, distance_graph)
533
4332.3.6 by Robert Collins
Teach graph.find_lefthand_distances about ghosts.
534
    def test_lefthand_distance_ghosts(self):
535
        """A simple does it work test for graph.lefthand_distance(keys)."""
536
        nodes = {'nonghost':[NULL_REVISION], 'toghost':['ghost']}
537
        graph = self.make_graph(nodes)
538
        distance_graph = graph.find_lefthand_distances(['nonghost', 'toghost'])
539
        self.assertEqual({'nonghost': 1, 'toghost': -1}, distance_graph)
540
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
541
    def test_recursive_unique_lca(self):
2490.2.25 by Aaron Bentley
Update from review
542
        """Test finding a unique least common ancestor.
2490.2.3 by Aaron Bentley
Implement new merge base picker
543
544
        ancestry_1 should always have a single common ancestor
545
        """
2490.2.21 by Aaron Bentley
Rename graph to deprecated_graph
546
        graph = self.make_graph(ancestry_1)
547
        self.assertEqual(NULL_REVISION,
548
                         graph.find_unique_lca(NULL_REVISION, NULL_REVISION))
549
        self.assertEqual(NULL_REVISION,
550
                         graph.find_unique_lca(NULL_REVISION, 'rev1'))
551
        self.assertEqual('rev1', graph.find_unique_lca('rev1', 'rev1'))
552
        self.assertEqual('rev1', graph.find_unique_lca('rev2a', 'rev2b'))
1551.19.10 by Aaron Bentley
Merge now warns when it encounters a criss-cross
553
        self.assertEqual(('rev1', 1,),
554
                         graph.find_unique_lca('rev2a', 'rev2b',
555
                         count_steps=True))
2490.2.3 by Aaron Bentley
Implement new merge base picker
556
3377.3.1 by John Arbash Meinel
Bring in some of the changes from graph_update and graph_optimization
557
    def assertRemoveDescendants(self, expected, graph, revisions):
558
        parents = graph.get_parent_map(revisions)
559
        self.assertEqual(expected,
560
                         graph._remove_simple_descendants(revisions, parents))
561
562
    def test__remove_simple_descendants(self):
563
        graph = self.make_graph(ancestry_1)
564
        self.assertRemoveDescendants(set(['rev1']), graph,
565
            set(['rev1', 'rev2a', 'rev2b', 'rev3', 'rev4']))
566
567
    def test__remove_simple_descendants_disjoint(self):
568
        graph = self.make_graph(ancestry_1)
569
        self.assertRemoveDescendants(set(['rev1', 'rev3']), graph,
570
            set(['rev1', 'rev3']))
571
572
    def test__remove_simple_descendants_chain(self):
573
        graph = self.make_graph(ancestry_1)
574
        self.assertRemoveDescendants(set(['rev1']), graph,
575
            set(['rev1', 'rev2a', 'rev3']))
576
577
    def test__remove_simple_descendants_siblings(self):
578
        graph = self.make_graph(ancestry_1)
579
        self.assertRemoveDescendants(set(['rev2a', 'rev2b']), graph,
580
            set(['rev2a', 'rev2b', 'rev3']))
581
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
582
    def test_unique_lca_criss_cross(self):
583
        """Ensure we don't pick non-unique lcas in a criss-cross"""
2490.2.21 by Aaron Bentley
Rename graph to deprecated_graph
584
        graph = self.make_graph(criss_cross)
585
        self.assertEqual('rev1', graph.find_unique_lca('rev3a', 'rev3b'))
1551.19.10 by Aaron Bentley
Merge now warns when it encounters a criss-cross
586
        lca, steps = graph.find_unique_lca('rev3a', 'rev3b', count_steps=True)
587
        self.assertEqual('rev1', lca)
588
        self.assertEqual(2, steps)
2490.2.4 by Aaron Bentley
More tests for unique common ancestor
589
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
590
    def test_unique_lca_null_revision(self):
2490.2.4 by Aaron Bentley
More tests for unique common ancestor
591
        """Ensure we pick NULL_REVISION when necessary"""
2490.2.21 by Aaron Bentley
Rename graph to deprecated_graph
592
        graph = self.make_graph(criss_cross2)
593
        self.assertEqual('rev1b', graph.find_unique_lca('rev2a', 'rev1b'))
2490.2.4 by Aaron Bentley
More tests for unique common ancestor
594
        self.assertEqual(NULL_REVISION,
2490.2.21 by Aaron Bentley
Rename graph to deprecated_graph
595
                         graph.find_unique_lca('rev2a', 'rev2b'))
2490.2.4 by Aaron Bentley
More tests for unique common ancestor
596
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
597
    def test_unique_lca_null_revision2(self):
2490.2.4 by Aaron Bentley
More tests for unique common ancestor
598
        """Ensure we pick NULL_REVISION when necessary"""
2490.2.21 by Aaron Bentley
Rename graph to deprecated_graph
599
        graph = self.make_graph(ancestry_2)
2490.2.4 by Aaron Bentley
More tests for unique common ancestor
600
        self.assertEqual(NULL_REVISION,
2490.2.21 by Aaron Bentley
Rename graph to deprecated_graph
601
                         graph.find_unique_lca('rev4a', 'rev1b'))
2490.2.6 by Aaron Bentley
Use new common-ancestor code everywhere
602
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
603
    def test_lca_double_shortcut(self):
604
        graph = self.make_graph(double_shortcut)
605
        self.assertEqual('c', graph.find_unique_lca('f', 'g'))
606
2490.2.6 by Aaron Bentley
Use new common-ancestor code everywhere
607
    def test_common_ancestor_two_repos(self):
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
608
        """Ensure we do unique_lca using data from two repos"""
2490.2.6 by Aaron Bentley
Use new common-ancestor code everywhere
609
        mainline_tree = self.prepare_memory_tree('mainline')
610
        self.build_ancestry(mainline_tree, mainline)
3010.1.6 by Robert Collins
Locking in test_graph.
611
        self.addCleanup(mainline_tree.unlock)
2490.2.6 by Aaron Bentley
Use new common-ancestor code everywhere
612
613
        # This is cheating, because the revisions in the graph are actually
614
        # different revisions, despite having the same revision-id.
615
        feature_tree = self.prepare_memory_tree('feature')
616
        self.build_ancestry(feature_tree, feature_branch)
3010.1.6 by Robert Collins
Locking in test_graph.
617
        self.addCleanup(feature_tree.unlock)
618
2490.2.21 by Aaron Bentley
Rename graph to deprecated_graph
619
        graph = mainline_tree.branch.repository.get_graph(
2490.2.6 by Aaron Bentley
Use new common-ancestor code everywhere
620
            feature_tree.branch.repository)
2490.2.21 by Aaron Bentley
Rename graph to deprecated_graph
621
        self.assertEqual('rev2b', graph.find_unique_lca('rev2a', 'rev3b'))
2490.2.23 by Aaron Bentley
Adapt find_borders to produce a graph difference
622
623
    def test_graph_difference(self):
624
        graph = self.make_graph(ancestry_1)
625
        self.assertEqual((set(), set()), graph.find_difference('rev1', 'rev1'))
626
        self.assertEqual((set(), set(['rev1'])),
627
                         graph.find_difference(NULL_REVISION, 'rev1'))
628
        self.assertEqual((set(['rev1']), set()),
629
                         graph.find_difference('rev1', NULL_REVISION))
630
        self.assertEqual((set(['rev2a', 'rev3']), set(['rev2b'])),
631
                         graph.find_difference('rev3', 'rev2b'))
632
        self.assertEqual((set(['rev4', 'rev3', 'rev2a']), set()),
633
                         graph.find_difference('rev4', 'rev2b'))
634
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
635
    def test_graph_difference_separate_ancestry(self):
636
        graph = self.make_graph(ancestry_2)
637
        self.assertEqual((set(['rev1a']), set(['rev1b'])),
638
                         graph.find_difference('rev1a', 'rev1b'))
639
        self.assertEqual((set(['rev1a', 'rev2a', 'rev3a', 'rev4a']),
640
                          set(['rev1b'])),
641
                         graph.find_difference('rev4a', 'rev1b'))
642
2490.2.23 by Aaron Bentley
Adapt find_borders to produce a graph difference
643
    def test_graph_difference_criss_cross(self):
644
        graph = self.make_graph(criss_cross)
645
        self.assertEqual((set(['rev3a']), set(['rev3b'])),
646
                         graph.find_difference('rev3a', 'rev3b'))
647
        self.assertEqual((set([]), set(['rev3b', 'rev2b'])),
648
                         graph.find_difference('rev2a', 'rev3b'))
2490.2.25 by Aaron Bentley
Update from review
649
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
650
    def test_graph_difference_extended_history(self):
651
        graph = self.make_graph(extended_history_shortcut)
652
        self.assertEqual((set(['e']), set(['f'])),
653
                         graph.find_difference('e', 'f'))
654
        self.assertEqual((set(['f']), set(['e'])),
655
                         graph.find_difference('f', 'e'))
656
657
    def test_graph_difference_double_shortcut(self):
658
        graph = self.make_graph(double_shortcut)
659
        self.assertEqual((set(['d', 'f']), set(['e', 'g'])),
660
                         graph.find_difference('f', 'g'))
661
662
    def test_graph_difference_complex_shortcut(self):
663
        graph = self.make_graph(complex_shortcut)
3377.3.1 by John Arbash Meinel
Bring in some of the changes from graph_update and graph_optimization
664
        self.assertEqual((set(['m', 'i', 'e']), set(['n', 'h'])),
665
                         graph.find_difference('m', 'n'))
666
667
    def test_graph_difference_complex_shortcut2(self):
668
        graph = self.make_graph(complex_shortcut2)
3377.3.13 by John Arbash Meinel
Change _search_for_extra_common slightly.
669
        self.assertEqual((set(['t']), set(['j', 'u'])),
670
                         graph.find_difference('t', 'u'))
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
671
672
    def test_graph_difference_shortcut_extra_root(self):
673
        graph = self.make_graph(shortcut_extra_root)
674
        self.assertEqual((set(['e']), set(['f', 'g'])),
675
                         graph.find_difference('e', 'f'))
676
3099.3.3 by John Arbash Meinel
Deprecate get_parents() in favor of get_parent_map()
677
    def test_stacked_parents_provider(self):
678
        parents1 = _mod_graph.DictParentsProvider({'rev2': ['rev3']})
679
        parents2 = _mod_graph.DictParentsProvider({'rev1': ['rev4']})
680
        stacked = _mod_graph._StackedParentsProvider([parents1, parents2])
681
        self.assertEqual({'rev1':['rev4'], 'rev2':['rev3']},
682
                         stacked.get_parent_map(['rev1', 'rev2']))
683
        self.assertEqual({'rev2':['rev3'], 'rev1':['rev4']},
684
                         stacked.get_parent_map(['rev2', 'rev1']))
685
        self.assertEqual({'rev2':['rev3']},
686
                         stacked.get_parent_map(['rev2', 'rev2']))
687
        self.assertEqual({'rev1':['rev4']},
688
                         stacked.get_parent_map(['rev1', 'rev1']))
2490.2.30 by Aaron Bentley
Add functionality for tsorting graphs
689
2490.2.31 by Aaron Bentley
Fix iter_topo_order to permit un-included parents
690
    def test_iter_topo_order(self):
2490.2.30 by Aaron Bentley
Add functionality for tsorting graphs
691
        graph = self.make_graph(ancestry_1)
692
        args = ['rev2a', 'rev3', 'rev1']
2490.2.31 by Aaron Bentley
Fix iter_topo_order to permit un-included parents
693
        topo_args = list(graph.iter_topo_order(args))
2490.2.30 by Aaron Bentley
Add functionality for tsorting graphs
694
        self.assertEqual(set(args), set(topo_args))
695
        self.assertTrue(topo_args.index('rev2a') > topo_args.index('rev1'))
696
        self.assertTrue(topo_args.index('rev2a') < topo_args.index('rev3'))
2653.2.1 by Aaron Bentley
Implement Graph.is_ancestor
697
698
    def test_is_ancestor(self):
699
        graph = self.make_graph(ancestry_1)
2653.2.3 by Aaron Bentley
correctly handle Graph.is_ancestor(x, x)
700
        self.assertEqual(True, graph.is_ancestor('null:', 'null:'))
2653.2.1 by Aaron Bentley
Implement Graph.is_ancestor
701
        self.assertEqual(True, graph.is_ancestor('null:', 'rev1'))
702
        self.assertEqual(False, graph.is_ancestor('rev1', 'null:'))
703
        self.assertEqual(True, graph.is_ancestor('null:', 'rev4'))
704
        self.assertEqual(False, graph.is_ancestor('rev4', 'null:'))
705
        self.assertEqual(False, graph.is_ancestor('rev4', 'rev2b'))
706
        self.assertEqual(True, graph.is_ancestor('rev2b', 'rev4'))
707
        self.assertEqual(False, graph.is_ancestor('rev2b', 'rev3'))
708
        self.assertEqual(False, graph.is_ancestor('rev3', 'rev2b'))
709
        instrumented_provider = InstrumentedParentsProvider(graph)
710
        instrumented_graph = _mod_graph.Graph(instrumented_provider)
711
        instrumented_graph.is_ancestor('rev2a', 'rev2b')
712
        self.assertTrue('null:' not in instrumented_provider.calls)
713
3921.3.5 by Marius Kruger
extract graph.is_between from builtins.cmd_tags.run, and test it
714
    def test_is_between(self):
715
        graph = self.make_graph(ancestry_1)
716
        self.assertEqual(True, graph.is_between('null:', 'null:', 'null:'))
717
        self.assertEqual(True, graph.is_between('rev1', 'null:', 'rev1'))
718
        self.assertEqual(True, graph.is_between('rev1', 'rev1', 'rev4'))
719
        self.assertEqual(True, graph.is_between('rev4', 'rev1', 'rev4'))
720
        self.assertEqual(True, graph.is_between('rev3', 'rev1', 'rev4'))
721
        self.assertEqual(False, graph.is_between('rev4', 'rev1', 'rev3'))
722
        self.assertEqual(False, graph.is_between('rev1', 'rev2a', 'rev4'))
723
        self.assertEqual(False, graph.is_between('null:', 'rev1', 'rev4'))
724
2653.2.1 by Aaron Bentley
Implement Graph.is_ancestor
725
    def test_is_ancestor_boundary(self):
726
        """Ensure that we avoid searching the whole graph.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
727
2653.2.1 by Aaron Bentley
Implement Graph.is_ancestor
728
        This requires searching through b as a common ancestor, so we
729
        can identify that e is common.
730
        """
731
        graph = self.make_graph(boundary)
732
        instrumented_provider = InstrumentedParentsProvider(graph)
733
        graph = _mod_graph.Graph(instrumented_provider)
734
        self.assertFalse(graph.is_ancestor('a', 'c'))
735
        self.assertTrue('null:' not in instrumented_provider.calls)
1551.15.78 by Aaron Bentley
Fix KeyError in filter_candidate_lca
736
3228.4.2 by John Arbash Meinel
Add a Graph.iter_ancestry()
737
    def test_iter_ancestry(self):
3228.4.10 by John Arbash Meinel
Respond to abentley's review comments.
738
        nodes = boundary.copy()
739
        nodes[NULL_REVISION] = ()
740
        graph = self.make_graph(nodes)
741
        expected = nodes.copy()
3228.4.2 by John Arbash Meinel
Add a Graph.iter_ancestry()
742
        expected.pop('a') # 'a' is not in the ancestry of 'c', all the
743
                          # other nodes are
3228.4.4 by John Arbash Meinel
Change iter_ancestry to take a group instead of a single node,
744
        self.assertEqual(expected, dict(graph.iter_ancestry(['c'])))
3228.4.10 by John Arbash Meinel
Respond to abentley's review comments.
745
        self.assertEqual(nodes, dict(graph.iter_ancestry(['a', 'c'])))
3228.4.2 by John Arbash Meinel
Add a Graph.iter_ancestry()
746
747
    def test_iter_ancestry_with_ghost(self):
748
        graph = self.make_graph(with_ghost)
749
        expected = with_ghost.copy()
750
        # 'a' is not in the ancestry of 'c', and 'g' is a ghost
3228.4.10 by John Arbash Meinel
Respond to abentley's review comments.
751
        expected['g'] = None
3228.4.4 by John Arbash Meinel
Change iter_ancestry to take a group instead of a single node,
752
        self.assertEqual(expected, dict(graph.iter_ancestry(['a', 'c'])))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
753
        expected.pop('a')
3228.4.4 by John Arbash Meinel
Change iter_ancestry to take a group instead of a single node,
754
        self.assertEqual(expected, dict(graph.iter_ancestry(['c'])))
3228.4.2 by John Arbash Meinel
Add a Graph.iter_ancestry()
755
1551.15.78 by Aaron Bentley
Fix KeyError in filter_candidate_lca
756
    def test_filter_candidate_lca(self):
757
        """Test filter_candidate_lca for a corner case
758
1551.15.83 by Aaron Bentley
Update test documentation
759
        This tests the case where we encounter the end of iteration for 'e'
760
        in the same pass as we discover that 'd' is an ancestor of 'e', and
761
        therefore 'e' can't be an lca.
762
763
        To compensate for different dict orderings on other Python
764
        implementations, we mirror 'd' and 'e' with 'b' and 'a'.
1551.15.78 by Aaron Bentley
Fix KeyError in filter_candidate_lca
765
        """
766
        # This test is sensitive to the iteration order of dicts.  It will
1551.15.82 by Aaron Bentley
Add symmetrical alternative to test case
767
        # pass incorrectly if 'e' and 'a' sort before 'c'
1551.15.84 by Aaron Bentley
Add ancestry graph for test case
768
        #
769
        # NULL_REVISION
770
        #     / \
771
        #    a   e
772
        #    |   |
773
        #    b   d
774
        #     \ /
775
        #      c
1551.15.82 by Aaron Bentley
Add symmetrical alternative to test case
776
        graph = self.make_graph({'c': ['b', 'd'], 'd': ['e'], 'b': ['a'],
777
                                 'a': [NULL_REVISION], 'e': [NULL_REVISION]})
2776.1.4 by Robert Collins
Trivial review feedback changes.
778
        self.assertEqual(set(['c']), graph.heads(['a', 'c', 'e']))
779
780
    def test_heads_null(self):
781
        graph = self.make_graph(ancestry_1)
782
        self.assertEqual(set(['null:']), graph.heads(['null:']))
783
        self.assertEqual(set(['rev1']), graph.heads(['null:', 'rev1']))
784
        self.assertEqual(set(['rev1']), graph.heads(['rev1', 'null:']))
785
        self.assertEqual(set(['rev1']), graph.heads(set(['rev1', 'null:'])))
786
        self.assertEqual(set(['rev1']), graph.heads(('rev1', 'null:')))
787
788
    def test_heads_one(self):
3052.5.5 by John Arbash Meinel
Special case Graph.heads() for NULL_REVISION rather than is_ancestor.
789
        # A single node will always be a head
2776.1.4 by Robert Collins
Trivial review feedback changes.
790
        graph = self.make_graph(ancestry_1)
791
        self.assertEqual(set(['null:']), graph.heads(['null:']))
792
        self.assertEqual(set(['rev1']), graph.heads(['rev1']))
793
        self.assertEqual(set(['rev2a']), graph.heads(['rev2a']))
794
        self.assertEqual(set(['rev2b']), graph.heads(['rev2b']))
795
        self.assertEqual(set(['rev3']), graph.heads(['rev3']))
796
        self.assertEqual(set(['rev4']), graph.heads(['rev4']))
797
798
    def test_heads_single(self):
799
        graph = self.make_graph(ancestry_1)
800
        self.assertEqual(set(['rev4']), graph.heads(['null:', 'rev4']))
801
        self.assertEqual(set(['rev2a']), graph.heads(['rev1', 'rev2a']))
802
        self.assertEqual(set(['rev2b']), graph.heads(['rev1', 'rev2b']))
803
        self.assertEqual(set(['rev3']), graph.heads(['rev1', 'rev3']))
804
        self.assertEqual(set(['rev4']), graph.heads(['rev1', 'rev4']))
805
        self.assertEqual(set(['rev4']), graph.heads(['rev2a', 'rev4']))
806
        self.assertEqual(set(['rev4']), graph.heads(['rev2b', 'rev4']))
807
        self.assertEqual(set(['rev4']), graph.heads(['rev3', 'rev4']))
808
809
    def test_heads_two_heads(self):
810
        graph = self.make_graph(ancestry_1)
811
        self.assertEqual(set(['rev2a', 'rev2b']),
812
                         graph.heads(['rev2a', 'rev2b']))
813
        self.assertEqual(set(['rev3', 'rev2b']),
814
                         graph.heads(['rev3', 'rev2b']))
815
816
    def test_heads_criss_cross(self):
817
        graph = self.make_graph(criss_cross)
818
        self.assertEqual(set(['rev2a']),
819
                         graph.heads(['rev2a', 'rev1']))
820
        self.assertEqual(set(['rev2b']),
821
                         graph.heads(['rev2b', 'rev1']))
822
        self.assertEqual(set(['rev3a']),
823
                         graph.heads(['rev3a', 'rev1']))
824
        self.assertEqual(set(['rev3b']),
825
                         graph.heads(['rev3b', 'rev1']))
826
        self.assertEqual(set(['rev2a', 'rev2b']),
827
                         graph.heads(['rev2a', 'rev2b']))
828
        self.assertEqual(set(['rev3a']),
829
                         graph.heads(['rev3a', 'rev2a']))
830
        self.assertEqual(set(['rev3a']),
831
                         graph.heads(['rev3a', 'rev2b']))
832
        self.assertEqual(set(['rev3a']),
833
                         graph.heads(['rev3a', 'rev2a', 'rev2b']))
834
        self.assertEqual(set(['rev3b']),
835
                         graph.heads(['rev3b', 'rev2a']))
836
        self.assertEqual(set(['rev3b']),
837
                         graph.heads(['rev3b', 'rev2b']))
838
        self.assertEqual(set(['rev3b']),
839
                         graph.heads(['rev3b', 'rev2a', 'rev2b']))
840
        self.assertEqual(set(['rev3a', 'rev3b']),
841
                         graph.heads(['rev3a', 'rev3b']))
842
        self.assertEqual(set(['rev3a', 'rev3b']),
843
                         graph.heads(['rev3a', 'rev3b', 'rev2a', 'rev2b']))
844
845
    def test_heads_shortcut(self):
846
        graph = self.make_graph(history_shortcut)
847
848
        self.assertEqual(set(['rev2a', 'rev2b', 'rev2c']),
849
                         graph.heads(['rev2a', 'rev2b', 'rev2c']))
850
        self.assertEqual(set(['rev3a', 'rev3b']),
851
                         graph.heads(['rev3a', 'rev3b']))
852
        self.assertEqual(set(['rev3a', 'rev3b']),
853
                         graph.heads(['rev2a', 'rev3a', 'rev3b']))
854
        self.assertEqual(set(['rev2a', 'rev3b']),
855
                         graph.heads(['rev2a', 'rev3b']))
856
        self.assertEqual(set(['rev2c', 'rev3a']),
857
                         graph.heads(['rev2c', 'rev3a']))
2921.3.1 by Robert Collins
* Graph ``heads()`` queries have been bugfixed to no longer access all
858
859
    def _run_heads_break_deeper(self, graph_dict, search):
860
        """Run heads on a graph-as-a-dict.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
861
2921.3.1 by Robert Collins
* Graph ``heads()`` queries have been bugfixed to no longer access all
862
        If the search asks for the parents of 'deeper' the test will fail.
863
        """
864
        class stub(object):
865
            pass
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
866
        def get_parent_map(keys):
867
            result = {}
868
            for key in keys:
869
                if key == 'deeper':
870
                    self.fail('key deeper was accessed')
871
                result[key] = graph_dict[key]
872
            return result
2921.3.1 by Robert Collins
* Graph ``heads()`` queries have been bugfixed to no longer access all
873
        an_obj = stub()
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
874
        an_obj.get_parent_map = get_parent_map
2921.3.1 by Robert Collins
* Graph ``heads()`` queries have been bugfixed to no longer access all
875
        graph = _mod_graph.Graph(an_obj)
876
        return graph.heads(search)
877
878
    def test_heads_limits_search(self):
879
        # test that a heads query does not search all of history
880
        graph_dict = {
881
            'left':['common'],
882
            'right':['common'],
883
            'common':['deeper'],
884
        }
885
        self.assertEqual(set(['left', 'right']),
886
            self._run_heads_break_deeper(graph_dict, ['left', 'right']))
887
888
    def test_heads_limits_search_assymetric(self):
889
        # test that a heads query does not search all of history
890
        graph_dict = {
891
            'left':['midleft'],
892
            'midleft':['common'],
893
            'right':['common'],
894
            'common':['aftercommon'],
895
            'aftercommon':['deeper'],
896
        }
897
        self.assertEqual(set(['left', 'right']),
898
            self._run_heads_break_deeper(graph_dict, ['left', 'right']))
899
900
    def test_heads_limits_search_common_search_must_continue(self):
901
        # test that common nodes are still queried, preventing
902
        # all-the-way-to-origin behaviour in the following graph:
903
        graph_dict = {
904
            'h1':['shortcut', 'common1'],
905
            'h2':['common1'],
906
            'shortcut':['common2'],
907
            'common1':['common2'],
908
            'common2':['deeper'],
909
        }
910
        self.assertEqual(set(['h1', 'h2']),
911
            self._run_heads_break_deeper(graph_dict, ['h1', 'h2']))
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
912
3177.3.1 by Robert Collins
* New method ``next_with_ghosts`` on the Graph breadth-first-search objects
913
    def test_breadth_first_search_start_ghosts(self):
3184.1.1 by Robert Collins
Add basic get_recipe to the graph breadth first searcher.
914
        graph = self.make_graph({})
3177.3.1 by Robert Collins
* New method ``next_with_ghosts`` on the Graph breadth-first-search objects
915
        # with_ghosts reports the ghosts
916
        search = graph._make_breadth_first_searcher(['a-ghost'])
917
        self.assertEqual((set(), set(['a-ghost'])), search.next_with_ghosts())
918
        self.assertRaises(StopIteration, search.next_with_ghosts)
919
        # next includes them
920
        search = graph._make_breadth_first_searcher(['a-ghost'])
921
        self.assertEqual(set(['a-ghost']), search.next())
922
        self.assertRaises(StopIteration, search.next)
923
924
    def test_breadth_first_search_deep_ghosts(self):
3184.1.1 by Robert Collins
Add basic get_recipe to the graph breadth first searcher.
925
        graph = self.make_graph({
3177.3.1 by Robert Collins
* New method ``next_with_ghosts`` on the Graph breadth-first-search objects
926
            'head':['present'],
927
            'present':['child', 'ghost'],
928
            'child':[],
3184.1.1 by Robert Collins
Add basic get_recipe to the graph breadth first searcher.
929
            })
3177.3.1 by Robert Collins
* New method ``next_with_ghosts`` on the Graph breadth-first-search objects
930
        # with_ghosts reports the ghosts
931
        search = graph._make_breadth_first_searcher(['head'])
932
        self.assertEqual((set(['head']), set()), search.next_with_ghosts())
933
        self.assertEqual((set(['present']), set()), search.next_with_ghosts())
934
        self.assertEqual((set(['child']), set(['ghost'])),
935
            search.next_with_ghosts())
936
        self.assertRaises(StopIteration, search.next_with_ghosts)
937
        # next includes them
938
        search = graph._make_breadth_first_searcher(['head'])
939
        self.assertEqual(set(['head']), search.next())
940
        self.assertEqual(set(['present']), search.next())
941
        self.assertEqual(set(['child', 'ghost']),
942
            search.next())
943
        self.assertRaises(StopIteration, search.next)
944
945
    def test_breadth_first_search_change_next_to_next_with_ghosts(self):
3177.3.3 by Robert Collins
Review feedback.
946
        # To make the API robust, we allow calling both next() and
947
        # next_with_ghosts() on the same searcher.
3184.1.1 by Robert Collins
Add basic get_recipe to the graph breadth first searcher.
948
        graph = self.make_graph({
3177.3.1 by Robert Collins
* New method ``next_with_ghosts`` on the Graph breadth-first-search objects
949
            'head':['present'],
950
            'present':['child', 'ghost'],
951
            'child':[],
3184.1.1 by Robert Collins
Add basic get_recipe to the graph breadth first searcher.
952
            })
3177.3.3 by Robert Collins
Review feedback.
953
        # start with next_with_ghosts
3177.3.1 by Robert Collins
* New method ``next_with_ghosts`` on the Graph breadth-first-search objects
954
        search = graph._make_breadth_first_searcher(['head'])
955
        self.assertEqual((set(['head']), set()), search.next_with_ghosts())
956
        self.assertEqual(set(['present']), search.next())
957
        self.assertEqual((set(['child']), set(['ghost'])),
958
            search.next_with_ghosts())
959
        self.assertRaises(StopIteration, search.next)
3177.3.3 by Robert Collins
Review feedback.
960
        # start with next
3177.3.1 by Robert Collins
* New method ``next_with_ghosts`` on the Graph breadth-first-search objects
961
        search = graph._make_breadth_first_searcher(['head'])
962
        self.assertEqual(set(['head']), search.next())
963
        self.assertEqual((set(['present']), set()), search.next_with_ghosts())
964
        self.assertEqual(set(['child', 'ghost']),
965
            search.next())
966
        self.assertRaises(StopIteration, search.next_with_ghosts)
967
3177.3.2 by Robert Collins
Update graph searchers stop_searching_any and start_searching for next_with_ghosts.
968
    def test_breadth_first_change_search(self):
3177.3.3 by Robert Collins
Review feedback.
969
        # Changing the search should work with both next and next_with_ghosts.
3184.1.1 by Robert Collins
Add basic get_recipe to the graph breadth first searcher.
970
        graph = self.make_graph({
3177.3.2 by Robert Collins
Update graph searchers stop_searching_any and start_searching for next_with_ghosts.
971
            'head':['present'],
972
            'present':['stopped'],
973
            'other':['other_2'],
974
            'other_2':[],
3184.1.1 by Robert Collins
Add basic get_recipe to the graph breadth first searcher.
975
            })
3177.3.2 by Robert Collins
Update graph searchers stop_searching_any and start_searching for next_with_ghosts.
976
        search = graph._make_breadth_first_searcher(['head'])
977
        self.assertEqual((set(['head']), set()), search.next_with_ghosts())
978
        self.assertEqual((set(['present']), set()), search.next_with_ghosts())
979
        self.assertEqual(set(['present']),
980
            search.stop_searching_any(['present']))
981
        self.assertEqual((set(['other']), set(['other_ghost'])),
982
            search.start_searching(['other', 'other_ghost']))
983
        self.assertEqual((set(['other_2']), set()), search.next_with_ghosts())
984
        self.assertRaises(StopIteration, search.next_with_ghosts)
985
        # next includes them
986
        search = graph._make_breadth_first_searcher(['head'])
987
        self.assertEqual(set(['head']), search.next())
988
        self.assertEqual(set(['present']), search.next())
989
        self.assertEqual(set(['present']),
990
            search.stop_searching_any(['present']))
991
        search.start_searching(['other', 'other_ghost'])
992
        self.assertEqual(set(['other_2']), search.next())
993
        self.assertRaises(StopIteration, search.next)
994
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
995
    def assertSeenAndResult(self, instructions, search, next):
996
        """Check the results of .seen and get_result() for a seach.
3184.1.1 by Robert Collins
Add basic get_recipe to the graph breadth first searcher.
997
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
998
        :param instructions: A list of tuples:
999
            (seen, recipe, included_keys, starts, stops).
1000
            seen, recipe and included_keys are results to check on the search
1001
            and the searches get_result(). starts and stops are parameters to
1002
            pass to start_searching and stop_searching_any during each
1003
            iteration, if they are not None.
3184.1.1 by Robert Collins
Add basic get_recipe to the graph breadth first searcher.
1004
        :param search: The search to use.
1005
        :param next: A callable to advance the search.
1006
        """
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1007
        for seen, recipe, included_keys, starts, stops in instructions:
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
1008
            # Adjust for recipe contract changes that don't vary for all the
1009
            # current tests.
1010
            recipe = ('search',) + recipe
3184.1.1 by Robert Collins
Add basic get_recipe to the graph breadth first searcher.
1011
            next()
3184.1.2 by Robert Collins
Add tests for starting and stopping searches in combination with get_recipe.
1012
            if starts is not None:
1013
                search.start_searching(starts)
1014
            if stops is not None:
1015
                search.stop_searching_any(stops)
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1016
            result = search.get_result()
1017
            self.assertEqual(recipe, result.get_recipe())
1018
            self.assertEqual(set(included_keys), result.get_keys())
3184.1.1 by Robert Collins
Add basic get_recipe to the graph breadth first searcher.
1019
            self.assertEqual(seen, search.seen)
1020
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1021
    def test_breadth_first_get_result_excludes_current_pending(self):
3184.1.1 by Robert Collins
Add basic get_recipe to the graph breadth first searcher.
1022
        graph = self.make_graph({
1023
            'head':['child'],
1024
            'child':[NULL_REVISION],
3184.1.3 by Robert Collins
Automatically exclude ghosts.
1025
            NULL_REVISION:[],
3184.1.1 by Robert Collins
Add basic get_recipe to the graph breadth first searcher.
1026
            })
1027
        search = graph._make_breadth_first_searcher(['head'])
1028
        # At the start, nothing has been seen, to its all excluded:
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1029
        result = search.get_result()
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
1030
        self.assertEqual(('search', set(['head']), set(['head']), 0),
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1031
            result.get_recipe())
1032
        self.assertEqual(set(), result.get_keys())
3184.1.1 by Robert Collins
Add basic get_recipe to the graph breadth first searcher.
1033
        self.assertEqual(set(), search.seen)
1034
        # using next:
1035
        expected = [
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1036
            (set(['head']), (set(['head']), set(['child']), 1),
1037
             ['head'], None, None),
3184.1.5 by Robert Collins
Record the number of found revisions for cross checking.
1038
            (set(['head', 'child']), (set(['head']), set([NULL_REVISION]), 2),
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1039
             ['head', 'child'], None, None),
3184.1.5 by Robert Collins
Record the number of found revisions for cross checking.
1040
            (set(['head', 'child', NULL_REVISION]), (set(['head']), set(), 3),
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1041
             ['head', 'child', NULL_REVISION], None, None),
3184.1.1 by Robert Collins
Add basic get_recipe to the graph breadth first searcher.
1042
            ]
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1043
        self.assertSeenAndResult(expected, search, search.next)
3184.1.1 by Robert Collins
Add basic get_recipe to the graph breadth first searcher.
1044
        # using next_with_ghosts:
1045
        search = graph._make_breadth_first_searcher(['head'])
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1046
        self.assertSeenAndResult(expected, search, search.next_with_ghosts)
3184.1.1 by Robert Collins
Add basic get_recipe to the graph breadth first searcher.
1047
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1048
    def test_breadth_first_get_result_starts_stops(self):
3184.1.2 by Robert Collins
Add tests for starting and stopping searches in combination with get_recipe.
1049
        graph = self.make_graph({
1050
            'head':['child'],
1051
            'child':[NULL_REVISION],
1052
            'otherhead':['otherchild'],
1053
            'otherchild':['excluded'],
1054
            'excluded':[NULL_REVISION],
3184.1.3 by Robert Collins
Automatically exclude ghosts.
1055
            NULL_REVISION:[]
3184.1.2 by Robert Collins
Add tests for starting and stopping searches in combination with get_recipe.
1056
            })
1057
        search = graph._make_breadth_first_searcher([])
1058
        # Starting with nothing and adding a search works:
1059
        search.start_searching(['head'])
3184.1.5 by Robert Collins
Record the number of found revisions for cross checking.
1060
        # head has been seen:
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1061
        result = search.get_result()
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
1062
        self.assertEqual(('search', set(['head']), set(['child']), 1),
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1063
            result.get_recipe())
1064
        self.assertEqual(set(['head']), result.get_keys())
3184.1.2 by Robert Collins
Add tests for starting and stopping searches in combination with get_recipe.
1065
        self.assertEqual(set(['head']), search.seen)
1066
        # using next:
1067
        expected = [
1068
            # stop at child, and start a new search at otherhead:
1069
            # - otherhead counts as seen immediately when start_searching is
1070
            # called.
1071
            (set(['head', 'child', 'otherhead']),
3184.1.5 by Robert Collins
Record the number of found revisions for cross checking.
1072
             (set(['head', 'otherhead']), set(['child', 'otherchild']), 2),
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1073
             ['head', 'otherhead'], ['otherhead'], ['child']),
3184.1.2 by Robert Collins
Add tests for starting and stopping searches in combination with get_recipe.
1074
            (set(['head', 'child', 'otherhead', 'otherchild']),
3184.1.5 by Robert Collins
Record the number of found revisions for cross checking.
1075
             (set(['head', 'otherhead']), set(['child', 'excluded']), 3),
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1076
             ['head', 'otherhead', 'otherchild'], None, None),
3184.1.5 by Robert Collins
Record the number of found revisions for cross checking.
1077
            # stop searching excluded now
3184.1.2 by Robert Collins
Add tests for starting and stopping searches in combination with get_recipe.
1078
            (set(['head', 'child', 'otherhead', 'otherchild', 'excluded']),
3184.1.5 by Robert Collins
Record the number of found revisions for cross checking.
1079
             (set(['head', 'otherhead']), set(['child', 'excluded']), 3),
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1080
             ['head', 'otherhead', 'otherchild'], None, ['excluded']),
3184.1.2 by Robert Collins
Add tests for starting and stopping searches in combination with get_recipe.
1081
            ]
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1082
        self.assertSeenAndResult(expected, search, search.next)
3184.1.2 by Robert Collins
Add tests for starting and stopping searches in combination with get_recipe.
1083
        # using next_with_ghosts:
1084
        search = graph._make_breadth_first_searcher([])
1085
        search.start_searching(['head'])
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1086
        self.assertSeenAndResult(expected, search, search.next_with_ghosts)
3184.1.2 by Robert Collins
Add tests for starting and stopping searches in combination with get_recipe.
1087
3184.2.1 by Robert Collins
Handle stopping ghosts in searches properly.
1088
    def test_breadth_first_stop_searching_not_queried(self):
1089
        # A client should be able to say 'stop node X' even if X has not been
1090
        # returned to the client.
1091
        graph = self.make_graph({
1092
            'head':['child', 'ghost1'],
1093
            'child':[NULL_REVISION],
1094
            NULL_REVISION:[],
1095
            })
1096
        search = graph._make_breadth_first_searcher(['head'])
1097
        expected = [
1098
            # NULL_REVISION and ghost1 have not been returned
4053.2.2 by Andrew Bennetts
Better fix, with test.
1099
            (set(['head']),
1100
             (set(['head']), set(['child', NULL_REVISION, 'ghost1']), 1),
3184.2.1 by Robert Collins
Handle stopping ghosts in searches properly.
1101
             ['head'], None, [NULL_REVISION, 'ghost1']),
1102
            # ghost1 has been returned, NULL_REVISION is to be returned in the
1103
            # next iteration.
1104
            (set(['head', 'child', 'ghost1']),
1105
             (set(['head']), set(['ghost1', NULL_REVISION]), 2),
1106
             ['head', 'child'], None, [NULL_REVISION, 'ghost1']),
1107
            ]
1108
        self.assertSeenAndResult(expected, search, search.next)
1109
        # using next_with_ghosts:
1110
        search = graph._make_breadth_first_searcher(['head'])
1111
        self.assertSeenAndResult(expected, search, search.next_with_ghosts)
1112
3808.1.1 by Andrew Bennetts
Possible fix for bug in new _walk_to_common_revisions.
1113
    def test_breadth_first_stop_searching_late(self):
1114
        # A client should be able to say 'stop node X' and have it excluded
1115
        # from the result even if X was seen in an older iteration of the
1116
        # search.
1117
        graph = self.make_graph({
1118
            'head':['middle'],
1119
            'middle':['child'],
1120
            'child':[NULL_REVISION],
1121
            NULL_REVISION:[],
1122
            })
1123
        search = graph._make_breadth_first_searcher(['head'])
1124
        expected = [
1125
            (set(['head']), (set(['head']), set(['middle']), 1),
1126
             ['head'], None, None),
1127
            (set(['head', 'middle']), (set(['head']), set(['child']), 2),
1128
             ['head', 'middle'], None, None),
1129
            # 'middle' came from the previous iteration, but we don't stop
1130
            # searching it until *after* advancing the searcher.
1131
            (set(['head', 'middle', 'child']),
3808.1.4 by John Arbash Meinel
make _walk_to_common responsible for stopping ancestors
1132
             (set(['head']), set(['middle', 'child']), 1),
3808.1.3 by Andrew Bennetts
Add another test, this one currently failing. Perhaps the current behaviour should be considered ok, rather than a failure?
1133
             ['head'], None, ['middle', 'child']),
1134
            ]
1135
        self.assertSeenAndResult(expected, search, search.next)
1136
        # using next_with_ghosts:
1137
        search = graph._make_breadth_first_searcher(['head'])
1138
        self.assertSeenAndResult(expected, search, search.next_with_ghosts)
1139
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1140
    def test_breadth_first_get_result_ghosts_are_excluded(self):
3184.1.3 by Robert Collins
Automatically exclude ghosts.
1141
        graph = self.make_graph({
1142
            'head':['child', 'ghost'],
1143
            'child':[NULL_REVISION],
1144
            NULL_REVISION:[],
1145
            })
1146
        search = graph._make_breadth_first_searcher(['head'])
1147
        # using next:
1148
        expected = [
1149
            (set(['head']),
3184.1.5 by Robert Collins
Record the number of found revisions for cross checking.
1150
             (set(['head']), set(['ghost', 'child']), 1),
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1151
             ['head'], None, None),
3184.1.3 by Robert Collins
Automatically exclude ghosts.
1152
            (set(['head', 'child', 'ghost']),
3184.1.5 by Robert Collins
Record the number of found revisions for cross checking.
1153
             (set(['head']), set([NULL_REVISION, 'ghost']), 2),
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1154
             ['head', 'child'], None, None),
3184.1.3 by Robert Collins
Automatically exclude ghosts.
1155
            ]
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1156
        self.assertSeenAndResult(expected, search, search.next)
3184.1.3 by Robert Collins
Automatically exclude ghosts.
1157
        # using next_with_ghosts:
1158
        search = graph._make_breadth_first_searcher(['head'])
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1159
        self.assertSeenAndResult(expected, search, search.next_with_ghosts)
3184.1.3 by Robert Collins
Automatically exclude ghosts.
1160
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1161
    def test_breadth_first_get_result_starting_a_ghost_ghost_is_excluded(self):
3184.1.4 by Robert Collins
Correctly exclude ghosts when ghosts are started on an existing search.
1162
        graph = self.make_graph({
1163
            'head':['child'],
1164
            'child':[NULL_REVISION],
1165
            NULL_REVISION:[],
1166
            })
1167
        search = graph._make_breadth_first_searcher(['head'])
1168
        # using next:
1169
        expected = [
1170
            (set(['head', 'ghost']),
3184.1.5 by Robert Collins
Record the number of found revisions for cross checking.
1171
             (set(['head', 'ghost']), set(['child', 'ghost']), 1),
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1172
             ['head'], ['ghost'], None),
3184.1.4 by Robert Collins
Correctly exclude ghosts when ghosts are started on an existing search.
1173
            (set(['head', 'child', 'ghost']),
3184.1.5 by Robert Collins
Record the number of found revisions for cross checking.
1174
             (set(['head', 'ghost']), set([NULL_REVISION, 'ghost']), 2),
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1175
             ['head', 'child'], None, None),
3184.1.5 by Robert Collins
Record the number of found revisions for cross checking.
1176
            ]
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1177
        self.assertSeenAndResult(expected, search, search.next)
3184.1.5 by Robert Collins
Record the number of found revisions for cross checking.
1178
        # using next_with_ghosts:
1179
        search = graph._make_breadth_first_searcher(['head'])
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1180
        self.assertSeenAndResult(expected, search, search.next_with_ghosts)
3184.1.5 by Robert Collins
Record the number of found revisions for cross checking.
1181
1182
    def test_breadth_first_revision_count_includes_NULL_REVISION(self):
1183
        graph = self.make_graph({
1184
            'head':[NULL_REVISION],
1185
            NULL_REVISION:[],
1186
            })
1187
        search = graph._make_breadth_first_searcher(['head'])
1188
        # using next:
1189
        expected = [
1190
            (set(['head']),
1191
             (set(['head']), set([NULL_REVISION]), 1),
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1192
             ['head'], None, None),
3184.1.5 by Robert Collins
Record the number of found revisions for cross checking.
1193
            (set(['head', NULL_REVISION]),
1194
             (set(['head']), set([]), 2),
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1195
             ['head', NULL_REVISION], None, None),
3184.1.5 by Robert Collins
Record the number of found revisions for cross checking.
1196
            ]
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1197
        self.assertSeenAndResult(expected, search, search.next)
3184.1.5 by Robert Collins
Record the number of found revisions for cross checking.
1198
        # using next_with_ghosts:
1199
        search = graph._make_breadth_first_searcher(['head'])
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1200
        self.assertSeenAndResult(expected, search, search.next_with_ghosts)
3184.1.5 by Robert Collins
Record the number of found revisions for cross checking.
1201
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1202
    def test_breadth_first_search_get_result_after_StopIteration(self):
3184.1.5 by Robert Collins
Record the number of found revisions for cross checking.
1203
        # StopIteration should not invalid anything..
1204
        graph = self.make_graph({
1205
            'head':[NULL_REVISION],
1206
            NULL_REVISION:[],
1207
            })
1208
        search = graph._make_breadth_first_searcher(['head'])
1209
        # using next:
1210
        expected = [
1211
            (set(['head']),
1212
             (set(['head']), set([NULL_REVISION]), 1),
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1213
             ['head'], None, None),
3184.1.5 by Robert Collins
Record the number of found revisions for cross checking.
1214
            (set(['head', 'ghost', NULL_REVISION]),
1215
             (set(['head', 'ghost']), set(['ghost']), 2),
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1216
             ['head', NULL_REVISION], ['ghost'], None),
3184.1.5 by Robert Collins
Record the number of found revisions for cross checking.
1217
            ]
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1218
        self.assertSeenAndResult(expected, search, search.next)
3184.1.5 by Robert Collins
Record the number of found revisions for cross checking.
1219
        self.assertRaises(StopIteration, search.next)
1220
        self.assertEqual(set(['head', 'ghost', NULL_REVISION]), search.seen)
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1221
        result = search.get_result()
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
1222
        self.assertEqual(('search', set(['ghost', 'head']), set(['ghost']), 2),
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1223
            result.get_recipe())
1224
        self.assertEqual(set(['head', NULL_REVISION]), result.get_keys())
3184.1.5 by Robert Collins
Record the number of found revisions for cross checking.
1225
        # using next_with_ghosts:
1226
        search = graph._make_breadth_first_searcher(['head'])
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1227
        self.assertSeenAndResult(expected, search, search.next_with_ghosts)
3184.1.5 by Robert Collins
Record the number of found revisions for cross checking.
1228
        self.assertRaises(StopIteration, search.next)
1229
        self.assertEqual(set(['head', 'ghost', NULL_REVISION]), search.seen)
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1230
        result = search.get_result()
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
1231
        self.assertEqual(('search', set(['ghost', 'head']), set(['ghost']), 2),
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
1232
            result.get_recipe())
1233
        self.assertEqual(set(['head', NULL_REVISION]), result.get_keys())
3184.1.4 by Robert Collins
Correctly exclude ghosts when ghosts are started on an existing search.
1234
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
1235
3445.1.2 by John Arbash Meinel
Handle when a known revision is an ancestor.
1236
class TestFindUniqueAncestors(TestGraphBase):
3377.3.24 by John Arbash Meinel
For some reason find_unique_ancestors is much slower than it should be.
1237
3377.3.21 by John Arbash Meinel
Simple brute-force implementation of find_unique_ancestors
1238
    def assertFindUniqueAncestors(self, graph, expected, node, common):
1239
        actual = graph.find_unique_ancestors(node, common)
1240
        self.assertEqual(expected, sorted(actual))
1241
1242
    def test_empty_set(self):
1243
        graph = self.make_graph(ancestry_1)
1244
        self.assertFindUniqueAncestors(graph, [], 'rev1', ['rev1'])
1245
        self.assertFindUniqueAncestors(graph, [], 'rev2b', ['rev2b'])
1246
        self.assertFindUniqueAncestors(graph, [], 'rev3', ['rev1', 'rev3'])
1247
1248
    def test_single_node(self):
1249
        graph = self.make_graph(ancestry_1)
1250
        self.assertFindUniqueAncestors(graph, ['rev2a'], 'rev2a', ['rev1'])
1251
        self.assertFindUniqueAncestors(graph, ['rev2b'], 'rev2b', ['rev1'])
1252
        self.assertFindUniqueAncestors(graph, ['rev3'], 'rev3', ['rev2a'])
1253
3377.3.24 by John Arbash Meinel
For some reason find_unique_ancestors is much slower than it should be.
1254
    def test_minimal_ancestry(self):
1255
        graph = self.make_breaking_graph(extended_history_shortcut,
1256
                                         [NULL_REVISION, 'a', 'b'])
1257
        self.assertFindUniqueAncestors(graph, ['e'], 'e', ['d'])
1258
3377.3.25 by John Arbash Meinel
A few more minimal ancestry checks
1259
        graph = self.make_breaking_graph(extended_history_shortcut,
1260
                                         ['b'])
1261
        self.assertFindUniqueAncestors(graph, ['f'], 'f', ['a', 'd'])
1262
1263
        graph = self.make_breaking_graph(complex_shortcut,
3377.3.27 by John Arbash Meinel
some simple updates
1264
                                         ['a', 'b'])
3377.3.25 by John Arbash Meinel
A few more minimal ancestry checks
1265
        self.assertFindUniqueAncestors(graph, ['h'], 'h', ['i'])
1266
        self.assertFindUniqueAncestors(graph, ['e', 'g', 'i'], 'i', ['h'])
3377.3.27 by John Arbash Meinel
some simple updates
1267
        self.assertFindUniqueAncestors(graph, ['h'], 'h', ['g'])
3377.3.26 by John Arbash Meinel
Found a graph leak.
1268
        self.assertFindUniqueAncestors(graph, ['h'], 'h', ['j'])
1269
3377.3.21 by John Arbash Meinel
Simple brute-force implementation of find_unique_ancestors
1270
    def test_in_ancestry(self):
1271
        graph = self.make_graph(ancestry_1)
1272
        self.assertFindUniqueAncestors(graph, [], 'rev1', ['rev3'])
1273
        self.assertFindUniqueAncestors(graph, [], 'rev2b', ['rev4'])
1274
1275
    def test_multiple_revisions(self):
1276
        graph = self.make_graph(ancestry_1)
1277
        self.assertFindUniqueAncestors(graph,
1278
            ['rev4'], 'rev4', ['rev3', 'rev2b'])
1279
        self.assertFindUniqueAncestors(graph,
1280
            ['rev2a', 'rev3', 'rev4'], 'rev4', ['rev2b'])
1281
3377.3.22 by John Arbash Meinel
include some tests using the complex graphs
1282
    def test_complex_shortcut(self):
1283
        graph = self.make_graph(complex_shortcut)
1284
        self.assertFindUniqueAncestors(graph,
1285
            ['h', 'n'], 'n', ['m'])
1286
        self.assertFindUniqueAncestors(graph,
1287
            ['e', 'i', 'm'], 'm', ['n'])
1288
1289
    def test_complex_shortcut2(self):
1290
        graph = self.make_graph(complex_shortcut2)
1291
        self.assertFindUniqueAncestors(graph,
1292
            ['j', 'u'], 'u', ['t'])
1293
        self.assertFindUniqueAncestors(graph,
1294
            ['t'], 't', ['u'])
1295
3377.3.35 by John Arbash Meinel
Add a test that exercises the multiple interesting unique code
1296
    def test_multiple_interesting_unique(self):
1297
        graph = self.make_graph(multiple_interesting_unique)
1298
        self.assertFindUniqueAncestors(graph,
1299
            ['j', 'y'], 'y', ['z'])
1300
        self.assertFindUniqueAncestors(graph,
1301
            ['p', 'z'], 'z', ['y'])
1302
3377.3.36 by John Arbash Meinel
Small updates, try to write a test for the race condition.
1303
    def test_racing_shortcuts(self):
1304
        graph = self.make_graph(racing_shortcuts)
1305
        self.assertFindUniqueAncestors(graph,
1306
            ['p', 'q', 'z'], 'z', ['y'])
1307
        self.assertFindUniqueAncestors(graph,
1308
            ['h', 'i', 'j', 'y'], 'j', ['z'])
1309
3377.3.21 by John Arbash Meinel
Simple brute-force implementation of find_unique_ancestors
1310
3445.1.4 by John Arbash Meinel
Change the function to be called 'find_distance_to_null'
1311
class TestGraphFindDistanceToNull(TestGraphBase):
3445.1.1 by John Arbash Meinel
Start working on a new Graph api to make finding revision numbers faster.
1312
    """Test an api that should be able to compute a revno"""
1313
3445.1.4 by John Arbash Meinel
Change the function to be called 'find_distance_to_null'
1314
    def assertFindDistance(self, revno, graph, target_id, known_ids):
1315
        """Assert the output of Graph.find_distance_to_null()"""
1316
        actual = graph.find_distance_to_null(target_id, known_ids)
3445.1.1 by John Arbash Meinel
Start working on a new Graph api to make finding revision numbers faster.
1317
        self.assertEqual(revno, actual)
1318
1319
    def test_nothing_known(self):
1320
        graph = self.make_graph(ancestry_1)
3445.1.4 by John Arbash Meinel
Change the function to be called 'find_distance_to_null'
1321
        self.assertFindDistance(0, graph, NULL_REVISION, [])
1322
        self.assertFindDistance(1, graph, 'rev1', [])
1323
        self.assertFindDistance(2, graph, 'rev2a', [])
1324
        self.assertFindDistance(2, graph, 'rev2b', [])
1325
        self.assertFindDistance(3, graph, 'rev3', [])
1326
        self.assertFindDistance(4, graph, 'rev4', [])
3445.1.1 by John Arbash Meinel
Start working on a new Graph api to make finding revision numbers faster.
1327
1328
    def test_rev_is_ghost(self):
1329
        graph = self.make_graph(ancestry_1)
1330
        e = self.assertRaises(errors.GhostRevisionsHaveNoRevno,
3445.1.4 by John Arbash Meinel
Change the function to be called 'find_distance_to_null'
1331
                              graph.find_distance_to_null, 'rev_missing', [])
3445.1.1 by John Arbash Meinel
Start working on a new Graph api to make finding revision numbers faster.
1332
        self.assertEqual('rev_missing', e.revision_id)
1333
        self.assertEqual('rev_missing', e.ghost_revision_id)
1334
1335
    def test_ancestor_is_ghost(self):
1336
        graph = self.make_graph({'rev':['parent']})
1337
        e = self.assertRaises(errors.GhostRevisionsHaveNoRevno,
3445.1.4 by John Arbash Meinel
Change the function to be called 'find_distance_to_null'
1338
                              graph.find_distance_to_null, 'rev', [])
3445.1.1 by John Arbash Meinel
Start working on a new Graph api to make finding revision numbers faster.
1339
        self.assertEqual('rev', e.revision_id)
1340
        self.assertEqual('parent', e.ghost_revision_id)
1341
3445.1.2 by John Arbash Meinel
Handle when a known revision is an ancestor.
1342
    def test_known_in_ancestry(self):
1343
        graph = self.make_graph(ancestry_1)
3445.1.4 by John Arbash Meinel
Change the function to be called 'find_distance_to_null'
1344
        self.assertFindDistance(2, graph, 'rev2a', [('rev1', 1)])
1345
        self.assertFindDistance(3, graph, 'rev3', [('rev2a', 2)])
3445.1.2 by John Arbash Meinel
Handle when a known revision is an ancestor.
1346
1347
    def test_known_in_ancestry_limits(self):
3445.1.3 by John Arbash Meinel
Search from all of the known revisions.
1348
        graph = self.make_breaking_graph(ancestry_1, ['rev1'])
3445.1.4 by John Arbash Meinel
Change the function to be called 'find_distance_to_null'
1349
        self.assertFindDistance(4, graph, 'rev4', [('rev3', 3)])
3445.1.2 by John Arbash Meinel
Handle when a known revision is an ancestor.
1350
3445.1.3 by John Arbash Meinel
Search from all of the known revisions.
1351
    def test_target_is_ancestor(self):
1352
        graph = self.make_graph(ancestry_1)
3445.1.4 by John Arbash Meinel
Change the function to be called 'find_distance_to_null'
1353
        self.assertFindDistance(2, graph, 'rev2a', [('rev3', 3)])
3445.1.3 by John Arbash Meinel
Search from all of the known revisions.
1354
1355
    def test_target_is_ancestor_limits(self):
1356
        """We shouldn't search all history if we run into ourselves"""
1357
        graph = self.make_breaking_graph(ancestry_1, ['rev1'])
3445.1.4 by John Arbash Meinel
Change the function to be called 'find_distance_to_null'
1358
        self.assertFindDistance(3, graph, 'rev3', [('rev4', 4)])
3445.1.3 by John Arbash Meinel
Search from all of the known revisions.
1359
1360
    def test_target_parallel_to_known_limits(self):
3445.1.8 by John Arbash Meinel
Clarity tweaks recommended by Ian
1361
        # Even though the known revision isn't part of the other ancestry, they
3445.1.3 by John Arbash Meinel
Search from all of the known revisions.
1362
        # eventually converge
1363
        graph = self.make_breaking_graph(with_tail, ['a'])
3445.1.4 by John Arbash Meinel
Change the function to be called 'find_distance_to_null'
1364
        self.assertFindDistance(6, graph, 'f', [('g', 6)])
1365
        self.assertFindDistance(7, graph, 'h', [('g', 6)])
1366
        self.assertFindDistance(8, graph, 'i', [('g', 6)])
1367
        self.assertFindDistance(6, graph, 'g', [('i', 8)])
3445.1.3 by John Arbash Meinel
Search from all of the known revisions.
1368
3445.1.1 by John Arbash Meinel
Start working on a new Graph api to make finding revision numbers faster.
1369
3514.2.8 by John Arbash Meinel
The insertion ordering into the weave has an impact on conflicts.
1370
class TestFindMergeOrder(TestGraphBase):
1371
1372
    def assertMergeOrder(self, expected, graph, tip, base_revisions):
1373
        self.assertEqual(expected, graph.find_merge_order(tip, base_revisions))
1374
1375
    def test_parents(self):
1376
        graph = self.make_graph(ancestry_1)
1377
        self.assertMergeOrder(['rev3', 'rev2b'], graph, 'rev4',
1378
                                                        ['rev3', 'rev2b'])
1379
        self.assertMergeOrder(['rev3', 'rev2b'], graph, 'rev4',
1380
                                                        ['rev2b', 'rev3'])
1381
1382
    def test_ancestors(self):
1383
        graph = self.make_graph(ancestry_1)
1384
        self.assertMergeOrder(['rev1', 'rev2b'], graph, 'rev4',
1385
                                                        ['rev1', 'rev2b'])
1386
        self.assertMergeOrder(['rev1', 'rev2b'], graph, 'rev4',
1387
                                                        ['rev2b', 'rev1'])
1388
1389
    def test_shortcut_one_ancestor(self):
1390
        # When we have enough info, we can stop searching
1391
        graph = self.make_breaking_graph(ancestry_1, ['rev3', 'rev2b', 'rev4'])
1392
        # Single ancestors shortcut right away
1393
        self.assertMergeOrder(['rev3'], graph, 'rev4', ['rev3'])
1394
1395
    def test_shortcut_after_one_ancestor(self):
1396
        graph = self.make_breaking_graph(ancestry_1, ['rev2a', 'rev2b'])
1397
        self.assertMergeOrder(['rev3', 'rev1'], graph, 'rev4', ['rev1', 'rev3'])
1398
1399
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
1400
class TestCachingParentsProvider(tests.TestCase):
4190.1.1 by Robert Collins
Negatively cache misses during read-locks in RemoteRepository.
1401
    """These tests run with:
1402
1403
    self.inst_pp, a recording parents provider with a graph of a->b, and b is a
1404
    ghost.
1405
    self.caching_pp, a CachingParentsProvider layered on inst_pp.
1406
    """
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
1407
1408
    def setUp(self):
1409
        super(TestCachingParentsProvider, self).setUp()
1410
        dict_pp = _mod_graph.DictParentsProvider({'a':('b',)})
1411
        self.inst_pp = InstrumentedParentsProvider(dict_pp)
1412
        self.caching_pp = _mod_graph.CachingParentsProvider(self.inst_pp)
1413
3099.3.3 by John Arbash Meinel
Deprecate get_parents() in favor of get_parent_map()
1414
    def test_get_parent_map(self):
1415
        """Requesting the same revision should be returned from cache"""
3835.1.16 by Aaron Bentley
Updates from review
1416
        self.assertEqual({}, self.caching_pp._cache)
3099.3.3 by John Arbash Meinel
Deprecate get_parents() in favor of get_parent_map()
1417
        self.assertEqual({'a':('b',)}, self.caching_pp.get_parent_map(['a']))
1418
        self.assertEqual(['a'], self.inst_pp.calls)
1419
        self.assertEqual({'a':('b',)}, self.caching_pp.get_parent_map(['a']))
1420
        # No new call, as it should have been returned from the cache
1421
        self.assertEqual(['a'], self.inst_pp.calls)
3835.1.16 by Aaron Bentley
Updates from review
1422
        self.assertEqual({'a':('b',)}, self.caching_pp._cache)
3099.3.3 by John Arbash Meinel
Deprecate get_parents() in favor of get_parent_map()
1423
1424
    def test_get_parent_map_not_present(self):
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
1425
        """The cache should also track when a revision doesn't exist"""
3099.3.3 by John Arbash Meinel
Deprecate get_parents() in favor of get_parent_map()
1426
        self.assertEqual({}, self.caching_pp.get_parent_map(['b']))
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
1427
        self.assertEqual(['b'], self.inst_pp.calls)
3099.3.3 by John Arbash Meinel
Deprecate get_parents() in favor of get_parent_map()
1428
        self.assertEqual({}, self.caching_pp.get_parent_map(['b']))
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
1429
        # No new calls
1430
        self.assertEqual(['b'], self.inst_pp.calls)
1431
3099.3.3 by John Arbash Meinel
Deprecate get_parents() in favor of get_parent_map()
1432
    def test_get_parent_map_mixed(self):
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
1433
        """Anything that can be returned from cache, should be"""
3099.3.3 by John Arbash Meinel
Deprecate get_parents() in favor of get_parent_map()
1434
        self.assertEqual({}, self.caching_pp.get_parent_map(['b']))
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
1435
        self.assertEqual(['b'], self.inst_pp.calls)
3099.3.3 by John Arbash Meinel
Deprecate get_parents() in favor of get_parent_map()
1436
        self.assertEqual({'a':('b',)},
1437
                         self.caching_pp.get_parent_map(['a', 'b']))
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
1438
        self.assertEqual(['b', 'a'], self.inst_pp.calls)
1439
3099.3.3 by John Arbash Meinel
Deprecate get_parents() in favor of get_parent_map()
1440
    def test_get_parent_map_repeated(self):
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
1441
        """Asking for the same parent 2x will only forward 1 request."""
3099.3.3 by John Arbash Meinel
Deprecate get_parents() in favor of get_parent_map()
1442
        self.assertEqual({'a':('b',)},
1443
                         self.caching_pp.get_parent_map(['b', 'a', 'b']))
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
1444
        # Use sorted because we don't care about the order, just that each is
1445
        # only present 1 time.
1446
        self.assertEqual(['a', 'b'], sorted(self.inst_pp.calls))
3514.2.14 by John Arbash Meinel
Bring in the code to collapse linear portions of the graph.
1447
4190.1.4 by Robert Collins
Cache ghosts when we can get them from a RemoteRepository in get_parent_map.
1448
    def test_note_missing_key(self):
1449
        """After noting that a key is missing it is cached."""
1450
        self.caching_pp.note_missing_key('b')
1451
        self.assertEqual({}, self.caching_pp.get_parent_map(['b']))
1452
        self.assertEqual([], self.inst_pp.calls)
1453
        self.assertEqual(set(['b']), self.caching_pp.missing_keys)
1454
3514.2.14 by John Arbash Meinel
Bring in the code to collapse linear portions of the graph.
1455
3835.1.12 by Aaron Bentley
Unify CachingExtraParentsProvider and CachingParentsProvider.
1456
class TestCachingParentsProviderExtras(tests.TestCaseWithTransport):
3835.1.16 by Aaron Bentley
Updates from review
1457
    """Test the behaviour when parents are provided that were not requested."""
3835.1.10 by Aaron Bentley
Move CachingExtraParentsProvider to Graph
1458
1459
    def setUp(self):
3835.1.12 by Aaron Bentley
Unify CachingExtraParentsProvider and CachingParentsProvider.
1460
        super(TestCachingParentsProviderExtras, self).setUp()
3835.1.11 by Aaron Bentley
Rename FakeParentsProvider to ExtraParentsProvider
1461
        class ExtraParentsProvider(object):
3835.1.10 by Aaron Bentley
Move CachingExtraParentsProvider to Graph
1462
1463
            def get_parent_map(self, keys):
1464
                return {'rev1': [], 'rev2': ['rev1',]}
1465
3835.1.11 by Aaron Bentley
Rename FakeParentsProvider to ExtraParentsProvider
1466
        self.inst_pp = InstrumentedParentsProvider(ExtraParentsProvider())
3835.1.12 by Aaron Bentley
Unify CachingExtraParentsProvider and CachingParentsProvider.
1467
        self.caching_pp = _mod_graph.CachingParentsProvider(
1468
            get_parent_map=self.inst_pp.get_parent_map)
3835.1.10 by Aaron Bentley
Move CachingExtraParentsProvider to Graph
1469
1470
    def test_uncached(self):
3835.1.12 by Aaron Bentley
Unify CachingExtraParentsProvider and CachingParentsProvider.
1471
        self.caching_pp.disable_cache()
3835.1.10 by Aaron Bentley
Move CachingExtraParentsProvider to Graph
1472
        self.assertEqual({'rev1': []},
1473
                         self.caching_pp.get_parent_map(['rev1']))
1474
        self.assertEqual(['rev1'], self.inst_pp.calls)
3835.1.16 by Aaron Bentley
Updates from review
1475
        self.assertIs(None, self.caching_pp._cache)
1476
1477
    def test_cache_initially_empty(self):
1478
        self.assertEqual({}, self.caching_pp._cache)
3835.1.10 by Aaron Bentley
Move CachingExtraParentsProvider to Graph
1479
1480
    def test_cached(self):
1481
        self.assertEqual({'rev1': []},
1482
                         self.caching_pp.get_parent_map(['rev1']))
1483
        self.assertEqual(['rev1'], self.inst_pp.calls)
1484
        self.assertEqual({'rev1': [], 'rev2': ['rev1']},
3835.1.16 by Aaron Bentley
Updates from review
1485
                         self.caching_pp._cache)
3835.1.10 by Aaron Bentley
Move CachingExtraParentsProvider to Graph
1486
        self.assertEqual({'rev1': []},
1487
                          self.caching_pp.get_parent_map(['rev1']))
1488
        self.assertEqual(['rev1'], self.inst_pp.calls)
3835.1.16 by Aaron Bentley
Updates from review
1489
1490
    def test_disable_cache_clears_cache(self):
1491
        # Put something in the cache
1492
        self.caching_pp.get_parent_map(['rev1'])
1493
        self.assertEqual(2, len(self.caching_pp._cache))
3835.1.10 by Aaron Bentley
Move CachingExtraParentsProvider to Graph
1494
        self.caching_pp.disable_cache()
3835.1.16 by Aaron Bentley
Updates from review
1495
        self.assertIs(None, self.caching_pp._cache)
3835.1.10 by Aaron Bentley
Move CachingExtraParentsProvider to Graph
1496
3835.1.19 by Aaron Bentley
Raise exception when caching is enabled twice.
1497
    def test_enable_cache_raises(self):
3835.1.20 by Aaron Bentley
Change custom error to an AssertionError.
1498
        e = self.assertRaises(AssertionError, self.caching_pp.enable_cache)
3835.1.19 by Aaron Bentley
Raise exception when caching is enabled twice.
1499
        self.assertEqual('Cache enabled when already enabled.', str(e))
1500
3835.1.15 by Aaron Bentley
Allow miss caching to be disabled.
1501
    def test_cache_misses(self):
1502
        self.caching_pp.get_parent_map(['rev3'])
1503
        self.caching_pp.get_parent_map(['rev3'])
1504
        self.assertEqual(['rev3'], self.inst_pp.calls)
1505
1506
    def test_no_cache_misses(self):
3835.1.19 by Aaron Bentley
Raise exception when caching is enabled twice.
1507
        self.caching_pp.disable_cache()
3835.1.15 by Aaron Bentley
Allow miss caching to be disabled.
1508
        self.caching_pp.enable_cache(cache_misses=False)
1509
        self.caching_pp.get_parent_map(['rev3'])
1510
        self.caching_pp.get_parent_map(['rev3'])
1511
        self.assertEqual(['rev3', 'rev3'], self.inst_pp.calls)
1512
3835.1.10 by Aaron Bentley
Move CachingExtraParentsProvider to Graph
1513
    def test_cache_extras(self):
1514
        self.assertEqual({}, self.caching_pp.get_parent_map(['rev3']))
1515
        self.assertEqual({'rev2': ['rev1']},
1516
                         self.caching_pp.get_parent_map(['rev2']))
1517
        self.assertEqual(['rev3'], self.inst_pp.calls)
1518
1519
3514.2.14 by John Arbash Meinel
Bring in the code to collapse linear portions of the graph.
1520
class TestCollapseLinearRegions(tests.TestCase):
1521
1522
    def assertCollapsed(self, collapsed, original):
1523
        self.assertEqual(collapsed,
1524
                         _mod_graph.collapse_linear_regions(original))
1525
1526
    def test_collapse_nothing(self):
1527
        d = {1:[2, 3], 2:[], 3:[]}
1528
        self.assertCollapsed(d, d)
1529
        d = {1:[2], 2:[3, 4], 3:[5], 4:[5], 5:[]}
1530
        self.assertCollapsed(d, d)
1531
1532
    def test_collapse_chain(self):
1533
        # Any time we have a linear chain, we should be able to collapse
1534
        d = {1:[2], 2:[3], 3:[4], 4:[5], 5:[]}
1535
        self.assertCollapsed({1:[5], 5:[]}, d)
1536
        d = {5:[4], 4:[3], 3:[2], 2:[1], 1:[]}
1537
        self.assertCollapsed({5:[1], 1:[]}, d)
1538
        d = {5:[3], 3:[4], 4:[1], 1:[2], 2:[]}
1539
        self.assertCollapsed({5:[2], 2:[]}, d)
1540
1541
    def test_collapse_with_multiple_children(self):
1542
        #    7
1543
        #    |
1544
        #    6
1545
        #   / \
1546
        #  4   5
1547
        #  |   |
3514.2.16 by John Arbash Meinel
Review feedback from Ian.
1548
        #  2   3
3514.2.14 by John Arbash Meinel
Bring in the code to collapse linear portions of the graph.
1549
        #   \ /
1550
        #    1
1551
        #
1552
        # 4 and 5 cannot be removed because 6 has 2 children
3514.2.16 by John Arbash Meinel
Review feedback from Ian.
1553
        # 2 and 3 cannot be removed because 1 has 2 parents
3514.2.14 by John Arbash Meinel
Bring in the code to collapse linear portions of the graph.
1554
        d = {1:[2, 3], 2:[4], 4:[6], 3:[5], 5:[6], 6:[7], 7:[]}
1555
        self.assertCollapsed(d, d)
4070.9.14 by Andrew Bennetts
Tweaks requested by Robert's review.
1556
1557
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
1558
class TestPendingAncestryResultGetKeys(TestCaseWithMemoryTransport):
4070.9.14 by Andrew Bennetts
Tweaks requested by Robert's review.
1559
    """Tests for bzrlib.graph.PendingAncestryResult."""
1560
1561
    def test_get_keys(self):
1562
        builder = self.make_branch_builder('b')
1563
        builder.start_series()
1564
        builder.build_snapshot('rev-1', None, [
1565
            ('add', ('', 'root-id', 'directory', ''))])
1566
        builder.build_snapshot('rev-2', ['rev-1'], [])
1567
        builder.finish_series()
1568
        repo = builder.get_branch().repository
1569
        repo.lock_read()
1570
        self.addCleanup(repo.unlock)
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
1571
        result = _mod_graph.PendingAncestryResult(['rev-2'], repo)
1572
        self.assertEqual(set(['rev-1', 'rev-2']), set(result.get_keys()))
4070.9.14 by Andrew Bennetts
Tweaks requested by Robert's review.
1573
4098.1.1 by Andrew Bennetts
Fix a bug with how PendingAncestryResult.get_keys handles NULL_REVISION.
1574
    def test_get_keys_excludes_null(self):
1575
        # Make a 'graph' with an iter_ancestry that returns NULL_REVISION
1576
        # somewhere other than the last element, which can happen in real
1577
        # ancestries.
1578
        class StubGraph(object):
1579
            def iter_ancestry(self, keys):
1580
                return [(NULL_REVISION, ()), ('foo', (NULL_REVISION,))]
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
1581
        result = _mod_graph.PendingAncestryResult(['rev-3'], None)
1582
        result_keys = result._get_keys(StubGraph())
4098.1.1 by Andrew Bennetts
Fix a bug with how PendingAncestryResult.get_keys handles NULL_REVISION.
1583
        # Only the non-null keys from the ancestry appear.
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
1584
        self.assertEqual(set(['foo']), set(result_keys))
1585
1586
1587
class TestPendingAncestryResultRefine(TestGraphBase):
1588
1589
    def test_refine(self):
1590
        # Used when pulling from a stacked repository, so test some revisions
1591
        # being satisfied from the stacking branch.
1592
        g = self.make_graph(
1593
            {"tip":["mid"], "mid":["base"], "tag":["base"],
1594
             "base":[NULL_REVISION], NULL_REVISION:[]})
1595
        result = _mod_graph.PendingAncestryResult(['tip', 'tag'], None)
1596
        result = result.refine(set(['tip']), set(['mid']))
1597
        self.assertEqual(set(['mid', 'tag']), result.heads)
1598
        result = result.refine(set(['mid', 'tag', 'base']),
1599
            set([NULL_REVISION]))
1600
        self.assertEqual(set([NULL_REVISION]), result.heads)
1601
        self.assertTrue(result.is_empty())
1602
1603
1604
class TestSearchResultRefine(TestGraphBase):
1605
1606
    def test_refine(self):
1607
        # Used when pulling from a stacked repository, so test some revisions
1608
        # being satisfied from the stacking branch.
1609
        g = self.make_graph(
1610
            {"tip":["mid"], "mid":["base"], "tag":["base"],
1611
             "base":[NULL_REVISION], NULL_REVISION:[]})
1612
        result = _mod_graph.SearchResult(set(['tip', 'tag']),
1613
            set([NULL_REVISION]), 4, set(['tip', 'mid', 'tag', 'base']))
1614
        result = result.refine(set(['tip']), set(['mid']))
1615
        recipe = result.get_recipe()
1616
        # We should be starting from tag (original head) and mid (seen ref)
1617
        self.assertEqual(set(['mid', 'tag']), recipe[1])
1618
        # We should be stopping at NULL (original stop) and tip (seen head)
1619
        self.assertEqual(set([NULL_REVISION, 'tip']), recipe[2])
1620
        self.assertEqual(3, recipe[3])
1621
        result = result.refine(set(['mid', 'tag', 'base']),
1622
            set([NULL_REVISION]))
1623
        recipe = result.get_recipe()
1624
        # We should be starting from nothing (NULL was known as a cut point)
1625
        self.assertEqual(set([]), recipe[1])
1626
        # We should be stopping at NULL (original stop) and tip (seen head) and
1627
        # tag (seen head) and mid(seen mid-point head). We could come back and
1628
        # define this as not including mid, for minimal results, but it is
1629
        # still 'correct' to include mid, and simpler/easier.
1630
        self.assertEqual(set([NULL_REVISION, 'tip', 'tag', 'mid']), recipe[2])
1631
        self.assertEqual(0, recipe[3])
1632
        self.assertTrue(result.is_empty())