/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
5557.1.7 by John Arbash Meinel
Merge in the bzr.dev 5582
1
# Copyright (C) 2006-2011 Canonical Ltd
1852.13.6 by Robert Collins
start hooking in the prototype dirstate serialiser.
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
1852.13.6 by Robert Collins
start hooking in the prototype dirstate serialiser.
16
17
"""Tests of the dirstate functionality being built for WorkingTreeFormat4."""
18
1852.13.20 by Robert Collins
Steps toward an object model.
19
import os
5847.4.17 by John Arbash Meinel
The 25ms was the time spent checking that we didn't alter the containing WT.
20
import tempfile
1852.13.20 by Robert Collins
Steps toward an object model.
21
2255.2.125 by John Arbash Meinel
Initial effort at adding a basic _bisect function to DirState.
22
from bzrlib import (
5847.4.16 by John Arbash Meinel
Switching from BranchBuilder to Inventory directly dropped us from 73ms to 26ms.
23
    bzrdir,
2255.2.125 by John Arbash Meinel
Initial effort at adding a basic _bisect function to DirState.
24
    dirstate,
25
    errors,
3477.2.1 by John Arbash Meinel
Assert that we properly encode inv_entry.symlink_target, (bug #135320)
26
    inventory,
4241.14.10 by Vincent Ladeuil
Add DirReader parametrized tests.
27
    memorytree,
2255.2.125 by John Arbash Meinel
Initial effort at adding a basic _bisect function to DirState.
28
    osutils,
3668.5.1 by Jelmer Vernooij
Use NULL_REVISION rather than None for Repository.revision_tree().
29
    revision as _mod_revision,
5847.4.16 by John Arbash Meinel
Switching from BranchBuilder to Inventory directly dropped us from 73ms to 26ms.
30
    revisiontree,
4241.14.10 by Vincent Ladeuil
Add DirReader parametrized tests.
31
    tests,
5847.4.14 by John Arbash Meinel
Create a direct helper for testing UpdateBasisByDelta cases.
32
    workingtree_4,
2255.2.125 by John Arbash Meinel
Initial effort at adding a basic _bisect function to DirState.
33
    )
5847.4.14 by John Arbash Meinel
Create a direct helper for testing UpdateBasisByDelta cases.
34
from bzrlib.transport import memory
4241.14.10 by Vincent Ladeuil
Add DirReader parametrized tests.
35
from bzrlib.tests import test_osutils
5559.2.2 by Martin Pool
Change to using standard load_tests_apply_scenarios.
36
from bzrlib.tests.scenarios import load_tests_apply_scenarios
1852.13.6 by Robert Collins
start hooking in the prototype dirstate serialiser.
37
38
39
# TODO:
2255.2.4 by Robert Collins
Snapshot dirstate development
40
# TESTS to write:
2255.2.15 by Robert Collins
Dirstate - truncate state file fixing bug in saving a smaller file, get more tree_implementation tests passing.
41
# general checks for NOT_IN_MEMORY error conditions.
42
# set_path_id on a NOT_IN_MEMORY dirstate
2255.2.4 by Robert Collins
Snapshot dirstate development
43
# set_path_id  unicode support
44
# set_path_id  setting id of a path not root
45
# set_path_id  setting id when there are parents without the id in the parents
46
# set_path_id  setting id when there are parents with the id in the parents
47
# set_path_id  setting id when state is not in memory
48
# set_path_id  setting id when state is in memory unmodified
49
# set_path_id  setting id when state is in memory modified
1852.13.6 by Robert Collins
start hooking in the prototype dirstate serialiser.
50
2255.2.236 by Martin Pool
Review cleanups: mostly updating or removing todo comments.
51
5559.2.2 by Martin Pool
Change to using standard load_tests_apply_scenarios.
52
load_tests = load_tests_apply_scenarios
4241.14.10 by Vincent Ladeuil
Add DirReader parametrized tests.
53
54
55
class TestCaseWithDirState(tests.TestCaseWithTransport):
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
56
    """Helper functions for creating DirState objects with various content."""
57
5559.2.2 by Martin Pool
Change to using standard load_tests_apply_scenarios.
58
    scenarios = test_osutils.dir_reader_scenarios()
59
4241.14.10 by Vincent Ladeuil
Add DirReader parametrized tests.
60
    # Set by load_tests
61
    _dir_reader_class = None
62
    _native_to_unicode = None # Not used yet
63
64
    def setUp(self):
65
        tests.TestCaseWithTransport.setUp(self)
66
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
67
        self.overrideAttr(osutils,
68
                          '_selected_dir_reader', self._dir_reader_class())
4241.14.10 by Vincent Ladeuil
Add DirReader parametrized tests.
69
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
70
    def create_empty_dirstate(self):
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
71
        """Return a locked but empty dirstate"""
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
72
        state = dirstate.DirState.initialize('dirstate')
73
        return state
74
75
    def create_dirstate_with_root(self):
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
76
        """Return a write-locked state with a single root entry."""
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
77
        packed_stat = 'AAAAREUHaIpFB2iKAAADAQAtkqUAAIGk'
78
        root_entry_direntry = ('', '', 'a-root-value'), [
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
79
            ('d', '', 0, False, packed_stat),
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
80
            ]
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
81
        dirblocks = []
82
        dirblocks.append(('', [root_entry_direntry]))
83
        dirblocks.append(('', []))
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
84
        state = self.create_empty_dirstate()
85
        try:
86
            state._set_data([], dirblocks)
2255.7.78 by Martin Pool
Add DirState._validate and call from the tests
87
            state._validate()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
88
        except:
89
            state.unlock()
90
            raise
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
91
        return state
92
93
    def create_dirstate_with_root_and_subdir(self):
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
94
        """Return a locked DirState with a root and a subdir"""
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
95
        packed_stat = 'AAAAREUHaIpFB2iKAAADAQAtkqUAAIGk'
96
        subdir_entry = ('', 'subdir', 'subdir-id'), [
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
97
            ('d', '', 0, False, packed_stat),
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
98
            ]
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
99
        state = self.create_dirstate_with_root()
100
        try:
101
            dirblocks = list(state._dirblocks)
102
            dirblocks[1][1].append(subdir_entry)
103
            state._set_data([], dirblocks)
104
        except:
105
            state.unlock()
106
            raise
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
107
        return state
108
109
    def create_complex_dirstate(self):
110
        """This dirstate contains multiple files and directories.
111
112
         /        a-root-value
113
         a/       a-dir
114
         b/       b-dir
115
         c        c-file
116
         d        d-file
117
         a/e/     e-dir
118
         a/f      f-file
119
         b/g      g-file
120
         b/h\xc3\xa5  h-\xc3\xa5-file  #This is u'\xe5' encoded into utf-8
121
2323.5.4 by Martin Pool
Move some dirstate test setup methods into the base class
122
        Notice that a/e is an empty directory.
123
124
        :return: The dirstate, still write-locked.
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
125
        """
126
        packed_stat = 'AAAAREUHaIpFB2iKAAADAQAtkqUAAIGk'
127
        null_sha = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
128
        root_entry = ('', '', 'a-root-value'), [
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
129
            ('d', '', 0, False, packed_stat),
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
130
            ]
131
        a_entry = ('', 'a', 'a-dir'), [
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
132
            ('d', '', 0, False, packed_stat),
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
133
            ]
134
        b_entry = ('', 'b', 'b-dir'), [
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
135
            ('d', '', 0, False, packed_stat),
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
136
            ]
137
        c_entry = ('', 'c', 'c-file'), [
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
138
            ('f', null_sha, 10, False, packed_stat),
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
139
            ]
140
        d_entry = ('', 'd', 'd-file'), [
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
141
            ('f', null_sha, 20, False, packed_stat),
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
142
            ]
143
        e_entry = ('a', 'e', 'e-dir'), [
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
144
            ('d', '', 0, False, packed_stat),
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
145
            ]
146
        f_entry = ('a', 'f', 'f-file'), [
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
147
            ('f', null_sha, 30, False, packed_stat),
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
148
            ]
149
        g_entry = ('b', 'g', 'g-file'), [
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
150
            ('f', null_sha, 30, False, packed_stat),
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
151
            ]
152
        h_entry = ('b', 'h\xc3\xa5', 'h-\xc3\xa5-file'), [
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
153
            ('f', null_sha, 40, False, packed_stat),
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
154
            ]
155
        dirblocks = []
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
156
        dirblocks.append(('', [root_entry]))
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
157
        dirblocks.append(('', [a_entry, b_entry, c_entry, d_entry]))
158
        dirblocks.append(('a', [e_entry, f_entry]))
159
        dirblocks.append(('b', [g_entry, h_entry]))
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
160
        state = dirstate.DirState.initialize('dirstate')
2255.7.78 by Martin Pool
Add DirState._validate and call from the tests
161
        state._validate()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
162
        try:
163
            state._set_data([], dirblocks)
164
        except:
165
            state.unlock()
166
            raise
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
167
        return state
168
169
    def check_state_with_reopen(self, expected_result, state):
170
        """Check that state has current state expected_result.
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
171
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
172
        This will check the current state, open the file anew and check it
173
        again.
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
174
        This function expects the current state to be locked for writing, and
175
        will unlock it before re-opening.
176
        This is required because we can't open a lock_read() while something
177
        else has a lock_write().
178
            write => mutually exclusive lock
179
            read => shared lock
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
180
        """
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
181
        # The state should already be write locked, since we just had to do
182
        # some operation to get here.
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
183
        self.assertTrue(state._lock_token is not None)
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
184
        try:
185
            self.assertEqual(expected_result[0],  state.get_parent_ids())
186
            # there should be no ghosts in this tree.
187
            self.assertEqual([], state.get_ghosts())
188
            # there should be one fileid in this tree - the root of the tree.
189
            self.assertEqual(expected_result[1], list(state._iter_entries()))
190
            state.save()
191
        finally:
192
            state.unlock()
2425.3.1 by John Arbash Meinel
Change the DirState.test_initialize test so that we don't try to read a locked file.
193
        del state
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
194
        state = dirstate.DirState.on_file('dirstate')
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
195
        state.lock_read()
196
        try:
197
            self.assertEqual(expected_result[1], list(state._iter_entries()))
198
        finally:
199
            state.unlock()
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
200
2323.5.4 by Martin Pool
Move some dirstate test setup methods into the base class
201
    def create_basic_dirstate(self):
202
        """Create a dirstate with a few files and directories.
203
204
            a
205
            b/
206
              c
207
              d/
208
                e
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
209
            b-c
2323.5.4 by Martin Pool
Move some dirstate test setup methods into the base class
210
            f
211
        """
212
        tree = self.make_branch_and_tree('tree')
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
213
        paths = ['a', 'b/', 'b/c', 'b/d/', 'b/d/e', 'b-c', 'f']
214
        file_ids = ['a-id', 'b-id', 'c-id', 'd-id', 'e-id', 'b-c-id', 'f-id']
2323.5.4 by Martin Pool
Move some dirstate test setup methods into the base class
215
        self.build_tree(['tree/' + p for p in paths])
216
        tree.set_root_id('TREE_ROOT')
217
        tree.add([p.rstrip('/') for p in paths], file_ids)
218
        tree.commit('initial', rev_id='rev-1')
219
        revision_id = 'rev-1'
220
        # a_packed_stat = dirstate.pack_stat(os.stat('tree/a'))
2520.3.1 by Vincent Ladeuil
Fix 110448 by adding a relpath parameter to get_transport.
221
        t = self.get_transport('tree')
2323.5.4 by Martin Pool
Move some dirstate test setup methods into the base class
222
        a_text = t.get_bytes('a')
223
        a_sha = osutils.sha_string(a_text)
224
        a_len = len(a_text)
225
        # b_packed_stat = dirstate.pack_stat(os.stat('tree/b'))
226
        # c_packed_stat = dirstate.pack_stat(os.stat('tree/b/c'))
227
        c_text = t.get_bytes('b/c')
228
        c_sha = osutils.sha_string(c_text)
229
        c_len = len(c_text)
230
        # d_packed_stat = dirstate.pack_stat(os.stat('tree/b/d'))
231
        # e_packed_stat = dirstate.pack_stat(os.stat('tree/b/d/e'))
232
        e_text = t.get_bytes('b/d/e')
233
        e_sha = osutils.sha_string(e_text)
234
        e_len = len(e_text)
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
235
        b_c_text = t.get_bytes('b-c')
236
        b_c_sha = osutils.sha_string(b_c_text)
237
        b_c_len = len(b_c_text)
2323.5.4 by Martin Pool
Move some dirstate test setup methods into the base class
238
        # f_packed_stat = dirstate.pack_stat(os.stat('tree/f'))
239
        f_text = t.get_bytes('f')
240
        f_sha = osutils.sha_string(f_text)
241
        f_len = len(f_text)
242
        null_stat = dirstate.DirState.NULLSTAT
243
        expected = {
244
            '':(('', '', 'TREE_ROOT'), [
245
                  ('d', '', 0, False, null_stat),
246
                  ('d', '', 0, False, revision_id),
247
                ]),
248
            'a':(('', 'a', 'a-id'), [
249
                   ('f', '', 0, False, null_stat),
250
                   ('f', a_sha, a_len, False, revision_id),
251
                 ]),
252
            'b':(('', 'b', 'b-id'), [
253
                  ('d', '', 0, False, null_stat),
254
                  ('d', '', 0, False, revision_id),
255
                 ]),
256
            'b/c':(('b', 'c', 'c-id'), [
257
                    ('f', '', 0, False, null_stat),
258
                    ('f', c_sha, c_len, False, revision_id),
259
                   ]),
260
            'b/d':(('b', 'd', 'd-id'), [
261
                    ('d', '', 0, False, null_stat),
262
                    ('d', '', 0, False, revision_id),
263
                   ]),
264
            'b/d/e':(('b/d', 'e', 'e-id'), [
265
                      ('f', '', 0, False, null_stat),
266
                      ('f', e_sha, e_len, False, revision_id),
267
                     ]),
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
268
            'b-c':(('', 'b-c', 'b-c-id'), [
269
                      ('f', '', 0, False, null_stat),
270
                      ('f', b_c_sha, b_c_len, False, revision_id),
271
                     ]),
2323.5.4 by Martin Pool
Move some dirstate test setup methods into the base class
272
            'f':(('', 'f', 'f-id'), [
273
                  ('f', '', 0, False, null_stat),
274
                  ('f', f_sha, f_len, False, revision_id),
275
                 ]),
276
        }
277
        state = dirstate.DirState.from_tree(tree, 'dirstate')
278
        try:
279
            state.save()
280
        finally:
281
            state.unlock()
282
        # Use a different object, to make sure nothing is pre-cached in memory.
283
        state = dirstate.DirState.on_file('dirstate')
284
        state.lock_read()
285
        self.addCleanup(state.unlock)
286
        self.assertEqual(dirstate.DirState.NOT_IN_MEMORY,
287
                         state._dirblock_state)
288
        # This is code is only really tested if we actually have to make more
289
        # than one read, so set the page size to something smaller.
290
        # We want it to contain about 2.2 records, so that we have a couple
291
        # records that we can read per attempt
292
        state._bisect_page_size = 200
293
        return tree, state, expected
294
295
    def create_duplicated_dirstate(self):
296
        """Create a dirstate with a deleted and added entries.
297
298
        This grabs a basic_dirstate, and then removes and re adds every entry
299
        with a new file id.
300
        """
301
        tree, state, expected = self.create_basic_dirstate()
302
        # Now we will just remove and add every file so we get an extra entry
303
        # per entry. Unversion in reverse order so we handle subdirs
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
304
        tree.unversion(['f-id', 'b-c-id', 'e-id', 'd-id', 'c-id', 'b-id', 'a-id'])
305
        tree.add(['a', 'b', 'b/c', 'b/d', 'b/d/e', 'b-c', 'f'],
306
                 ['a-id2', 'b-id2', 'c-id2', 'd-id2', 'e-id2', 'b-c-id2', 'f-id2'])
2323.5.4 by Martin Pool
Move some dirstate test setup methods into the base class
307
308
        # Update the expected dictionary.
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
309
        for path in ['a', 'b', 'b/c', 'b/d', 'b/d/e', 'b-c', 'f']:
2323.5.4 by Martin Pool
Move some dirstate test setup methods into the base class
310
            orig = expected[path]
311
            path2 = path + '2'
312
            # This record was deleted in the current tree
313
            expected[path] = (orig[0], [dirstate.DirState.NULL_PARENT_DETAILS,
314
                                        orig[1][1]])
315
            new_key = (orig[0][0], orig[0][1], orig[0][2]+'2')
316
            # And didn't exist in the basis tree
317
            expected[path2] = (new_key, [orig[1][0],
318
                                         dirstate.DirState.NULL_PARENT_DETAILS])
319
320
        # We will replace the 'dirstate' file underneath 'state', but that is
321
        # okay as lock as we unlock 'state' first.
322
        state.unlock()
323
        try:
324
            new_state = dirstate.DirState.from_tree(tree, 'dirstate')
325
            try:
326
                new_state.save()
327
            finally:
328
                new_state.unlock()
329
        finally:
330
            # But we need to leave state in a read-lock because we already have
331
            # a cleanup scheduled
332
            state.lock_read()
333
        return tree, state, expected
334
335
    def create_renamed_dirstate(self):
336
        """Create a dirstate with a few internal renames.
337
338
        This takes the basic dirstate, and moves the paths around.
339
        """
340
        tree, state, expected = self.create_basic_dirstate()
341
        # Rename a file
342
        tree.rename_one('a', 'b/g')
343
        # And a directory
344
        tree.rename_one('b/d', 'h')
345
346
        old_a = expected['a']
347
        expected['a'] = (old_a[0], [('r', 'b/g', 0, False, ''), old_a[1][1]])
348
        expected['b/g'] = (('b', 'g', 'a-id'), [old_a[1][0],
349
                                                ('r', 'a', 0, False, '')])
350
        old_d = expected['b/d']
351
        expected['b/d'] = (old_d[0], [('r', 'h', 0, False, ''), old_d[1][1]])
352
        expected['h'] = (('', 'h', 'd-id'), [old_d[1][0],
353
                                             ('r', 'b/d', 0, False, '')])
354
355
        old_e = expected['b/d/e']
356
        expected['b/d/e'] = (old_e[0], [('r', 'h/e', 0, False, ''),
357
                             old_e[1][1]])
358
        expected['h/e'] = (('h', 'e', 'e-id'), [old_e[1][0],
359
                                                ('r', 'b/d/e', 0, False, '')])
360
361
        state.unlock()
362
        try:
363
            new_state = dirstate.DirState.from_tree(tree, 'dirstate')
364
            try:
365
                new_state.save()
366
            finally:
367
                new_state.unlock()
368
        finally:
369
            state.lock_read()
370
        return tree, state, expected
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
371
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
372
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
373
class TestTreeToDirState(TestCaseWithDirState):
1852.13.6 by Robert Collins
start hooking in the prototype dirstate serialiser.
374
375
    def test_empty_to_dirstate(self):
376
        """We should be able to create a dirstate for an empty tree."""
377
        # There are no files on disk and no parents
378
        tree = self.make_branch_and_tree('tree')
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
379
        expected_result = ([], [
2946.3.3 by John Arbash Meinel
Prefer tree.get_root_id() as more explicit than tree.path2id('')
380
            (('', '', tree.get_root_id()), # common details
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
381
             [('d', '', 0, False, dirstate.DirState.NULLSTAT), # current tree
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
382
             ])])
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
383
        state = dirstate.DirState.from_tree(tree, 'dirstate')
2255.7.78 by Martin Pool
Add DirState._validate and call from the tests
384
        state._validate()
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
385
        self.check_state_with_reopen(expected_result, state)
1852.13.6 by Robert Collins
start hooking in the prototype dirstate serialiser.
386
387
    def test_1_parents_empty_to_dirstate(self):
388
        # create a parent by doing a commit
389
        tree = self.make_branch_and_tree('tree')
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
390
        rev_id = tree.commit('first post').encode('utf8')
391
        root_stat_pack = dirstate.pack_stat(os.stat(tree.basedir))
392
        expected_result = ([rev_id], [
2946.3.3 by John Arbash Meinel
Prefer tree.get_root_id() as more explicit than tree.path2id('')
393
            (('', '', tree.get_root_id()), # common details
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
394
             [('d', '', 0, False, dirstate.DirState.NULLSTAT), # current tree
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
395
              ('d', '', 0, False, rev_id), # first parent details
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
396
             ])])
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
397
        state = dirstate.DirState.from_tree(tree, 'dirstate')
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
398
        self.check_state_with_reopen(expected_result, state)
2323.6.13 by Martin Pool
Fix some tests that need to lock dirstate before validating
399
        state.lock_read()
400
        try:
401
            state._validate()
402
        finally:
403
            state.unlock()
1852.13.6 by Robert Collins
start hooking in the prototype dirstate serialiser.
404
405
    def test_2_parents_empty_to_dirstate(self):
406
        # create a parent by doing a commit
407
        tree = self.make_branch_and_tree('tree')
408
        rev_id = tree.commit('first post')
409
        tree2 = tree.bzrdir.sprout('tree2').open_workingtree()
1852.13.24 by Robert Collins
Get back to the broken-pending-revision-tree-from-dirstate state of development, changing dirstate from_tree to use _set_data rather than generating lines itself.
410
        rev_id2 = tree2.commit('second post', allow_pointless=True)
1852.13.19 by Robert Collins
Get DirState objects roundtripping an add of a ghost tree.
411
        tree.merge_from_branch(tree2.branch)
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
412
        expected_result = ([rev_id, rev_id2], [
2946.3.3 by John Arbash Meinel
Prefer tree.get_root_id() as more explicit than tree.path2id('')
413
            (('', '', tree.get_root_id()), # common details
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
414
             [('d', '', 0, False, dirstate.DirState.NULLSTAT), # current tree
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
415
              ('d', '', 0, False, rev_id), # first parent details
4599.4.24 by Robert Collins
Prepare dirstate tests for 2a as default.
416
              ('d', '', 0, False, rev_id), # second parent details
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
417
             ])])
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
418
        state = dirstate.DirState.from_tree(tree, 'dirstate')
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
419
        self.check_state_with_reopen(expected_result, state)
2323.6.13 by Martin Pool
Fix some tests that need to lock dirstate before validating
420
        state.lock_read()
421
        try:
422
            state._validate()
423
        finally:
424
            state.unlock()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
425
1852.13.6 by Robert Collins
start hooking in the prototype dirstate serialiser.
426
    def test_empty_unknowns_are_ignored_to_dirstate(self):
427
        """We should be able to create a dirstate for an empty tree."""
428
        # There are no files on disk and no parents
429
        tree = self.make_branch_and_tree('tree')
1852.13.10 by Robert Collins
Use just the tree api to generate dirstate information.
430
        self.build_tree(['tree/unknown'])
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
431
        expected_result = ([], [
2946.3.3 by John Arbash Meinel
Prefer tree.get_root_id() as more explicit than tree.path2id('')
432
            (('', '', tree.get_root_id()), # common details
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
433
             [('d', '', 0, False, dirstate.DirState.NULLSTAT), # current tree
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
434
             ])])
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
435
        state = dirstate.DirState.from_tree(tree, 'dirstate')
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
436
        self.check_state_with_reopen(expected_result, state)
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
437
1852.13.12 by Robert Collins
get actual parent info for the first parent.
438
    def get_tree_with_a_file(self):
439
        tree = self.make_branch_and_tree('tree')
440
        self.build_tree(['tree/a file'])
3010.1.2 by Robert Collins
Use valid file-ids for dirstate tests.
441
        tree.add('a file', 'a-file-id')
1852.13.12 by Robert Collins
get actual parent info for the first parent.
442
        return tree
443
1852.13.6 by Robert Collins
start hooking in the prototype dirstate serialiser.
444
    def test_non_empty_no_parents_to_dirstate(self):
445
        """We should be able to create a dirstate for an empty tree."""
1852.13.11 by Robert Collins
Get one content containing test passing.
446
        # There are files on disk and no parents
1852.13.12 by Robert Collins
get actual parent info for the first parent.
447
        tree = self.get_tree_with_a_file()
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
448
        expected_result = ([], [
2946.3.3 by John Arbash Meinel
Prefer tree.get_root_id() as more explicit than tree.path2id('')
449
            (('', '', tree.get_root_id()), # common details
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
450
             [('d', '', 0, False, dirstate.DirState.NULLSTAT), # current tree
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
451
             ]),
3010.1.2 by Robert Collins
Use valid file-ids for dirstate tests.
452
            (('', 'a file', 'a-file-id'), # common
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
453
             [('f', '', 0, False, dirstate.DirState.NULLSTAT), # current
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
454
             ]),
455
            ])
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
456
        state = dirstate.DirState.from_tree(tree, 'dirstate')
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
457
        self.check_state_with_reopen(expected_result, state)
1852.13.6 by Robert Collins
start hooking in the prototype dirstate serialiser.
458
459
    def test_1_parents_not_empty_to_dirstate(self):
460
        # create a parent by doing a commit
1852.13.12 by Robert Collins
get actual parent info for the first parent.
461
        tree = self.get_tree_with_a_file()
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
462
        rev_id = tree.commit('first post').encode('utf8')
1852.13.12 by Robert Collins
get actual parent info for the first parent.
463
        # change the current content to be different this will alter stat, sha
464
        # and length:
465
        self.build_tree_contents([('tree/a file', 'new content\n')])
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
466
        expected_result = ([rev_id], [
2946.3.3 by John Arbash Meinel
Prefer tree.get_root_id() as more explicit than tree.path2id('')
467
            (('', '', tree.get_root_id()), # common details
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
468
             [('d', '', 0, False, dirstate.DirState.NULLSTAT), # current tree
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
469
              ('d', '', 0, False, rev_id), # first parent details
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
470
             ]),
3010.1.2 by Robert Collins
Use valid file-ids for dirstate tests.
471
            (('', 'a file', 'a-file-id'), # common
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
472
             [('f', '', 0, False, dirstate.DirState.NULLSTAT), # current
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
473
              ('f', 'c3ed76e4bfd45ff1763ca206055bca8e9fc28aa8', 24, False,
474
               rev_id), # first parent
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
475
             ]),
476
            ])
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
477
        state = dirstate.DirState.from_tree(tree, 'dirstate')
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
478
        self.check_state_with_reopen(expected_result, state)
1852.13.6 by Robert Collins
start hooking in the prototype dirstate serialiser.
479
480
    def test_2_parents_not_empty_to_dirstate(self):
481
        # create a parent by doing a commit
1852.13.13 by Robert Collins
2-parent case working.
482
        tree = self.get_tree_with_a_file()
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
483
        rev_id = tree.commit('first post').encode('utf8')
1852.13.6 by Robert Collins
start hooking in the prototype dirstate serialiser.
484
        tree2 = tree.bzrdir.sprout('tree2').open_workingtree()
1852.13.13 by Robert Collins
2-parent case working.
485
        # change the current content to be different this will alter stat, sha
486
        # and length:
487
        self.build_tree_contents([('tree2/a file', 'merge content\n')])
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
488
        rev_id2 = tree2.commit('second post').encode('utf8')
1852.13.19 by Robert Collins
Get DirState objects roundtripping an add of a ghost tree.
489
        tree.merge_from_branch(tree2.branch)
1852.13.13 by Robert Collins
2-parent case working.
490
        # change the current content to be different this will alter stat, sha
491
        # and length again, giving us three distinct values:
492
        self.build_tree_contents([('tree/a file', 'new content\n')])
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
493
        expected_result = ([rev_id, rev_id2], [
2946.3.3 by John Arbash Meinel
Prefer tree.get_root_id() as more explicit than tree.path2id('')
494
            (('', '', tree.get_root_id()), # common details
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
495
             [('d', '', 0, False, dirstate.DirState.NULLSTAT), # current tree
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
496
              ('d', '', 0, False, rev_id), # first parent details
4599.4.24 by Robert Collins
Prepare dirstate tests for 2a as default.
497
              ('d', '', 0, False, rev_id), # second parent details
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
498
             ]),
3010.1.2 by Robert Collins
Use valid file-ids for dirstate tests.
499
            (('', 'a file', 'a-file-id'), # common
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
500
             [('f', '', 0, False, dirstate.DirState.NULLSTAT), # current
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
501
              ('f', 'c3ed76e4bfd45ff1763ca206055bca8e9fc28aa8', 24, False,
502
               rev_id), # first parent
503
              ('f', '314d796174c9412647c3ce07dfb5d36a94e72958', 14, False,
504
               rev_id2), # second parent
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
505
             ]),
506
            ])
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
507
        state = dirstate.DirState.from_tree(tree, 'dirstate')
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
508
        self.check_state_with_reopen(expected_result, state)
509
2255.7.94 by Martin Pool
Fix dirstate sorting bug and refine the _validate() assertions:
510
    def test_colliding_fileids(self):
511
        # test insertion of parents creating several entries at the same path.
512
        # we used to have a bug where they could cause the dirstate to break
513
        # its ordering invariants.
514
        # create some trees to test from
515
        parents = []
516
        for i in range(7):
517
            tree = self.make_branch_and_tree('tree%d' % i)
518
            self.build_tree(['tree%d/name' % i,])
519
            tree.add(['name'], ['file-id%d' % i])
520
            revision_id = 'revid-%d' % i
521
            tree.commit('message', rev_id=revision_id)
522
            parents.append((revision_id,
523
                tree.branch.repository.revision_tree(revision_id)))
524
        # now fold these trees into a dirstate
525
        state = dirstate.DirState.initialize('dirstate')
526
        try:
527
            state.set_parent_trees(parents, [])
528
            state._validate()
529
        finally:
530
            state.unlock()
531
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
532
533
class TestDirStateOnFile(TestCaseWithDirState):
1852.13.15 by Robert Collins
Ensure Format4 working trees start with a dirstate.
534
5802.3.2 by John Arbash Meinel
We have to update some tests, because what used to be IN_MEMORY_MODIFIED isn't.
535
    def create_updated_dirstate(self):
536
        self.build_tree(['a-file'])
537
        tree = self.make_branch_and_tree('.')
538
        tree.add(['a-file'], ['a-id'])
539
        tree.commit('add a-file')
540
        # Save and unlock the state, re-open it in readonly mode
541
        state = dirstate.DirState.from_tree(tree, 'dirstate')
542
        state.save()
543
        state.unlock()
544
        state = dirstate.DirState.on_file('dirstate')
545
        state.lock_read()
546
        return state
547
1852.13.15 by Robert Collins
Ensure Format4 working trees start with a dirstate.
548
    def test_construct_with_path(self):
549
        tree = self.make_branch_and_tree('tree')
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
550
        state = dirstate.DirState.from_tree(tree, 'dirstate.from_tree')
1852.13.15 by Robert Collins
Ensure Format4 working trees start with a dirstate.
551
        # we want to be able to get the lines of the dirstate that we will
552
        # write to disk.
553
        lines = state.get_lines()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
554
        state.unlock()
1852.13.15 by Robert Collins
Ensure Format4 working trees start with a dirstate.
555
        self.build_tree_contents([('dirstate', ''.join(lines))])
556
        # get a state object
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
557
        # no parents, default tree content
558
        expected_result = ([], [
2946.3.3 by John Arbash Meinel
Prefer tree.get_root_id() as more explicit than tree.path2id('')
559
            (('', '', tree.get_root_id()), # common details
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
560
             # current tree details, but new from_tree skips statting, it
561
             # uses set_state_from_inventory, and thus depends on the
562
             # inventory state.
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
563
             [('d', '', 0, False, dirstate.DirState.NULLSTAT),
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
564
             ])
565
            ])
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
566
        state = dirstate.DirState.on_file('dirstate')
567
        state.lock_write() # check_state_with_reopen will save() and unlock it
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
568
        self.check_state_with_reopen(expected_result, state)
569
570
    def test_can_save_clean_on_file(self):
571
        tree = self.make_branch_and_tree('tree')
572
        state = dirstate.DirState.from_tree(tree, 'dirstate')
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
573
        try:
574
            # doing a save should work here as there have been no changes.
575
            state.save()
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
576
            # TODO: stat it and check it hasn't changed; may require waiting
577
            # for the state accuracy window.
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
578
        finally:
579
            state.unlock()
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
580
2353.4.5 by John Arbash Meinel
Update DirState to use the new 'temporary_write_lock', and add tests that it works.
581
    def test_can_save_in_read_lock(self):
5802.3.2 by John Arbash Meinel
We have to update some tests, because what used to be IN_MEMORY_MODIFIED isn't.
582
        state = self.create_updated_dirstate()
2353.4.5 by John Arbash Meinel
Update DirState to use the new 'temporary_write_lock', and add tests that it works.
583
        try:
584
            entry = state._get_entry(0, path_utf8='a-file')
3709.4.1 by Robert Collins
Sha files for the stat cache more lazily rather than on first-examination, allowing less overall sha calculations to occur.
585
            # The current size should be 0 (default)
586
            self.assertEqual(0, entry[1][0][2])
2353.4.5 by John Arbash Meinel
Update DirState to use the new 'temporary_write_lock', and add tests that it works.
587
            # We should have a real entry.
588
            self.assertNotEqual((None, None), entry)
5802.3.2 by John Arbash Meinel
We have to update some tests, because what used to be IN_MEMORY_MODIFIED isn't.
589
            # Set the cutoff-time into the future, so things look cacheable
2485.3.14 by John Arbash Meinel
Update the code so that symlinks aren't cached at incorrect times
590
            state._sha_cutoff_time()
5802.3.2 by John Arbash Meinel
We have to update some tests, because what used to be IN_MEMORY_MODIFIED isn't.
591
            state._cutoff_time += 10.0
592
            st = os.lstat('a-file')
593
            sha1sum = dirstate.update_entry(state, entry, 'a-file', st)
594
            # We updated the current sha1sum because the file is cacheable
595
            self.assertEqual('ecc5374e9ed82ad3ea3b4d452ea995a5fd3e70e3',
596
                             sha1sum)
2353.4.5 by John Arbash Meinel
Update DirState to use the new 'temporary_write_lock', and add tests that it works.
597
598
            # The dirblock has been updated
5802.3.2 by John Arbash Meinel
We have to update some tests, because what used to be IN_MEMORY_MODIFIED isn't.
599
            self.assertEqual(st.st_size, entry[1][0][2])
5807.4.3 by John Arbash Meinel
Get the test suite to run clean for bt.test_dirstate bt.test__dirstate bt.test_workingtree
600
            self.assertEqual(dirstate.DirState.IN_MEMORY_HASH_MODIFIED,
2353.4.5 by John Arbash Meinel
Update DirState to use the new 'temporary_write_lock', and add tests that it works.
601
                             state._dirblock_state)
602
603
            del entry
604
            # Now, since we are the only one holding a lock, we should be able
605
            # to save and have it written to disk
606
            state.save()
607
        finally:
608
            state.unlock()
609
610
        # Re-open the file, and ensure that the state has been updated.
611
        state = dirstate.DirState.on_file('dirstate')
612
        state.lock_read()
613
        try:
614
            entry = state._get_entry(0, path_utf8='a-file')
5802.3.2 by John Arbash Meinel
We have to update some tests, because what used to be IN_MEMORY_MODIFIED isn't.
615
            self.assertEqual(st.st_size, entry[1][0][2])
2353.4.5 by John Arbash Meinel
Update DirState to use the new 'temporary_write_lock', and add tests that it works.
616
        finally:
617
            state.unlock()
618
619
    def test_save_fails_quietly_if_locked(self):
620
        """If dirstate is locked, save will fail without complaining."""
5802.3.2 by John Arbash Meinel
We have to update some tests, because what used to be IN_MEMORY_MODIFIED isn't.
621
        state = self.create_updated_dirstate()
2353.4.5 by John Arbash Meinel
Update DirState to use the new 'temporary_write_lock', and add tests that it works.
622
        try:
623
            entry = state._get_entry(0, path_utf8='a-file')
5802.3.2 by John Arbash Meinel
We have to update some tests, because what used to be IN_MEMORY_MODIFIED isn't.
624
            # No cached sha1 yet.
625
            self.assertEqual('', entry[1][0][1])
626
            # Set the cutoff-time into the future, so things look cacheable
627
            state._sha_cutoff_time()
628
            state._cutoff_time += 10.0
629
            st = os.lstat('a-file')
630
            sha1sum = dirstate.update_entry(state, entry, 'a-file', st)
631
            self.assertEqual('ecc5374e9ed82ad3ea3b4d452ea995a5fd3e70e3',
632
                             sha1sum)
5807.4.3 by John Arbash Meinel
Get the test suite to run clean for bt.test_dirstate bt.test__dirstate bt.test_workingtree
633
            self.assertEqual(dirstate.DirState.IN_MEMORY_HASH_MODIFIED,
2353.4.5 by John Arbash Meinel
Update DirState to use the new 'temporary_write_lock', and add tests that it works.
634
                             state._dirblock_state)
635
636
            # Now, before we try to save, grab another dirstate, and take out a
637
            # read lock.
638
            # TODO: jam 20070315 Ideally this would be locked by another
639
            #       process. To make sure the file is really OS locked.
640
            state2 = dirstate.DirState.on_file('dirstate')
641
            state2.lock_read()
642
            try:
643
                # This won't actually write anything, because it couldn't grab
644
                # a write lock. But it shouldn't raise an error, either.
645
                # TODO: jam 20070315 We should probably distinguish between
646
                #       being dirty because of 'update_entry'. And dirty
647
                #       because of real modification. So that save() *does*
648
                #       raise a real error if it fails when we have real
649
                #       modifications.
650
                state.save()
651
            finally:
652
                state2.unlock()
653
        finally:
654
            state.unlock()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
655
2353.4.5 by John Arbash Meinel
Update DirState to use the new 'temporary_write_lock', and add tests that it works.
656
        # The file on disk should not be modified.
657
        state = dirstate.DirState.on_file('dirstate')
658
        state.lock_read()
659
        try:
660
            entry = state._get_entry(0, path_utf8='a-file')
661
            self.assertEqual('', entry[1][0][1])
662
        finally:
663
            state.unlock()
664
3221.1.7 by Martin Pool
Update and rename test for Dirstate._changes_aborted
665
    def test_save_refuses_if_changes_aborted(self):
3207.2.2 by John Arbash Meinel
Fix bug #187169, when an invalid delta is supplied to update_basis_by_delta
666
        self.build_tree(['a-file', 'a-dir/'])
667
        state = dirstate.DirState.initialize('dirstate')
668
        try:
669
            # No stat and no sha1 sum.
670
            state.add('a-file', 'a-file-id', 'file', None, '')
671
            state.save()
672
        finally:
673
            state.unlock()
674
675
        # The dirstate should include TREE_ROOT and 'a-file' and nothing else
676
        expected_blocks = [
677
            ('', [(('', '', 'TREE_ROOT'),
678
                   [('d', '', 0, False, dirstate.DirState.NULLSTAT)])]),
679
            ('', [(('', 'a-file', 'a-file-id'),
680
                   [('f', '', 0, False, dirstate.DirState.NULLSTAT)])]),
681
        ]
682
683
        state = dirstate.DirState.on_file('dirstate')
684
        state.lock_write()
685
        try:
686
            state._read_dirblocks_if_needed()
687
            self.assertEqual(expected_blocks, state._dirblocks)
688
689
            # Now modify the state, but mark it as inconsistent
690
            state.add('a-dir', 'a-dir-id', 'directory', None, '')
3221.1.7 by Martin Pool
Update and rename test for Dirstate._changes_aborted
691
            state._changes_aborted = True
3207.2.2 by John Arbash Meinel
Fix bug #187169, when an invalid delta is supplied to update_basis_by_delta
692
            state.save()
693
        finally:
694
            state.unlock()
695
696
        state = dirstate.DirState.on_file('dirstate')
697
        state.lock_read()
698
        try:
699
            state._read_dirblocks_if_needed()
700
            self.assertEqual(expected_blocks, state._dirblocks)
701
        finally:
702
            state.unlock()
703
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
704
705
class TestDirStateInitialize(TestCaseWithDirState):
1852.13.15 by Robert Collins
Ensure Format4 working trees start with a dirstate.
706
707
    def test_initialize(self):
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
708
        expected_result = ([], [
709
            (('', '', 'TREE_ROOT'), # common details
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
710
             [('d', '', 0, False, dirstate.DirState.NULLSTAT), # current tree
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
711
             ])
712
            ])
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
713
        state = dirstate.DirState.initialize('dirstate')
714
        try:
715
            self.assertIsInstance(state, dirstate.DirState)
716
            lines = state.get_lines()
2425.3.1 by John Arbash Meinel
Change the DirState.test_initialize test so that we don't try to read a locked file.
717
        finally:
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
718
            state.unlock()
2425.3.1 by John Arbash Meinel
Change the DirState.test_initialize test so that we don't try to read a locked file.
719
        # On win32 you can't read from a locked file, even within the same
720
        # process. So we have to unlock and release before we check the file
721
        # contents.
722
        self.assertFileEqual(''.join(lines), 'dirstate')
723
        state.lock_read() # check_state_with_reopen will unlock
724
        self.check_state_with_reopen(expected_result, state)
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
725
726
727
class TestDirStateManipulations(TestCaseWithDirState):
1852.13.19 by Robert Collins
Get DirState objects roundtripping an add of a ghost tree.
728
5630.2.6 by John Arbash Meinel
Implement a reset-to-known-state ability for DirState.
729
    def make_minimal_tree(self):
730
        tree1 = self.make_branch_and_memory_tree('tree1')
731
        tree1.lock_write()
732
        self.addCleanup(tree1.unlock)
733
        tree1.add('')
734
        revid1 = tree1.commit('foo')
735
        return tree1, revid1
736
5050.26.1 by John Arbash Meinel
Fix a bug in update_minimal.
737
    def test_update_minimal_updates_id_index(self):
738
        state = self.create_dirstate_with_root_and_subdir()
739
        self.addCleanup(state.unlock)
740
        id_index = state._get_id_index()
741
        self.assertEqual(['a-root-value', 'subdir-id'], sorted(id_index))
742
        state.add('file-name', 'file-id', 'file', None, '')
743
        self.assertEqual(['a-root-value', 'file-id', 'subdir-id'],
744
                         sorted(id_index))
745
        state.update_minimal(('', 'new-name', 'file-id'), 'f',
746
                             path_utf8='new-name')
747
        self.assertEqual(['a-root-value', 'file-id', 'subdir-id'],
748
                         sorted(id_index))
749
        self.assertEqual([('', 'new-name', 'file-id')],
750
                         sorted(id_index['file-id']))
751
        state._validate()
752
2255.2.16 by Robert Collins
Implement WorkingTreeFormat4._write_inventory for better compatability with existing code, letting more test_test_trees pass, now up to test_tree_with_subdirs_and_all_content_types.
753
    def test_set_state_from_inventory_no_content_no_parents(self):
754
        # setting the current inventory is a slow but important api to support.
5630.2.6 by John Arbash Meinel
Implement a reset-to-known-state ability for DirState.
755
        tree1, revid1 = self.make_minimal_tree()
756
        inv = tree1.inventory
757
        root_id = inv.path2id('')
2255.2.87 by Robert Collins
core dirstate tests passing with new structure.
758
        expected_result = [], [
759
            (('', '', root_id), [
2255.2.124 by John Arbash Meinel
Remove direct access to Dirstate prefering dirstate.Dirstate
760
             ('d', '', 0, False, dirstate.DirState.NULLSTAT)])]
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
761
        state = dirstate.DirState.initialize('dirstate')
762
        try:
763
            state.set_state_from_inventory(inv)
2255.2.124 by John Arbash Meinel
Remove direct access to Dirstate prefering dirstate.Dirstate
764
            self.assertEqual(dirstate.DirState.IN_MEMORY_UNMODIFIED,
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
765
                             state._header_state)
2255.2.124 by John Arbash Meinel
Remove direct access to Dirstate prefering dirstate.Dirstate
766
            self.assertEqual(dirstate.DirState.IN_MEMORY_MODIFIED,
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
767
                             state._dirblock_state)
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
768
        except:
769
            state.unlock()
770
            raise
771
        else:
772
            # This will unlock it
773
            self.check_state_with_reopen(expected_result, state)
2255.2.16 by Robert Collins
Implement WorkingTreeFormat4._write_inventory for better compatability with existing code, letting more test_test_trees pass, now up to test_tree_with_subdirs_and_all_content_types.
774
5630.2.6 by John Arbash Meinel
Implement a reset-to-known-state ability for DirState.
775
    def test_set_state_from_scratch_no_parents(self):
776
        tree1, revid1 = self.make_minimal_tree()
777
        inv = tree1.inventory
778
        root_id = inv.path2id('')
779
        expected_result = [], [
780
            (('', '', root_id), [
781
             ('d', '', 0, False, dirstate.DirState.NULLSTAT)])]
782
        state = dirstate.DirState.initialize('dirstate')
783
        try:
784
            state.set_state_from_scratch(inv, [], [])
785
            self.assertEqual(dirstate.DirState.IN_MEMORY_MODIFIED,
786
                             state._header_state)
787
            self.assertEqual(dirstate.DirState.IN_MEMORY_MODIFIED,
788
                             state._dirblock_state)
789
        except:
790
            state.unlock()
791
            raise
792
        else:
793
            # This will unlock it
794
            self.check_state_with_reopen(expected_result, state)
795
796
    def test_set_state_from_scratch_identical_parent(self):
797
        tree1, revid1 = self.make_minimal_tree()
798
        inv = tree1.inventory
799
        root_id = inv.path2id('')
800
        rev_tree1 = tree1.branch.repository.revision_tree(revid1)
801
        d_entry = ('d', '', 0, False, dirstate.DirState.NULLSTAT)
802
        parent_entry = ('d', '', 0, False, revid1)
803
        expected_result = [revid1], [
804
            (('', '', root_id), [d_entry, parent_entry])]
805
        state = dirstate.DirState.initialize('dirstate')
806
        try:
807
            state.set_state_from_scratch(inv, [(revid1, rev_tree1)], [])
808
            self.assertEqual(dirstate.DirState.IN_MEMORY_MODIFIED,
809
                             state._header_state)
810
            self.assertEqual(dirstate.DirState.IN_MEMORY_MODIFIED,
811
                             state._dirblock_state)
812
        except:
813
            state.unlock()
814
            raise
815
        else:
816
            # This will unlock it
817
            self.check_state_with_reopen(expected_result, state)
818
2872.4.3 by Martin Pool
Fix comparison for merge sort in Dirstate.set_state_from_inventory
819
    def test_set_state_from_inventory_preserves_hashcache(self):
2872.4.11 by Martin Pool
Review documentation cleanups
820
        # https://bugs.launchpad.net/bzr/+bug/146176
2872.4.1 by Martin Pool
Add xfail test for #146176
821
        # set_state_from_inventory should preserve the stat and hash value for
822
        # workingtree files that are not changed by the inventory.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
823
2872.4.1 by Martin Pool
Add xfail test for #146176
824
        tree = self.make_branch_and_tree('.')
825
        # depends on the default format using dirstate...
826
        tree.lock_write()
827
        try:
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
828
            # make a dirstate with some valid hashcache data
2872.4.1 by Martin Pool
Add xfail test for #146176
829
            # file on disk, but that's not needed for this test
830
            foo_contents = 'contents of foo'
831
            self.build_tree_contents([('foo', foo_contents)])
832
            tree.add('foo', 'foo-id')
833
834
            foo_stat = os.stat('foo')
835
            foo_packed = dirstate.pack_stat(foo_stat)
836
            foo_sha = osutils.sha_string(foo_contents)
837
            foo_size = len(foo_contents)
838
839
            # should not be cached yet, because the file's too fresh
2872.4.8 by Martin Pool
Clear up test code
840
            self.assertEqual(
841
                (('', 'foo', 'foo-id',),
842
                 [('f', '', 0, False, dirstate.DirState.NULLSTAT)]),
843
                tree._dirstate._get_entry(0, 'foo-id'))
2872.4.1 by Martin Pool
Add xfail test for #146176
844
            # poke in some hashcache information - it wouldn't normally be
845
            # stored because it's too fresh
846
            tree._dirstate.update_minimal(
847
                ('', 'foo', 'foo-id'),
848
                'f', False, foo_sha, foo_packed, foo_size, 'foo')
849
            # now should be cached
2872.4.8 by Martin Pool
Clear up test code
850
            self.assertEqual(
851
                (('', 'foo', 'foo-id',),
852
                 [('f', foo_sha, foo_size, False, foo_packed)]),
853
                tree._dirstate._get_entry(0, 'foo-id'))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
854
2872.4.1 by Martin Pool
Add xfail test for #146176
855
            # extract the inventory, and add something to it
856
            inv = tree._get_inventory()
2872.4.3 by Martin Pool
Fix comparison for merge sort in Dirstate.set_state_from_inventory
857
            # should see the file we poked in...
858
            self.assertTrue(inv.has_id('foo-id'))
859
            self.assertTrue(inv.has_filename('foo'))
2872.4.1 by Martin Pool
Add xfail test for #146176
860
            inv.add_path('bar', 'file', 'bar-id')
2872.4.13 by Martin Pool
Validate dirstate during tests
861
            tree._dirstate._validate()
2872.4.11 by Martin Pool
Review documentation cleanups
862
            # this used to cause it to lose its hashcache
2872.4.1 by Martin Pool
Add xfail test for #146176
863
            tree._dirstate.set_state_from_inventory(inv)
2872.4.13 by Martin Pool
Validate dirstate during tests
864
            tree._dirstate._validate()
2872.4.1 by Martin Pool
Add xfail test for #146176
865
        finally:
866
            tree.unlock()
867
868
        tree.lock_read()
869
        try:
870
            # now check that the state still has the original hashcache value
871
            state = tree._dirstate
2872.4.13 by Martin Pool
Validate dirstate during tests
872
            state._validate()
2872.4.1 by Martin Pool
Add xfail test for #146176
873
            foo_tuple = state._get_entry(0, path_utf8='foo')
2872.4.3 by Martin Pool
Fix comparison for merge sort in Dirstate.set_state_from_inventory
874
            self.assertEqual(
2872.4.1 by Martin Pool
Add xfail test for #146176
875
                (('', 'foo', 'foo-id',),
876
                 [('f', foo_sha, len(foo_contents), False,
877
                   dirstate.pack_stat(foo_stat))]),
878
                foo_tuple)
879
        finally:
880
            tree.unlock()
881
2487.1.1 by John Arbash Meinel
Adding a (broken) test that set_state_from_inventory works
882
    def test_set_state_from_inventory_mixed_paths(self):
883
        tree1 = self.make_branch_and_tree('tree1')
884
        self.build_tree(['tree1/a/', 'tree1/a/b/', 'tree1/a-b/',
885
                         'tree1/a/b/foo', 'tree1/a-b/bar'])
886
        tree1.lock_write()
887
        try:
888
            tree1.add(['a', 'a/b', 'a-b', 'a/b/foo', 'a-b/bar'],
889
                      ['a-id', 'b-id', 'a-b-id', 'foo-id', 'bar-id'])
890
            tree1.commit('rev1', rev_id='rev1')
891
            root_id = tree1.get_root_id()
892
            inv = tree1.inventory
893
        finally:
894
            tree1.unlock()
895
        expected_result1 = [('', '', root_id, 'd'),
896
                            ('', 'a', 'a-id', 'd'),
897
                            ('', 'a-b', 'a-b-id', 'd'),
898
                            ('a', 'b', 'b-id', 'd'),
899
                            ('a/b', 'foo', 'foo-id', 'f'),
900
                            ('a-b', 'bar', 'bar-id', 'f'),
901
                           ]
902
        expected_result2 = [('', '', root_id, 'd'),
903
                            ('', 'a', 'a-id', 'd'),
904
                            ('', 'a-b', 'a-b-id', 'd'),
905
                            ('a-b', 'bar', 'bar-id', 'f'),
906
                           ]
907
        state = dirstate.DirState.initialize('dirstate')
908
        try:
909
            state.set_state_from_inventory(inv)
910
            values = []
911
            for entry in state._iter_entries():
912
                values.append(entry[0] + entry[1][0][:1])
913
            self.assertEqual(expected_result1, values)
914
            del inv['b-id']
915
            state.set_state_from_inventory(inv)
916
            values = []
917
            for entry in state._iter_entries():
918
                values.append(entry[0] + entry[1][0][:1])
919
            self.assertEqual(expected_result2, values)
920
        finally:
921
            state.unlock()
922
2255.2.4 by Robert Collins
Snapshot dirstate development
923
    def test_set_path_id_no_parents(self):
924
        """The id of a path can be changed trivally with no parents."""
925
        state = dirstate.DirState.initialize('dirstate')
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
926
        try:
927
            # check precondition to be sure the state does change appropriately.
4634.123.4 by John Arbash Meinel
Start working on some direct dirstate tests.
928
            root_entry = (('', '', 'TREE_ROOT'), [('d', '', 0, False, 'x'*32)])
929
            self.assertEqual([root_entry], list(state._iter_entries()))
930
            self.assertEqual(root_entry, state._get_entry(0, path_utf8=''))
931
            self.assertEqual(root_entry,
932
                             state._get_entry(0, fileid_utf8='TREE_ROOT'))
933
            self.assertEqual((None, None),
4634.123.9 by John Arbash Meinel
Fix a bug in the dirstate logic for 'set_path_id'.
934
                             state._get_entry(0, fileid_utf8='second-root-id'))
935
            state.set_path_id('', 'second-root-id')
936
            new_root_entry = (('', '', 'second-root-id'),
4634.123.4 by John Arbash Meinel
Start working on some direct dirstate tests.
937
                              [('d', '', 0, False, 'x'*32)])
938
            expected_rows = [new_root_entry]
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
939
            self.assertEqual(expected_rows, list(state._iter_entries()))
4634.123.4 by John Arbash Meinel
Start working on some direct dirstate tests.
940
            self.assertEqual(new_root_entry, state._get_entry(0, path_utf8=''))
941
            self.assertEqual(new_root_entry, 
4634.123.9 by John Arbash Meinel
Fix a bug in the dirstate logic for 'set_path_id'.
942
                             state._get_entry(0, fileid_utf8='second-root-id'))
4634.123.4 by John Arbash Meinel
Start working on some direct dirstate tests.
943
            self.assertEqual((None, None),
944
                             state._get_entry(0, fileid_utf8='TREE_ROOT'))
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
945
            # should work across save too
946
            state.save()
947
        finally:
948
            state.unlock()
2255.2.15 by Robert Collins
Dirstate - truncate state file fixing bug in saving a smaller file, get more tree_implementation tests passing.
949
        state = dirstate.DirState.on_file('dirstate')
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
950
        state.lock_read()
951
        try:
2323.6.13 by Martin Pool
Fix some tests that need to lock dirstate before validating
952
            state._validate()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
953
            self.assertEqual(expected_rows, list(state._iter_entries()))
954
        finally:
955
            state.unlock()
2255.2.4 by Robert Collins
Snapshot dirstate development
956
2255.7.68 by Martin Pool
Add a test for setting the root id in a dirstate with parent trees
957
    def test_set_path_id_with_parents(self):
958
        """Set the root file id in a dirstate with parents"""
959
        mt = self.make_branch_and_tree('mt')
2255.2.178 by Martin Pool
test_set_path_id_with_parents shouldn't depend on tree default root id
960
        # in case the default tree format uses a different root id
961
        mt.set_root_id('TREE_ROOT')
2255.7.68 by Martin Pool
Add a test for setting the root id in a dirstate with parent trees
962
        mt.commit('foo', rev_id='parent-revid')
963
        rt = mt.branch.repository.revision_tree('parent-revid')
964
        state = dirstate.DirState.initialize('dirstate')
2255.7.78 by Martin Pool
Add DirState._validate and call from the tests
965
        state._validate()
2255.7.68 by Martin Pool
Add a test for setting the root id in a dirstate with parent trees
966
        try:
967
            state.set_parent_trees([('parent-revid', rt)], ghosts=[])
4634.123.9 by John Arbash Meinel
Fix a bug in the dirstate logic for 'set_path_id'.
968
            root_entry = (('', '', 'TREE_ROOT'),
969
                          [('d', '', 0, False, 'x'*32),
970
                           ('d', '', 0, False, 'parent-revid')])
971
            self.assertEqual(root_entry, state._get_entry(0, path_utf8=''))
972
            self.assertEqual(root_entry,
973
                             state._get_entry(0, fileid_utf8='TREE_ROOT'))
974
            self.assertEqual((None, None),
975
                             state._get_entry(0, fileid_utf8='Asecond-root-id'))
976
            state.set_path_id('', 'Asecond-root-id')
2255.2.177 by Martin Pool
merge dirstate sorting fix, add more validation tests
977
            state._validate()
2255.7.68 by Martin Pool
Add a test for setting the root id in a dirstate with parent trees
978
            # now see that it is what we expected
4634.123.9 by John Arbash Meinel
Fix a bug in the dirstate logic for 'set_path_id'.
979
            old_root_entry = (('', '', 'TREE_ROOT'),
980
                              [('a', '', 0, False, ''),
981
                               ('d', '', 0, False, 'parent-revid')])
982
            new_root_entry = (('', '', 'Asecond-root-id'),
983
                              [('d', '', 0, False, ''),
984
                               ('a', '', 0, False, '')])
985
            expected_rows = [new_root_entry, old_root_entry]
2255.11.2 by Martin Pool
Add more dirstate root-id-changing tests
986
            state._validate()
2255.7.68 by Martin Pool
Add a test for setting the root id in a dirstate with parent trees
987
            self.assertEqual(expected_rows, list(state._iter_entries()))
4634.123.9 by John Arbash Meinel
Fix a bug in the dirstate logic for 'set_path_id'.
988
            self.assertEqual(new_root_entry, state._get_entry(0, path_utf8=''))
989
            self.assertEqual(old_root_entry, state._get_entry(1, path_utf8=''))
990
            self.assertEqual((None, None),
991
                             state._get_entry(0, fileid_utf8='TREE_ROOT'))
992
            self.assertEqual(old_root_entry,
993
                             state._get_entry(1, fileid_utf8='TREE_ROOT'))
994
            self.assertEqual(new_root_entry,
995
                             state._get_entry(0, fileid_utf8='Asecond-root-id'))
996
            self.assertEqual((None, None),
997
                             state._get_entry(1, fileid_utf8='Asecond-root-id'))
2255.7.68 by Martin Pool
Add a test for setting the root id in a dirstate with parent trees
998
            # should work across save too
999
            state.save()
1000
        finally:
1001
            state.unlock()
1002
        # now flush & check we get the same
1003
        state = dirstate.DirState.on_file('dirstate')
1004
        state.lock_read()
1005
        try:
2255.11.2 by Martin Pool
Add more dirstate root-id-changing tests
1006
            state._validate()
2255.7.68 by Martin Pool
Add a test for setting the root id in a dirstate with parent trees
1007
            self.assertEqual(expected_rows, list(state._iter_entries()))
1008
        finally:
1009
            state.unlock()
2255.11.2 by Martin Pool
Add more dirstate root-id-changing tests
1010
        # now change within an existing file-backed state
1011
        state.lock_write()
1012
        try:
1013
            state._validate()
1014
            state.set_path_id('', 'tree-root-2')
1015
            state._validate()
1016
        finally:
1017
            state.unlock()
1018
1852.13.24 by Robert Collins
Get back to the broken-pending-revision-tree-from-dirstate state of development, changing dirstate from_tree to use _set_data rather than generating lines itself.
1019
    def test_set_parent_trees_no_content(self):
1020
        # set_parent_trees is a slow but important api to support.
1021
        tree1 = self.make_branch_and_memory_tree('tree1')
2255.2.2 by Robert Collins
Partial updates for API changes in trunk.
1022
        tree1.lock_write()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1023
        try:
1024
            tree1.add('')
1025
            revid1 = tree1.commit('foo')
1026
        finally:
1027
            tree1.unlock()
2255.2.4 by Robert Collins
Snapshot dirstate development
1028
        branch2 = tree1.branch.bzrdir.clone('tree2').open_branch()
4241.14.10 by Vincent Ladeuil
Add DirReader parametrized tests.
1029
        tree2 = memorytree.MemoryTree.create_on_branch(branch2)
2255.2.2 by Robert Collins
Partial updates for API changes in trunk.
1030
        tree2.lock_write()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1031
        try:
1032
            revid2 = tree2.commit('foo')
2946.3.3 by John Arbash Meinel
Prefer tree.get_root_id() as more explicit than tree.path2id('')
1033
            root_id = tree2.get_root_id()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1034
        finally:
1035
            tree2.unlock()
1036
        state = dirstate.DirState.initialize('dirstate')
1037
        try:
1038
            state.set_path_id('', root_id)
1039
            state.set_parent_trees(
1040
                ((revid1, tree1.branch.repository.revision_tree(revid1)),
1041
                 (revid2, tree2.branch.repository.revision_tree(revid2)),
1042
                 ('ghost-rev', None)),
1043
                ['ghost-rev'])
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1044
            # check we can reopen and use the dirstate after setting parent
1045
            # trees.
2255.7.78 by Martin Pool
Add DirState._validate and call from the tests
1046
            state._validate()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1047
            state.save()
2255.7.78 by Martin Pool
Add DirState._validate and call from the tests
1048
            state._validate()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1049
        finally:
1050
            state.unlock()
2255.2.3 by Robert Collins
Split out working tree format 4 to its own file, create stub dirstate revision object, start working on dirstate.set_parent_trees - a key failure point.
1051
        state = dirstate.DirState.on_file('dirstate')
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1052
        state.lock_write()
1053
        try:
1054
            self.assertEqual([revid1, revid2, 'ghost-rev'],
1055
                             state.get_parent_ids())
1056
            # iterating the entire state ensures that the state is parsable.
1057
            list(state._iter_entries())
1058
            # be sure that it sets not appends - change it
1059
            state.set_parent_trees(
1060
                ((revid1, tree1.branch.repository.revision_tree(revid1)),
1061
                 ('ghost-rev', None)),
1062
                ['ghost-rev'])
1063
            # and now put it back.
1064
            state.set_parent_trees(
1065
                ((revid1, tree1.branch.repository.revision_tree(revid1)),
1066
                 (revid2, tree2.branch.repository.revision_tree(revid2)),
3668.5.1 by Jelmer Vernooij
Use NULL_REVISION rather than None for Repository.revision_tree().
1067
                 ('ghost-rev', tree2.branch.repository.revision_tree(
1068
                                   _mod_revision.NULL_REVISION))),
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1069
                ['ghost-rev'])
1070
            self.assertEqual([revid1, revid2, 'ghost-rev'],
1071
                             state.get_parent_ids())
1072
            # the ghost should be recorded as such by set_parent_trees.
1073
            self.assertEqual(['ghost-rev'], state.get_ghosts())
1074
            self.assertEqual(
1075
                [(('', '', root_id), [
2255.2.124 by John Arbash Meinel
Remove direct access to Dirstate prefering dirstate.Dirstate
1076
                  ('d', '', 0, False, dirstate.DirState.NULLSTAT),
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1077
                  ('d', '', 0, False, revid1),
4599.4.24 by Robert Collins
Prepare dirstate tests for 2a as default.
1078
                  ('d', '', 0, False, revid1)
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1079
                  ])],
1080
                list(state._iter_entries()))
1081
        finally:
1082
            state.unlock()
1852.13.19 by Robert Collins
Get DirState objects roundtripping an add of a ghost tree.
1083
2255.2.9 by Robert Collins
Dirstate: Fix setting of parent trees to record data about entries not in
1084
    def test_set_parent_trees_file_missing_from_tree(self):
1085
        # Adding a parent tree may reference files not in the current state.
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1086
        # they should get listed just once by id, even if they are in two
2255.2.9 by Robert Collins
Dirstate: Fix setting of parent trees to record data about entries not in
1087
        # separate trees.
1088
        # set_parent_trees is a slow but important api to support.
1089
        tree1 = self.make_branch_and_memory_tree('tree1')
1090
        tree1.lock_write()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1091
        try:
1092
            tree1.add('')
1093
            tree1.add(['a file'], ['file-id'], ['file'])
1094
            tree1.put_file_bytes_non_atomic('file-id', 'file-content')
1095
            revid1 = tree1.commit('foo')
1096
        finally:
1097
            tree1.unlock()
2255.2.9 by Robert Collins
Dirstate: Fix setting of parent trees to record data about entries not in
1098
        branch2 = tree1.branch.bzrdir.clone('tree2').open_branch()
4241.14.10 by Vincent Ladeuil
Add DirReader parametrized tests.
1099
        tree2 = memorytree.MemoryTree.create_on_branch(branch2)
2255.2.9 by Robert Collins
Dirstate: Fix setting of parent trees to record data about entries not in
1100
        tree2.lock_write()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1101
        try:
1102
            tree2.put_file_bytes_non_atomic('file-id', 'new file-content')
1103
            revid2 = tree2.commit('foo')
2946.3.3 by John Arbash Meinel
Prefer tree.get_root_id() as more explicit than tree.path2id('')
1104
            root_id = tree2.get_root_id()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1105
        finally:
1106
            tree2.unlock()
2255.2.9 by Robert Collins
Dirstate: Fix setting of parent trees to record data about entries not in
1107
        # check the layout in memory
2255.2.87 by Robert Collins
core dirstate tests passing with new structure.
1108
        expected_result = [revid1.encode('utf8'), revid2.encode('utf8')], [
1109
            (('', '', root_id), [
2255.2.124 by John Arbash Meinel
Remove direct access to Dirstate prefering dirstate.Dirstate
1110
             ('d', '', 0, False, dirstate.DirState.NULLSTAT),
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
1111
             ('d', '', 0, False, revid1.encode('utf8')),
4599.4.24 by Robert Collins
Prepare dirstate tests for 2a as default.
1112
             ('d', '', 0, False, revid1.encode('utf8'))
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1113
             ]),
2255.2.87 by Robert Collins
core dirstate tests passing with new structure.
1114
            (('', 'a file', 'file-id'), [
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
1115
             ('a', '', 0, False, ''),
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1116
             ('f', '2439573625385400f2a669657a7db6ae7515d371', 12, False,
1117
              revid1.encode('utf8')),
1118
             ('f', '542e57dc1cda4af37cb8e55ec07ce60364bb3c7d', 16, False,
1119
              revid2.encode('utf8'))
1120
             ])
2255.2.9 by Robert Collins
Dirstate: Fix setting of parent trees to record data about entries not in
1121
            ]
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1122
        state = dirstate.DirState.initialize('dirstate')
1123
        try:
1124
            state.set_path_id('', root_id)
1125
            state.set_parent_trees(
1126
                ((revid1, tree1.branch.repository.revision_tree(revid1)),
1127
                 (revid2, tree2.branch.repository.revision_tree(revid2)),
1128
                 ), [])
1129
        except:
1130
            state.unlock()
1131
            raise
1132
        else:
1133
            # check_state_with_reopen will unlock
1134
            self.check_state_with_reopen(expected_result, state)
2255.2.9 by Robert Collins
Dirstate: Fix setting of parent trees to record data about entries not in
1135
1852.13.20 by Robert Collins
Steps toward an object model.
1136
    ### add a path via _set_data - so we dont need delta work, just
1137
    # raw data in, and ensure that it comes out via get_lines happily.
1852.13.19 by Robert Collins
Get DirState objects roundtripping an add of a ghost tree.
1138
1852.13.25 by Robert Collins
Snapshot state
1139
    def test_add_path_to_root_no_parents_all_data(self):
1140
        # The most trivial addition of a path is when there are no parents and
1141
        # its in the root and all data about the file is supplied
1142
        self.build_tree(['a file'])
1143
        stat = os.lstat('a file')
1144
        # the 1*20 is the sha1 pretend value.
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1145
        state = dirstate.DirState.initialize('dirstate')
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1146
        expected_entries = [
1147
            (('', '', 'TREE_ROOT'), [
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1148
             ('d', '', 0, False, dirstate.DirState.NULLSTAT), # current tree
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1149
             ]),
3010.1.2 by Robert Collins
Use valid file-ids for dirstate tests.
1150
            (('', 'a file', 'a-file-id'), [
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1151
             ('f', '1'*20, 19, False, dirstate.pack_stat(stat)), # current tree
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1152
             ]),
2255.2.13 by Robert Collins
Test adding of directories to the root of a dirstate.
1153
            ]
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1154
        try:
3010.1.2 by Robert Collins
Use valid file-ids for dirstate tests.
1155
            state.add('a file', 'a-file-id', 'file', stat, '1'*20)
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1156
            # having added it, it should be in the output of iter_entries.
1157
            self.assertEqual(expected_entries, list(state._iter_entries()))
1158
            # saving and reloading should not affect this.
1159
            state.save()
1160
        finally:
1161
            state.unlock()
2255.2.13 by Robert Collins
Test adding of directories to the root of a dirstate.
1162
        state = dirstate.DirState.on_file('dirstate')
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1163
        state.lock_read()
4241.14.10 by Vincent Ladeuil
Add DirReader parametrized tests.
1164
        self.addCleanup(state.unlock)
1165
        self.assertEqual(expected_entries, list(state._iter_entries()))
2255.2.13 by Robert Collins
Test adding of directories to the root of a dirstate.
1166
1167
    def test_add_path_to_unversioned_directory(self):
2255.2.29 by Robert Collins
Change the error raised from Dirstate.add for an unversioned parent path to match the WorkingTree interface.
1168
        """Adding a path to an unversioned directory should error.
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1169
1170
        This is a duplicate of TestWorkingTree.test_add_in_unversioned,
2255.2.29 by Robert Collins
Change the error raised from Dirstate.add for an unversioned parent path to match the WorkingTree interface.
1171
        once dirstate is stable and if it is merged with WorkingTree3, consider
1172
        removing this copy of the test.
1173
        """
2255.2.13 by Robert Collins
Test adding of directories to the root of a dirstate.
1174
        self.build_tree(['unversioned/', 'unversioned/a file'])
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1175
        state = dirstate.DirState.initialize('dirstate')
4241.14.10 by Vincent Ladeuil
Add DirReader parametrized tests.
1176
        self.addCleanup(state.unlock)
1177
        self.assertRaises(errors.NotVersionedError, state.add,
1178
                          'unversioned/a file', 'a-file-id', 'file', None, None)
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1179
2255.2.13 by Robert Collins
Test adding of directories to the root of a dirstate.
1180
    def test_add_directory_to_root_no_parents_all_data(self):
1181
        # The most trivial addition of a dir is when there are no parents and
1182
        # its in the root and all data about the file is supplied
1183
        self.build_tree(['a dir/'])
1184
        stat = os.lstat('a dir')
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1185
        expected_entries = [
1186
            (('', '', 'TREE_ROOT'), [
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1187
             ('d', '', 0, False, dirstate.DirState.NULLSTAT), # current tree
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1188
             ]),
1189
            (('', 'a dir', 'a dir id'), [
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1190
             ('d', '', 0, False, dirstate.pack_stat(stat)), # current tree
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1191
             ]),
2255.2.13 by Robert Collins
Test adding of directories to the root of a dirstate.
1192
            ]
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1193
        state = dirstate.DirState.initialize('dirstate')
1194
        try:
1195
            state.add('a dir', 'a dir id', 'directory', stat, None)
1196
            # having added it, it should be in the output of iter_entries.
1197
            self.assertEqual(expected_entries, list(state._iter_entries()))
1198
            # saving and reloading should not affect this.
1199
            state.save()
1200
        finally:
1201
            state.unlock()
2255.2.13 by Robert Collins
Test adding of directories to the root of a dirstate.
1202
        state = dirstate.DirState.on_file('dirstate')
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1203
        state.lock_read()
4241.14.10 by Vincent Ladeuil
Add DirReader parametrized tests.
1204
        self.addCleanup(state.unlock)
2255.7.78 by Martin Pool
Add DirState._validate and call from the tests
1205
        state._validate()
4241.14.10 by Vincent Ladeuil
Add DirReader parametrized tests.
1206
        self.assertEqual(expected_entries, list(state._iter_entries()))
1852.13.25 by Robert Collins
Snapshot state
1207
4241.14.10 by Vincent Ladeuil
Add DirReader parametrized tests.
1208
    def _test_add_symlink_to_root_no_parents_all_data(self, link_name, target):
2255.2.14 by Robert Collins
Dirstate: fix adding of directories to setup the next directories block, and test representation of symlinks. Also fix iter_rows to not reset the dirty bit.
1209
        # The most trivial addition of a symlink when there are no parents and
1210
        # its in the root and all data about the file is supplied
2321.3.8 by Alexander Belchenko
Cleanup patch after John's review
1211
        # bzr doesn't support fake symlinks on windows, yet.
4241.14.10 by Vincent Ladeuil
Add DirReader parametrized tests.
1212
        self.requireFeature(tests.SymlinkFeature)
1213
        os.symlink(target, link_name)
1214
        stat = os.lstat(link_name)
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1215
        expected_entries = [
1216
            (('', '', 'TREE_ROOT'), [
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1217
             ('d', '', 0, False, dirstate.DirState.NULLSTAT), # current tree
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1218
             ]),
4241.14.11 by Vincent Ladeuil
Fix wrong encoding.
1219
            (('', link_name.encode('UTF-8'), 'a link id'), [
1220
             ('l', target.encode('UTF-8'), stat[6],
4241.14.10 by Vincent Ladeuil
Add DirReader parametrized tests.
1221
              False, dirstate.pack_stat(stat)), # current tree
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1222
             ]),
2255.2.14 by Robert Collins
Dirstate: fix adding of directories to setup the next directories block, and test representation of symlinks. Also fix iter_rows to not reset the dirty bit.
1223
            ]
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1224
        state = dirstate.DirState.initialize('dirstate')
1225
        try:
4241.14.10 by Vincent Ladeuil
Add DirReader parametrized tests.
1226
            state.add(link_name, 'a link id', 'symlink', stat,
4241.14.11 by Vincent Ladeuil
Fix wrong encoding.
1227
                      target.encode('UTF-8'))
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1228
            # having added it, it should be in the output of iter_entries.
1229
            self.assertEqual(expected_entries, list(state._iter_entries()))
1230
            # saving and reloading should not affect this.
1231
            state.save()
1232
        finally:
1233
            state.unlock()
2255.2.14 by Robert Collins
Dirstate: fix adding of directories to setup the next directories block, and test representation of symlinks. Also fix iter_rows to not reset the dirty bit.
1234
        state = dirstate.DirState.on_file('dirstate')
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1235
        state.lock_read()
4241.14.10 by Vincent Ladeuil
Add DirReader parametrized tests.
1236
        self.addCleanup(state.unlock)
1237
        self.assertEqual(expected_entries, list(state._iter_entries()))
1238
1239
    def test_add_symlink_to_root_no_parents_all_data(self):
1240
        self._test_add_symlink_to_root_no_parents_all_data('a link', 'target')
1241
1242
    def test_add_symlink_unicode_to_root_no_parents_all_data(self):
1243
        self.requireFeature(tests.UnicodeFilenameFeature)
1244
        self._test_add_symlink_to_root_no_parents_all_data(
1245
            u'\N{Euro Sign}link', u'targ\N{Euro Sign}et')
2255.2.14 by Robert Collins
Dirstate: fix adding of directories to setup the next directories block, and test representation of symlinks. Also fix iter_rows to not reset the dirty bit.
1246
1247
    def test_add_directory_and_child_no_parents_all_data(self):
1248
        # after adding a directory, we should be able to add children to it.
1249
        self.build_tree(['a dir/', 'a dir/a file'])
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1250
        dirstat = os.lstat('a dir')
2255.2.14 by Robert Collins
Dirstate: fix adding of directories to setup the next directories block, and test representation of symlinks. Also fix iter_rows to not reset the dirty bit.
1251
        filestat = os.lstat('a dir/a file')
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1252
        expected_entries = [
1253
            (('', '', 'TREE_ROOT'), [
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1254
             ('d', '', 0, False, dirstate.DirState.NULLSTAT), # current tree
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1255
             ]),
1256
            (('', 'a dir', 'a dir id'), [
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1257
             ('d', '', 0, False, dirstate.pack_stat(dirstat)), # current tree
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1258
             ]),
3010.1.2 by Robert Collins
Use valid file-ids for dirstate tests.
1259
            (('a dir', 'a file', 'a-file-id'), [
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1260
             ('f', '1'*20, 25, False,
1261
              dirstate.pack_stat(filestat)), # current tree details
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1262
             ]),
2255.2.14 by Robert Collins
Dirstate: fix adding of directories to setup the next directories block, and test representation of symlinks. Also fix iter_rows to not reset the dirty bit.
1263
            ]
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1264
        state = dirstate.DirState.initialize('dirstate')
1265
        try:
1266
            state.add('a dir', 'a dir id', 'directory', dirstat, None)
3010.1.2 by Robert Collins
Use valid file-ids for dirstate tests.
1267
            state.add('a dir/a file', 'a-file-id', 'file', filestat, '1'*20)
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1268
            # added it, it should be in the output of iter_entries.
1269
            self.assertEqual(expected_entries, list(state._iter_entries()))
1270
            # saving and reloading should not affect this.
1271
            state.save()
1272
        finally:
1273
            state.unlock()
2255.2.14 by Robert Collins
Dirstate: fix adding of directories to setup the next directories block, and test representation of symlinks. Also fix iter_rows to not reset the dirty bit.
1274
        state = dirstate.DirState.on_file('dirstate')
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1275
        state.lock_read()
4241.14.10 by Vincent Ladeuil
Add DirReader parametrized tests.
1276
        self.addCleanup(state.unlock)
1277
        self.assertEqual(expected_entries, list(state._iter_entries()))
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1278
2255.7.93 by Martin Pool
Add support for tree-references in dirstate
1279
    def test_add_tree_reference(self):
1280
        # make a dirstate and add a tree reference
1281
        state = dirstate.DirState.initialize('dirstate')
1282
        expected_entry = (
1283
            ('', 'subdir', 'subdir-id'),
1284
            [('t', 'subtree-123123', 0, False,
1285
              'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')],
1286
            )
1287
        try:
1288
            state.add('subdir', 'subdir-id', 'tree-reference', None, 'subtree-123123')
1289
            entry = state._get_entry(0, 'subdir-id', 'subdir')
1290
            self.assertEqual(entry, expected_entry)
1291
            state._validate()
1292
            state.save()
1293
        finally:
1294
            state.unlock()
1295
        # now check we can read it back
1296
        state.lock_read()
4241.14.10 by Vincent Ladeuil
Add DirReader parametrized tests.
1297
        self.addCleanup(state.unlock)
2255.7.93 by Martin Pool
Add support for tree-references in dirstate
1298
        state._validate()
4241.14.10 by Vincent Ladeuil
Add DirReader parametrized tests.
1299
        entry2 = state._get_entry(0, 'subdir-id', 'subdir')
1300
        self.assertEqual(entry, entry2)
1301
        self.assertEqual(entry, expected_entry)
1302
        # and lookup by id should work too
1303
        entry2 = state._get_entry(0, fileid_utf8='subdir-id')
1304
        self.assertEqual(entry, expected_entry)
2255.7.93 by Martin Pool
Add support for tree-references in dirstate
1305
2255.2.225 by Martin Pool
Prohibit dirstate from getting entries called ..
1306
    def test_add_forbidden_names(self):
1307
        state = dirstate.DirState.initialize('dirstate')
2255.2.233 by John Arbash Meinel
DirState.initialize returns a locked state, unlock as part of cleanup.
1308
        self.addCleanup(state.unlock)
2255.2.225 by Martin Pool
Prohibit dirstate from getting entries called ..
1309
        self.assertRaises(errors.BzrError,
1310
            state.add, '.', 'ass-id', 'directory', None, None)
1311
        self.assertRaises(errors.BzrError,
1312
            state.add, '..', 'ass-id', 'directory', None, None)
1313
4536.4.1 by Robert Collins
Fix dirstate.set_state_from_inventory to have a more stable old_iterator, fixing rename problems in new trees. (Robert Collins, bug 395556)
1314
    def test_set_state_with_rename_b_a_bug_395556(self):
1315
        # bug 395556 uncovered a bug where the dirstate ends up with a false
1316
        # relocation record - in a tree with no parents there should be no
1317
        # absent or relocated records. This then leads to further corruption
1318
        # when a commit occurs, as the incorrect relocation gathers an
1319
        # incorrect absent in tree 1, and future changes go to pot.
1320
        tree1 = self.make_branch_and_tree('tree1')
1321
        self.build_tree(['tree1/b'])
1322
        tree1.lock_write()
1323
        try:
1324
            tree1.add(['b'], ['b-id'])
1325
            root_id = tree1.get_root_id()
1326
            inv = tree1.inventory
1327
            state = dirstate.DirState.initialize('dirstate')
1328
            try:
1329
                # Set the initial state with 'b'
1330
                state.set_state_from_inventory(inv)
1331
                inv.rename('b-id', root_id, 'a')
1332
                # Set the new state with 'a', which currently corrupts.
1333
                state.set_state_from_inventory(inv)
1334
                expected_result1 = [('', '', root_id, 'd'),
1335
                                    ('', 'a', 'b-id', 'f'),
1336
                                   ]
1337
                values = []
1338
                for entry in state._iter_entries():
1339
                    values.append(entry[0] + entry[1][0][:1])
1340
                self.assertEqual(expected_result1, values)
1341
            finally:
1342
                state.unlock()
1343
        finally:
1344
            tree1.unlock()
1345
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1346
5807.4.5 by John Arbash Meinel
Start adding tests that _worth_saving_limit works as expected.
1347
class TestDirStateHashUpdates(TestCaseWithDirState):
1348
1349
    def do_update_entry(self, state, path):
1350
        entry = state._get_entry(0, path_utf8=path)
1351
        stat = os.lstat(path)
1352
        return dirstate.update_entry(state, entry, os.path.abspath(path), stat)
1353
5912.1.1 by John Arbash Meinel
Fix a test that was failing on win32.
1354
    def _read_state_content(self, state):
1355
        """Read the content of the dirstate file.
1356
1357
        On Windows when one process locks a file, you can't even open() the
1358
        file in another process (to read it). So we go directly to
1359
        state._state_file. This should always be the exact disk representation,
1360
        so it is reasonable to do so.
1361
        DirState also always seeks before reading, so it doesn't matter if we
1362
        bump the file pointer.
1363
        """
1364
        state._state_file.seek(0)
1365
        return state._state_file.read()
1366
5807.4.5 by John Arbash Meinel
Start adding tests that _worth_saving_limit works as expected.
1367
    def test_worth_saving_limit_avoids_writing(self):
5807.4.6 by John Arbash Meinel
Merge newer bzr.dev and resolve conflicts.
1368
        tree = self.make_branch_and_tree('.')
5807.4.5 by John Arbash Meinel
Start adding tests that _worth_saving_limit works as expected.
1369
        self.build_tree(['c', 'd'])
5807.4.6 by John Arbash Meinel
Merge newer bzr.dev and resolve conflicts.
1370
        tree.lock_write()
1371
        tree.add(['c', 'd'], ['c-id', 'd-id'])
1372
        tree.commit('add c and d')
1373
        state = InstrumentedDirState.on_file(tree.current_dirstate()._filename,
5807.4.5 by John Arbash Meinel
Start adding tests that _worth_saving_limit works as expected.
1374
                                             worth_saving_limit=2)
5807.4.6 by John Arbash Meinel
Merge newer bzr.dev and resolve conflicts.
1375
        tree.unlock()
5807.4.5 by John Arbash Meinel
Start adding tests that _worth_saving_limit works as expected.
1376
        state.lock_write()
1377
        self.addCleanup(state.unlock)
1378
        state._read_dirblocks_if_needed()
1379
        state.adjust_time(+20) # Allow things to be cached
1380
        self.assertEqual(dirstate.DirState.IN_MEMORY_UNMODIFIED,
1381
                         state._dirblock_state)
5912.1.1 by John Arbash Meinel
Fix a test that was failing on win32.
1382
        content = self._read_state_content(state)
5807.4.5 by John Arbash Meinel
Start adding tests that _worth_saving_limit works as expected.
1383
        self.do_update_entry(state, 'c')
1384
        self.assertEqual(1, len(state._known_hash_changes))
1385
        self.assertEqual(dirstate.DirState.IN_MEMORY_HASH_MODIFIED,
1386
                         state._dirblock_state)
1387
        state.save()
1388
        # It should not have set the state to IN_MEMORY_UNMODIFIED because the
1389
        # hash values haven't been written out.
1390
        self.assertEqual(dirstate.DirState.IN_MEMORY_HASH_MODIFIED,
1391
                         state._dirblock_state)
5912.1.1 by John Arbash Meinel
Fix a test that was failing on win32.
1392
        self.assertEqual(content, self._read_state_content(state))
5807.4.5 by John Arbash Meinel
Start adding tests that _worth_saving_limit works as expected.
1393
        self.assertEqual(dirstate.DirState.IN_MEMORY_HASH_MODIFIED,
1394
                         state._dirblock_state)
1395
        self.do_update_entry(state, 'd')
1396
        self.assertEqual(2, len(state._known_hash_changes))
1397
        state.save()
1398
        self.assertEqual(dirstate.DirState.IN_MEMORY_UNMODIFIED,
1399
                         state._dirblock_state)
1400
        self.assertEqual(0, len(state._known_hash_changes))
1401
5807.4.6 by John Arbash Meinel
Merge newer bzr.dev and resolve conflicts.
1402
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1403
class TestGetLines(TestCaseWithDirState):
1852.13.19 by Robert Collins
Get DirState objects roundtripping an add of a ghost tree.
1404
1852.13.24 by Robert Collins
Get back to the broken-pending-revision-tree-from-dirstate state of development, changing dirstate from_tree to use _set_data rather than generating lines itself.
1405
    def test_get_line_with_2_rows(self):
2255.2.66 by John Arbash Meinel
Move _get_row and _get_block_row_index into Dirstate itself.
1406
        state = self.create_dirstate_with_root_and_subdir()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1407
        try:
2255.7.20 by John Arbash Meinel
update test for format 3, and enable caching of path split while lock is held.
1408
            self.assertEqual(['#bazaar dirstate flat format 3\n',
2255.2.239 by Robert Collins
Change from adler to crc checksums, as adler32 in python is not stable from 32 to 64 bit systems.
1409
                'crc32: 41262208\n',
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1410
                'num_entries: 2\n',
1411
                '0\x00\n\x00'
1412
                '0\x00\n\x00'
1413
                '\x00\x00a-root-value\x00'
1414
                'd\x00\x000\x00n\x00AAAAREUHaIpFB2iKAAADAQAtkqUAAIGk\x00\n\x00'
1415
                '\x00subdir\x00subdir-id\x00'
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1416
                'd\x00\x000\x00n\x00AAAAREUHaIpFB2iKAAADAQAtkqUAAIGk\x00\n\x00'
1417
                ], state.get_lines())
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1418
        finally:
1419
            state.unlock()
1852.13.24 by Robert Collins
Get back to the broken-pending-revision-tree-from-dirstate state of development, changing dirstate from_tree to use _set_data rather than generating lines itself.
1420
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1421
    def test_entry_to_line(self):
2255.2.66 by John Arbash Meinel
Move _get_row and _get_block_row_index into Dirstate itself.
1422
        state = self.create_dirstate_with_root()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1423
        try:
1424
            self.assertEqual(
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1425
                '\x00\x00a-root-value\x00d\x00\x000\x00n'
1426
                '\x00AAAAREUHaIpFB2iKAAADAQAtkqUAAIGk',
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1427
                state._entry_to_line(state._dirblocks[0][1][0]))
1428
        finally:
1429
            state.unlock()
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1430
1431
    def test_entry_to_line_with_parent(self):
1432
        packed_stat = 'AAAAREUHaIpFB2iKAAADAQAtkqUAAIGk'
1433
        root_entry = ('', '', 'a-root-value'), [
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
1434
            ('d', '', 0, False, packed_stat), # current tree details
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1435
             # first: a pointer to the current location
1436
            ('a', 'dirname/basename', 0, False, ''),
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1437
            ]
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1438
        state = dirstate.DirState.initialize('dirstate')
1439
        try:
1440
            self.assertEqual(
1441
                '\x00\x00a-root-value\x00'
1442
                'd\x00\x000\x00n\x00AAAAREUHaIpFB2iKAAADAQAtkqUAAIGk\x00'
1443
                'a\x00dirname/basename\x000\x00n\x00',
1444
                state._entry_to_line(root_entry))
1445
        finally:
1446
            state.unlock()
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1447
1448
    def test_entry_to_line_with_two_parents_at_different_paths(self):
1449
        # / in the tree, at / in one parent and /dirname/basename in the other.
1450
        packed_stat = 'AAAAREUHaIpFB2iKAAADAQAtkqUAAIGk'
1451
        root_entry = ('', '', 'a-root-value'), [
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
1452
            ('d', '', 0, False, packed_stat), # current tree details
1453
            ('d', '', 0, False, 'rev_id'), # first parent details
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1454
             # second: a pointer to the current location
1455
            ('a', 'dirname/basename', 0, False, ''),
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1456
            ]
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1457
        state = dirstate.DirState.initialize('dirstate')
1458
        try:
1459
            self.assertEqual(
1460
                '\x00\x00a-root-value\x00'
1461
                'd\x00\x000\x00n\x00AAAAREUHaIpFB2iKAAADAQAtkqUAAIGk\x00'
1462
                'd\x00\x000\x00n\x00rev_id\x00'
1463
                'a\x00dirname/basename\x000\x00n\x00',
1464
                state._entry_to_line(root_entry))
1465
        finally:
1466
            state.unlock()
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1467
1468
    def test_iter_entries(self):
1469
        # we should be able to iterate the dirstate entries from end to end
1852.13.24 by Robert Collins
Get back to the broken-pending-revision-tree-from-dirstate state of development, changing dirstate from_tree to use _set_data rather than generating lines itself.
1470
        # this is for get_lines to be easy to read.
1471
        packed_stat = 'AAAAREUHaIpFB2iKAAADAQAtkqUAAIGk'
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
1472
        dirblocks = []
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1473
        root_entries = [(('', '', 'a-root-value'), [
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
1474
            ('d', '', 0, False, packed_stat), # current tree details
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1475
            ])]
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
1476
        dirblocks.append(('', root_entries))
1852.13.24 by Robert Collins
Get back to the broken-pending-revision-tree-from-dirstate state of development, changing dirstate from_tree to use _set_data rather than generating lines itself.
1477
        # add two files in the root
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1478
        subdir_entry = ('', 'subdir', 'subdir-id'), [
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
1479
            ('d', '', 0, False, packed_stat), # current tree details
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1480
            ]
1481
        afile_entry = ('', 'afile', 'afile-id'), [
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
1482
            ('f', 'sha1value', 34, False, packed_stat), # current tree details
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1483
            ]
1484
        dirblocks.append(('', [subdir_entry, afile_entry]))
1852.13.24 by Robert Collins
Get back to the broken-pending-revision-tree-from-dirstate state of development, changing dirstate from_tree to use _set_data rather than generating lines itself.
1485
        # and one in subdir
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1486
        file_entry2 = ('subdir', '2file', '2file-id'), [
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
1487
            ('f', 'sha1value', 23, False, packed_stat), # current tree details
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1488
            ]
1489
        dirblocks.append(('subdir', [file_entry2]))
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1490
        state = dirstate.DirState.initialize('dirstate')
1491
        try:
1492
            state._set_data([], dirblocks)
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1493
            expected_entries = [root_entries[0], subdir_entry, afile_entry,
1494
                                file_entry2]
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1495
            self.assertEqual(expected_entries, list(state._iter_entries()))
1496
        finally:
1497
            state.unlock()
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1498
1499
1500
class TestGetBlockRowIndex(TestCaseWithDirState):
2255.2.66 by John Arbash Meinel
Move _get_row and _get_block_row_index into Dirstate itself.
1501
1502
    def assertBlockRowIndexEqual(self, block_index, row_index, dir_present,
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1503
        file_present, state, dirname, basename, tree_index):
2255.2.66 by John Arbash Meinel
Move _get_row and _get_block_row_index into Dirstate itself.
1504
        self.assertEqual((block_index, row_index, dir_present, file_present),
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1505
            state._get_block_entry_index(dirname, basename, tree_index))
2255.2.66 by John Arbash Meinel
Move _get_row and _get_block_row_index into Dirstate itself.
1506
        if dir_present:
1507
            block = state._dirblocks[block_index]
1508
            self.assertEqual(dirname, block[0])
1509
        if dir_present and file_present:
1510
            row = state._dirblocks[block_index][1][row_index]
1511
            self.assertEqual(dirname, row[0][0])
1512
            self.assertEqual(basename, row[0][1])
1513
1514
    def test_simple_structure(self):
1515
        state = self.create_dirstate_with_root_and_subdir()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1516
        self.addCleanup(state.unlock)
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
1517
        self.assertBlockRowIndexEqual(1, 0, True, True, state, '', 'subdir', 0)
1518
        self.assertBlockRowIndexEqual(1, 0, True, False, state, '', 'bdir', 0)
1519
        self.assertBlockRowIndexEqual(1, 1, True, False, state, '', 'zdir', 0)
1520
        self.assertBlockRowIndexEqual(2, 0, False, False, state, 'a', 'foo', 0)
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1521
        self.assertBlockRowIndexEqual(2, 0, False, False, state,
1522
                                      'subdir', 'foo', 0)
2255.2.66 by John Arbash Meinel
Move _get_row and _get_block_row_index into Dirstate itself.
1523
1524
    def test_complex_structure_exists(self):
1525
        state = self.create_complex_dirstate()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1526
        self.addCleanup(state.unlock)
2255.2.66 by John Arbash Meinel
Move _get_row and _get_block_row_index into Dirstate itself.
1527
        # Make sure we can find everything that exists
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
1528
        self.assertBlockRowIndexEqual(0, 0, True, True, state, '', '', 0)
1529
        self.assertBlockRowIndexEqual(1, 0, True, True, state, '', 'a', 0)
1530
        self.assertBlockRowIndexEqual(1, 1, True, True, state, '', 'b', 0)
1531
        self.assertBlockRowIndexEqual(1, 2, True, True, state, '', 'c', 0)
1532
        self.assertBlockRowIndexEqual(1, 3, True, True, state, '', 'd', 0)
1533
        self.assertBlockRowIndexEqual(2, 0, True, True, state, 'a', 'e', 0)
1534
        self.assertBlockRowIndexEqual(2, 1, True, True, state, 'a', 'f', 0)
1535
        self.assertBlockRowIndexEqual(3, 0, True, True, state, 'b', 'g', 0)
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1536
        self.assertBlockRowIndexEqual(3, 1, True, True, state,
1537
                                      'b', 'h\xc3\xa5', 0)
2255.2.66 by John Arbash Meinel
Move _get_row and _get_block_row_index into Dirstate itself.
1538
1539
    def test_complex_structure_missing(self):
1540
        state = self.create_complex_dirstate()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1541
        self.addCleanup(state.unlock)
2255.2.66 by John Arbash Meinel
Move _get_row and _get_block_row_index into Dirstate itself.
1542
        # Make sure things would be inserted in the right locations
1543
        # '_' comes before 'a'
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
1544
        self.assertBlockRowIndexEqual(0, 0, True, True, state, '', '', 0)
1545
        self.assertBlockRowIndexEqual(1, 0, True, False, state, '', '_', 0)
1546
        self.assertBlockRowIndexEqual(1, 1, True, False, state, '', 'aa', 0)
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1547
        self.assertBlockRowIndexEqual(1, 4, True, False, state,
1548
                                      '', 'h\xc3\xa5', 0)
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
1549
        self.assertBlockRowIndexEqual(2, 0, False, False, state, '_', 'a', 0)
1550
        self.assertBlockRowIndexEqual(3, 0, False, False, state, 'aa', 'a', 0)
1551
        self.assertBlockRowIndexEqual(4, 0, False, False, state, 'bb', 'a', 0)
2255.2.66 by John Arbash Meinel
Move _get_row and _get_block_row_index into Dirstate itself.
1552
        # This would be inserted between a/ and b/
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
1553
        self.assertBlockRowIndexEqual(3, 0, False, False, state, 'a/e', 'a', 0)
2255.2.66 by John Arbash Meinel
Move _get_row and _get_block_row_index into Dirstate itself.
1554
        # Put at the end
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
1555
        self.assertBlockRowIndexEqual(4, 0, False, False, state, 'e', 'a', 0)
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1556
1557
1558
class TestGetEntry(TestCaseWithDirState):
1559
1560
    def assertEntryEqual(self, dirname, basename, file_id, state, path, index):
1561
        """Check that the right entry is returned for a request to getEntry."""
2255.2.87 by Robert Collins
core dirstate tests passing with new structure.
1562
        entry = state._get_entry(index, path_utf8=path)
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1563
        if file_id is None:
1564
            self.assertEqual((None, None), entry)
2255.2.66 by John Arbash Meinel
Move _get_row and _get_block_row_index into Dirstate itself.
1565
        else:
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1566
            cur = entry[0]
1567
            self.assertEqual((dirname, basename, file_id), cur[:3])
2255.2.66 by John Arbash Meinel
Move _get_row and _get_block_row_index into Dirstate itself.
1568
1569
    def test_simple_structure(self):
1570
        state = self.create_dirstate_with_root_and_subdir()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1571
        self.addCleanup(state.unlock)
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1572
        self.assertEntryEqual('', '', 'a-root-value', state, '', 0)
1573
        self.assertEntryEqual('', 'subdir', 'subdir-id', state, 'subdir', 0)
1574
        self.assertEntryEqual(None, None, None, state, 'missing', 0)
1575
        self.assertEntryEqual(None, None, None, state, 'missing/foo', 0)
1576
        self.assertEntryEqual(None, None, None, state, 'subdir/foo', 0)
2255.2.66 by John Arbash Meinel
Move _get_row and _get_block_row_index into Dirstate itself.
1577
1578
    def test_complex_structure_exists(self):
1579
        state = self.create_complex_dirstate()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1580
        self.addCleanup(state.unlock)
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1581
        self.assertEntryEqual('', '', 'a-root-value', state, '', 0)
1582
        self.assertEntryEqual('', 'a', 'a-dir', state, 'a', 0)
1583
        self.assertEntryEqual('', 'b', 'b-dir', state, 'b', 0)
1584
        self.assertEntryEqual('', 'c', 'c-file', state, 'c', 0)
1585
        self.assertEntryEqual('', 'd', 'd-file', state, 'd', 0)
1586
        self.assertEntryEqual('a', 'e', 'e-dir', state, 'a/e', 0)
1587
        self.assertEntryEqual('a', 'f', 'f-file', state, 'a/f', 0)
1588
        self.assertEntryEqual('b', 'g', 'g-file', state, 'b/g', 0)
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1589
        self.assertEntryEqual('b', 'h\xc3\xa5', 'h-\xc3\xa5-file', state,
1590
                              'b/h\xc3\xa5', 0)
2255.2.66 by John Arbash Meinel
Move _get_row and _get_block_row_index into Dirstate itself.
1591
1592
    def test_complex_structure_missing(self):
1593
        state = self.create_complex_dirstate()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1594
        self.addCleanup(state.unlock)
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1595
        self.assertEntryEqual(None, None, None, state, '_', 0)
1596
        self.assertEntryEqual(None, None, None, state, '_\xc3\xa5', 0)
1597
        self.assertEntryEqual(None, None, None, state, 'a/b', 0)
1598
        self.assertEntryEqual(None, None, None, state, 'c/d', 0)
2255.2.66 by John Arbash Meinel
Move _get_row and _get_block_row_index into Dirstate itself.
1599
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1600
    def test_get_entry_uninitialized(self):
1601
        """Calling get_entry will load data if it needs to"""
2255.2.66 by John Arbash Meinel
Move _get_row and _get_block_row_index into Dirstate itself.
1602
        state = self.create_dirstate_with_root()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1603
        try:
1604
            state.save()
1605
        finally:
1606
            state.unlock()
2255.2.66 by John Arbash Meinel
Move _get_row and _get_block_row_index into Dirstate itself.
1607
        del state
1608
        state = dirstate.DirState.on_file('dirstate')
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1609
        state.lock_read()
1610
        try:
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1611
            self.assertEqual(dirstate.DirState.NOT_IN_MEMORY,
1612
                             state._header_state)
1613
            self.assertEqual(dirstate.DirState.NOT_IN_MEMORY,
1614
                             state._dirblock_state)
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1615
            self.assertEntryEqual('', '', 'a-root-value', state, '', 0)
1616
        finally:
1617
            state.unlock()
2255.3.2 by John Arbash Meinel
(broken) some basic work on adding bisect functionality to dirstate.
1618
1619
2929.2.1 by Robert Collins
* Commit updates the state of the working tree via a delta rather than
1620
class TestIterChildEntries(TestCaseWithDirState):
1621
1622
    def create_dirstate_with_two_trees(self):
1623
        """This dirstate contains multiple files and directories.
1624
1625
         /        a-root-value
1626
         a/       a-dir
1627
         b/       b-dir
1628
         c        c-file
1629
         d        d-file
1630
         a/e/     e-dir
1631
         a/f      f-file
1632
         b/g      g-file
1633
         b/h\xc3\xa5  h-\xc3\xa5-file  #This is u'\xe5' encoded into utf-8
1634
1635
        Notice that a/e is an empty directory.
1636
1637
        There is one parent tree, which has the same shape with the following variations:
1638
        b/g in the parent is gone.
1639
        b/h in the parent has a different id
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1640
        b/i is new in the parent
2929.2.1 by Robert Collins
* Commit updates the state of the working tree via a delta rather than
1641
        c is renamed to b/j in the parent
1642
1643
        :return: The dirstate, still write-locked.
1644
        """
1645
        packed_stat = 'AAAAREUHaIpFB2iKAAADAQAtkqUAAIGk'
1646
        null_sha = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
1647
        NULL_PARENT_DETAILS = dirstate.DirState.NULL_PARENT_DETAILS
1648
        root_entry = ('', '', 'a-root-value'), [
1649
            ('d', '', 0, False, packed_stat),
1650
            ('d', '', 0, False, 'parent-revid'),
1651
            ]
1652
        a_entry = ('', 'a', 'a-dir'), [
1653
            ('d', '', 0, False, packed_stat),
1654
            ('d', '', 0, False, 'parent-revid'),
1655
            ]
1656
        b_entry = ('', 'b', 'b-dir'), [
1657
            ('d', '', 0, False, packed_stat),
1658
            ('d', '', 0, False, 'parent-revid'),
1659
            ]
1660
        c_entry = ('', 'c', 'c-file'), [
1661
            ('f', null_sha, 10, False, packed_stat),
1662
            ('r', 'b/j', 0, False, ''),
1663
            ]
1664
        d_entry = ('', 'd', 'd-file'), [
1665
            ('f', null_sha, 20, False, packed_stat),
1666
            ('f', 'd', 20, False, 'parent-revid'),
1667
            ]
1668
        e_entry = ('a', 'e', 'e-dir'), [
1669
            ('d', '', 0, False, packed_stat),
1670
            ('d', '', 0, False, 'parent-revid'),
1671
            ]
1672
        f_entry = ('a', 'f', 'f-file'), [
1673
            ('f', null_sha, 30, False, packed_stat),
1674
            ('f', 'f', 20, False, 'parent-revid'),
1675
            ]
1676
        g_entry = ('b', 'g', 'g-file'), [
1677
            ('f', null_sha, 30, False, packed_stat),
1678
            NULL_PARENT_DETAILS,
1679
            ]
1680
        h_entry1 = ('b', 'h\xc3\xa5', 'h-\xc3\xa5-file1'), [
1681
            ('f', null_sha, 40, False, packed_stat),
1682
            NULL_PARENT_DETAILS,
1683
            ]
1684
        h_entry2 = ('b', 'h\xc3\xa5', 'h-\xc3\xa5-file2'), [
1685
            NULL_PARENT_DETAILS,
1686
            ('f', 'h', 20, False, 'parent-revid'),
1687
            ]
1688
        i_entry = ('b', 'i', 'i-file'), [
1689
            NULL_PARENT_DETAILS,
1690
            ('f', 'h', 20, False, 'parent-revid'),
1691
            ]
1692
        j_entry = ('b', 'j', 'c-file'), [
1693
            ('r', 'c', 0, False, ''),
1694
            ('f', 'j', 20, False, 'parent-revid'),
1695
            ]
1696
        dirblocks = []
1697
        dirblocks.append(('', [root_entry]))
1698
        dirblocks.append(('', [a_entry, b_entry, c_entry, d_entry]))
1699
        dirblocks.append(('a', [e_entry, f_entry]))
1700
        dirblocks.append(('b', [g_entry, h_entry1, h_entry2, i_entry, j_entry]))
1701
        state = dirstate.DirState.initialize('dirstate')
1702
        state._validate()
1703
        try:
1704
            state._set_data(['parent'], dirblocks)
1705
        except:
1706
            state.unlock()
1707
            raise
1708
        return state, dirblocks
1709
1710
    def test_iter_children_b(self):
1711
        state, dirblocks = self.create_dirstate_with_two_trees()
1712
        self.addCleanup(state.unlock)
1713
        expected_result = []
1714
        expected_result.append(dirblocks[3][1][2]) # h2
1715
        expected_result.append(dirblocks[3][1][3]) # i
1716
        expected_result.append(dirblocks[3][1][4]) # j
1717
        self.assertEqual(expected_result,
1718
            list(state._iter_child_entries(1, 'b')))
1719
2929.2.2 by Robert Collins
Review feedback on dirstate update_basis_via_delta logic.
1720
    def test_iter_child_root(self):
1721
        state, dirblocks = self.create_dirstate_with_two_trees()
1722
        self.addCleanup(state.unlock)
1723
        expected_result = []
1724
        expected_result.append(dirblocks[1][1][0]) # a
1725
        expected_result.append(dirblocks[1][1][1]) # b
1726
        expected_result.append(dirblocks[1][1][3]) # d
1727
        expected_result.append(dirblocks[2][1][0]) # e
1728
        expected_result.append(dirblocks[2][1][1]) # f
1729
        expected_result.append(dirblocks[3][1][2]) # h2
1730
        expected_result.append(dirblocks[3][1][3]) # i
1731
        expected_result.append(dirblocks[3][1][4]) # j
1732
        self.assertEqual(expected_result,
1733
            list(state._iter_child_entries(1, '')))
1734
2929.2.1 by Robert Collins
* Commit updates the state of the working tree via a delta rather than
1735
4241.14.10 by Vincent Ladeuil
Add DirReader parametrized tests.
1736
class TestDirstateSortOrder(tests.TestCaseWithTransport):
2255.8.5 by John Arbash Meinel
Add a test that dirstate adds records in the right order.
1737
    """Test that DirState adds entries in the right order."""
1738
1739
    def test_add_sorting(self):
2255.7.21 by John Arbash Meinel
Get iter_changes working again, by fixing set_parent_trees to
1740
        """Add entries in lexicographical order, we get path sorted order.
1741
1742
        This tests it to a depth of 4, to make sure we don't just get it right
1743
        at a single depth. 'a/a' should come before 'a-a', even though it
1744
        doesn't lexicographically.
1745
        """
1746
        dirs = ['a', 'a/a', 'a/a/a', 'a/a/a/a',
1747
                'a-a', 'a/a-a', 'a/a/a-a', 'a/a/a/a-a',
2255.8.5 by John Arbash Meinel
Add a test that dirstate adds records in the right order.
1748
               ]
1749
        null_sha = ''
1750
        state = dirstate.DirState.initialize('dirstate')
1751
        self.addCleanup(state.unlock)
1752
1753
        fake_stat = os.stat('dirstate')
1754
        for d in dirs:
1755
            d_id = d.replace('/', '_')+'-id'
1756
            file_path = d + '/f'
1757
            file_id = file_path.replace('/', '_')+'-id'
1758
            state.add(d, d_id, 'directory', fake_stat, null_sha)
1759
            state.add(file_path, file_id, 'file', fake_stat, null_sha)
1760
1761
        expected = ['', '', 'a',
2255.7.21 by John Arbash Meinel
Get iter_changes working again, by fixing set_parent_trees to
1762
                'a/a', 'a/a/a', 'a/a/a/a',
1763
                'a/a/a/a-a', 'a/a/a-a', 'a/a-a', 'a-a',
2255.8.5 by John Arbash Meinel
Add a test that dirstate adds records in the right order.
1764
               ]
2255.7.21 by John Arbash Meinel
Get iter_changes working again, by fixing set_parent_trees to
1765
        split = lambda p:p.split('/')
1766
        self.assertEqual(sorted(expected, key=split), expected)
1767
        dirblock_names = [d[0] for d in state._dirblocks]
1768
        self.assertEqual(expected, dirblock_names)
1769
1770
    def test_set_parent_trees_correct_order(self):
1771
        """After calling set_parent_trees() we should maintain the order."""
1772
        dirs = ['a', 'a-a', 'a/a']
1773
        null_sha = ''
1774
        state = dirstate.DirState.initialize('dirstate')
1775
        self.addCleanup(state.unlock)
1776
1777
        fake_stat = os.stat('dirstate')
1778
        for d in dirs:
1779
            d_id = d.replace('/', '_')+'-id'
1780
            file_path = d + '/f'
1781
            file_id = file_path.replace('/', '_')+'-id'
1782
            state.add(d, d_id, 'directory', fake_stat, null_sha)
1783
            state.add(file_path, file_id, 'file', fake_stat, null_sha)
1784
1785
        expected = ['', '', 'a', 'a/a', 'a-a']
1786
        dirblock_names = [d[0] for d in state._dirblocks]
1787
        self.assertEqual(expected, dirblock_names)
1788
1789
        # *really* cheesy way to just get an empty tree
1790
        repo = self.make_repository('repo')
3668.5.1 by Jelmer Vernooij
Use NULL_REVISION rather than None for Repository.revision_tree().
1791
        empty_tree = repo.revision_tree(_mod_revision.NULL_REVISION)
2255.7.21 by John Arbash Meinel
Get iter_changes working again, by fixing set_parent_trees to
1792
        state.set_parent_trees([('null:', empty_tree)], [])
1793
2255.8.5 by John Arbash Meinel
Add a test that dirstate adds records in the right order.
1794
        dirblock_names = [d[0] for d in state._dirblocks]
1795
        self.assertEqual(expected, dirblock_names)
1796
1797
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1798
class InstrumentedDirState(dirstate.DirState):
2255.10.1 by John Arbash Meinel
Update WorkingTree4 so that it doesn't use a HashCache,
1799
    """An DirState with instrumented sha1 functionality."""
1800
5807.4.5 by John Arbash Meinel
Start adding tests that _worth_saving_limit works as expected.
1801
    def __init__(self, path, sha1_provider, worth_saving_limit=0):
1802
        super(InstrumentedDirState, self).__init__(path, sha1_provider,
1803
            worth_saving_limit=worth_saving_limit)
2255.10.1 by John Arbash Meinel
Update WorkingTree4 so that it doesn't use a HashCache,
1804
        self._time_offset = 0
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1805
        self._log = []
2872.3.3 by Martin Pool
Fix up test_update_entry to work with -Dhashcache
1806
        # member is dynamically set in DirState.__init__ to turn on trace
4132.2.2 by Ian Clatworthy
make sha1_provider a mandatory param for DirState.__init__()
1807
        self._sha1_provider = sha1_provider
2872.3.3 by Martin Pool
Fix up test_update_entry to work with -Dhashcache
1808
        self._sha1_file = self._sha1_file_and_log
2255.10.1 by John Arbash Meinel
Update WorkingTree4 so that it doesn't use a HashCache,
1809
1810
    def _sha_cutoff_time(self):
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1811
        timestamp = super(InstrumentedDirState, self)._sha_cutoff_time()
2255.10.6 by John Arbash Meinel
Save approx 30-60ms (5-10%) on a LP tree by not calling time.time() for every entry.
1812
        self._cutoff_time = timestamp + self._time_offset
2255.10.1 by John Arbash Meinel
Update WorkingTree4 so that it doesn't use a HashCache,
1813
2872.3.3 by Martin Pool
Fix up test_update_entry to work with -Dhashcache
1814
    def _sha1_file_and_log(self, abspath):
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1815
        self._log.append(('sha1', abspath))
4132.2.2 by Ian Clatworthy
make sha1_provider a mandatory param for DirState.__init__()
1816
        return self._sha1_provider.sha1(abspath)
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1817
1818
    def _read_link(self, abspath, old_link):
1819
        self._log.append(('read_link', abspath, old_link))
1820
        return super(InstrumentedDirState, self)._read_link(abspath, old_link)
1821
1822
    def _lstat(self, abspath, entry):
1823
        self._log.append(('lstat', abspath))
1824
        return super(InstrumentedDirState, self)._lstat(abspath, entry)
1825
1826
    def _is_executable(self, mode, old_executable):
1827
        self._log.append(('is_exec', mode, old_executable))
1828
        return super(InstrumentedDirState, self)._is_executable(mode,
1829
                                                                old_executable)
2255.10.1 by John Arbash Meinel
Update WorkingTree4 so that it doesn't use a HashCache,
1830
1831
    def adjust_time(self, secs):
1832
        """Move the clock forward or back.
1833
1834
        :param secs: The amount to adjust the clock by. Positive values make it
1835
        seem as if we are in the future, negative values make it seem like we
1836
        are in the past.
1837
        """
1838
        self._time_offset += secs
2255.10.6 by John Arbash Meinel
Save approx 30-60ms (5-10%) on a LP tree by not calling time.time() for every entry.
1839
        self._cutoff_time = None
2255.10.1 by John Arbash Meinel
Update WorkingTree4 so that it doesn't use a HashCache,
1840
1841
1842
class _FakeStat(object):
1843
    """A class with the same attributes as a real stat result."""
1844
1845
    def __init__(self, size, mtime, ctime, dev, ino, mode):
1846
        self.st_size = size
1847
        self.st_mtime = mtime
1848
        self.st_ctime = ctime
1849
        self.st_dev = dev
1850
        self.st_ino = ino
1851
        self.st_mode = mode
1852
4132.2.3 by Ian Clatworthy
add test as suggested by poolie's review
1853
    @staticmethod
1854
    def from_stat(st):
1855
        return _FakeStat(st.st_size, st.st_mtime, st.st_ctime, st.st_dev,
1856
            st.st_ino, st.st_mode)
1857
2255.10.1 by John Arbash Meinel
Update WorkingTree4 so that it doesn't use a HashCache,
1858
4241.14.10 by Vincent Ladeuil
Add DirReader parametrized tests.
1859
class TestPackStat(tests.TestCaseWithTransport):
2255.10.1 by John Arbash Meinel
Update WorkingTree4 so that it doesn't use a HashCache,
1860
1861
    def assertPackStat(self, expected, stat_value):
1862
        """Check the packed and serialized form of a stat value."""
1863
        self.assertEqual(expected, dirstate.pack_stat(stat_value))
1864
1865
    def test_pack_stat_int(self):
1866
        st = _FakeStat(6859L, 1172758614, 1172758617, 777L, 6499538L, 0100644)
1867
        # Make sure that all parameters have an impact on the packed stat.
1868
        self.assertPackStat('AAAay0Xm4FZF5uBZAAADCQBjLNIAAIGk', st)
1869
        st.st_size = 7000L
1870
        #                ay0 => bWE
1871
        self.assertPackStat('AAAbWEXm4FZF5uBZAAADCQBjLNIAAIGk', st)
1872
        st.st_mtime = 1172758620
1873
        #                     4FZ => 4Fx
1874
        self.assertPackStat('AAAbWEXm4FxF5uBZAAADCQBjLNIAAIGk', st)
1875
        st.st_ctime = 1172758630
1876
        #                          uBZ => uBm
1877
        self.assertPackStat('AAAbWEXm4FxF5uBmAAADCQBjLNIAAIGk', st)
1878
        st.st_dev = 888L
1879
        #                                DCQ => DeA
1880
        self.assertPackStat('AAAbWEXm4FxF5uBmAAADeABjLNIAAIGk', st)
1881
        st.st_ino = 6499540L
1882
        #                                     LNI => LNQ
1883
        self.assertPackStat('AAAbWEXm4FxF5uBmAAADeABjLNQAAIGk', st)
1884
        st.st_mode = 0100744
1885
        #                                          IGk => IHk
1886
        self.assertPackStat('AAAbWEXm4FxF5uBmAAADeABjLNQAAIHk', st)
1887
1888
    def test_pack_stat_float(self):
1889
        """On some platforms mtime and ctime are floats.
1890
1891
        Make sure we don't get warnings or errors, and that we ignore changes <
1892
        1s
1893
        """
1894
        st = _FakeStat(7000L, 1172758614.0, 1172758617.0,
1895
                       777L, 6499538L, 0100644)
1896
        # These should all be the same as the integer counterparts
1897
        self.assertPackStat('AAAbWEXm4FZF5uBZAAADCQBjLNIAAIGk', st)
1898
        st.st_mtime = 1172758620.0
1899
        #                     FZF5 => FxF5
1900
        self.assertPackStat('AAAbWEXm4FxF5uBZAAADCQBjLNIAAIGk', st)
1901
        st.st_ctime = 1172758630.0
1902
        #                          uBZ => uBm
1903
        self.assertPackStat('AAAbWEXm4FxF5uBmAAADCQBjLNIAAIGk', st)
1904
        # fractional seconds are discarded, so no change from above
1905
        st.st_mtime = 1172758620.453
1906
        self.assertPackStat('AAAbWEXm4FxF5uBmAAADCQBjLNIAAIGk', st)
1907
        st.st_ctime = 1172758630.228
1908
        self.assertPackStat('AAAbWEXm4FxF5uBmAAADCQBjLNIAAIGk', st)
1909
1910
2323.5.4 by Martin Pool
Move some dirstate test setup methods into the base class
1911
class TestBisect(TestCaseWithDirState):
2255.3.2 by John Arbash Meinel
(broken) some basic work on adding bisect functionality to dirstate.
1912
    """Test the ability to bisect into the disk format."""
1913
2255.2.131 by John Arbash Meinel
Change the return values for bisect functions so they just return
1914
    def assertBisect(self, expected_map, map_keys, state, paths):
2255.2.125 by John Arbash Meinel
Initial effort at adding a basic _bisect function to DirState.
1915
        """Assert that bisecting for paths returns the right result.
1916
2255.2.131 by John Arbash Meinel
Change the return values for bisect functions so they just return
1917
        :param expected_map: A map from key => entry value
1918
        :param map_keys: The keys to expect for each path
2255.2.125 by John Arbash Meinel
Initial effort at adding a basic _bisect function to DirState.
1919
        :param state: The DirState object.
1920
        :param paths: A list of paths, these will automatically be split into
1921
                      (dir, name) tuples, and sorted according to how _bisect
1922
                      requires.
1923
        """
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
1924
        result = state._bisect(paths)
2255.2.126 by John Arbash Meinel
Switch the bisect code to support the fact that we can have
1925
        # For now, results are just returned in whatever order we read them.
1926
        # We could sort by (dir, name, file_id) or something like that, but in
1927
        # the end it would still be fairly arbitrary, and we don't want the
2255.2.131 by John Arbash Meinel
Change the return values for bisect functions so they just return
1928
        # extra overhead if we can avoid it. So sort everything to make sure
1929
        # equality is true
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1930
        self.assertEqual(len(map_keys), len(paths))
2255.2.131 by John Arbash Meinel
Change the return values for bisect functions so they just return
1931
        expected = {}
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
1932
        for path, keys in zip(paths, map_keys):
2255.2.131 by John Arbash Meinel
Change the return values for bisect functions so they just return
1933
            if keys is None:
1934
                # This should not be present in the output
1935
                continue
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
1936
            expected[path] = sorted(expected_map[k] for k in keys)
2255.2.131 by John Arbash Meinel
Change the return values for bisect functions so they just return
1937
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
1938
        # The returned values are just arranged randomly based on when they
1939
        # were read, for testing, make sure it is properly sorted.
1940
        for path in result:
1941
            result[path].sort()
2255.2.131 by John Arbash Meinel
Change the return values for bisect functions so they just return
1942
1943
        self.assertEqual(expected, result)
1944
1945
    def assertBisectDirBlocks(self, expected_map, map_keys, state, paths):
2255.2.130 by John Arbash Meinel
Add a very similar function which grabs everything for a particular directory block.
1946
        """Assert that bisecting for dirbblocks returns the right result.
1947
2255.2.132 by John Arbash Meinel
Implement _bisect_recursive, which uses multiple bisect calls to
1948
        :param expected_map: A map from key => expected values
2255.2.131 by John Arbash Meinel
Change the return values for bisect functions so they just return
1949
        :param map_keys: A nested list of paths we expect to be returned.
2255.2.130 by John Arbash Meinel
Add a very similar function which grabs everything for a particular directory block.
1950
            Something like [['a', 'b', 'f'], ['b/c', 'b/d']]
1951
        :param state: The DirState object.
1952
        :param paths: A list of directories
1953
        """
1954
        result = state._bisect_dirblocks(paths)
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1955
        self.assertEqual(len(map_keys), len(paths))
2255.2.131 by John Arbash Meinel
Change the return values for bisect functions so they just return
1956
        expected = {}
1957
        for path, keys in zip(paths, map_keys):
1958
            if keys is None:
1959
                # This should not be present in the output
1960
                continue
1961
            expected[path] = sorted(expected_map[k] for k in keys)
1962
        for path in result:
1963
            result[path].sort()
1964
1965
        self.assertEqual(expected, result)
2255.2.130 by John Arbash Meinel
Add a very similar function which grabs everything for a particular directory block.
1966
2255.2.132 by John Arbash Meinel
Implement _bisect_recursive, which uses multiple bisect calls to
1967
    def assertBisectRecursive(self, expected_map, map_keys, state, paths):
1968
        """Assert the return value of a recursive bisection.
1969
1970
        :param expected_map: A map from key => entry value
1971
        :param map_keys: A list of paths we expect to be returned.
1972
            Something like ['a', 'b', 'f', 'b/d', 'b/d2']
1973
        :param state: The DirState object.
1974
        :param paths: A list of files and directories. It will be broken up
1975
            into (dir, name) pairs and sorted before calling _bisect_recursive.
1976
        """
1977
        expected = {}
1978
        for key in map_keys:
1979
            entry = expected_map[key]
1980
            dir_name_id, trees_info = entry
1981
            expected[dir_name_id] = trees_info
1982
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
1983
        result = state._bisect_recursive(paths)
2255.2.132 by John Arbash Meinel
Implement _bisect_recursive, which uses multiple bisect calls to
1984
1985
        self.assertEqual(expected, result)
1986
2255.3.2 by John Arbash Meinel
(broken) some basic work on adding bisect functionality to dirstate.
1987
    def test_bisect_each(self):
1988
        """Find a single record using bisect."""
2255.2.125 by John Arbash Meinel
Initial effort at adding a basic _bisect function to DirState.
1989
        tree, state, expected = self.create_basic_dirstate()
2255.3.2 by John Arbash Meinel
(broken) some basic work on adding bisect functionality to dirstate.
1990
1991
        # Bisect should return the rows for the specified files.
2255.2.131 by John Arbash Meinel
Change the return values for bisect functions so they just return
1992
        self.assertBisect(expected, [['']], state, [''])
1993
        self.assertBisect(expected, [['a']], state, ['a'])
1994
        self.assertBisect(expected, [['b']], state, ['b'])
1995
        self.assertBisect(expected, [['b/c']], state, ['b/c'])
1996
        self.assertBisect(expected, [['b/d']], state, ['b/d'])
1997
        self.assertBisect(expected, [['b/d/e']], state, ['b/d/e'])
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
1998
        self.assertBisect(expected, [['b-c']], state, ['b-c'])
2255.2.131 by John Arbash Meinel
Change the return values for bisect functions so they just return
1999
        self.assertBisect(expected, [['f']], state, ['f'])
2255.2.125 by John Arbash Meinel
Initial effort at adding a basic _bisect function to DirState.
2000
2001
    def test_bisect_multi(self):
2002
        """Bisect can be used to find multiple records at the same time."""
2003
        tree, state, expected = self.create_basic_dirstate()
2004
        # Bisect should be capable of finding multiple entries at the same time
2255.2.131 by John Arbash Meinel
Change the return values for bisect functions so they just return
2005
        self.assertBisect(expected, [['a'], ['b'], ['f']],
2255.2.126 by John Arbash Meinel
Switch the bisect code to support the fact that we can have
2006
                          state, ['a', 'b', 'f'])
2255.2.131 by John Arbash Meinel
Change the return values for bisect functions so they just return
2007
        self.assertBisect(expected, [['f'], ['b/d'], ['b/d/e']],
2474.1.61 by John Arbash Meinel
Finish fixing DirState._bisect and the bisect tests
2008
                          state, ['f', 'b/d', 'b/d/e'])
2009
        self.assertBisect(expected, [['b'], ['b-c'], ['b/c']],
2010
                          state, ['b', 'b-c', 'b/c'])
2255.2.126 by John Arbash Meinel
Switch the bisect code to support the fact that we can have
2011
2012
    def test_bisect_one_page(self):
2013
        """Test bisect when there is only 1 page to read"""
2014
        tree, state, expected = self.create_basic_dirstate()
2015
        state._bisect_page_size = 5000
2255.2.131 by John Arbash Meinel
Change the return values for bisect functions so they just return
2016
        self.assertBisect(expected,[['']], state, [''])
2017
        self.assertBisect(expected,[['a']], state, ['a'])
2018
        self.assertBisect(expected,[['b']], state, ['b'])
2019
        self.assertBisect(expected,[['b/c']], state, ['b/c'])
2020
        self.assertBisect(expected,[['b/d']], state, ['b/d'])
2021
        self.assertBisect(expected,[['b/d/e']], state, ['b/d/e'])
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
2022
        self.assertBisect(expected,[['b-c']], state, ['b-c'])
2255.2.131 by John Arbash Meinel
Change the return values for bisect functions so they just return
2023
        self.assertBisect(expected,[['f']], state, ['f'])
2024
        self.assertBisect(expected,[['a'], ['b'], ['f']],
2255.2.126 by John Arbash Meinel
Switch the bisect code to support the fact that we can have
2025
                          state, ['a', 'b', 'f'])
2474.1.61 by John Arbash Meinel
Finish fixing DirState._bisect and the bisect tests
2026
        self.assertBisect(expected, [['b/d'], ['b/d/e'], ['f']],
2255.2.126 by John Arbash Meinel
Switch the bisect code to support the fact that we can have
2027
                          state, ['b/d', 'b/d/e', 'f'])
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
2028
        self.assertBisect(expected, [['b'], ['b/c'], ['b-c']],
2029
                          state, ['b', 'b/c', 'b-c'])
2255.2.126 by John Arbash Meinel
Switch the bisect code to support the fact that we can have
2030
2031
    def test_bisect_duplicate_paths(self):
2032
        """When bisecting for a path, handle multiple entries."""
2033
        tree, state, expected = self.create_duplicated_dirstate()
2034
2035
        # Now make sure that both records are properly returned.
2255.2.131 by John Arbash Meinel
Change the return values for bisect functions so they just return
2036
        self.assertBisect(expected, [['']], state, [''])
2037
        self.assertBisect(expected, [['a', 'a2']], state, ['a'])
2038
        self.assertBisect(expected, [['b', 'b2']], state, ['b'])
2039
        self.assertBisect(expected, [['b/c', 'b/c2']], state, ['b/c'])
2040
        self.assertBisect(expected, [['b/d', 'b/d2']], state, ['b/d'])
2041
        self.assertBisect(expected, [['b/d/e', 'b/d/e2']],
2255.2.129 by John Arbash Meinel
Start cleaning up the code, and fix one more edge case
2042
                          state, ['b/d/e'])
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
2043
        self.assertBisect(expected, [['b-c', 'b-c2']], state, ['b-c'])
2255.2.131 by John Arbash Meinel
Change the return values for bisect functions so they just return
2044
        self.assertBisect(expected, [['f', 'f2']], state, ['f'])
2255.2.126 by John Arbash Meinel
Switch the bisect code to support the fact that we can have
2045
2046
    def test_bisect_page_size_too_small(self):
2255.2.128 by John Arbash Meinel
Rather than falling over when the page size is to small, just increase it and try again.
2047
        """If the page size is too small, we will auto increase it."""
2255.2.126 by John Arbash Meinel
Switch the bisect code to support the fact that we can have
2048
        tree, state, expected = self.create_basic_dirstate()
2049
        state._bisect_page_size = 50
2255.2.131 by John Arbash Meinel
Change the return values for bisect functions so they just return
2050
        self.assertBisect(expected, [None], state, ['b/e'])
2051
        self.assertBisect(expected, [['a']], state, ['a'])
2052
        self.assertBisect(expected, [['b']], state, ['b'])
2053
        self.assertBisect(expected, [['b/c']], state, ['b/c'])
2054
        self.assertBisect(expected, [['b/d']], state, ['b/d'])
2055
        self.assertBisect(expected, [['b/d/e']], state, ['b/d/e'])
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
2056
        self.assertBisect(expected, [['b-c']], state, ['b-c'])
2255.2.131 by John Arbash Meinel
Change the return values for bisect functions so they just return
2057
        self.assertBisect(expected, [['f']], state, ['f'])
2255.2.126 by John Arbash Meinel
Switch the bisect code to support the fact that we can have
2058
2059
    def test_bisect_missing(self):
2060
        """Test that bisect return None if it cannot find a path."""
2061
        tree, state, expected = self.create_basic_dirstate()
2255.2.131 by John Arbash Meinel
Change the return values for bisect functions so they just return
2062
        self.assertBisect(expected, [None], state, ['foo'])
2063
        self.assertBisect(expected, [None], state, ['b/foo'])
2064
        self.assertBisect(expected, [None], state, ['bar/foo'])
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
2065
        self.assertBisect(expected, [None], state, ['b-c/foo'])
2255.2.126 by John Arbash Meinel
Switch the bisect code to support the fact that we can have
2066
2255.2.131 by John Arbash Meinel
Change the return values for bisect functions so they just return
2067
        self.assertBisect(expected, [['a'], None, ['b/d']],
2255.2.126 by John Arbash Meinel
Switch the bisect code to support the fact that we can have
2068
                          state, ['a', 'foo', 'b/d'])
2255.2.127 by John Arbash Meinel
Expand the test suite to cover more cases.
2069
2070
    def test_bisect_rename(self):
2071
        """Check that we find a renamed row."""
2072
        tree, state, expected = self.create_renamed_dirstate()
2073
2074
        # Search for the pre and post renamed entries
2255.2.131 by John Arbash Meinel
Change the return values for bisect functions so they just return
2075
        self.assertBisect(expected, [['a']], state, ['a'])
2076
        self.assertBisect(expected, [['b/g']], state, ['b/g'])
2255.2.132 by John Arbash Meinel
Implement _bisect_recursive, which uses multiple bisect calls to
2077
        self.assertBisect(expected, [['b/d']], state, ['b/d'])
2078
        self.assertBisect(expected, [['h']], state, ['h'])
2079
2080
        # What about b/d/e? shouldn't that also get 2 directory entries?
2081
        self.assertBisect(expected, [['b/d/e']], state, ['b/d/e'])
2082
        self.assertBisect(expected, [['h/e']], state, ['h/e'])
2255.2.130 by John Arbash Meinel
Add a very similar function which grabs everything for a particular directory block.
2083
2084
    def test_bisect_dirblocks(self):
2085
        tree, state, expected = self.create_duplicated_dirstate()
2086
        self.assertBisectDirBlocks(expected,
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
2087
            [['', 'a', 'a2', 'b', 'b2', 'b-c', 'b-c2', 'f', 'f2']],
2088
            state, [''])
2255.2.130 by John Arbash Meinel
Add a very similar function which grabs everything for a particular directory block.
2089
        self.assertBisectDirBlocks(expected,
2090
            [['b/c', 'b/c2', 'b/d', 'b/d2']], state, ['b'])
2091
        self.assertBisectDirBlocks(expected,
2092
            [['b/d/e', 'b/d/e2']], state, ['b/d'])
2093
        self.assertBisectDirBlocks(expected,
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
2094
            [['', 'a', 'a2', 'b', 'b2', 'b-c', 'b-c2', 'f', 'f2'],
2255.2.130 by John Arbash Meinel
Add a very similar function which grabs everything for a particular directory block.
2095
             ['b/c', 'b/c2', 'b/d', 'b/d2'],
2096
             ['b/d/e', 'b/d/e2'],
2097
            ], state, ['', 'b', 'b/d'])
2098
2099
    def test_bisect_dirblocks_missing(self):
2100
        tree, state, expected = self.create_basic_dirstate()
2101
        self.assertBisectDirBlocks(expected, [['b/d/e'], None],
2102
            state, ['b/d', 'b/e'])
2103
        # Files don't show up in this search
2104
        self.assertBisectDirBlocks(expected, [None], state, ['a'])
2105
        self.assertBisectDirBlocks(expected, [None], state, ['b/c'])
2106
        self.assertBisectDirBlocks(expected, [None], state, ['c'])
2107
        self.assertBisectDirBlocks(expected, [None], state, ['b/d/e'])
2108
        self.assertBisectDirBlocks(expected, [None], state, ['f'])
2255.2.132 by John Arbash Meinel
Implement _bisect_recursive, which uses multiple bisect calls to
2109
2110
    def test_bisect_recursive_each(self):
2111
        tree, state, expected = self.create_basic_dirstate()
2112
        self.assertBisectRecursive(expected, ['a'], state, ['a'])
2113
        self.assertBisectRecursive(expected, ['b/c'], state, ['b/c'])
2114
        self.assertBisectRecursive(expected, ['b/d/e'], state, ['b/d/e'])
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
2115
        self.assertBisectRecursive(expected, ['b-c'], state, ['b-c'])
2255.2.132 by John Arbash Meinel
Implement _bisect_recursive, which uses multiple bisect calls to
2116
        self.assertBisectRecursive(expected, ['b/d', 'b/d/e'],
2117
                                   state, ['b/d'])
2118
        self.assertBisectRecursive(expected, ['b', 'b/c', 'b/d', 'b/d/e'],
2119
                                   state, ['b'])
2474.1.61 by John Arbash Meinel
Finish fixing DirState._bisect and the bisect tests
2120
        self.assertBisectRecursive(expected, ['', 'a', 'b', 'b-c', 'f', 'b/c',
2255.2.132 by John Arbash Meinel
Implement _bisect_recursive, which uses multiple bisect calls to
2121
                                              'b/d', 'b/d/e'],
2122
                                   state, [''])
2123
2124
    def test_bisect_recursive_multiple(self):
2125
        tree, state, expected = self.create_basic_dirstate()
2126
        self.assertBisectRecursive(expected, ['a', 'b/c'], state, ['a', 'b/c'])
2127
        self.assertBisectRecursive(expected, ['b/d', 'b/d/e'],
2128
                                   state, ['b/d', 'b/d/e'])
2129
2130
    def test_bisect_recursive_missing(self):
2131
        tree, state, expected = self.create_basic_dirstate()
2132
        self.assertBisectRecursive(expected, [], state, ['d'])
2133
        self.assertBisectRecursive(expected, [], state, ['b/e'])
2134
        self.assertBisectRecursive(expected, [], state, ['g'])
2135
        self.assertBisectRecursive(expected, ['a'], state, ['a', 'g'])
2136
2137
    def test_bisect_recursive_renamed(self):
2138
        tree, state, expected = self.create_renamed_dirstate()
2139
2140
        # Looking for either renamed item should find the other
2141
        self.assertBisectRecursive(expected, ['a', 'b/g'], state, ['a'])
2142
        self.assertBisectRecursive(expected, ['a', 'b/g'], state, ['b/g'])
2143
        # Looking in the containing directory should find the rename target,
2144
        # and anything in a subdir of the renamed target.
2145
        self.assertBisectRecursive(expected, ['a', 'b', 'b/c', 'b/d',
2146
                                              'b/d/e', 'b/g', 'h', 'h/e'],
2147
                                   state, ['b'])
2148
2255.8.2 by John Arbash Meinel
Add a helper function, which allows us to store keys as plain paths,
2149
2323.5.4 by Martin Pool
Move some dirstate test setup methods into the base class
2150
class TestDirstateValidation(TestCaseWithDirState):
2151
2152
    def test_validate_correct_dirstate(self):
2153
        state = self.create_complex_dirstate()
2154
        state._validate()
2155
        state.unlock()
2156
        # and make sure we can also validate with a read lock
2157
        state.lock_read()
2158
        try:
2159
            state._validate()
2160
        finally:
2161
            state.unlock()
2323.5.6 by Martin Pool
Add some tests and better messages for DirState._validate
2162
2163
    def test_dirblock_not_sorted(self):
2164
        tree, state, expected = self.create_renamed_dirstate()
2165
        state._read_dirblocks_if_needed()
2166
        last_dirblock = state._dirblocks[-1]
2167
        # we're appending to the dirblock, but this name comes before some of
2168
        # the existing names; that's wrong
2169
        last_dirblock[1].append(
2170
            (('h', 'aaaa', 'a-id'),
2171
             [('a', '', 0, False, ''),
2172
              ('a', '', 0, False, '')]))
2173
        e = self.assertRaises(AssertionError,
2174
            state._validate)
2175
        self.assertContainsRe(str(e), 'not sorted')
2176
2177
    def test_dirblock_name_mismatch(self):
2178
        tree, state, expected = self.create_renamed_dirstate()
2179
        state._read_dirblocks_if_needed()
2180
        last_dirblock = state._dirblocks[-1]
2181
        # add an entry with the wrong directory name
2182
        last_dirblock[1].append(
2183
            (('', 'z', 'a-id'),
2184
             [('a', '', 0, False, ''),
2185
              ('a', '', 0, False, '')]))
2186
        e = self.assertRaises(AssertionError,
2187
            state._validate)
2188
        self.assertContainsRe(str(e),
2189
            "doesn't match directory name")
2190
2323.5.7 by Martin Pool
Better DirState._validate and tests for it.
2191
    def test_dirblock_missing_rename(self):
2192
        tree, state, expected = self.create_renamed_dirstate()
2193
        state._read_dirblocks_if_needed()
2194
        last_dirblock = state._dirblocks[-1]
2323.5.6 by Martin Pool
Add some tests and better messages for DirState._validate
2195
        # make another entry for a-id, without a correct 'r' pointer to
2196
        # the real occurrence in the working tree
2323.5.7 by Martin Pool
Better DirState._validate and tests for it.
2197
        last_dirblock[1].append(
2198
            (('h', 'z', 'a-id'),
2199
             [('a', '', 0, False, ''),
2200
              ('a', '', 0, False, '')]))
2201
        e = self.assertRaises(AssertionError,
2202
            state._validate)
2203
        self.assertContainsRe(str(e),
2204
            'file a-id is absent in row')
2474.1.41 by John Arbash Meinel
Change the name of cmp_dirblock_strings to cmp_by_dirs
2205
2645.2.1 by Wouter van Heyst
The DirState fingerprint for tree-references should be an empty string instead of None
2206
2207
class TestDirstateTreeReference(TestCaseWithDirState):
2208
2209
    def test_reference_revision_is_none(self):
2210
        tree = self.make_branch_and_tree('tree', format='dirstate-with-subtree')
2211
        subtree = self.make_branch_and_tree('tree/subtree',
2212
                            format='dirstate-with-subtree')
2213
        subtree.set_root_id('subtree')
2214
        tree.add_reference(subtree)
2215
        tree.add('subtree')
2216
        state = dirstate.DirState.from_tree(tree, 'dirstate')
2217
        key = ('', 'subtree', 'subtree')
2218
        expected = ('', [(key,
2219
            [('t', '', 0, False, 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')])])
2220
2221
        try:
2222
            self.assertEqual(expected, state._find_block(key))
2223
        finally:
2224
            state.unlock()
2984.1.1 by John Arbash Meinel
Fix bug #161131: Correct DirState._discard_merge_parents logic.
2225
2226
2227
class TestDiscardMergeParents(TestCaseWithDirState):
2228
2229
    def test_discard_no_parents(self):
2230
        # This should be a no-op
2231
        state = self.create_empty_dirstate()
2232
        self.addCleanup(state.unlock)
2233
        state._discard_merge_parents()
2234
        state._validate()
2235
2236
    def test_discard_one_parent(self):
2237
        # No-op
2238
        packed_stat = 'AAAAREUHaIpFB2iKAAADAQAtkqUAAIGk'
2239
        root_entry_direntry = ('', '', 'a-root-value'), [
2240
            ('d', '', 0, False, packed_stat),
2241
            ('d', '', 0, False, packed_stat),
2242
            ]
2243
        dirblocks = []
2244
        dirblocks.append(('', [root_entry_direntry]))
2245
        dirblocks.append(('', []))
2246
2247
        state = self.create_empty_dirstate()
2248
        self.addCleanup(state.unlock)
2249
        state._set_data(['parent-id'], dirblocks[:])
2250
        state._validate()
2251
2252
        state._discard_merge_parents()
2253
        state._validate()
2254
        self.assertEqual(dirblocks, state._dirblocks)
2255
2256
    def test_discard_simple(self):
2257
        # No-op
2258
        packed_stat = 'AAAAREUHaIpFB2iKAAADAQAtkqUAAIGk'
2259
        root_entry_direntry = ('', '', 'a-root-value'), [
2260
            ('d', '', 0, False, packed_stat),
2261
            ('d', '', 0, False, packed_stat),
2262
            ('d', '', 0, False, packed_stat),
2263
            ]
2264
        expected_root_entry_direntry = ('', '', 'a-root-value'), [
2265
            ('d', '', 0, False, packed_stat),
2266
            ('d', '', 0, False, packed_stat),
2267
            ]
2268
        dirblocks = []
2269
        dirblocks.append(('', [root_entry_direntry]))
2270
        dirblocks.append(('', []))
2271
2272
        state = self.create_empty_dirstate()
2273
        self.addCleanup(state.unlock)
2274
        state._set_data(['parent-id', 'merged-id'], dirblocks[:])
2275
        state._validate()
2276
2277
        # This should strip of the extra column
2278
        state._discard_merge_parents()
2279
        state._validate()
2280
        expected_dirblocks = [('', [expected_root_entry_direntry]), ('', [])]
2281
        self.assertEqual(expected_dirblocks, state._dirblocks)
2282
2283
    def test_discard_absent(self):
2284
        """If entries are only in a merge, discard should remove the entries"""
2285
        null_stat = dirstate.DirState.NULLSTAT
2286
        present_dir = ('d', '', 0, False, null_stat)
2287
        present_file = ('f', '', 0, False, null_stat)
2288
        absent = dirstate.DirState.NULL_PARENT_DETAILS
2289
        root_key = ('', '', 'a-root-value')
2290
        file_in_root_key = ('', 'file-in-root', 'a-file-id')
2291
        file_in_merged_key = ('', 'file-in-merged', 'b-file-id')
2292
        dirblocks = [('', [(root_key, [present_dir, present_dir, present_dir])]),
2293
                     ('', [(file_in_merged_key,
2294
                            [absent, absent, present_file]),
2295
                           (file_in_root_key,
2296
                            [present_file, present_file, present_file]),
2297
                          ]),
2298
                    ]
2299
2300
        state = self.create_empty_dirstate()
2301
        self.addCleanup(state.unlock)
2302
        state._set_data(['parent-id', 'merged-id'], dirblocks[:])
2303
        state._validate()
2304
2305
        exp_dirblocks = [('', [(root_key, [present_dir, present_dir])]),
2306
                         ('', [(file_in_root_key,
2307
                                [present_file, present_file]),
2308
                              ]),
2309
                        ]
2310
        state._discard_merge_parents()
2311
        state._validate()
2312
        self.assertEqual(exp_dirblocks, state._dirblocks)
2313
2314
    def test_discard_renamed(self):
2315
        null_stat = dirstate.DirState.NULLSTAT
2316
        present_dir = ('d', '', 0, False, null_stat)
2317
        present_file = ('f', '', 0, False, null_stat)
2318
        absent = dirstate.DirState.NULL_PARENT_DETAILS
2319
        root_key = ('', '', 'a-root-value')
2320
        file_in_root_key = ('', 'file-in-root', 'a-file-id')
2321
        # Renamed relative to parent
2322
        file_rename_s_key = ('', 'file-s', 'b-file-id')
2323
        file_rename_t_key = ('', 'file-t', 'b-file-id')
2324
        # And one that is renamed between the parents, but absent in this
2325
        key_in_1 = ('', 'file-in-1', 'c-file-id')
2326
        key_in_2 = ('', 'file-in-2', 'c-file-id')
2327
2328
        dirblocks = [
2329
            ('', [(root_key, [present_dir, present_dir, present_dir])]),
2330
            ('', [(key_in_1,
2331
                   [absent, present_file, ('r', 'file-in-2', 'c-file-id')]),
2332
                  (key_in_2,
2333
                   [absent, ('r', 'file-in-1', 'c-file-id'), present_file]),
2334
                  (file_in_root_key,
2335
                   [present_file, present_file, present_file]),
2336
                  (file_rename_s_key,
2337
                   [('r', 'file-t', 'b-file-id'), absent, present_file]),
2338
                  (file_rename_t_key,
2339
                   [present_file, absent, ('r', 'file-s', 'b-file-id')]),
2340
                 ]),
2341
        ]
2342
        exp_dirblocks = [
2343
            ('', [(root_key, [present_dir, present_dir])]),
2344
            ('', [(key_in_1, [absent, present_file]),
2345
                  (file_in_root_key, [present_file, present_file]),
2346
                  (file_rename_t_key, [present_file, absent]),
2347
                 ]),
2348
        ]
2349
        state = self.create_empty_dirstate()
2350
        self.addCleanup(state.unlock)
2351
        state._set_data(['parent-id', 'merged-id'], dirblocks[:])
2352
        state._validate()
2353
2354
        state._discard_merge_parents()
2355
        state._validate()
2356
        self.assertEqual(exp_dirblocks, state._dirblocks)
2357
2358
    def test_discard_all_subdir(self):
2359
        null_stat = dirstate.DirState.NULLSTAT
2360
        present_dir = ('d', '', 0, False, null_stat)
2361
        present_file = ('f', '', 0, False, null_stat)
2362
        absent = dirstate.DirState.NULL_PARENT_DETAILS
2363
        root_key = ('', '', 'a-root-value')
2364
        subdir_key = ('', 'sub', 'dir-id')
2365
        child1_key = ('sub', 'child1', 'child1-id')
2366
        child2_key = ('sub', 'child2', 'child2-id')
2367
        child3_key = ('sub', 'child3', 'child3-id')
2368
2369
        dirblocks = [
2370
            ('', [(root_key, [present_dir, present_dir, present_dir])]),
2371
            ('', [(subdir_key, [present_dir, present_dir, present_dir])]),
2372
            ('sub', [(child1_key, [absent, absent, present_file]),
2373
                     (child2_key, [absent, absent, present_file]),
2374
                     (child3_key, [absent, absent, present_file]),
2375
                    ]),
2376
        ]
2377
        exp_dirblocks = [
2378
            ('', [(root_key, [present_dir, present_dir])]),
2379
            ('', [(subdir_key, [present_dir, present_dir])]),
2380
            ('sub', []),
2381
        ]
2382
        state = self.create_empty_dirstate()
2383
        self.addCleanup(state.unlock)
2384
        state._set_data(['parent-id', 'merged-id'], dirblocks[:])
2385
        state._validate()
2386
2387
        state._discard_merge_parents()
2388
        state._validate()
2389
        self.assertEqual(exp_dirblocks, state._dirblocks)
3477.2.1 by John Arbash Meinel
Assert that we properly encode inv_entry.symlink_target, (bug #135320)
2390
2391
4241.14.10 by Vincent Ladeuil
Add DirReader parametrized tests.
2392
class Test_InvEntryToDetails(tests.TestCase):
3477.2.1 by John Arbash Meinel
Assert that we properly encode inv_entry.symlink_target, (bug #135320)
2393
2394
    def assertDetails(self, expected, inv_entry):
2395
        details = dirstate.DirState._inv_entry_to_details(inv_entry)
2396
        self.assertEqual(expected, details)
3477.2.2 by John Arbash Meinel
Change how we handle unicode targets, and add a NEWS entry.
2397
        # details should always allow join() and always be a plain str when
2398
        # finished
2399
        (minikind, fingerprint, size, executable, tree_data) = details
2400
        self.assertIsInstance(minikind, str)
2401
        self.assertIsInstance(fingerprint, str)
2402
        self.assertIsInstance(tree_data, str)
3477.2.1 by John Arbash Meinel
Assert that we properly encode inv_entry.symlink_target, (bug #135320)
2403
2404
    def test_unicode_symlink(self):
4241.14.10 by Vincent Ladeuil
Add DirReader parametrized tests.
2405
        inv_entry = inventory.InventoryLink('link-file-id',
2406
                                            u'nam\N{Euro Sign}e',
3477.2.1 by John Arbash Meinel
Assert that we properly encode inv_entry.symlink_target, (bug #135320)
2407
                                            'link-parent-id')
2408
        inv_entry.revision = 'link-revision-id'
4241.14.10 by Vincent Ladeuil
Add DirReader parametrized tests.
2409
        target = u'link-targ\N{Euro Sign}t'
2410
        inv_entry.symlink_target = target
2411
        self.assertDetails(('l', target.encode('UTF-8'), 0, False,
2412
                            'link-revision-id'), inv_entry)
2413
2414
2415
class TestSHA1Provider(tests.TestCaseInTempDir):
4132.2.1 by Ian Clatworthy
make sha1_provider a parameter to DirState()
2416
2417
    def test_sha1provider_is_an_interface(self):
4132.2.5 by Ian Clatworthy
feedback from poolie - use SHA, not Sha, in class names
2418
        p = dirstate.SHA1Provider()
4132.2.1 by Ian Clatworthy
make sha1_provider a parameter to DirState()
2419
        self.assertRaises(NotImplementedError, p.sha1, "foo")
2420
        self.assertRaises(NotImplementedError, p.stat_and_sha1, "foo")
2421
2422
    def test_defaultsha1provider_sha1(self):
2423
        text = 'test\r\nwith\nall\rpossible line endings\r\n'
2424
        self.build_tree_contents([('foo', text)])
2425
        expected_sha = osutils.sha_string(text)
4132.2.5 by Ian Clatworthy
feedback from poolie - use SHA, not Sha, in class names
2426
        p = dirstate.DefaultSHA1Provider()
4132.2.1 by Ian Clatworthy
make sha1_provider a parameter to DirState()
2427
        self.assertEqual(expected_sha, p.sha1('foo'))
2428
2429
    def test_defaultsha1provider_stat_and_sha1(self):
2430
        text = 'test\r\nwith\nall\rpossible line endings\r\n'
2431
        self.build_tree_contents([('foo', text)])
2432
        expected_sha = osutils.sha_string(text)
4132.2.5 by Ian Clatworthy
feedback from poolie - use SHA, not Sha, in class names
2433
        p = dirstate.DefaultSHA1Provider()
4132.2.1 by Ian Clatworthy
make sha1_provider a parameter to DirState()
2434
        statvalue, sha1 = p.stat_and_sha1('foo')
2435
        self.assertTrue(len(statvalue) >= 10)
2436
        self.assertEqual(len(text), statvalue.st_size)
2437
        self.assertEqual(expected_sha, sha1)
5847.4.14 by John Arbash Meinel
Create a direct helper for testing UpdateBasisByDelta cases.
2438
2439
5847.4.16 by John Arbash Meinel
Switching from BranchBuilder to Inventory directly dropped us from 73ms to 26ms.
2440
class _Repo(object):
5847.4.17 by John Arbash Meinel
The 25ms was the time spent checking that we didn't alter the containing WT.
2441
    """A minimal api to get InventoryRevisionTree to work."""
5847.4.16 by John Arbash Meinel
Switching from BranchBuilder to Inventory directly dropped us from 73ms to 26ms.
2442
2443
    def __init__(self):
2444
        default_format = bzrdir.format_registry.make_bzrdir('default')
2445
        self._format = default_format.repository_format
2446
2447
    def lock_read(self):
2448
        pass
2449
2450
    def unlock(self):
2451
        pass
2452
5847.4.17 by John Arbash Meinel
The 25ms was the time spent checking that we didn't alter the containing WT.
2453
2454
class TestUpdateBasisByDelta(tests.TestCase):
5847.4.14 by John Arbash Meinel
Create a direct helper for testing UpdateBasisByDelta cases.
2455
5847.4.22 by John Arbash Meinel
Cleanup dirstate a bit.
2456
    def path_to_ie(self, path, file_id, rev_id, dir_ids):
2457
        if path.endswith('/'):
2458
            is_dir = True
5847.4.28 by John Arbash Meinel
Some more direct tests. Fix some bugs in the create_entry code.
2459
            path = path[:-1]
5847.4.22 by John Arbash Meinel
Cleanup dirstate a bit.
2460
        else:
2461
            is_dir = False
2462
        dirname, basename = osutils.split(path)
5847.4.27 by John Arbash Meinel
Handle missing parent, though bugs may still remain
2463
        try:
2464
            dir_id = dir_ids[dirname]
2465
        except KeyError:
5847.4.28 by John Arbash Meinel
Some more direct tests. Fix some bugs in the create_entry code.
2466
            dir_id = osutils.basename(dirname) + '-id'
5847.4.22 by John Arbash Meinel
Cleanup dirstate a bit.
2467
        if is_dir:
2468
            ie = inventory.InventoryDirectory(file_id, basename, dir_id)
5847.4.29 by John Arbash Meinel
Simplify a bit. Handle that when a directory is added, we need to add its block.
2469
            dir_ids[path] = file_id
5847.4.22 by John Arbash Meinel
Cleanup dirstate a bit.
2470
        else:
2471
            ie = inventory.InventoryFile(file_id, basename, dir_id)
2472
            ie.text_size = 0
2473
            ie.text_sha1 = ''
2474
        ie.revision = rev_id
2475
        return ie
2476
5847.4.16 by John Arbash Meinel
Switching from BranchBuilder to Inventory directly dropped us from 73ms to 26ms.
2477
    def create_tree_from_shape(self, rev_id, shape):
2478
        dir_ids = {'': 'root-id'}
2479
        inv = inventory.Inventory('root-id', rev_id)
5847.4.14 by John Arbash Meinel
Create a direct helper for testing UpdateBasisByDelta cases.
2480
        for path, file_id in shape:
5847.4.32 by John Arbash Meinel
Update the test suite to handle root changes.
2481
            if path == '':
2482
                # Replace the root entry
2483
                del inv._byid[inv.root.file_id]
2484
                inv.root.file_id = file_id
2485
                inv._byid[file_id] = inv.root
2486
                dir_ids[''] = file_id
2487
                continue
5847.4.22 by John Arbash Meinel
Cleanup dirstate a bit.
2488
            inv.add(self.path_to_ie(path, file_id, rev_id, dir_ids))
5847.4.16 by John Arbash Meinel
Switching from BranchBuilder to Inventory directly dropped us from 73ms to 26ms.
2489
        return revisiontree.InventoryRevisionTree(_Repo(), inv, rev_id)
5847.4.14 by John Arbash Meinel
Create a direct helper for testing UpdateBasisByDelta cases.
2490
5847.4.17 by John Arbash Meinel
The 25ms was the time spent checking that we didn't alter the containing WT.
2491
    def create_empty_dirstate(self):
2492
        fd, path = tempfile.mkstemp(prefix='bzr-dirstate')
2493
        self.addCleanup(os.remove, path)
2494
        os.close(fd)
2495
        state = dirstate.DirState.initialize(path)
2496
        self.addCleanup(state.unlock)
2497
        return state
2498
5847.4.22 by John Arbash Meinel
Cleanup dirstate a bit.
2499
    def create_inv_delta(self, delta, rev_id):
2500
        """Translate a 'delta shape' into an actual InventoryDelta"""
2501
        dir_ids = {'': 'root-id'}
2502
        inv_delta = []
2503
        for old_path, new_path, file_id in delta:
2504
            if old_path is not None and old_path.endswith('/'):
2505
                # Don't have to actually do anything for this, because only
2506
                # new_path creates InventoryEntries
5847.4.28 by John Arbash Meinel
Some more direct tests. Fix some bugs in the create_entry code.
2507
                old_path = old_path[:-1]
5847.4.22 by John Arbash Meinel
Cleanup dirstate a bit.
2508
            if new_path is None: # Delete
2509
                inv_delta.append((old_path, None, file_id, None))
2510
                continue
2511
            ie = self.path_to_ie(new_path, file_id, rev_id, dir_ids)
2512
            inv_delta.append((old_path, new_path, file_id, ie))
2513
        return inv_delta
2514
5847.4.15 by John Arbash Meinel
two simple tests in the new framework.
2515
    def assertUpdate(self, active, basis, target):
5847.4.14 by John Arbash Meinel
Create a direct helper for testing UpdateBasisByDelta cases.
2516
        """Assert that update_basis_by_delta works how we want.
2517
2518
        Set up a DirState object with active_shape for tree 0, basis_shape for
2519
        tree 1. Then apply the delta from basis_shape to target_shape,
2520
        and assert that the DirState is still valid, and that its stored
2521
        content matches the target_shape.
2522
        """
5847.4.22 by John Arbash Meinel
Cleanup dirstate a bit.
2523
        active_tree = self.create_tree_from_shape('active', active)
2524
        basis_tree = self.create_tree_from_shape('basis', basis)
2525
        target_tree = self.create_tree_from_shape('target', target)
5847.4.17 by John Arbash Meinel
The 25ms was the time spent checking that we didn't alter the containing WT.
2526
        state = self.create_empty_dirstate()
5847.4.15 by John Arbash Meinel
two simple tests in the new framework.
2527
        state.set_state_from_scratch(active_tree.inventory,
5847.4.14 by John Arbash Meinel
Create a direct helper for testing UpdateBasisByDelta cases.
2528
            [('basis', basis_tree)], [])
2529
        delta = target_tree.inventory._make_delta(basis_tree.inventory)
5847.4.15 by John Arbash Meinel
two simple tests in the new framework.
2530
        state.update_basis_by_delta(delta, 'target')
2531
        state._validate()
2532
        dirstate_tree = workingtree_4.DirStateRevisionTree(state,
5847.4.16 by John Arbash Meinel
Switching from BranchBuilder to Inventory directly dropped us from 73ms to 26ms.
2533
            'target', _Repo())
5847.4.17 by John Arbash Meinel
The 25ms was the time spent checking that we didn't alter the containing WT.
2534
        # The target now that delta has been applied should match the
2535
        # RevisionTree
5847.4.14 by John Arbash Meinel
Create a direct helper for testing UpdateBasisByDelta cases.
2536
        self.assertEqual([], list(dirstate_tree.iter_changes(target_tree)))
5847.4.17 by John Arbash Meinel
The 25ms was the time spent checking that we didn't alter the containing WT.
2537
        # And the dirblock state should be identical to the state if we created
2538
        # it from scratch.
2539
        state2 = self.create_empty_dirstate()
2540
        state2.set_state_from_scratch(active_tree.inventory,
2541
            [('target', target_tree)], [])
5847.4.20 by John Arbash Meinel
Handle a bunch of rename cases.
2542
        self.assertEqual(state2._dirblocks, state._dirblocks)
5847.4.15 by John Arbash Meinel
two simple tests in the new framework.
2543
        return state
5847.4.14 by John Arbash Meinel
Create a direct helper for testing UpdateBasisByDelta cases.
2544
5847.4.22 by John Arbash Meinel
Cleanup dirstate a bit.
2545
    def assertBadDelta(self, active, basis, delta):
2546
        """Test that we raise InconsistentDelta when appropriate.
2547
2548
        :param active: The active tree shape
2549
        :param basis: The basis tree shape
2550
        :param delta: A description of the delta to apply. Similar to the form
2551
            for regular inventory deltas, but omitting the InventoryEntry.
2552
            So adding a file is: (None, 'path', 'file-id')
2553
            Adding a directory is: (None, 'path/', 'dir-id')
2554
            Renaming a dir is: ('old/', 'new/', 'dir-id')
2555
            etc.
2556
        """
2557
        active_tree = self.create_tree_from_shape('active', active)
2558
        basis_tree = self.create_tree_from_shape('basis', basis)
2559
        inv_delta = self.create_inv_delta(delta, 'target')
2560
        state = self.create_empty_dirstate()
2561
        state.set_state_from_scratch(active_tree.inventory,
2562
            [('basis', basis_tree)], [])
5847.4.25 by John Arbash Meinel
Trap an InconsistentDelta case. add can try to add another
2563
        self.assertRaises(errors.InconsistentDelta,
2564
            state.update_basis_by_delta, inv_delta, 'target')
5847.4.26 by John Arbash Meinel
_check_delta_ids_absent thought it didn't have to set _changes_aborted=True
2565
        ## try:
2566
        ##     state.update_basis_by_delta(inv_delta, 'target')
2567
        ## except errors.InconsistentDelta, e:
2568
        ##     import pdb; pdb.set_trace()
2569
        ## else:
2570
        ##     import pdb; pdb.set_trace()
5847.4.22 by John Arbash Meinel
Cleanup dirstate a bit.
2571
        self.assertTrue(state._changes_aborted)
2572
5847.4.15 by John Arbash Meinel
two simple tests in the new framework.
2573
    def test_remove_file_matching_active_state(self):
2574
        state = self.assertUpdate(
2575
            active=[],
2576
            basis =[('file', 'file-id')],
2577
            target=[],
2578
            )
5847.4.17 by John Arbash Meinel
The 25ms was the time spent checking that we didn't alter the containing WT.
2579
2580
    def test_remove_file_present_in_active_state(self):
2581
        state = self.assertUpdate(
2582
            active=[('file', 'file-id')],
2583
            basis =[('file', 'file-id')],
2584
            target=[],
2585
            )
5847.4.18 by John Arbash Meinel
And now we add a bunch more tests, and finally have a failing case.
2586
2587
    def test_remove_file_present_elsewhere_in_active_state(self):
2588
        state = self.assertUpdate(
2589
            active=[('other-file', 'file-id')],
2590
            basis =[('file', 'file-id')],
2591
            target=[],
2592
            )
2593
2594
    def test_remove_file_active_state_has_diff_file(self):
2595
        state = self.assertUpdate(
2596
            active=[('file', 'file-id-2')],
2597
            basis =[('file', 'file-id')],
2598
            target=[],
2599
            )
2600
2601
    def test_remove_file_active_state_has_diff_file_and_file_elsewhere(self):
2602
        state = self.assertUpdate(
2603
            active=[('file', 'file-id-2'),
2604
                    ('other-file', 'file-id')],
2605
            basis =[('file', 'file-id')],
2606
            target=[],
2607
            )
2608
2609
    def test_add_file_matching_active_state(self):
2610
        state = self.assertUpdate(
2611
            active=[('file', 'file-id')],
2612
            basis =[],
2613
            target=[('file', 'file-id')],
2614
            )
2615
2616
    def test_add_file_missing_in_active_state(self):
2617
        state = self.assertUpdate(
2618
            active=[],
2619
            basis =[],
2620
            target=[('file', 'file-id')],
2621
            )
2622
2623
    def test_add_file_elsewhere_in_active_state(self):
2624
        state = self.assertUpdate(
2625
            active=[('other-file', 'file-id')],
2626
            basis =[],
2627
            target=[('file', 'file-id')],
2628
            )
5847.4.20 by John Arbash Meinel
Handle a bunch of rename cases.
2629
2630
    def test_add_file_active_state_has_diff_file_and_file_elsewhere(self):
2631
        state = self.assertUpdate(
2632
            active=[('other-file', 'file-id'),
2633
                    ('file', 'file-id-2')],
2634
            basis =[],
2635
            target=[('file', 'file-id')],
2636
            )
2637
2638
    def test_rename_file_matching_active_state(self):
2639
        state = self.assertUpdate(
2640
            active=[('other-file', 'file-id')],
2641
            basis =[('file', 'file-id')],
2642
            target=[('other-file', 'file-id')],
2643
            )
2644
2645
    def test_rename_file_missing_in_active_state(self):
2646
        state = self.assertUpdate(
2647
            active=[],
2648
            basis =[('file', 'file-id')],
2649
            target=[('other-file', 'file-id')],
2650
            )
2651
2652
    def test_rename_file_present_elsewhere_in_active_state(self):
2653
        state = self.assertUpdate(
2654
            active=[('third', 'file-id')],
2655
            basis =[('file', 'file-id')],
2656
            target=[('other-file', 'file-id')],
2657
            )
2658
2659
    def test_rename_file_active_state_has_diff_source_file(self):
2660
        state = self.assertUpdate(
2661
            active=[('file', 'file-id-2')],
2662
            basis =[('file', 'file-id')],
2663
            target=[('other-file', 'file-id')],
2664
            )
2665
2666
    def test_rename_file_active_state_has_diff_target_file(self):
2667
        state = self.assertUpdate(
2668
            active=[('other-file', 'file-id-2')],
2669
            basis =[('file', 'file-id')],
2670
            target=[('other-file', 'file-id')],
2671
            )
5847.4.21 by John Arbash Meinel
We were raising exceptions improperly. A couple more tests cases, so far so good.
2672
2673
    def test_rename_file_active_has_swapped_files(self):
2674
        state = self.assertUpdate(
2675
            active=[('file', 'file-id'),
2676
                    ('other-file', 'file-id-2')],
2677
            basis= [('file', 'file-id'),
2678
                    ('other-file', 'file-id-2')],
2679
            target=[('file', 'file-id-2'),
2680
                    ('other-file', 'file-id')])
2681
2682
    def test_rename_file_basis_has_swapped_files(self):
2683
        state = self.assertUpdate(
2684
            active=[('file', 'file-id'),
2685
                    ('other-file', 'file-id-2')],
2686
            basis= [('file', 'file-id-2'),
2687
                    ('other-file', 'file-id')],
2688
            target=[('file', 'file-id'),
2689
                    ('other-file', 'file-id-2')])
5847.4.23 by John Arbash Meinel
Add the first invalid delta test.
2690
5847.4.29 by John Arbash Meinel
Simplify a bit. Handle that when a directory is added, we need to add its block.
2691
    def test_rename_directory_with_contents(self):
2692
        state = self.assertUpdate( # active matches basis
2693
            active=[('dir1/', 'dir-id'),
2694
                    ('dir1/file', 'file-id')],
2695
            basis= [('dir1/', 'dir-id'),
2696
                    ('dir1/file', 'file-id')],
2697
            target=[('dir2/', 'dir-id'),
2698
                    ('dir2/file', 'file-id')])
2699
        state = self.assertUpdate( # active matches target
2700
            active=[('dir2/', 'dir-id'),
2701
                    ('dir2/file', 'file-id')],
2702
            basis= [('dir1/', 'dir-id'),
2703
                    ('dir1/file', 'file-id')],
2704
            target=[('dir2/', 'dir-id'),
2705
                    ('dir2/file', 'file-id')])
2706
        state = self.assertUpdate( # active empty
2707
            active=[],
2708
            basis= [('dir1/', 'dir-id'),
2709
                    ('dir1/file', 'file-id')],
2710
            target=[('dir2/', 'dir-id'),
2711
                    ('dir2/file', 'file-id')])
2712
        state = self.assertUpdate( # active present at other location
2713
            active=[('dir3/', 'dir-id'),
2714
                    ('dir3/file', 'file-id')],
2715
            basis= [('dir1/', 'dir-id'),
2716
                    ('dir1/file', 'file-id')],
2717
            target=[('dir2/', 'dir-id'),
2718
                    ('dir2/file', 'file-id')])
2719
        state = self.assertUpdate( # active has different ids
2720
            active=[('dir1/', 'dir1-id'),
2721
                    ('dir1/file', 'file1-id'),
2722
                    ('dir2/', 'dir2-id'),
2723
                    ('dir2/file', 'file2-id')],
2724
            basis= [('dir1/', 'dir-id'),
2725
                    ('dir1/file', 'file-id')],
2726
            target=[('dir2/', 'dir-id'),
2727
                    ('dir2/file', 'file-id')])
2728
5847.4.23 by John Arbash Meinel
Add the first invalid delta test.
2729
    def test_invalid_file_not_present(self):
2730
        state = self.assertBadDelta(
2731
            active=[('file', 'file-id')],
2732
            basis= [('file', 'file-id')],
2733
            delta=[('other-file', 'file', 'file-id')])
2734
5847.4.24 by John Arbash Meinel
Start handling an InconsistentDelta case exposed by test_inv cases.
2735
    def test_invalid_new_id_same_path(self):
5847.4.25 by John Arbash Meinel
Trap an InconsistentDelta case. add can try to add another
2736
        # The bad entry comes after
5847.4.24 by John Arbash Meinel
Start handling an InconsistentDelta case exposed by test_inv cases.
2737
        state = self.assertBadDelta(
2738
            active=[('file', 'file-id')],
2739
            basis= [('file', 'file-id')],
2740
            delta=[(None, 'file', 'file-id-2')])
5847.4.25 by John Arbash Meinel
Trap an InconsistentDelta case. add can try to add another
2741
        # The bad entry comes first
2742
        state = self.assertBadDelta(
2743
            active=[('file', 'file-id-2')],
5847.4.27 by John Arbash Meinel
Handle missing parent, though bugs may still remain
2744
            basis=[('file', 'file-id-2')],
5847.4.25 by John Arbash Meinel
Trap an InconsistentDelta case. add can try to add another
2745
            delta=[(None, 'file', 'file-id')])
5847.4.24 by John Arbash Meinel
Start handling an InconsistentDelta case exposed by test_inv cases.
2746
5847.4.27 by John Arbash Meinel
Handle missing parent, though bugs may still remain
2747
    def test_invalid_existing_id(self):
5847.4.26 by John Arbash Meinel
_check_delta_ids_absent thought it didn't have to set _changes_aborted=True
2748
        state = self.assertBadDelta(
2749
            active=[('file', 'file-id')],
2750
            basis= [('file', 'file-id')],
2751
            delta=[(None, 'file', 'file-id')])
2752
5847.4.27 by John Arbash Meinel
Handle missing parent, though bugs may still remain
2753
    def test_invalid_parent_missing(self):
2754
        state = self.assertBadDelta(
2755
            active=[],
2756
            basis= [],
2757
            delta=[(None, 'path/path2', 'file-id')])
5847.4.28 by John Arbash Meinel
Some more direct tests. Fix some bugs in the create_entry code.
2758
        # Note: we force the active tree to have the directory, by knowing how
2759
        #       path_to_ie handles entries with missing parents
2760
        state = self.assertBadDelta(
2761
            active=[('path/', 'path-id')],
5847.4.33 by John Arbash Meinel
Clean up the _update_basis_apply_changes code
2762
            basis= [],
5847.4.28 by John Arbash Meinel
Some more direct tests. Fix some bugs in the create_entry code.
2763
            delta=[(None, 'path/path2', 'file-id')])
2764
        state = self.assertBadDelta(
2765
            active=[('path/', 'path-id'),
2766
                    ('path/path2', 'file-id')],
5847.4.33 by John Arbash Meinel
Clean up the _update_basis_apply_changes code
2767
            basis= [],
5847.4.28 by John Arbash Meinel
Some more direct tests. Fix some bugs in the create_entry code.
2768
            delta=[(None, 'path/path2', 'file-id')])
2769
5847.4.36 by John Arbash Meinel
test cases for stuff like a parent becoming its own parent,
2770
    def test_renamed_dir_same_path(self):
2771
        # We replace the parent directory, with another parent dir. But the C
2772
        # file doesn't look like it has been moved.
2773
        state = self.assertUpdate(# Same as basis
5847.4.38 by John Arbash Meinel
Removing the 'fast-path' for paths that look unchanged fixes the bug.
2774
            active=[('dir/', 'A-id'),
2775
                    ('dir/B', 'B-id')],
2776
            basis= [('dir/', 'A-id'),
2777
                    ('dir/B', 'B-id')],
2778
            target=[('dir/', 'C-id'),
2779
                    ('dir/B', 'B-id')])
2780
        state = self.assertUpdate(# Same as target
2781
            active=[('dir/', 'C-id'),
2782
                    ('dir/B', 'B-id')],
2783
            basis= [('dir/', 'A-id'),
2784
                    ('dir/B', 'B-id')],
2785
            target=[('dir/', 'C-id'),
2786
                    ('dir/B', 'B-id')])
2787
        state = self.assertUpdate(# empty active
2788
            active=[],
2789
            basis= [('dir/', 'A-id'),
2790
                    ('dir/B', 'B-id')],
2791
            target=[('dir/', 'C-id'),
2792
                    ('dir/B', 'B-id')])
2793
        state = self.assertUpdate(# different active
2794
            active=[('dir/', 'D-id'),
2795
                    ('dir/B', 'B-id')],
2796
            basis= [('dir/', 'A-id'),
2797
                    ('dir/B', 'B-id')],
2798
            target=[('dir/', 'C-id'),
2799
                    ('dir/B', 'B-id')])
5847.4.36 by John Arbash Meinel
test cases for stuff like a parent becoming its own parent,
2800
2801
    def test_parent_child_swap(self):
2802
        state = self.assertUpdate(# Same as basis
2803
            active=[('A/', 'A-id'),
2804
                    ('A/B/', 'B-id'),
2805
                    ('A/B/C', 'C-id')],
2806
            basis= [('A/', 'A-id'),
2807
                    ('A/B/', 'B-id'),
2808
                    ('A/B/C', 'C-id')],
2809
            target=[('A/', 'B-id'),
2810
                    ('A/B/', 'A-id'),
2811
                    ('A/B/C', 'C-id')])
2812
        state = self.assertUpdate(# Same as target
2813
            active=[('A/', 'B-id'),
2814
                    ('A/B/', 'A-id'),
2815
                    ('A/B/C', 'C-id')],
2816
            basis= [('A/', 'A-id'),
2817
                    ('A/B/', 'B-id'),
2818
                    ('A/B/C', 'C-id')],
2819
            target=[('A/', 'B-id'),
2820
                    ('A/B/', 'A-id'),
2821
                    ('A/B/C', 'C-id')])
2822
        state = self.assertUpdate(# empty active
2823
            active=[],
2824
            basis= [('A/', 'A-id'),
2825
                    ('A/B/', 'B-id'),
2826
                    ('A/B/C', 'C-id')],
2827
            target=[('A/', 'B-id'),
2828
                    ('A/B/', 'A-id'),
2829
                    ('A/B/C', 'C-id')])
2830
        state = self.assertUpdate(# different active
2831
            active=[('D/', 'A-id'),
2832
                    ('D/E/', 'B-id'),
2833
                    ('F', 'C-id')],
2834
            basis= [('A/', 'A-id'),
2835
                    ('A/B/', 'B-id'),
2836
                    ('A/B/C', 'C-id')],
2837
            target=[('A/', 'B-id'),
2838
                    ('A/B/', 'A-id'),
2839
                    ('A/B/C', 'C-id')])
2840
5847.4.32 by John Arbash Meinel
Update the test suite to handle root changes.
2841
    def test_change_root_id(self):
2842
        state = self.assertUpdate( # same as basis
2843
            active=[('', 'root-id'),
2844
                    ('file', 'file-id')],
2845
            basis= [('', 'root-id'),
2846
                    ('file', 'file-id')],
2847
            target=[('', 'target-root-id'),
2848
                    ('file', 'file-id')])
2849
        state = self.assertUpdate( # same as target
2850
            active=[('', 'target-root-id'),
2851
                    ('file', 'file-id')],
2852
            basis= [('', 'root-id'),
2853
                    ('file', 'file-id')],
2854
            target=[('', 'target-root-id'),
2855
                    ('file', 'root-id')])
2856
        state = self.assertUpdate( # all different
2857
            active=[('', 'active-root-id'),
2858
                    ('file', 'file-id')],
2859
            basis= [('', 'root-id'),
2860
                    ('file', 'file-id')],
2861
            target=[('', 'target-root-id'),
2862
                    ('file', 'root-id')])
5847.4.33 by John Arbash Meinel
Clean up the _update_basis_apply_changes code
2863
2864
    def test_change_file_absent_in_active(self):
2865
        state = self.assertUpdate(
2866
            active=[],
2867
            basis= [('file', 'file-id')],
2868
            target=[('file', 'file-id')])
2869
2870
    def test_invalid_changed_file(self):
2871
        state = self.assertBadDelta( # Not present in basis
2872
            active=[('file', 'file-id')],
2873
            basis= [],
2874
            delta=[('file', 'file', 'file-id')])
2875
        state = self.assertBadDelta( # present at another location in basis
2876
            active=[('file', 'file-id')],
2877
            basis= [('other-file', 'file-id')],
2878
            delta=[('file', 'file', 'file-id')])