/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/tests/test_inv.py

  • Committer: Jelmer Vernooij
  • Date: 2017-06-10 18:34:12 UTC
  • mto: This revision was merged to the branch mainline in revision 6690.
  • Revision ID: jelmer@jelmer.uk-20170610183412-s9fro6la0e1848x6
More moves.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
 
1
# Copyright (C) 2005-2012, 2016 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
 
18
 
from bzrlib import (
19
 
    chk_map,
20
 
    groupcompress,
21
 
    bzrdir,
 
18
from .. import (
22
19
    errors,
23
 
    inventory,
24
20
    osutils,
25
21
    repository,
26
22
    revision,
27
23
    tests,
28
 
    )
29
 
from bzrlib.inventory import (CHKInventory, Inventory, ROOT_ID, InventoryFile,
30
 
    InventoryDirectory, InventoryEntry, TreeReference)
31
 
from bzrlib.tests import (
 
24
    workingtree,
 
25
    )
 
26
from ..bzr import (
 
27
    chk_map,
 
28
    groupcompress,
 
29
    inventory,
 
30
    )
 
31
from ..bzr.inventory import (
 
32
    CHKInventory,
 
33
    Inventory,
 
34
    ROOT_ID,
 
35
    InventoryFile,
 
36
    InventoryDirectory,
 
37
    InventoryEntry,
 
38
    TreeReference,
 
39
    mutable_inventory_from_tree,
 
40
    )
 
41
from . import (
32
42
    TestCase,
33
43
    TestCaseWithTransport,
34
 
    condition_isinstance,
35
 
    multiply_tests,
36
 
    split_suite_by_condition,
37
44
    )
38
 
from bzrlib.tests.per_workingtree import workingtree_formats
39
 
 
40
 
 
41
 
def load_tests(standard_tests, module, loader):
42
 
    """Parameterise some inventory tests."""
43
 
    to_adapt, result = split_suite_by_condition(standard_tests,
44
 
        condition_isinstance(TestDeltaApplication))
 
45
from .scenarios import load_tests_apply_scenarios
 
46
 
 
47
 
 
48
load_tests = load_tests_apply_scenarios
 
49
 
 
50
 
 
51
def delta_application_scenarios():
45
52
    scenarios = [
46
53
        ('Inventory', {'apply_delta':apply_inventory_Inventory}),
47
54
        ]
52
59
    # just creating trees.
53
60
    formats = set()
54
61
    for _, format in repository.format_registry.iteritems():
55
 
        scenarios.append((str(format.__name__), {
56
 
            'apply_delta':apply_inventory_Repository_add_inventory_by_delta,
57
 
            'format':format}))
58
 
    for format in workingtree_formats():
 
62
        if format.supports_full_versioned_files:
 
63
            scenarios.append((str(format.__name__), {
 
64
                'apply_delta':apply_inventory_Repository_add_inventory_by_delta,
 
65
                'format':format}))
 
66
    for format in workingtree.format_registry._get_all():
 
67
        repo_fmt = format._matchingbzrdir.repository_format
 
68
        if not repo_fmt.supports_full_versioned_files:
 
69
            continue
59
70
        scenarios.append(
60
71
            (str(format.__class__.__name__) + ".update_basis_by_delta", {
61
72
            'apply_delta':apply_inventory_WT_basis,
64
75
            (str(format.__class__.__name__) + ".apply_inventory_delta", {
65
76
            'apply_delta':apply_inventory_WT,
66
77
            'format':format}))
67
 
    return multiply_tests(to_adapt, scenarios, result)
 
78
    return scenarios
68
79
 
69
80
 
70
81
def create_texts_for_inv(repo, inv):
74
85
        else:
75
86
            lines = []
76
87
        repo.texts.add_lines((ie.file_id, ie.revision), [], lines)
77
 
    
78
 
def apply_inventory_Inventory(self, basis, delta):
 
88
 
 
89
 
 
90
def apply_inventory_Inventory(self, basis, delta, invalid_delta=True):
79
91
    """Apply delta to basis and return the result.
80
 
    
 
92
 
81
93
    :param basis: An inventory to be used as the basis.
82
94
    :param delta: The inventory delta to apply:
83
95
    :return: An inventory resulting from the application.
86
98
    return basis
87
99
 
88
100
 
89
 
def apply_inventory_WT(self, basis, delta):
 
101
def apply_inventory_WT(self, basis, delta, invalid_delta=True):
90
102
    """Apply delta to basis and return the result.
91
103
 
92
104
    This sets the tree state to be basis, and then calls apply_inventory_delta.
93
 
    
 
105
 
94
106
    :param basis: An inventory to be used as the basis.
95
107
    :param delta: The inventory delta to apply:
96
108
    :return: An inventory resulting from the application.
97
109
    """
98
 
    control = self.make_bzrdir('tree', format=self.format._matchingbzrdir)
 
110
    control = self.make_controldir('tree', format=self.format._matchingbzrdir)
99
111
    control.create_repository()
100
112
    control.create_branch()
101
113
    tree = self.format.initialize(control)
105
117
    finally:
106
118
        tree.unlock()
107
119
    # Fresh object, reads disk again.
108
 
    tree = tree.bzrdir.open_workingtree()
 
120
    tree = tree.controldir.open_workingtree()
109
121
    tree.lock_write()
110
122
    try:
111
123
        tree.apply_inventory_delta(delta)
112
124
    finally:
113
125
        tree.unlock()
114
126
    # reload tree - ensure we get what was written.
115
 
    tree = tree.bzrdir.open_workingtree()
 
127
    tree = tree.controldir.open_workingtree()
116
128
    tree.lock_read()
117
129
    self.addCleanup(tree.unlock)
118
 
    # One could add 'tree._validate' here but that would cause 'early' failues 
119
 
    # as far as higher level code is concerned. Possibly adding an
120
 
    # expect_fail parameter to this function and if that is False then do a
121
 
    # validate call.
122
 
    return tree.inventory
123
 
 
124
 
 
125
 
def apply_inventory_WT_basis(self, basis, delta):
 
130
    if not invalid_delta:
 
131
        tree._validate()
 
132
    return tree.root_inventory
 
133
 
 
134
 
 
135
def _create_repo_revisions(repo, basis, delta, invalid_delta):
 
136
    repo.start_write_group()
 
137
    try:
 
138
        rev = revision.Revision('basis', timestamp=0, timezone=None,
 
139
            message="", committer="foo@example.com")
 
140
        basis.revision_id = 'basis'
 
141
        create_texts_for_inv(repo, basis)
 
142
        repo.add_revision('basis', rev, basis)
 
143
        if invalid_delta:
 
144
            # We don't want to apply the delta to the basis, because we expect
 
145
            # the delta is invalid.
 
146
            result_inv = basis
 
147
            result_inv.revision_id = 'result'
 
148
            target_entries = None
 
149
        else:
 
150
            result_inv = basis.create_by_apply_delta(delta, 'result')
 
151
            create_texts_for_inv(repo, result_inv)
 
152
            target_entries = list(result_inv.iter_entries_by_dir())
 
153
        rev = revision.Revision('result', timestamp=0, timezone=None,
 
154
            message="", committer="foo@example.com")
 
155
        repo.add_revision('result', rev, result_inv)
 
156
        repo.commit_write_group()
 
157
    except:
 
158
        repo.abort_write_group()
 
159
        raise
 
160
    return target_entries
 
161
 
 
162
 
 
163
def _get_basis_entries(tree):
 
164
    basis_tree = tree.basis_tree()
 
165
    basis_tree.lock_read()
 
166
    basis_tree_entries = list(basis_tree.inventory.iter_entries_by_dir())
 
167
    basis_tree.unlock()
 
168
    return basis_tree_entries
 
169
 
 
170
 
 
171
def _populate_different_tree(tree, basis, delta):
 
172
    """Put all entries into tree, but at a unique location."""
 
173
    added_ids = set()
 
174
    added_paths = set()
 
175
    tree.add(['unique-dir'], ['unique-dir-id'], ['directory'])
 
176
    for path, ie in basis.iter_entries_by_dir():
 
177
        if ie.file_id in added_ids:
 
178
            continue
 
179
        # We want a unique path for each of these, we use the file-id
 
180
        tree.add(['unique-dir/' + ie.file_id], [ie.file_id], [ie.kind])
 
181
        added_ids.add(ie.file_id)
 
182
    for old_path, new_path, file_id, ie in delta:
 
183
        if file_id in added_ids:
 
184
            continue
 
185
        tree.add(['unique-dir/' + file_id], [file_id], [ie.kind])
 
186
 
 
187
 
 
188
def apply_inventory_WT_basis(test, basis, delta, invalid_delta=True):
126
189
    """Apply delta to basis and return the result.
127
190
 
128
191
    This sets the parent and then calls update_basis_by_delta.
130
193
    allow safety checks made by the WT to succeed, and finally ensures that all
131
194
    items in the delta with a new path are present in the WT before calling
132
195
    update_basis_by_delta.
133
 
    
 
196
 
134
197
    :param basis: An inventory to be used as the basis.
135
198
    :param delta: The inventory delta to apply:
136
199
    :return: An inventory resulting from the application.
137
200
    """
138
 
    control = self.make_bzrdir('tree', format=self.format._matchingbzrdir)
 
201
    control = test.make_controldir('tree', format=test.format._matchingbzrdir)
139
202
    control.create_repository()
140
203
    control.create_branch()
141
 
    tree = self.format.initialize(control)
 
204
    tree = test.format.initialize(control)
142
205
    tree.lock_write()
143
206
    try:
144
 
        repo = tree.branch.repository
145
 
        repo.start_write_group()
146
 
        try:
147
 
            rev = revision.Revision('basis', timestamp=0, timezone=None,
148
 
                message="", committer="foo@example.com")
149
 
            basis.revision_id = 'basis'
150
 
            create_texts_for_inv(tree.branch.repository, basis)
151
 
            repo.add_revision('basis', rev, basis)
152
 
            # Add a revision for the result, with the basis content - 
153
 
            # update_basis_by_delta doesn't check that the delta results in
154
 
            # result, and we want inconsistent deltas to get called on the
155
 
            # tree, or else the code isn't actually checked.
156
 
            rev = revision.Revision('result', timestamp=0, timezone=None,
157
 
                message="", committer="foo@example.com")
158
 
            basis.revision_id = 'result'
159
 
            repo.add_revision('result', rev, basis)
160
 
            repo.commit_write_group()
161
 
        except:
162
 
            repo.abort_write_group()
163
 
            raise
 
207
        target_entries = _create_repo_revisions(tree.branch.repository, basis,
 
208
                                                delta, invalid_delta)
164
209
        # Set the basis state as the trees current state
165
210
        tree._write_inventory(basis)
166
211
        # This reads basis from the repo and puts it into the tree's local
167
212
        # cache, if it has one.
168
213
        tree.set_parent_ids(['basis'])
169
 
        paths = {}
170
 
        parents = set()
171
 
        for old, new, id, entry in delta:
172
 
            if None in (new, entry):
173
 
                continue
174
 
            paths[new] = (entry.file_id, entry.kind)
175
 
            parents.add(osutils.dirname(new))
176
 
        parents = osutils.minimum_path_selection(parents)
177
 
        parents.discard('')
178
 
        # Put place holders in the tree to permit adding the other entries.
179
 
        for pos, parent in enumerate(parents):
180
 
            if not tree.path2id(parent):
181
 
                # add a synthetic directory in the tree so we can can put the
182
 
                # tree0 entries in place for dirstate.
183
 
                tree.add([parent], ["id%d" % pos], ["directory"])
184
 
        if paths:
185
 
            # Many deltas may cause this mini-apply to fail, but we want to see what
186
 
            # the delta application code says, not the prep that we do to deal with 
187
 
            # limitations of dirstate's update_basis code.
188
 
            for path, (file_id, kind) in sorted(paths.items()):
189
 
                try:
190
 
                    tree.add([path], [file_id], [kind])
191
 
                except (KeyboardInterrupt, SystemExit):
192
 
                    raise
193
 
                except:
194
 
                    pass
195
214
    finally:
196
215
        tree.unlock()
197
216
    # Fresh lock, reads disk again.
198
217
    tree.lock_write()
199
218
    try:
200
219
        tree.update_basis_by_delta('result', delta)
 
220
        if not invalid_delta:
 
221
            tree._validate()
201
222
    finally:
202
223
        tree.unlock()
203
224
    # reload tree - ensure we get what was written.
204
 
    tree = tree.bzrdir.open_workingtree()
 
225
    tree = tree.controldir.open_workingtree()
205
226
    basis_tree = tree.basis_tree()
206
227
    basis_tree.lock_read()
207
 
    self.addCleanup(basis_tree.unlock)
208
 
    # Note, that if the tree does not have a local cache, the trick above of
209
 
    # setting the result as the basis, will come back to bite us. That said,
210
 
    # all the implementations in bzr do have a local cache.
211
 
    return basis_tree.inventory
212
 
 
213
 
 
214
 
def apply_inventory_Repository_add_inventory_by_delta(self, basis, delta):
 
228
    test.addCleanup(basis_tree.unlock)
 
229
    basis_inv = basis_tree.root_inventory
 
230
    if target_entries:
 
231
        basis_entries = list(basis_inv.iter_entries_by_dir())
 
232
        test.assertEqual(target_entries, basis_entries)
 
233
    return basis_inv
 
234
 
 
235
 
 
236
def apply_inventory_Repository_add_inventory_by_delta(self, basis, delta,
 
237
                                                      invalid_delta=True):
215
238
    """Apply delta to basis and return the result.
216
239
    
217
240
    This inserts basis as a whole inventory and then uses
222
245
    :return: An inventory resulting from the application.
223
246
    """
224
247
    format = self.format()
225
 
    control = self.make_bzrdir('tree', format=format._matchingbzrdir)
 
248
    control = self.make_controldir('tree', format=format._matchingbzrdir)
226
249
    repo = format.initialize(control)
227
250
    repo.lock_write()
228
251
    try:
253
276
    finally:
254
277
        repo.unlock()
255
278
    # Fresh lock, reads disk again.
256
 
    repo = repo.bzrdir.open_repository()
 
279
    repo = repo.controldir.open_repository()
257
280
    repo.lock_read()
258
281
    self.addCleanup(repo.unlock)
259
282
    return repo.get_inventory('result')
304
327
        inv = inventory.Inventory(root_id='someroot')
305
328
        inv.root.revision = 'therev'
306
329
        inv2 = inv.copy()
307
 
        self.assertEquals('someroot', inv2.root.file_id)
308
 
        self.assertEquals('therev', inv2.root.revision)
 
330
        self.assertEqual('someroot', inv2.root.file_id)
 
331
        self.assertEqual('therev', inv2.root.revision)
309
332
 
310
333
    def test_create_tree_reference(self):
311
334
        inv = inventory.Inventory('tree-root-123')
330
353
 
331
354
 
332
355
class TestDeltaApplication(TestCaseWithTransport):
 
356
 
 
357
    scenarios = delta_application_scenarios()
333
358
 
334
359
    def get_empty_inventory(self, reference_inv=None):
335
360
        """Get an empty inventory.
350
375
            inv.root.revision = 'basis'
351
376
        return inv
352
377
 
 
378
    def make_file_ie(self, file_id='file-id', name='name', parent_id=None):
 
379
        ie_file = inventory.InventoryFile(file_id, name, parent_id)
 
380
        ie_file.revision = 'result'
 
381
        ie_file.text_size = 0
 
382
        ie_file.text_sha1 = ''
 
383
        return ie_file
 
384
 
353
385
    def test_empty_delta(self):
354
386
        inv = self.get_empty_inventory()
355
387
        delta = []
379
411
        file1.revision = 'result'
380
412
        file1.text_size = 0
381
413
        file1.text_sha1 = ""
382
 
        file2 = inventory.InventoryFile('id', 'path2', inv.root.file_id)
383
 
        file2.revision = 'result'
384
 
        file2.text_size = 0
385
 
        file2.text_sha1 = ""
 
414
        file2 = file1.copy()
 
415
        file2.name = 'path2'
386
416
        delta = [(None, u'path1', 'id', file1), (None, u'path2', 'id', file2)]
387
417
        self.assertRaises(errors.InconsistentDelta, self.apply_delta, self,
388
418
            inv, delta)
393
423
        file1.revision = 'result'
394
424
        file1.text_size = 0
395
425
        file1.text_sha1 = ""
396
 
        file2 = inventory.InventoryFile('id2', 'path', inv.root.file_id)
397
 
        file2.revision = 'result'
398
 
        file2.text_size = 0
399
 
        file2.text_sha1 = ""
 
426
        file2 = file1.copy()
 
427
        file2.file_id = 'id2'
400
428
        delta = [(None, u'path', 'id1', file1), (None, u'path', 'id2', file2)]
401
429
        self.assertRaises(errors.InconsistentDelta, self.apply_delta, self,
402
430
            inv, delta)
574
602
        self.assertRaises(errors.InconsistentDelta, self.apply_delta, self,
575
603
            inv, delta)
576
604
 
577
 
 
578
 
class TestInventory(TestCase):
 
605
    def test_add_file(self):
 
606
        inv = self.get_empty_inventory()
 
607
        file1 = inventory.InventoryFile('file-id', 'path', inv.root.file_id)
 
608
        file1.revision = 'result'
 
609
        file1.text_size = 0
 
610
        file1.text_sha1 = ''
 
611
        delta = [(None, u'path', 'file-id', file1)]
 
612
        res_inv = self.apply_delta(self, inv, delta, invalid_delta=False)
 
613
        self.assertEqual('file-id', res_inv['file-id'].file_id)
 
614
 
 
615
    def test_remove_file(self):
 
616
        inv = self.get_empty_inventory()
 
617
        file1 = inventory.InventoryFile('file-id', 'path', inv.root.file_id)
 
618
        file1.revision = 'result'
 
619
        file1.text_size = 0
 
620
        file1.text_sha1 = ''
 
621
        inv.add(file1)
 
622
        delta = [(u'path', None, 'file-id', None)]
 
623
        res_inv = self.apply_delta(self, inv, delta, invalid_delta=False)
 
624
        self.assertEqual(None, res_inv.path2id('path'))
 
625
        self.assertRaises(errors.NoSuchId, res_inv.id2path, 'file-id')
 
626
 
 
627
    def test_rename_file(self):
 
628
        inv = self.get_empty_inventory()
 
629
        file1 = self.make_file_ie(name='path', parent_id=inv.root.file_id)
 
630
        inv.add(file1)
 
631
        file2 = self.make_file_ie(name='path2', parent_id=inv.root.file_id)
 
632
        delta = [(u'path', 'path2', 'file-id', file2)]
 
633
        res_inv = self.apply_delta(self, inv, delta, invalid_delta=False)
 
634
        self.assertEqual(None, res_inv.path2id('path'))
 
635
        self.assertEqual('file-id', res_inv.path2id('path2'))
 
636
 
 
637
    def test_replaced_at_new_path(self):
 
638
        inv = self.get_empty_inventory()
 
639
        file1 = self.make_file_ie(file_id='id1', parent_id=inv.root.file_id)
 
640
        inv.add(file1)
 
641
        file2 = self.make_file_ie(file_id='id2', parent_id=inv.root.file_id)
 
642
        delta = [(u'name', None, 'id1', None),
 
643
                 (None, u'name', 'id2', file2)]
 
644
        res_inv = self.apply_delta(self, inv, delta, invalid_delta=False)
 
645
        self.assertEqual('id2', res_inv.path2id('name'))
 
646
 
 
647
    def test_rename_dir(self):
 
648
        inv = self.get_empty_inventory()
 
649
        dir1 = inventory.InventoryDirectory('dir-id', 'dir1', inv.root.file_id)
 
650
        dir1.revision = 'basis'
 
651
        file1 = self.make_file_ie(parent_id='dir-id')
 
652
        inv.add(dir1)
 
653
        inv.add(file1)
 
654
        dir2 = inventory.InventoryDirectory('dir-id', 'dir2', inv.root.file_id)
 
655
        dir2.revision = 'result'
 
656
        delta = [('dir1', 'dir2', 'dir-id', dir2)]
 
657
        res_inv = self.apply_delta(self, inv, delta, invalid_delta=False)
 
658
        # The file should be accessible under the new path
 
659
        self.assertEqual('file-id', res_inv.path2id('dir2/name'))
 
660
 
 
661
    def test_renamed_dir_with_renamed_child(self):
 
662
        inv = self.get_empty_inventory()
 
663
        dir1 = inventory.InventoryDirectory('dir-id', 'dir1', inv.root.file_id)
 
664
        dir1.revision = 'basis'
 
665
        file1 = self.make_file_ie('file-id-1', 'name1', parent_id='dir-id')
 
666
        file2 = self.make_file_ie('file-id-2', 'name2', parent_id='dir-id')
 
667
        inv.add(dir1)
 
668
        inv.add(file1)
 
669
        inv.add(file2)
 
670
        dir2 = inventory.InventoryDirectory('dir-id', 'dir2', inv.root.file_id)
 
671
        dir2.revision = 'result'
 
672
        file2b = self.make_file_ie('file-id-2', 'name2', inv.root.file_id)
 
673
        delta = [('dir1', 'dir2', 'dir-id', dir2),
 
674
                 ('dir1/name2', 'name2', 'file-id-2', file2b)]
 
675
        res_inv = self.apply_delta(self, inv, delta, invalid_delta=False)
 
676
        # The file should be accessible under the new path
 
677
        self.assertEqual('file-id-1', res_inv.path2id('dir2/name1'))
 
678
        self.assertEqual(None, res_inv.path2id('dir2/name2'))
 
679
        self.assertEqual('file-id-2', res_inv.path2id('name2'))
579
680
 
580
681
    def test_is_root(self):
581
682
        """Ensure our root-checking code is accurate."""
590
691
        self.assertFalse(inv.is_root('TREE_ROOT'))
591
692
        self.assertFalse(inv.is_root('booga'))
592
693
 
 
694
    def test_entries_for_empty_inventory(self):
 
695
        """Test that entries() will not fail for an empty inventory"""
 
696
        inv = Inventory(root_id=None)
 
697
        self.assertEqual([], inv.entries())
 
698
 
593
699
 
594
700
class TestInventoryEntry(TestCase):
595
701
 
607
713
 
608
714
    def test_dir_detect_changes(self):
609
715
        left = inventory.InventoryDirectory('123', 'hello.c', ROOT_ID)
610
 
        left.text_sha1 = 123
611
 
        left.executable = True
612
 
        left.symlink_target='foo'
613
716
        right = inventory.InventoryDirectory('123', 'hello.c', ROOT_ID)
614
 
        right.text_sha1 = 321
615
 
        right.symlink_target='bar'
616
717
        self.assertEqual((False, False), left.detect_changes(right))
617
718
        self.assertEqual((False, False), right.detect_changes(left))
618
719
 
632
733
 
633
734
    def test_symlink_detect_changes(self):
634
735
        left = inventory.InventoryLink('123', 'hello.c', ROOT_ID)
635
 
        left.text_sha1 = 123
636
 
        left.executable = True
637
736
        left.symlink_target='foo'
638
737
        right = inventory.InventoryLink('123', 'hello.c', ROOT_ID)
639
 
        right.text_sha1 = 321
640
738
        right.symlink_target='foo'
641
739
        self.assertEqual((False, False), left.detect_changes(right))
642
740
        self.assertEqual((False, False), right.detect_changes(left))
646
744
 
647
745
    def test_file_has_text(self):
648
746
        file = inventory.InventoryFile('123', 'hello.c', ROOT_ID)
649
 
        self.failUnless(file.has_text())
 
747
        self.assertTrue(file.has_text())
650
748
 
651
749
    def test_directory_has_text(self):
652
750
        dir = inventory.InventoryDirectory('123', 'hello.c', ROOT_ID)
653
 
        self.failIf(dir.has_text())
 
751
        self.assertFalse(dir.has_text())
654
752
 
655
753
    def test_link_has_text(self):
656
754
        link = inventory.InventoryLink('123', 'hello.c', ROOT_ID)
657
 
        self.failIf(link.has_text())
 
755
        self.assertFalse(link.has_text())
658
756
 
659
757
    def test_make_entry(self):
660
758
        self.assertIsInstance(inventory.make_entry("file", "name", ROOT_ID),
843
941
        new_inv = CHKInventory.deserialise(chk_bytes, bytes, ("revid",))
844
942
        root_entry = new_inv[inv.root.file_id]
845
943
        self.assertEqual(None, root_entry._children)
846
 
        self.assertEqual(['file'], root_entry.children.keys())
 
944
        self.assertEqual({'file'}, set(root_entry.children))
847
945
        file_direct = new_inv["fileid"]
848
946
        file_found = root_entry.children['file']
849
947
        self.assertEqual(file_direct.kind, file_found.kind)
883
981
        chk_inv = CHKInventory.from_inventory(chk_bytes, inv)
884
982
        bytes = ''.join(chk_inv.to_lines())
885
983
        new_inv = CHKInventory.deserialise(chk_bytes, bytes, ("revid",))
886
 
        fileids = list(new_inv.__iter__())
887
 
        fileids.sort()
 
984
        fileids = sorted(new_inv.__iter__())
888
985
        self.assertEqual([inv.root.file_id, "fileid"], fileids)
889
986
 
890
987
    def test__len__(self):
1005
1102
        delta = [("", None, base_inv.root.file_id, None),
1006
1103
            (None, "",  "myrootid", inv.root)]
1007
1104
        new_inv = base_inv.create_by_apply_delta(delta, "expectedid")
1008
 
        self.assertEquals(reference_inv.root, new_inv.root)
 
1105
        self.assertEqual(reference_inv.root, new_inv.root)
1009
1106
 
1010
1107
    def test_create_by_apply_delta_empty_add_child(self):
1011
1108
        inv = Inventory()
1215
1312
        self.assertEqual(('tree\xce\xa9name', 'tree-root-id', 'tree-rev-id'),
1216
1313
                         inv._bytes_to_utf8name_key(bytes))
1217
1314
 
 
1315
    def make_basic_utf8_inventory(self):
 
1316
        inv = Inventory()
 
1317
        inv.revision_id = "revid"
 
1318
        inv.root.revision = "rootrev"
 
1319
        root_id = inv.root.file_id
 
1320
        inv.add(InventoryFile("fileid", u'f\xefle', root_id))
 
1321
        inv["fileid"].revision = "filerev"
 
1322
        inv["fileid"].text_sha1 = "ffff"
 
1323
        inv["fileid"].text_size = 0
 
1324
        inv.add(InventoryDirectory("dirid", u'dir-\N{EURO SIGN}', root_id))
 
1325
        inv.add(InventoryFile("childid", u'ch\xefld', "dirid"))
 
1326
        inv["childid"].revision = "filerev"
 
1327
        inv["childid"].text_sha1 = "ffff"
 
1328
        inv["childid"].text_size = 0
 
1329
        chk_bytes = self.get_chk_bytes()
 
1330
        chk_inv = CHKInventory.from_inventory(chk_bytes, inv)
 
1331
        bytes = ''.join(chk_inv.to_lines())
 
1332
        return CHKInventory.deserialise(chk_bytes, bytes, ("revid",))
 
1333
 
 
1334
    def test__preload_handles_utf8(self):
 
1335
        new_inv = self.make_basic_utf8_inventory()
 
1336
        self.assertEqual({}, new_inv._fileid_to_entry_cache)
 
1337
        self.assertFalse(new_inv._fully_cached)
 
1338
        new_inv._preload_cache()
 
1339
        self.assertEqual(
 
1340
            sorted([new_inv.root_id, "fileid", "dirid", "childid"]),
 
1341
            sorted(new_inv._fileid_to_entry_cache.keys()))
 
1342
        ie_root = new_inv._fileid_to_entry_cache[new_inv.root_id]
 
1343
        self.assertEqual([u'dir-\N{EURO SIGN}', u'f\xefle'],
 
1344
                         sorted(ie_root._children.keys()))
 
1345
        ie_dir = new_inv._fileid_to_entry_cache['dirid']
 
1346
        self.assertEqual([u'ch\xefld'], sorted(ie_dir._children.keys()))
 
1347
 
 
1348
    def test__preload_populates_cache(self):
 
1349
        inv = Inventory()
 
1350
        inv.revision_id = "revid"
 
1351
        inv.root.revision = "rootrev"
 
1352
        root_id = inv.root.file_id
 
1353
        inv.add(InventoryFile("fileid", "file", root_id))
 
1354
        inv["fileid"].revision = "filerev"
 
1355
        inv["fileid"].executable = True
 
1356
        inv["fileid"].text_sha1 = "ffff"
 
1357
        inv["fileid"].text_size = 1
 
1358
        inv.add(InventoryDirectory("dirid", "dir", root_id))
 
1359
        inv.add(InventoryFile("childid", "child", "dirid"))
 
1360
        inv["childid"].revision = "filerev"
 
1361
        inv["childid"].executable = False
 
1362
        inv["childid"].text_sha1 = "dddd"
 
1363
        inv["childid"].text_size = 1
 
1364
        chk_bytes = self.get_chk_bytes()
 
1365
        chk_inv = CHKInventory.from_inventory(chk_bytes, inv)
 
1366
        bytes = ''.join(chk_inv.to_lines())
 
1367
        new_inv = CHKInventory.deserialise(chk_bytes, bytes, ("revid",))
 
1368
        self.assertEqual({}, new_inv._fileid_to_entry_cache)
 
1369
        self.assertFalse(new_inv._fully_cached)
 
1370
        new_inv._preload_cache()
 
1371
        self.assertEqual(
 
1372
            sorted([root_id, "fileid", "dirid", "childid"]),
 
1373
            sorted(new_inv._fileid_to_entry_cache.keys()))
 
1374
        self.assertTrue(new_inv._fully_cached)
 
1375
        ie_root = new_inv._fileid_to_entry_cache[root_id]
 
1376
        self.assertEqual(['dir', 'file'], sorted(ie_root._children.keys()))
 
1377
        ie_dir = new_inv._fileid_to_entry_cache['dirid']
 
1378
        self.assertEqual(['child'], sorted(ie_dir._children.keys()))
 
1379
 
 
1380
    def test__preload_handles_partially_evaluated_inventory(self):
 
1381
        new_inv = self.make_basic_utf8_inventory()
 
1382
        ie = new_inv[new_inv.root_id]
 
1383
        self.assertIs(None, ie._children)
 
1384
        self.assertEqual([u'dir-\N{EURO SIGN}', u'f\xefle'],
 
1385
                         sorted(ie.children.keys()))
 
1386
        # Accessing .children loads _children
 
1387
        self.assertEqual([u'dir-\N{EURO SIGN}', u'f\xefle'],
 
1388
                         sorted(ie._children.keys()))
 
1389
        new_inv._preload_cache()
 
1390
        # No change
 
1391
        self.assertEqual([u'dir-\N{EURO SIGN}', u'f\xefle'],
 
1392
                         sorted(ie._children.keys()))
 
1393
        ie_dir = new_inv["dirid"]
 
1394
        self.assertEqual([u'ch\xefld'],
 
1395
                         sorted(ie_dir._children.keys()))
 
1396
 
 
1397
    def test_filter_change_in_renamed_subfolder(self):
 
1398
        inv = Inventory('tree-root')
 
1399
        src_ie = inv.add_path('src', 'directory', 'src-id')
 
1400
        inv.add_path('src/sub/', 'directory', 'sub-id')
 
1401
        a_ie = inv.add_path('src/sub/a', 'file', 'a-id')
 
1402
        a_ie.text_sha1 = osutils.sha_string('content\n')
 
1403
        a_ie.text_size = len('content\n')
 
1404
        chk_bytes = self.get_chk_bytes()
 
1405
        inv = CHKInventory.from_inventory(chk_bytes, inv)
 
1406
        inv = inv.create_by_apply_delta([
 
1407
            ("src/sub/a", "src/sub/a", "a-id", a_ie),
 
1408
            ("src", "src2", "src-id", src_ie),
 
1409
            ], 'new-rev-2')
 
1410
        new_inv = inv.filter(['a-id', 'src-id'])
 
1411
        self.assertEqual([
 
1412
            ('', 'tree-root'),
 
1413
            ('src', 'src-id'),
 
1414
            ('src/sub', 'sub-id'),
 
1415
            ('src/sub/a', 'a-id'),
 
1416
            ], [(path, ie.file_id) for path, ie in new_inv.iter_entries()])
1218
1417
 
1219
1418
class TestCHKInventoryExpand(tests.TestCaseWithMemoryTransport):
1220
1419
 
1275
1474
            s = expected_children.setdefault(entry.parent_id, [])
1276
1475
            s.append(entry.file_id)
1277
1476
        val_children = dict((k, sorted(v)) for k, v
1278
 
                            in val_children.iteritems())
 
1477
                            in val_children.items())
1279
1478
        expected_children = dict((k, sorted(v)) for k, v
1280
 
                            in expected_children.iteritems())
 
1479
                            in expected_children.items())
1281
1480
        self.assertEqual(expected_children, val_children)
1282
1481
 
1283
1482
    def test_make_simple_inventory(self):
1346
1545
        inv = self.make_simple_inventory()
1347
1546
        self.assertExpand(['TREE_ROOT', 'dir1-id', 'sub-dir1-id', 'top-id',
1348
1547
                           'subsub-file1-id'], inv, ['top-id', 'subsub-file1-id'])
 
1548
 
 
1549
 
 
1550
class TestMutableInventoryFromTree(TestCaseWithTransport):
 
1551
 
 
1552
    def test_empty(self):
 
1553
        repository = self.make_repository('.')
 
1554
        tree = repository.revision_tree(revision.NULL_REVISION)
 
1555
        inv = mutable_inventory_from_tree(tree)
 
1556
        self.assertEqual(revision.NULL_REVISION, inv.revision_id)
 
1557
        self.assertEqual(0, len(inv))
 
1558
 
 
1559
    def test_some_files(self):
 
1560
        wt = self.make_branch_and_tree('.')
 
1561
        self.build_tree(['a'])
 
1562
        wt.add(['a'], ['thefileid'])
 
1563
        revid = wt.commit("commit")
 
1564
        tree = wt.branch.repository.revision_tree(revid)
 
1565
        inv = mutable_inventory_from_tree(tree)
 
1566
        self.assertEqual(revid, inv.revision_id)
 
1567
        self.assertEqual(2, len(inv))
 
1568
        self.assertEqual("a", inv['thefileid'].name)
 
1569
        # The inventory should be mutable and independent of
 
1570
        # the original tree
 
1571
        self.assertFalse(tree.root_inventory['thefileid'].executable)
 
1572
        inv['thefileid'].executable = True
 
1573
        self.assertFalse(tree.root_inventory['thefileid'].executable)