/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
2255.2.27 by John Arbash Meinel
Fix a copyright statement to let 'source' tests pass
1
# Copyright (C) 2006, 2007 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
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
17
"""Tests of the dirstate functionality being built for WorkingTreeFormat4."""
18
2255.8.2 by John Arbash Meinel
Add a helper function, which allows us to store keys as plain paths,
19
import bisect
1852.13.20 by Robert Collins
Steps toward an object model.
20
import os
2255.10.7 by John Arbash Meinel
Some updates to how we handle the executable bit. In preparation for supporting Win32
21
import time
1852.13.20 by Robert Collins
Steps toward an object model.
22
2255.2.125 by John Arbash Meinel
Initial effort at adding a basic _bisect function to DirState.
23
from bzrlib import (
24
    dirstate,
25
    errors,
26
    osutils,
27
    )
2255.2.4 by Robert Collins
Snapshot dirstate development
28
from bzrlib.memorytree import MemoryTree
2321.3.3 by Alexander Belchenko
test_dirstate: skip tests with symlinks on platforms that don't have symlinks support
29
from bzrlib.tests import (
2949.5.1 by Alexander Belchenko
selftest: use SymlinkFeature instead of TestSkipped where appropriate
30
        SymlinkFeature,
2321.3.3 by Alexander Belchenko
test_dirstate: skip tests with symlinks on platforms that don't have symlinks support
31
        TestCase,
32
        TestCaseWithTransport,
33
        )
1852.13.6 by Robert Collins
start hooking in the prototype dirstate serialiser.
34
35
36
# TODO:
2255.2.4 by Robert Collins
Snapshot dirstate development
37
# 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.
38
# general checks for NOT_IN_MEMORY error conditions.
39
# set_path_id on a NOT_IN_MEMORY dirstate
2255.2.4 by Robert Collins
Snapshot dirstate development
40
# set_path_id  unicode support
41
# set_path_id  setting id of a path not root
42
# set_path_id  setting id when there are parents without the id in the parents
43
# set_path_id  setting id when there are parents with the id in the parents
44
# set_path_id  setting id when state is not in memory
45
# set_path_id  setting id when state is in memory unmodified
46
# set_path_id  setting id when state is in memory modified
1852.13.6 by Robert Collins
start hooking in the prototype dirstate serialiser.
47
2255.2.236 by Martin Pool
Review cleanups: mostly updating or removing todo comments.
48
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
49
class TestCaseWithDirState(TestCaseWithTransport):
50
    """Helper functions for creating DirState objects with various content."""
51
52
    def create_empty_dirstate(self):
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
53
        """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.
54
        state = dirstate.DirState.initialize('dirstate')
55
        return state
56
57
    def create_dirstate_with_root(self):
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
58
        """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.
59
        packed_stat = 'AAAAREUHaIpFB2iKAAADAQAtkqUAAIGk'
60
        root_entry_direntry = ('', '', 'a-root-value'), [
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
61
            ('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.
62
            ]
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
63
        dirblocks = []
64
        dirblocks.append(('', [root_entry_direntry]))
65
        dirblocks.append(('', []))
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
66
        state = self.create_empty_dirstate()
67
        try:
68
            state._set_data([], dirblocks)
2255.7.78 by Martin Pool
Add DirState._validate and call from the tests
69
            state._validate()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
70
        except:
71
            state.unlock()
72
            raise
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
73
        return state
74
75
    def create_dirstate_with_root_and_subdir(self):
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
76
        """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.
77
        packed_stat = 'AAAAREUHaIpFB2iKAAADAQAtkqUAAIGk'
78
        subdir_entry = ('', 'subdir', 'subdir-id'), [
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.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
81
        state = self.create_dirstate_with_root()
82
        try:
83
            dirblocks = list(state._dirblocks)
84
            dirblocks[1][1].append(subdir_entry)
85
            state._set_data([], dirblocks)
86
        except:
87
            state.unlock()
88
            raise
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
89
        return state
90
91
    def create_complex_dirstate(self):
92
        """This dirstate contains multiple files and directories.
93
94
         /        a-root-value
95
         a/       a-dir
96
         b/       b-dir
97
         c        c-file
98
         d        d-file
99
         a/e/     e-dir
100
         a/f      f-file
101
         b/g      g-file
102
         b/h\xc3\xa5  h-\xc3\xa5-file  #This is u'\xe5' encoded into utf-8
103
2323.5.4 by Martin Pool
Move some dirstate test setup methods into the base class
104
        Notice that a/e is an empty directory.
105
106
        :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.
107
        """
108
        packed_stat = 'AAAAREUHaIpFB2iKAAADAQAtkqUAAIGk'
109
        null_sha = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
110
        root_entry = ('', '', 'a-root-value'), [
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
111
            ('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.
112
            ]
113
        a_entry = ('', 'a', 'a-dir'), [
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
114
            ('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.
115
            ]
116
        b_entry = ('', 'b', 'b-dir'), [
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
117
            ('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.
118
            ]
119
        c_entry = ('', 'c', 'c-file'), [
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
120
            ('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.
121
            ]
122
        d_entry = ('', 'd', 'd-file'), [
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
123
            ('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.
124
            ]
125
        e_entry = ('a', 'e', 'e-dir'), [
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
126
            ('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.
127
            ]
128
        f_entry = ('a', 'f', 'f-file'), [
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
129
            ('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.
130
            ]
131
        g_entry = ('b', 'g', 'g-file'), [
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
132
            ('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.
133
            ]
134
        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
135
            ('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.
136
            ]
137
        dirblocks = []
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
138
        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.
139
        dirblocks.append(('', [a_entry, b_entry, c_entry, d_entry]))
140
        dirblocks.append(('a', [e_entry, f_entry]))
141
        dirblocks.append(('b', [g_entry, h_entry]))
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
142
        state = dirstate.DirState.initialize('dirstate')
2255.7.78 by Martin Pool
Add DirState._validate and call from the tests
143
        state._validate()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
144
        try:
145
            state._set_data([], dirblocks)
146
        except:
147
            state.unlock()
148
            raise
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
149
        return state
150
151
    def check_state_with_reopen(self, expected_result, state):
152
        """Check that state has current state expected_result.
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
153
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
154
        This will check the current state, open the file anew and check it
155
        again.
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
156
        This function expects the current state to be locked for writing, and
157
        will unlock it before re-opening.
158
        This is required because we can't open a lock_read() while something
159
        else has a lock_write().
160
            write => mutually exclusive lock
161
            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.
162
        """
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
163
        # The state should already be write locked, since we just had to do
164
        # some operation to get here.
165
        assert state._lock_token is not None
166
        try:
167
            self.assertEqual(expected_result[0],  state.get_parent_ids())
168
            # there should be no ghosts in this tree.
169
            self.assertEqual([], state.get_ghosts())
170
            # there should be one fileid in this tree - the root of the tree.
171
            self.assertEqual(expected_result[1], list(state._iter_entries()))
172
            state.save()
173
        finally:
174
            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.
175
        del state
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
176
        state = dirstate.DirState.on_file('dirstate')
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
177
        state.lock_read()
178
        try:
179
            self.assertEqual(expected_result[1], list(state._iter_entries()))
180
        finally:
181
            state.unlock()
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
182
2323.5.4 by Martin Pool
Move some dirstate test setup methods into the base class
183
    def create_basic_dirstate(self):
184
        """Create a dirstate with a few files and directories.
185
186
            a
187
            b/
188
              c
189
              d/
190
                e
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
191
            b-c
2323.5.4 by Martin Pool
Move some dirstate test setup methods into the base class
192
            f
193
        """
194
        tree = self.make_branch_and_tree('tree')
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
195
        paths = ['a', 'b/', 'b/c', 'b/d/', 'b/d/e', 'b-c', 'f']
196
        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
197
        self.build_tree(['tree/' + p for p in paths])
198
        tree.set_root_id('TREE_ROOT')
199
        tree.add([p.rstrip('/') for p in paths], file_ids)
200
        tree.commit('initial', rev_id='rev-1')
201
        revision_id = 'rev-1'
202
        # 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.
203
        t = self.get_transport('tree')
2323.5.4 by Martin Pool
Move some dirstate test setup methods into the base class
204
        a_text = t.get_bytes('a')
205
        a_sha = osutils.sha_string(a_text)
206
        a_len = len(a_text)
207
        # b_packed_stat = dirstate.pack_stat(os.stat('tree/b'))
208
        # c_packed_stat = dirstate.pack_stat(os.stat('tree/b/c'))
209
        c_text = t.get_bytes('b/c')
210
        c_sha = osutils.sha_string(c_text)
211
        c_len = len(c_text)
212
        # d_packed_stat = dirstate.pack_stat(os.stat('tree/b/d'))
213
        # e_packed_stat = dirstate.pack_stat(os.stat('tree/b/d/e'))
214
        e_text = t.get_bytes('b/d/e')
215
        e_sha = osutils.sha_string(e_text)
216
        e_len = len(e_text)
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
217
        b_c_text = t.get_bytes('b-c')
218
        b_c_sha = osutils.sha_string(b_c_text)
219
        b_c_len = len(b_c_text)
2323.5.4 by Martin Pool
Move some dirstate test setup methods into the base class
220
        # f_packed_stat = dirstate.pack_stat(os.stat('tree/f'))
221
        f_text = t.get_bytes('f')
222
        f_sha = osutils.sha_string(f_text)
223
        f_len = len(f_text)
224
        null_stat = dirstate.DirState.NULLSTAT
225
        expected = {
226
            '':(('', '', 'TREE_ROOT'), [
227
                  ('d', '', 0, False, null_stat),
228
                  ('d', '', 0, False, revision_id),
229
                ]),
230
            'a':(('', 'a', 'a-id'), [
231
                   ('f', '', 0, False, null_stat),
232
                   ('f', a_sha, a_len, False, revision_id),
233
                 ]),
234
            'b':(('', 'b', 'b-id'), [
235
                  ('d', '', 0, False, null_stat),
236
                  ('d', '', 0, False, revision_id),
237
                 ]),
238
            'b/c':(('b', 'c', 'c-id'), [
239
                    ('f', '', 0, False, null_stat),
240
                    ('f', c_sha, c_len, False, revision_id),
241
                   ]),
242
            'b/d':(('b', 'd', 'd-id'), [
243
                    ('d', '', 0, False, null_stat),
244
                    ('d', '', 0, False, revision_id),
245
                   ]),
246
            'b/d/e':(('b/d', 'e', 'e-id'), [
247
                      ('f', '', 0, False, null_stat),
248
                      ('f', e_sha, e_len, False, revision_id),
249
                     ]),
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
250
            'b-c':(('', 'b-c', 'b-c-id'), [
251
                      ('f', '', 0, False, null_stat),
252
                      ('f', b_c_sha, b_c_len, False, revision_id),
253
                     ]),
2323.5.4 by Martin Pool
Move some dirstate test setup methods into the base class
254
            'f':(('', 'f', 'f-id'), [
255
                  ('f', '', 0, False, null_stat),
256
                  ('f', f_sha, f_len, False, revision_id),
257
                 ]),
258
        }
259
        state = dirstate.DirState.from_tree(tree, 'dirstate')
260
        try:
261
            state.save()
262
        finally:
263
            state.unlock()
264
        # Use a different object, to make sure nothing is pre-cached in memory.
265
        state = dirstate.DirState.on_file('dirstate')
266
        state.lock_read()
267
        self.addCleanup(state.unlock)
268
        self.assertEqual(dirstate.DirState.NOT_IN_MEMORY,
269
                         state._dirblock_state)
270
        # This is code is only really tested if we actually have to make more
271
        # than one read, so set the page size to something smaller.
272
        # We want it to contain about 2.2 records, so that we have a couple
273
        # records that we can read per attempt
274
        state._bisect_page_size = 200
275
        return tree, state, expected
276
277
    def create_duplicated_dirstate(self):
278
        """Create a dirstate with a deleted and added entries.
279
280
        This grabs a basic_dirstate, and then removes and re adds every entry
281
        with a new file id.
282
        """
283
        tree, state, expected = self.create_basic_dirstate()
284
        # Now we will just remove and add every file so we get an extra entry
285
        # per entry. Unversion in reverse order so we handle subdirs
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
286
        tree.unversion(['f-id', 'b-c-id', 'e-id', 'd-id', 'c-id', 'b-id', 'a-id'])
287
        tree.add(['a', 'b', 'b/c', 'b/d', 'b/d/e', 'b-c', 'f'],
288
                 ['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
289
290
        # Update the expected dictionary.
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
291
        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
292
            orig = expected[path]
293
            path2 = path + '2'
294
            # This record was deleted in the current tree
295
            expected[path] = (orig[0], [dirstate.DirState.NULL_PARENT_DETAILS,
296
                                        orig[1][1]])
297
            new_key = (orig[0][0], orig[0][1], orig[0][2]+'2')
298
            # And didn't exist in the basis tree
299
            expected[path2] = (new_key, [orig[1][0],
300
                                         dirstate.DirState.NULL_PARENT_DETAILS])
301
302
        # We will replace the 'dirstate' file underneath 'state', but that is
303
        # okay as lock as we unlock 'state' first.
304
        state.unlock()
305
        try:
306
            new_state = dirstate.DirState.from_tree(tree, 'dirstate')
307
            try:
308
                new_state.save()
309
            finally:
310
                new_state.unlock()
311
        finally:
312
            # But we need to leave state in a read-lock because we already have
313
            # a cleanup scheduled
314
            state.lock_read()
315
        return tree, state, expected
316
317
    def create_renamed_dirstate(self):
318
        """Create a dirstate with a few internal renames.
319
320
        This takes the basic dirstate, and moves the paths around.
321
        """
322
        tree, state, expected = self.create_basic_dirstate()
323
        # Rename a file
324
        tree.rename_one('a', 'b/g')
325
        # And a directory
326
        tree.rename_one('b/d', 'h')
327
328
        old_a = expected['a']
329
        expected['a'] = (old_a[0], [('r', 'b/g', 0, False, ''), old_a[1][1]])
330
        expected['b/g'] = (('b', 'g', 'a-id'), [old_a[1][0],
331
                                                ('r', 'a', 0, False, '')])
332
        old_d = expected['b/d']
333
        expected['b/d'] = (old_d[0], [('r', 'h', 0, False, ''), old_d[1][1]])
334
        expected['h'] = (('', 'h', 'd-id'), [old_d[1][0],
335
                                             ('r', 'b/d', 0, False, '')])
336
337
        old_e = expected['b/d/e']
338
        expected['b/d/e'] = (old_e[0], [('r', 'h/e', 0, False, ''),
339
                             old_e[1][1]])
340
        expected['h/e'] = (('h', 'e', 'e-id'), [old_e[1][0],
341
                                                ('r', 'b/d/e', 0, False, '')])
342
343
        state.unlock()
344
        try:
345
            new_state = dirstate.DirState.from_tree(tree, 'dirstate')
346
            try:
347
                new_state.save()
348
            finally:
349
                new_state.unlock()
350
        finally:
351
            state.lock_read()
352
        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.
353
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
354
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
355
class TestTreeToDirState(TestCaseWithDirState):
1852.13.6 by Robert Collins
start hooking in the prototype dirstate serialiser.
356
357
    def test_empty_to_dirstate(self):
358
        """We should be able to create a dirstate for an empty tree."""
359
        # There are no files on disk and no parents
360
        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.
361
        expected_result = ([], [
2946.3.3 by John Arbash Meinel
Prefer tree.get_root_id() as more explicit than tree.path2id('')
362
            (('', '', tree.get_root_id()), # common details
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
363
             [('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.
364
             ])])
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
365
        state = dirstate.DirState.from_tree(tree, 'dirstate')
2255.7.78 by Martin Pool
Add DirState._validate and call from the tests
366
        state._validate()
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
367
        self.check_state_with_reopen(expected_result, state)
1852.13.6 by Robert Collins
start hooking in the prototype dirstate serialiser.
368
369
    def test_1_parents_empty_to_dirstate(self):
370
        # create a parent by doing a commit
371
        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.
372
        rev_id = tree.commit('first post').encode('utf8')
373
        root_stat_pack = dirstate.pack_stat(os.stat(tree.basedir))
374
        expected_result = ([rev_id], [
2946.3.3 by John Arbash Meinel
Prefer tree.get_root_id() as more explicit than tree.path2id('')
375
            (('', '', tree.get_root_id()), # common details
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
376
             [('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
377
              ('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.
378
             ])])
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
379
        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.
380
        self.check_state_with_reopen(expected_result, state)
2323.6.13 by Martin Pool
Fix some tests that need to lock dirstate before validating
381
        state.lock_read()
382
        try:
383
            state._validate()
384
        finally:
385
            state.unlock()
1852.13.6 by Robert Collins
start hooking in the prototype dirstate serialiser.
386
387
    def test_2_parents_empty_to_dirstate(self):
388
        # create a parent by doing a commit
389
        tree = self.make_branch_and_tree('tree')
390
        rev_id = tree.commit('first post')
391
        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.
392
        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.
393
        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.
394
        expected_result = ([rev_id, rev_id2], [
2946.3.3 by John Arbash Meinel
Prefer tree.get_root_id() as more explicit than tree.path2id('')
395
            (('', '', tree.get_root_id()), # common details
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
396
             [('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
397
              ('d', '', 0, False, rev_id), # first parent details
398
              ('d', '', 0, False, rev_id2), # 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.
399
             ])])
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
400
        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.
401
        self.check_state_with_reopen(expected_result, state)
2323.6.13 by Martin Pool
Fix some tests that need to lock dirstate before validating
402
        state.lock_read()
403
        try:
404
            state._validate()
405
        finally:
406
            state.unlock()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
407
1852.13.6 by Robert Collins
start hooking in the prototype dirstate serialiser.
408
    def test_empty_unknowns_are_ignored_to_dirstate(self):
409
        """We should be able to create a dirstate for an empty tree."""
410
        # There are no files on disk and no parents
411
        tree = self.make_branch_and_tree('tree')
1852.13.10 by Robert Collins
Use just the tree api to generate dirstate information.
412
        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.
413
        expected_result = ([], [
2946.3.3 by John Arbash Meinel
Prefer tree.get_root_id() as more explicit than tree.path2id('')
414
            (('', '', tree.get_root_id()), # common details
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
415
             [('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.
416
             ])])
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
417
        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.
418
        self.check_state_with_reopen(expected_result, state)
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
419
1852.13.12 by Robert Collins
get actual parent info for the first parent.
420
    def get_tree_with_a_file(self):
421
        tree = self.make_branch_and_tree('tree')
422
        self.build_tree(['tree/a file'])
3010.1.2 by Robert Collins
Use valid file-ids for dirstate tests.
423
        tree.add('a file', 'a-file-id')
1852.13.12 by Robert Collins
get actual parent info for the first parent.
424
        return tree
425
1852.13.6 by Robert Collins
start hooking in the prototype dirstate serialiser.
426
    def test_non_empty_no_parents_to_dirstate(self):
427
        """We should be able to create a dirstate for an empty tree."""
1852.13.11 by Robert Collins
Get one content containing test passing.
428
        # There are files on disk and no parents
1852.13.12 by Robert Collins
get actual parent info for the first parent.
429
        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.
430
        expected_result = ([], [
2946.3.3 by John Arbash Meinel
Prefer tree.get_root_id() as more explicit than tree.path2id('')
431
            (('', '', tree.get_root_id()), # common details
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
432
             [('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.
433
             ]),
3010.1.2 by Robert Collins
Use valid file-ids for dirstate tests.
434
            (('', 'a file', 'a-file-id'), # common
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
435
             [('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.
436
             ]),
437
            ])
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
438
        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.
439
        self.check_state_with_reopen(expected_result, state)
1852.13.6 by Robert Collins
start hooking in the prototype dirstate serialiser.
440
441
    def test_1_parents_not_empty_to_dirstate(self):
442
        # create a parent by doing a commit
1852.13.12 by Robert Collins
get actual parent info for the first parent.
443
        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.
444
        rev_id = tree.commit('first post').encode('utf8')
1852.13.12 by Robert Collins
get actual parent info for the first parent.
445
        # change the current content to be different this will alter stat, sha
446
        # and length:
447
        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.
448
        expected_result = ([rev_id], [
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.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
451
              ('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.
452
             ]),
3010.1.2 by Robert Collins
Use valid file-ids for dirstate tests.
453
            (('', 'a file', 'a-file-id'), # common
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
454
             [('f', '', 0, False, dirstate.DirState.NULLSTAT), # current
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
455
              ('f', 'c3ed76e4bfd45ff1763ca206055bca8e9fc28aa8', 24, False,
456
               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.
457
             ]),
458
            ])
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
459
        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.
460
        self.check_state_with_reopen(expected_result, state)
1852.13.6 by Robert Collins
start hooking in the prototype dirstate serialiser.
461
462
    def test_2_parents_not_empty_to_dirstate(self):
463
        # create a parent by doing a commit
1852.13.13 by Robert Collins
2-parent case working.
464
        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.
465
        rev_id = tree.commit('first post').encode('utf8')
1852.13.6 by Robert Collins
start hooking in the prototype dirstate serialiser.
466
        tree2 = tree.bzrdir.sprout('tree2').open_workingtree()
1852.13.13 by Robert Collins
2-parent case working.
467
        # change the current content to be different this will alter stat, sha
468
        # and length:
469
        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.
470
        rev_id2 = tree2.commit('second post').encode('utf8')
1852.13.19 by Robert Collins
Get DirState objects roundtripping an add of a ghost tree.
471
        tree.merge_from_branch(tree2.branch)
1852.13.13 by Robert Collins
2-parent case working.
472
        # change the current content to be different this will alter stat, sha
473
        # and length again, giving us three distinct values:
474
        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.
475
        expected_result = ([rev_id, rev_id2], [
2946.3.3 by John Arbash Meinel
Prefer tree.get_root_id() as more explicit than tree.path2id('')
476
            (('', '', tree.get_root_id()), # common details
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
477
             [('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
478
              ('d', '', 0, False, rev_id), # first parent details
479
              ('d', '', 0, False, rev_id2), # 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.
480
             ]),
3010.1.2 by Robert Collins
Use valid file-ids for dirstate tests.
481
            (('', 'a file', 'a-file-id'), # common
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
482
             [('f', '', 0, False, dirstate.DirState.NULLSTAT), # current
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
483
              ('f', 'c3ed76e4bfd45ff1763ca206055bca8e9fc28aa8', 24, False,
484
               rev_id), # first parent
485
              ('f', '314d796174c9412647c3ce07dfb5d36a94e72958', 14, False,
486
               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.
487
             ]),
488
            ])
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
489
        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.
490
        self.check_state_with_reopen(expected_result, state)
491
2255.7.94 by Martin Pool
Fix dirstate sorting bug and refine the _validate() assertions:
492
    def test_colliding_fileids(self):
493
        # test insertion of parents creating several entries at the same path.
494
        # we used to have a bug where they could cause the dirstate to break
495
        # its ordering invariants.
496
        # create some trees to test from
497
        parents = []
498
        for i in range(7):
499
            tree = self.make_branch_and_tree('tree%d' % i)
500
            self.build_tree(['tree%d/name' % i,])
501
            tree.add(['name'], ['file-id%d' % i])
502
            revision_id = 'revid-%d' % i
503
            tree.commit('message', rev_id=revision_id)
504
            parents.append((revision_id,
505
                tree.branch.repository.revision_tree(revision_id)))
506
        # now fold these trees into a dirstate
507
        state = dirstate.DirState.initialize('dirstate')
508
        try:
509
            state.set_parent_trees(parents, [])
510
            state._validate()
511
        finally:
512
            state.unlock()
513
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
514
515
class TestDirStateOnFile(TestCaseWithDirState):
1852.13.15 by Robert Collins
Ensure Format4 working trees start with a dirstate.
516
517
    def test_construct_with_path(self):
518
        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.
519
        state = dirstate.DirState.from_tree(tree, 'dirstate.from_tree')
1852.13.15 by Robert Collins
Ensure Format4 working trees start with a dirstate.
520
        # we want to be able to get the lines of the dirstate that we will
521
        # write to disk.
522
        lines = state.get_lines()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
523
        state.unlock()
1852.13.15 by Robert Collins
Ensure Format4 working trees start with a dirstate.
524
        self.build_tree_contents([('dirstate', ''.join(lines))])
525
        # 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.
526
        # no parents, default tree content
527
        expected_result = ([], [
2946.3.3 by John Arbash Meinel
Prefer tree.get_root_id() as more explicit than tree.path2id('')
528
            (('', '', tree.get_root_id()), # common details
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
529
             # current tree details, but new from_tree skips statting, it
530
             # uses set_state_from_inventory, and thus depends on the
531
             # inventory state.
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
532
             [('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.
533
             ])
534
            ])
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
535
        state = dirstate.DirState.on_file('dirstate')
536
        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.
537
        self.check_state_with_reopen(expected_result, state)
538
539
    def test_can_save_clean_on_file(self):
540
        tree = self.make_branch_and_tree('tree')
541
        state = dirstate.DirState.from_tree(tree, 'dirstate')
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
542
        try:
543
            # doing a save should work here as there have been no changes.
544
            state.save()
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
545
            # TODO: stat it and check it hasn't changed; may require waiting
546
            # for the state accuracy window.
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
547
        finally:
548
            state.unlock()
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
549
2353.4.5 by John Arbash Meinel
Update DirState to use the new 'temporary_write_lock', and add tests that it works.
550
    def test_can_save_in_read_lock(self):
551
        self.build_tree(['a-file'])
552
        state = dirstate.DirState.initialize('dirstate')
553
        try:
554
            # No stat and no sha1 sum.
555
            state.add('a-file', 'a-file-id', 'file', None, '')
556
            state.save()
557
        finally:
558
            state.unlock()
559
560
        # Now open in readonly mode
561
        state = dirstate.DirState.on_file('dirstate')
562
        state.lock_read()
563
        try:
564
            entry = state._get_entry(0, path_utf8='a-file')
565
            # The current sha1 sum should be empty
566
            self.assertEqual('', entry[1][0][1])
567
            # We should have a real entry.
568
            self.assertNotEqual((None, None), entry)
2485.3.14 by John Arbash Meinel
Update the code so that symlinks aren't cached at incorrect times
569
            # Make sure everything is old enough
570
            state._sha_cutoff_time()
571
            state._cutoff_time += 10
2353.4.5 by John Arbash Meinel
Update DirState to use the new 'temporary_write_lock', and add tests that it works.
572
            sha1sum = state.update_entry(entry, 'a-file', os.lstat('a-file'))
573
            # We should have gotten a real sha1
574
            self.assertEqual('ecc5374e9ed82ad3ea3b4d452ea995a5fd3e70e3',
575
                             sha1sum)
576
577
            # The dirblock has been updated
578
            self.assertEqual(sha1sum, entry[1][0][1])
579
            self.assertEqual(dirstate.DirState.IN_MEMORY_MODIFIED,
580
                             state._dirblock_state)
581
582
            del entry
583
            # Now, since we are the only one holding a lock, we should be able
584
            # to save and have it written to disk
585
            state.save()
586
        finally:
587
            state.unlock()
588
589
        # Re-open the file, and ensure that the state has been updated.
590
        state = dirstate.DirState.on_file('dirstate')
591
        state.lock_read()
592
        try:
593
            entry = state._get_entry(0, path_utf8='a-file')
594
            self.assertEqual(sha1sum, entry[1][0][1])
595
        finally:
596
            state.unlock()
597
598
    def test_save_fails_quietly_if_locked(self):
599
        """If dirstate is locked, save will fail without complaining."""
600
        self.build_tree(['a-file'])
601
        state = dirstate.DirState.initialize('dirstate')
602
        try:
603
            # No stat and no sha1 sum.
604
            state.add('a-file', 'a-file-id', 'file', None, '')
605
            state.save()
606
        finally:
607
            state.unlock()
608
609
        state = dirstate.DirState.on_file('dirstate')
610
        state.lock_read()
611
        try:
612
            entry = state._get_entry(0, path_utf8='a-file')
613
            sha1sum = state.update_entry(entry, 'a-file', os.lstat('a-file'))
614
            # We should have gotten a real sha1
615
            self.assertEqual('ecc5374e9ed82ad3ea3b4d452ea995a5fd3e70e3',
616
                             sha1sum)
617
            self.assertEqual(dirstate.DirState.IN_MEMORY_MODIFIED,
618
                             state._dirblock_state)
619
620
            # Now, before we try to save, grab another dirstate, and take out a
621
            # read lock.
622
            # TODO: jam 20070315 Ideally this would be locked by another
623
            #       process. To make sure the file is really OS locked.
624
            state2 = dirstate.DirState.on_file('dirstate')
625
            state2.lock_read()
626
            try:
627
                # This won't actually write anything, because it couldn't grab
628
                # a write lock. But it shouldn't raise an error, either.
629
                # TODO: jam 20070315 We should probably distinguish between
630
                #       being dirty because of 'update_entry'. And dirty
631
                #       because of real modification. So that save() *does*
632
                #       raise a real error if it fails when we have real
633
                #       modifications.
634
                state.save()
635
            finally:
636
                state2.unlock()
637
        finally:
638
            state.unlock()
639
        
640
        # The file on disk should not be modified.
641
        state = dirstate.DirState.on_file('dirstate')
642
        state.lock_read()
643
        try:
644
            entry = state._get_entry(0, path_utf8='a-file')
645
            self.assertEqual('', entry[1][0][1])
646
        finally:
647
            state.unlock()
648
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
649
650
class TestDirStateInitialize(TestCaseWithDirState):
1852.13.15 by Robert Collins
Ensure Format4 working trees start with a dirstate.
651
652
    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.
653
        expected_result = ([], [
654
            (('', '', 'TREE_ROOT'), # common details
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
655
             [('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.
656
             ])
657
            ])
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
658
        state = dirstate.DirState.initialize('dirstate')
659
        try:
660
            self.assertIsInstance(state, dirstate.DirState)
661
            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.
662
        finally:
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
663
            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.
664
        # On win32 you can't read from a locked file, even within the same
665
        # process. So we have to unlock and release before we check the file
666
        # contents.
667
        self.assertFileEqual(''.join(lines), 'dirstate')
668
        state.lock_read() # check_state_with_reopen will unlock
669
        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.
670
671
672
class TestDirStateManipulations(TestCaseWithDirState):
1852.13.19 by Robert Collins
Get DirState objects roundtripping an add of a ghost tree.
673
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.
674
    def test_set_state_from_inventory_no_content_no_parents(self):
675
        # setting the current inventory is a slow but important api to support.
676
        tree1 = self.make_branch_and_memory_tree('tree1')
677
        tree1.lock_write()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
678
        try:
679
            tree1.add('')
680
            revid1 = tree1.commit('foo').encode('utf8')
2946.3.3 by John Arbash Meinel
Prefer tree.get_root_id() as more explicit than tree.path2id('')
681
            root_id = tree1.get_root_id()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
682
            inv = tree1.inventory
683
        finally:
684
            tree1.unlock()
2255.2.87 by Robert Collins
core dirstate tests passing with new structure.
685
        expected_result = [], [
686
            (('', '', root_id), [
2255.2.124 by John Arbash Meinel
Remove direct access to Dirstate prefering dirstate.Dirstate
687
             ('d', '', 0, False, dirstate.DirState.NULLSTAT)])]
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
688
        state = dirstate.DirState.initialize('dirstate')
689
        try:
690
            state.set_state_from_inventory(inv)
2255.2.124 by John Arbash Meinel
Remove direct access to Dirstate prefering dirstate.Dirstate
691
            self.assertEqual(dirstate.DirState.IN_MEMORY_UNMODIFIED,
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
692
                             state._header_state)
2255.2.124 by John Arbash Meinel
Remove direct access to Dirstate prefering dirstate.Dirstate
693
            self.assertEqual(dirstate.DirState.IN_MEMORY_MODIFIED,
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
694
                             state._dirblock_state)
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
695
        except:
696
            state.unlock()
697
            raise
698
        else:
699
            # This will unlock it
700
            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.
701
2872.4.3 by Martin Pool
Fix comparison for merge sort in Dirstate.set_state_from_inventory
702
    def test_set_state_from_inventory_preserves_hashcache(self):
2872.4.11 by Martin Pool
Review documentation cleanups
703
        # https://bugs.launchpad.net/bzr/+bug/146176
2872.4.1 by Martin Pool
Add xfail test for #146176
704
        # set_state_from_inventory should preserve the stat and hash value for
705
        # workingtree files that are not changed by the inventory.
706
       
707
        tree = self.make_branch_and_tree('.')
708
        # depends on the default format using dirstate...
709
        tree.lock_write()
710
        try:
711
            # make a dirstate with some valid hashcache data 
712
            # file on disk, but that's not needed for this test
713
            foo_contents = 'contents of foo'
714
            self.build_tree_contents([('foo', foo_contents)])
715
            tree.add('foo', 'foo-id')
716
717
            foo_stat = os.stat('foo')
718
            foo_packed = dirstate.pack_stat(foo_stat)
719
            foo_sha = osutils.sha_string(foo_contents)
720
            foo_size = len(foo_contents)
721
722
            # should not be cached yet, because the file's too fresh
2872.4.8 by Martin Pool
Clear up test code
723
            self.assertEqual(
724
                (('', 'foo', 'foo-id',),
725
                 [('f', '', 0, False, dirstate.DirState.NULLSTAT)]),
726
                tree._dirstate._get_entry(0, 'foo-id'))
2872.4.1 by Martin Pool
Add xfail test for #146176
727
            # poke in some hashcache information - it wouldn't normally be
728
            # stored because it's too fresh
729
            tree._dirstate.update_minimal(
730
                ('', 'foo', 'foo-id'),
731
                'f', False, foo_sha, foo_packed, foo_size, 'foo')
732
            # now should be cached
2872.4.8 by Martin Pool
Clear up test code
733
            self.assertEqual(
734
                (('', 'foo', 'foo-id',),
735
                 [('f', foo_sha, foo_size, False, foo_packed)]),
736
                tree._dirstate._get_entry(0, 'foo-id'))
2872.4.1 by Martin Pool
Add xfail test for #146176
737
           
738
            # extract the inventory, and add something to it
739
            inv = tree._get_inventory()
2872.4.3 by Martin Pool
Fix comparison for merge sort in Dirstate.set_state_from_inventory
740
            # should see the file we poked in...
741
            self.assertTrue(inv.has_id('foo-id'))
742
            self.assertTrue(inv.has_filename('foo'))
2872.4.1 by Martin Pool
Add xfail test for #146176
743
            inv.add_path('bar', 'file', 'bar-id')
2872.4.13 by Martin Pool
Validate dirstate during tests
744
            tree._dirstate._validate()
2872.4.11 by Martin Pool
Review documentation cleanups
745
            # this used to cause it to lose its hashcache
2872.4.1 by Martin Pool
Add xfail test for #146176
746
            tree._dirstate.set_state_from_inventory(inv)
2872.4.13 by Martin Pool
Validate dirstate during tests
747
            tree._dirstate._validate()
2872.4.1 by Martin Pool
Add xfail test for #146176
748
        finally:
749
            tree.unlock()
750
751
        tree.lock_read()
752
        try:
753
            # now check that the state still has the original hashcache value
754
            state = tree._dirstate
2872.4.13 by Martin Pool
Validate dirstate during tests
755
            state._validate()
2872.4.1 by Martin Pool
Add xfail test for #146176
756
            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
757
            self.assertEqual(
2872.4.1 by Martin Pool
Add xfail test for #146176
758
                (('', 'foo', 'foo-id',),
759
                 [('f', foo_sha, len(foo_contents), False,
760
                   dirstate.pack_stat(foo_stat))]),
761
                foo_tuple)
762
        finally:
763
            tree.unlock()
764
765
2487.1.1 by John Arbash Meinel
Adding a (broken) test that set_state_from_inventory works
766
    def test_set_state_from_inventory_mixed_paths(self):
767
        tree1 = self.make_branch_and_tree('tree1')
768
        self.build_tree(['tree1/a/', 'tree1/a/b/', 'tree1/a-b/',
769
                         'tree1/a/b/foo', 'tree1/a-b/bar'])
770
        tree1.lock_write()
771
        try:
772
            tree1.add(['a', 'a/b', 'a-b', 'a/b/foo', 'a-b/bar'],
773
                      ['a-id', 'b-id', 'a-b-id', 'foo-id', 'bar-id'])
774
            tree1.commit('rev1', rev_id='rev1')
775
            root_id = tree1.get_root_id()
776
            inv = tree1.inventory
777
        finally:
778
            tree1.unlock()
779
        expected_result1 = [('', '', root_id, 'd'),
780
                            ('', 'a', 'a-id', 'd'),
781
                            ('', 'a-b', 'a-b-id', 'd'),
782
                            ('a', 'b', 'b-id', 'd'),
783
                            ('a/b', 'foo', 'foo-id', 'f'),
784
                            ('a-b', 'bar', 'bar-id', 'f'),
785
                           ]
786
        expected_result2 = [('', '', root_id, 'd'),
787
                            ('', 'a', 'a-id', 'd'),
788
                            ('', 'a-b', 'a-b-id', 'd'),
789
                            ('a-b', 'bar', 'bar-id', 'f'),
790
                           ]
791
        state = dirstate.DirState.initialize('dirstate')
792
        try:
793
            state.set_state_from_inventory(inv)
794
            values = []
795
            for entry in state._iter_entries():
796
                values.append(entry[0] + entry[1][0][:1])
797
            self.assertEqual(expected_result1, values)
798
            del inv['b-id']
799
            state.set_state_from_inventory(inv)
800
            values = []
801
            for entry in state._iter_entries():
802
                values.append(entry[0] + entry[1][0][:1])
803
            self.assertEqual(expected_result2, values)
804
        finally:
805
            state.unlock()
806
2255.2.4 by Robert Collins
Snapshot dirstate development
807
    def test_set_path_id_no_parents(self):
808
        """The id of a path can be changed trivally with no parents."""
809
        state = dirstate.DirState.initialize('dirstate')
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
810
        try:
811
            # check precondition to be sure the state does change appropriately.
812
            self.assertEqual(
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
813
                [(('', '', 'TREE_ROOT'), [('d', '', 0, False,
814
                   'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')])],
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
815
                list(state._iter_entries()))
816
            state.set_path_id('', 'foobarbaz')
817
            expected_rows = [
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
818
                (('', '', 'foobarbaz'), [('d', '', 0, False,
819
                   'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')])]
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
820
            self.assertEqual(expected_rows, list(state._iter_entries()))
821
            # should work across save too
822
            state.save()
823
        finally:
824
            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.
825
        state = dirstate.DirState.on_file('dirstate')
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
826
        state.lock_read()
827
        try:
2323.6.13 by Martin Pool
Fix some tests that need to lock dirstate before validating
828
            state._validate()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
829
            self.assertEqual(expected_rows, list(state._iter_entries()))
830
        finally:
831
            state.unlock()
2255.2.4 by Robert Collins
Snapshot dirstate development
832
2255.7.68 by Martin Pool
Add a test for setting the root id in a dirstate with parent trees
833
    def test_set_path_id_with_parents(self):
834
        """Set the root file id in a dirstate with parents"""
835
        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
836
        # in case the default tree format uses a different root id
837
        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
838
        mt.commit('foo', rev_id='parent-revid')
839
        rt = mt.branch.repository.revision_tree('parent-revid')
840
        state = dirstate.DirState.initialize('dirstate')
2255.7.78 by Martin Pool
Add DirState._validate and call from the tests
841
        state._validate()
2255.7.68 by Martin Pool
Add a test for setting the root id in a dirstate with parent trees
842
        try:
843
            state.set_parent_trees([('parent-revid', rt)], ghosts=[])
844
            state.set_path_id('', 'foobarbaz')
2255.2.177 by Martin Pool
merge dirstate sorting fix, add more validation tests
845
            state._validate()
2255.7.68 by Martin Pool
Add a test for setting the root id in a dirstate with parent trees
846
            # now see that it is what we expected
847
            expected_rows = [
848
                (('', '', 'TREE_ROOT'),
849
                    [('a', '', 0, False, ''),
850
                     ('d', '', 0, False, 'parent-revid'),
851
                     ]),
852
                (('', '', 'foobarbaz'),
853
                    [('d', '', 0, False, ''),
854
                     ('a', '', 0, False, ''),
855
                     ]),
856
                ]
2255.11.2 by Martin Pool
Add more dirstate root-id-changing tests
857
            state._validate()
2255.7.68 by Martin Pool
Add a test for setting the root id in a dirstate with parent trees
858
            self.assertEqual(expected_rows, list(state._iter_entries()))
859
            # should work across save too
860
            state.save()
861
        finally:
862
            state.unlock()
863
        # now flush & check we get the same
864
        state = dirstate.DirState.on_file('dirstate')
865
        state.lock_read()
866
        try:
2255.11.2 by Martin Pool
Add more dirstate root-id-changing tests
867
            state._validate()
2255.7.68 by Martin Pool
Add a test for setting the root id in a dirstate with parent trees
868
            self.assertEqual(expected_rows, list(state._iter_entries()))
869
        finally:
870
            state.unlock()
2255.11.2 by Martin Pool
Add more dirstate root-id-changing tests
871
        # now change within an existing file-backed state
872
        state.lock_write()
873
        try:
874
            state._validate()
875
            state.set_path_id('', 'tree-root-2')
876
            state._validate()
877
        finally:
878
            state.unlock()
879
2255.7.68 by Martin Pool
Add a test for setting the root id in a dirstate with parent trees
880
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.
881
    def test_set_parent_trees_no_content(self):
882
        # set_parent_trees is a slow but important api to support.
883
        tree1 = self.make_branch_and_memory_tree('tree1')
2255.2.2 by Robert Collins
Partial updates for API changes in trunk.
884
        tree1.lock_write()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
885
        try:
886
            tree1.add('')
887
            revid1 = tree1.commit('foo')
888
        finally:
889
            tree1.unlock()
2255.2.4 by Robert Collins
Snapshot dirstate development
890
        branch2 = tree1.branch.bzrdir.clone('tree2').open_branch()
891
        tree2 = MemoryTree.create_on_branch(branch2)
2255.2.2 by Robert Collins
Partial updates for API changes in trunk.
892
        tree2.lock_write()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
893
        try:
894
            revid2 = tree2.commit('foo')
2946.3.3 by John Arbash Meinel
Prefer tree.get_root_id() as more explicit than tree.path2id('')
895
            root_id = tree2.get_root_id()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
896
        finally:
897
            tree2.unlock()
898
        state = dirstate.DirState.initialize('dirstate')
899
        try:
900
            state.set_path_id('', root_id)
901
            state.set_parent_trees(
902
                ((revid1, tree1.branch.repository.revision_tree(revid1)),
903
                 (revid2, tree2.branch.repository.revision_tree(revid2)),
904
                 ('ghost-rev', None)),
905
                ['ghost-rev'])
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
906
            # check we can reopen and use the dirstate after setting parent
907
            # trees.
2255.7.78 by Martin Pool
Add DirState._validate and call from the tests
908
            state._validate()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
909
            state.save()
2255.7.78 by Martin Pool
Add DirState._validate and call from the tests
910
            state._validate()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
911
        finally:
912
            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.
913
        state = dirstate.DirState.on_file('dirstate')
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
914
        state.lock_write()
915
        try:
916
            self.assertEqual([revid1, revid2, 'ghost-rev'],
917
                             state.get_parent_ids())
918
            # iterating the entire state ensures that the state is parsable.
919
            list(state._iter_entries())
920
            # be sure that it sets not appends - change it
921
            state.set_parent_trees(
922
                ((revid1, tree1.branch.repository.revision_tree(revid1)),
923
                 ('ghost-rev', None)),
924
                ['ghost-rev'])
925
            # and now put it back.
926
            state.set_parent_trees(
927
                ((revid1, tree1.branch.repository.revision_tree(revid1)),
928
                 (revid2, tree2.branch.repository.revision_tree(revid2)),
929
                 ('ghost-rev', tree2.branch.repository.revision_tree(None))),
930
                ['ghost-rev'])
931
            self.assertEqual([revid1, revid2, 'ghost-rev'],
932
                             state.get_parent_ids())
933
            # the ghost should be recorded as such by set_parent_trees.
934
            self.assertEqual(['ghost-rev'], state.get_ghosts())
935
            self.assertEqual(
936
                [(('', '', root_id), [
2255.2.124 by John Arbash Meinel
Remove direct access to Dirstate prefering dirstate.Dirstate
937
                  ('d', '', 0, False, dirstate.DirState.NULLSTAT),
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
938
                  ('d', '', 0, False, revid1),
939
                  ('d', '', 0, False, revid2)
940
                  ])],
941
                list(state._iter_entries()))
942
        finally:
943
            state.unlock()
1852.13.19 by Robert Collins
Get DirState objects roundtripping an add of a ghost tree.
944
2255.2.9 by Robert Collins
Dirstate: Fix setting of parent trees to record data about entries not in
945
    def test_set_parent_trees_file_missing_from_tree(self):
946
        # 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
947
        # 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
948
        # separate trees.
949
        # set_parent_trees is a slow but important api to support.
950
        tree1 = self.make_branch_and_memory_tree('tree1')
951
        tree1.lock_write()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
952
        try:
953
            tree1.add('')
954
            tree1.add(['a file'], ['file-id'], ['file'])
955
            tree1.put_file_bytes_non_atomic('file-id', 'file-content')
956
            revid1 = tree1.commit('foo')
957
        finally:
958
            tree1.unlock()
2255.2.9 by Robert Collins
Dirstate: Fix setting of parent trees to record data about entries not in
959
        branch2 = tree1.branch.bzrdir.clone('tree2').open_branch()
960
        tree2 = MemoryTree.create_on_branch(branch2)
961
        tree2.lock_write()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
962
        try:
963
            tree2.put_file_bytes_non_atomic('file-id', 'new file-content')
964
            revid2 = tree2.commit('foo')
2946.3.3 by John Arbash Meinel
Prefer tree.get_root_id() as more explicit than tree.path2id('')
965
            root_id = tree2.get_root_id()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
966
        finally:
967
            tree2.unlock()
2255.2.9 by Robert Collins
Dirstate: Fix setting of parent trees to record data about entries not in
968
        # check the layout in memory
2255.2.87 by Robert Collins
core dirstate tests passing with new structure.
969
        expected_result = [revid1.encode('utf8'), revid2.encode('utf8')], [
970
            (('', '', root_id), [
2255.2.124 by John Arbash Meinel
Remove direct access to Dirstate prefering dirstate.Dirstate
971
             ('d', '', 0, False, dirstate.DirState.NULLSTAT),
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
972
             ('d', '', 0, False, revid1.encode('utf8')),
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
973
             ('d', '', 0, False, revid2.encode('utf8'))
974
             ]),
2255.2.87 by Robert Collins
core dirstate tests passing with new structure.
975
            (('', 'a file', 'file-id'), [
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
976
             ('a', '', 0, False, ''),
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
977
             ('f', '2439573625385400f2a669657a7db6ae7515d371', 12, False,
978
              revid1.encode('utf8')),
979
             ('f', '542e57dc1cda4af37cb8e55ec07ce60364bb3c7d', 16, False,
980
              revid2.encode('utf8'))
981
             ])
2255.2.9 by Robert Collins
Dirstate: Fix setting of parent trees to record data about entries not in
982
            ]
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
983
        state = dirstate.DirState.initialize('dirstate')
984
        try:
985
            state.set_path_id('', root_id)
986
            state.set_parent_trees(
987
                ((revid1, tree1.branch.repository.revision_tree(revid1)),
988
                 (revid2, tree2.branch.repository.revision_tree(revid2)),
989
                 ), [])
990
        except:
991
            state.unlock()
992
            raise
993
        else:
994
            # check_state_with_reopen will unlock
995
            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
996
1852.13.20 by Robert Collins
Steps toward an object model.
997
    ### add a path via _set_data - so we dont need delta work, just
998
    # 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.
999
1852.13.25 by Robert Collins
Snapshot state
1000
    def test_add_path_to_root_no_parents_all_data(self):
1001
        # The most trivial addition of a path is when there are no parents and
1002
        # its in the root and all data about the file is supplied
1003
        self.build_tree(['a file'])
1004
        stat = os.lstat('a file')
1005
        # the 1*20 is the sha1 pretend value.
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1006
        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.
1007
        expected_entries = [
1008
            (('', '', 'TREE_ROOT'), [
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1009
             ('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.
1010
             ]),
3010.1.2 by Robert Collins
Use valid file-ids for dirstate tests.
1011
            (('', 'a file', 'a-file-id'), [
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1012
             ('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.
1013
             ]),
2255.2.13 by Robert Collins
Test adding of directories to the root of a dirstate.
1014
            ]
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1015
        try:
3010.1.2 by Robert Collins
Use valid file-ids for dirstate tests.
1016
            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.
1017
            # having added it, it should be in the output of iter_entries.
1018
            self.assertEqual(expected_entries, list(state._iter_entries()))
1019
            # saving and reloading should not affect this.
1020
            state.save()
1021
        finally:
1022
            state.unlock()
2255.2.13 by Robert Collins
Test adding of directories to the root of a dirstate.
1023
        state = dirstate.DirState.on_file('dirstate')
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1024
        state.lock_read()
1025
        try:
1026
            self.assertEqual(expected_entries, list(state._iter_entries()))
1027
        finally:
1028
            state.unlock()
2255.2.13 by Robert Collins
Test adding of directories to the root of a dirstate.
1029
1030
    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.
1031
        """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.
1032
1033
        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.
1034
        once dirstate is stable and if it is merged with WorkingTree3, consider
1035
        removing this copy of the test.
1036
        """
2255.2.13 by Robert Collins
Test adding of directories to the root of a dirstate.
1037
        self.build_tree(['unversioned/', 'unversioned/a file'])
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1038
        state = dirstate.DirState.initialize('dirstate')
1039
        try:
1040
            self.assertRaises(errors.NotVersionedError, state.add,
3010.1.2 by Robert Collins
Use valid file-ids for dirstate tests.
1041
                '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.
1042
        finally:
1043
            state.unlock()
1044
2255.2.13 by Robert Collins
Test adding of directories to the root of a dirstate.
1045
    def test_add_directory_to_root_no_parents_all_data(self):
1046
        # The most trivial addition of a dir is when there are no parents and
1047
        # its in the root and all data about the file is supplied
1048
        self.build_tree(['a dir/'])
1049
        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.
1050
        expected_entries = [
1051
            (('', '', 'TREE_ROOT'), [
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1052
             ('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.
1053
             ]),
1054
            (('', 'a dir', 'a dir id'), [
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1055
             ('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.
1056
             ]),
2255.2.13 by Robert Collins
Test adding of directories to the root of a dirstate.
1057
            ]
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1058
        state = dirstate.DirState.initialize('dirstate')
1059
        try:
1060
            state.add('a dir', 'a dir id', 'directory', stat, None)
1061
            # having added it, it should be in the output of iter_entries.
1062
            self.assertEqual(expected_entries, list(state._iter_entries()))
1063
            # saving and reloading should not affect this.
1064
            state.save()
1065
        finally:
1066
            state.unlock()
2255.2.13 by Robert Collins
Test adding of directories to the root of a dirstate.
1067
        state = dirstate.DirState.on_file('dirstate')
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1068
        state.lock_read()
2255.7.78 by Martin Pool
Add DirState._validate and call from the tests
1069
        state._validate()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1070
        try:
1071
            self.assertEqual(expected_entries, list(state._iter_entries()))
1072
        finally:
1073
            state.unlock()
1852.13.25 by Robert Collins
Snapshot state
1074
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.
1075
    def test_add_symlink_to_root_no_parents_all_data(self):
1076
        # The most trivial addition of a symlink when there are no parents and
1077
        # its in the root and all data about the file is supplied
2321.3.8 by Alexander Belchenko
Cleanup patch after John's review
1078
        # bzr doesn't support fake symlinks on windows, yet.
2949.5.1 by Alexander Belchenko
selftest: use SymlinkFeature instead of TestSkipped where appropriate
1079
        self.requireFeature(SymlinkFeature)
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.
1080
        os.symlink('target', 'a link')
1081
        stat = os.lstat('a link')
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1082
        expected_entries = [
1083
            (('', '', 'TREE_ROOT'), [
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1084
             ('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.
1085
             ]),
1086
            (('', 'a link', 'a link id'), [
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1087
             ('l', 'target', 6, 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.
1088
             ]),
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.
1089
            ]
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1090
        state = dirstate.DirState.initialize('dirstate')
1091
        try:
1092
            state.add('a link', 'a link id', 'symlink', stat, 'target')
1093
            # having added it, it should be in the output of iter_entries.
1094
            self.assertEqual(expected_entries, list(state._iter_entries()))
1095
            # saving and reloading should not affect this.
1096
            state.save()
1097
        finally:
1098
            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.
1099
        state = dirstate.DirState.on_file('dirstate')
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1100
        state.lock_read()
1101
        try:
1102
            self.assertEqual(expected_entries, list(state._iter_entries()))
1103
        finally:
1104
            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.
1105
1106
    def test_add_directory_and_child_no_parents_all_data(self):
1107
        # after adding a directory, we should be able to add children to it.
1108
        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.
1109
        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.
1110
        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.
1111
        expected_entries = [
1112
            (('', '', 'TREE_ROOT'), [
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1113
             ('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.
1114
             ]),
1115
            (('', 'a dir', 'a dir id'), [
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1116
             ('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.
1117
             ]),
3010.1.2 by Robert Collins
Use valid file-ids for dirstate tests.
1118
            (('a dir', 'a file', 'a-file-id'), [
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1119
             ('f', '1'*20, 25, False,
1120
              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.
1121
             ]),
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.
1122
            ]
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1123
        state = dirstate.DirState.initialize('dirstate')
1124
        try:
1125
            state.add('a dir', 'a dir id', 'directory', dirstat, None)
3010.1.2 by Robert Collins
Use valid file-ids for dirstate tests.
1126
            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.
1127
            # added it, it should be in the output of iter_entries.
1128
            self.assertEqual(expected_entries, list(state._iter_entries()))
1129
            # saving and reloading should not affect this.
1130
            state.save()
1131
        finally:
1132
            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.
1133
        state = dirstate.DirState.on_file('dirstate')
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1134
        state.lock_read()
1135
        try:
1136
            self.assertEqual(expected_entries, list(state._iter_entries()))
1137
        finally:
1138
            state.unlock()
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1139
2255.7.93 by Martin Pool
Add support for tree-references in dirstate
1140
    def test_add_tree_reference(self):
1141
        # make a dirstate and add a tree reference
1142
        state = dirstate.DirState.initialize('dirstate')
1143
        expected_entry = (
1144
            ('', 'subdir', 'subdir-id'),
1145
            [('t', 'subtree-123123', 0, False,
1146
              'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')],
1147
            )
1148
        try:
1149
            state.add('subdir', 'subdir-id', 'tree-reference', None, 'subtree-123123')
1150
            entry = state._get_entry(0, 'subdir-id', 'subdir')
1151
            self.assertEqual(entry, expected_entry)
1152
            state._validate()
1153
            state.save()
1154
        finally:
1155
            state.unlock()
1156
        # now check we can read it back
1157
        state.lock_read()
1158
        state._validate()
1159
        try:
1160
            entry2 = state._get_entry(0, 'subdir-id', 'subdir')
1161
            self.assertEqual(entry, entry2)
1162
            self.assertEqual(entry, expected_entry)
1163
            # and lookup by id should work too
1164
            entry2 = state._get_entry(0, fileid_utf8='subdir-id')
1165
            self.assertEqual(entry, expected_entry)
1166
        finally:
1167
            state.unlock()
1168
2255.2.225 by Martin Pool
Prohibit dirstate from getting entries called ..
1169
    def test_add_forbidden_names(self):
1170
        state = dirstate.DirState.initialize('dirstate')
2255.2.233 by John Arbash Meinel
DirState.initialize returns a locked state, unlock as part of cleanup.
1171
        self.addCleanup(state.unlock)
2255.2.225 by Martin Pool
Prohibit dirstate from getting entries called ..
1172
        self.assertRaises(errors.BzrError,
1173
            state.add, '.', 'ass-id', 'directory', None, None)
1174
        self.assertRaises(errors.BzrError,
1175
            state.add, '..', 'ass-id', 'directory', None, None)
1176
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1177
1178
class TestGetLines(TestCaseWithDirState):
1852.13.19 by Robert Collins
Get DirState objects roundtripping an add of a ghost tree.
1179
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.
1180
    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.
1181
        state = self.create_dirstate_with_root_and_subdir()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1182
        try:
2255.7.20 by John Arbash Meinel
update test for format 3, and enable caching of path split while lock is held.
1183
            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.
1184
                'crc32: 41262208\n',
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1185
                'num_entries: 2\n',
1186
                '0\x00\n\x00'
1187
                '0\x00\n\x00'
1188
                '\x00\x00a-root-value\x00'
1189
                'd\x00\x000\x00n\x00AAAAREUHaIpFB2iKAAADAQAtkqUAAIGk\x00\n\x00'
1190
                '\x00subdir\x00subdir-id\x00'
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1191
                'd\x00\x000\x00n\x00AAAAREUHaIpFB2iKAAADAQAtkqUAAIGk\x00\n\x00'
1192
                ], state.get_lines())
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1193
        finally:
1194
            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.
1195
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1196
    def test_entry_to_line(self):
2255.2.66 by John Arbash Meinel
Move _get_row and _get_block_row_index into Dirstate itself.
1197
        state = self.create_dirstate_with_root()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1198
        try:
1199
            self.assertEqual(
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1200
                '\x00\x00a-root-value\x00d\x00\x000\x00n'
1201
                '\x00AAAAREUHaIpFB2iKAAADAQAtkqUAAIGk',
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1202
                state._entry_to_line(state._dirblocks[0][1][0]))
1203
        finally:
1204
            state.unlock()
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1205
1206
    def test_entry_to_line_with_parent(self):
1207
        packed_stat = 'AAAAREUHaIpFB2iKAAADAQAtkqUAAIGk'
1208
        root_entry = ('', '', 'a-root-value'), [
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
1209
            ('d', '', 0, False, packed_stat), # current tree details
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1210
             # first: a pointer to the current location
1211
            ('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.
1212
            ]
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1213
        state = dirstate.DirState.initialize('dirstate')
1214
        try:
1215
            self.assertEqual(
1216
                '\x00\x00a-root-value\x00'
1217
                'd\x00\x000\x00n\x00AAAAREUHaIpFB2iKAAADAQAtkqUAAIGk\x00'
1218
                'a\x00dirname/basename\x000\x00n\x00',
1219
                state._entry_to_line(root_entry))
1220
        finally:
1221
            state.unlock()
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1222
1223
    def test_entry_to_line_with_two_parents_at_different_paths(self):
1224
        # / in the tree, at / in one parent and /dirname/basename in the other.
1225
        packed_stat = 'AAAAREUHaIpFB2iKAAADAQAtkqUAAIGk'
1226
        root_entry = ('', '', 'a-root-value'), [
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
1227
            ('d', '', 0, False, packed_stat), # current tree details
1228
            ('d', '', 0, False, 'rev_id'), # first parent details
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1229
             # second: a pointer to the current location
1230
            ('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.
1231
            ]
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1232
        state = dirstate.DirState.initialize('dirstate')
1233
        try:
1234
            self.assertEqual(
1235
                '\x00\x00a-root-value\x00'
1236
                'd\x00\x000\x00n\x00AAAAREUHaIpFB2iKAAADAQAtkqUAAIGk\x00'
1237
                'd\x00\x000\x00n\x00rev_id\x00'
1238
                'a\x00dirname/basename\x000\x00n\x00',
1239
                state._entry_to_line(root_entry))
1240
        finally:
1241
            state.unlock()
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1242
1243
    def test_iter_entries(self):
1244
        # 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.
1245
        # this is for get_lines to be easy to read.
1246
        packed_stat = 'AAAAREUHaIpFB2iKAAADAQAtkqUAAIGk'
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
1247
        dirblocks = []
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1248
        root_entries = [(('', '', 'a-root-value'), [
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
1249
            ('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.
1250
            ])]
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
1251
        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.
1252
        # 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.
1253
        subdir_entry = ('', 'subdir', 'subdir-id'), [
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
1254
            ('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.
1255
            ]
1256
        afile_entry = ('', 'afile', 'afile-id'), [
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
1257
            ('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.
1258
            ]
1259
        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.
1260
        # 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.
1261
        file_entry2 = ('subdir', '2file', '2file-id'), [
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
1262
            ('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.
1263
            ]
1264
        dirblocks.append(('subdir', [file_entry2]))
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1265
        state = dirstate.DirState.initialize('dirstate')
1266
        try:
1267
            state._set_data([], dirblocks)
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1268
            expected_entries = [root_entries[0], subdir_entry, afile_entry,
1269
                                file_entry2]
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1270
            self.assertEqual(expected_entries, list(state._iter_entries()))
1271
        finally:
1272
            state.unlock()
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1273
1274
1275
class TestGetBlockRowIndex(TestCaseWithDirState):
2255.2.66 by John Arbash Meinel
Move _get_row and _get_block_row_index into Dirstate itself.
1276
1277
    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.
1278
        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.
1279
        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.
1280
            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.
1281
        if dir_present:
1282
            block = state._dirblocks[block_index]
1283
            self.assertEqual(dirname, block[0])
1284
        if dir_present and file_present:
1285
            row = state._dirblocks[block_index][1][row_index]
1286
            self.assertEqual(dirname, row[0][0])
1287
            self.assertEqual(basename, row[0][1])
1288
1289
    def test_simple_structure(self):
1290
        state = self.create_dirstate_with_root_and_subdir()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1291
        self.addCleanup(state.unlock)
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
1292
        self.assertBlockRowIndexEqual(1, 0, True, True, state, '', 'subdir', 0)
1293
        self.assertBlockRowIndexEqual(1, 0, True, False, state, '', 'bdir', 0)
1294
        self.assertBlockRowIndexEqual(1, 1, True, False, state, '', 'zdir', 0)
1295
        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
1296
        self.assertBlockRowIndexEqual(2, 0, False, False, state,
1297
                                      'subdir', 'foo', 0)
2255.2.66 by John Arbash Meinel
Move _get_row and _get_block_row_index into Dirstate itself.
1298
1299
    def test_complex_structure_exists(self):
1300
        state = self.create_complex_dirstate()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1301
        self.addCleanup(state.unlock)
2255.2.66 by John Arbash Meinel
Move _get_row and _get_block_row_index into Dirstate itself.
1302
        # Make sure we can find everything that exists
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
1303
        self.assertBlockRowIndexEqual(0, 0, True, True, state, '', '', 0)
1304
        self.assertBlockRowIndexEqual(1, 0, True, True, state, '', 'a', 0)
1305
        self.assertBlockRowIndexEqual(1, 1, True, True, state, '', 'b', 0)
1306
        self.assertBlockRowIndexEqual(1, 2, True, True, state, '', 'c', 0)
1307
        self.assertBlockRowIndexEqual(1, 3, True, True, state, '', 'd', 0)
1308
        self.assertBlockRowIndexEqual(2, 0, True, True, state, 'a', 'e', 0)
1309
        self.assertBlockRowIndexEqual(2, 1, True, True, state, 'a', 'f', 0)
1310
        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
1311
        self.assertBlockRowIndexEqual(3, 1, True, True, state,
1312
                                      'b', 'h\xc3\xa5', 0)
2255.2.66 by John Arbash Meinel
Move _get_row and _get_block_row_index into Dirstate itself.
1313
1314
    def test_complex_structure_missing(self):
1315
        state = self.create_complex_dirstate()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1316
        self.addCleanup(state.unlock)
2255.2.66 by John Arbash Meinel
Move _get_row and _get_block_row_index into Dirstate itself.
1317
        # Make sure things would be inserted in the right locations
1318
        # '_' comes before 'a'
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
1319
        self.assertBlockRowIndexEqual(0, 0, True, True, state, '', '', 0)
1320
        self.assertBlockRowIndexEqual(1, 0, True, False, state, '', '_', 0)
1321
        self.assertBlockRowIndexEqual(1, 1, True, False, state, '', 'aa', 0)
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1322
        self.assertBlockRowIndexEqual(1, 4, True, False, state,
1323
                                      '', 'h\xc3\xa5', 0)
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
1324
        self.assertBlockRowIndexEqual(2, 0, False, False, state, '_', 'a', 0)
1325
        self.assertBlockRowIndexEqual(3, 0, False, False, state, 'aa', 'a', 0)
1326
        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.
1327
        # This would be inserted between a/ and b/
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
1328
        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.
1329
        # Put at the end
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
1330
        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.
1331
1332
1333
class TestGetEntry(TestCaseWithDirState):
1334
1335
    def assertEntryEqual(self, dirname, basename, file_id, state, path, index):
1336
        """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.
1337
        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.
1338
        if file_id is None:
1339
            self.assertEqual((None, None), entry)
2255.2.66 by John Arbash Meinel
Move _get_row and _get_block_row_index into Dirstate itself.
1340
        else:
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1341
            cur = entry[0]
1342
            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.
1343
1344
    def test_simple_structure(self):
1345
        state = self.create_dirstate_with_root_and_subdir()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1346
        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.
1347
        self.assertEntryEqual('', '', 'a-root-value', state, '', 0)
1348
        self.assertEntryEqual('', 'subdir', 'subdir-id', state, 'subdir', 0)
1349
        self.assertEntryEqual(None, None, None, state, 'missing', 0)
1350
        self.assertEntryEqual(None, None, None, state, 'missing/foo', 0)
1351
        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.
1352
1353
    def test_complex_structure_exists(self):
1354
        state = self.create_complex_dirstate()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1355
        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.
1356
        self.assertEntryEqual('', '', 'a-root-value', state, '', 0)
1357
        self.assertEntryEqual('', 'a', 'a-dir', state, 'a', 0)
1358
        self.assertEntryEqual('', 'b', 'b-dir', state, 'b', 0)
1359
        self.assertEntryEqual('', 'c', 'c-file', state, 'c', 0)
1360
        self.assertEntryEqual('', 'd', 'd-file', state, 'd', 0)
1361
        self.assertEntryEqual('a', 'e', 'e-dir', state, 'a/e', 0)
1362
        self.assertEntryEqual('a', 'f', 'f-file', state, 'a/f', 0)
1363
        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
1364
        self.assertEntryEqual('b', 'h\xc3\xa5', 'h-\xc3\xa5-file', state,
1365
                              'b/h\xc3\xa5', 0)
2255.2.66 by John Arbash Meinel
Move _get_row and _get_block_row_index into Dirstate itself.
1366
1367
    def test_complex_structure_missing(self):
1368
        state = self.create_complex_dirstate()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1369
        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.
1370
        self.assertEntryEqual(None, None, None, state, '_', 0)
1371
        self.assertEntryEqual(None, None, None, state, '_\xc3\xa5', 0)
1372
        self.assertEntryEqual(None, None, None, state, 'a/b', 0)
1373
        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.
1374
2255.2.85 by Robert Collins
[BROKEN] Partial conversion to new dirstate structure, please continue on the tests matching dirstate from here.
1375
    def test_get_entry_uninitialized(self):
1376
        """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.
1377
        state = self.create_dirstate_with_root()
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1378
        try:
1379
            state.save()
1380
        finally:
1381
            state.unlock()
2255.2.66 by John Arbash Meinel
Move _get_row and _get_block_row_index into Dirstate itself.
1382
        del state
1383
        state = dirstate.DirState.on_file('dirstate')
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1384
        state.lock_read()
1385
        try:
2255.2.123 by John Arbash Meinel
Simple line wrapping cleanup in test_dirstate.py
1386
            self.assertEqual(dirstate.DirState.NOT_IN_MEMORY,
1387
                             state._header_state)
1388
            self.assertEqual(dirstate.DirState.NOT_IN_MEMORY,
1389
                             state._dirblock_state)
2255.5.1 by John Arbash Meinel
Update the dirstate tests to lock and unlock properly.
1390
            self.assertEntryEqual('', '', 'a-root-value', state, '', 0)
1391
        finally:
1392
            state.unlock()
2255.3.2 by John Arbash Meinel
(broken) some basic work on adding bisect functionality to dirstate.
1393
1394
2929.2.1 by Robert Collins
* Commit updates the state of the working tree via a delta rather than
1395
class TestIterChildEntries(TestCaseWithDirState):
1396
1397
    def create_dirstate_with_two_trees(self):
1398
        """This dirstate contains multiple files and directories.
1399
1400
         /        a-root-value
1401
         a/       a-dir
1402
         b/       b-dir
1403
         c        c-file
1404
         d        d-file
1405
         a/e/     e-dir
1406
         a/f      f-file
1407
         b/g      g-file
1408
         b/h\xc3\xa5  h-\xc3\xa5-file  #This is u'\xe5' encoded into utf-8
1409
1410
        Notice that a/e is an empty directory.
1411
1412
        There is one parent tree, which has the same shape with the following variations:
1413
        b/g in the parent is gone.
1414
        b/h in the parent has a different id
1415
        b/i is new in the parent 
1416
        c is renamed to b/j in the parent
1417
1418
        :return: The dirstate, still write-locked.
1419
        """
1420
        packed_stat = 'AAAAREUHaIpFB2iKAAADAQAtkqUAAIGk'
1421
        null_sha = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
1422
        NULL_PARENT_DETAILS = dirstate.DirState.NULL_PARENT_DETAILS
1423
        root_entry = ('', '', 'a-root-value'), [
1424
            ('d', '', 0, False, packed_stat),
1425
            ('d', '', 0, False, 'parent-revid'),
1426
            ]
1427
        a_entry = ('', 'a', 'a-dir'), [
1428
            ('d', '', 0, False, packed_stat),
1429
            ('d', '', 0, False, 'parent-revid'),
1430
            ]
1431
        b_entry = ('', 'b', 'b-dir'), [
1432
            ('d', '', 0, False, packed_stat),
1433
            ('d', '', 0, False, 'parent-revid'),
1434
            ]
1435
        c_entry = ('', 'c', 'c-file'), [
1436
            ('f', null_sha, 10, False, packed_stat),
1437
            ('r', 'b/j', 0, False, ''),
1438
            ]
1439
        d_entry = ('', 'd', 'd-file'), [
1440
            ('f', null_sha, 20, False, packed_stat),
1441
            ('f', 'd', 20, False, 'parent-revid'),
1442
            ]
1443
        e_entry = ('a', 'e', 'e-dir'), [
1444
            ('d', '', 0, False, packed_stat),
1445
            ('d', '', 0, False, 'parent-revid'),
1446
            ]
1447
        f_entry = ('a', 'f', 'f-file'), [
1448
            ('f', null_sha, 30, False, packed_stat),
1449
            ('f', 'f', 20, False, 'parent-revid'),
1450
            ]
1451
        g_entry = ('b', 'g', 'g-file'), [
1452
            ('f', null_sha, 30, False, packed_stat),
1453
            NULL_PARENT_DETAILS,
1454
            ]
1455
        h_entry1 = ('b', 'h\xc3\xa5', 'h-\xc3\xa5-file1'), [
1456
            ('f', null_sha, 40, False, packed_stat),
1457
            NULL_PARENT_DETAILS,
1458
            ]
1459
        h_entry2 = ('b', 'h\xc3\xa5', 'h-\xc3\xa5-file2'), [
1460
            NULL_PARENT_DETAILS,
1461
            ('f', 'h', 20, False, 'parent-revid'),
1462
            ]
1463
        i_entry = ('b', 'i', 'i-file'), [
1464
            NULL_PARENT_DETAILS,
1465
            ('f', 'h', 20, False, 'parent-revid'),
1466
            ]
1467
        j_entry = ('b', 'j', 'c-file'), [
1468
            ('r', 'c', 0, False, ''),
1469
            ('f', 'j', 20, False, 'parent-revid'),
1470
            ]
1471
        dirblocks = []
1472
        dirblocks.append(('', [root_entry]))
1473
        dirblocks.append(('', [a_entry, b_entry, c_entry, d_entry]))
1474
        dirblocks.append(('a', [e_entry, f_entry]))
1475
        dirblocks.append(('b', [g_entry, h_entry1, h_entry2, i_entry, j_entry]))
1476
        state = dirstate.DirState.initialize('dirstate')
1477
        state._validate()
1478
        try:
1479
            state._set_data(['parent'], dirblocks)
1480
        except:
1481
            state.unlock()
1482
            raise
1483
        return state, dirblocks
1484
1485
    def test_iter_children_b(self):
1486
        state, dirblocks = self.create_dirstate_with_two_trees()
1487
        self.addCleanup(state.unlock)
1488
        expected_result = []
1489
        expected_result.append(dirblocks[3][1][2]) # h2
1490
        expected_result.append(dirblocks[3][1][3]) # i
1491
        expected_result.append(dirblocks[3][1][4]) # j
1492
        self.assertEqual(expected_result,
1493
            list(state._iter_child_entries(1, 'b')))
1494
2929.2.2 by Robert Collins
Review feedback on dirstate update_basis_via_delta logic.
1495
    def test_iter_child_root(self):
1496
        state, dirblocks = self.create_dirstate_with_two_trees()
1497
        self.addCleanup(state.unlock)
1498
        expected_result = []
1499
        expected_result.append(dirblocks[1][1][0]) # a
1500
        expected_result.append(dirblocks[1][1][1]) # b
1501
        expected_result.append(dirblocks[1][1][3]) # d
1502
        expected_result.append(dirblocks[2][1][0]) # e
1503
        expected_result.append(dirblocks[2][1][1]) # f
1504
        expected_result.append(dirblocks[3][1][2]) # h2
1505
        expected_result.append(dirblocks[3][1][3]) # i
1506
        expected_result.append(dirblocks[3][1][4]) # j
1507
        self.assertEqual(expected_result,
1508
            list(state._iter_child_entries(1, '')))
1509
2929.2.1 by Robert Collins
* Commit updates the state of the working tree via a delta rather than
1510
2255.8.5 by John Arbash Meinel
Add a test that dirstate adds records in the right order.
1511
class TestDirstateSortOrder(TestCaseWithTransport):
1512
    """Test that DirState adds entries in the right order."""
1513
1514
    def test_add_sorting(self):
2255.7.21 by John Arbash Meinel
Get iter_changes working again, by fixing set_parent_trees to
1515
        """Add entries in lexicographical order, we get path sorted order.
1516
1517
        This tests it to a depth of 4, to make sure we don't just get it right
1518
        at a single depth. 'a/a' should come before 'a-a', even though it
1519
        doesn't lexicographically.
1520
        """
1521
        dirs = ['a', 'a/a', 'a/a/a', 'a/a/a/a',
1522
                '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.
1523
               ]
1524
        null_sha = ''
1525
        state = dirstate.DirState.initialize('dirstate')
1526
        self.addCleanup(state.unlock)
1527
1528
        fake_stat = os.stat('dirstate')
1529
        for d in dirs:
1530
            d_id = d.replace('/', '_')+'-id'
1531
            file_path = d + '/f'
1532
            file_id = file_path.replace('/', '_')+'-id'
1533
            state.add(d, d_id, 'directory', fake_stat, null_sha)
1534
            state.add(file_path, file_id, 'file', fake_stat, null_sha)
1535
1536
        expected = ['', '', 'a',
2255.7.21 by John Arbash Meinel
Get iter_changes working again, by fixing set_parent_trees to
1537
                'a/a', 'a/a/a', 'a/a/a/a',
1538
                '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.
1539
               ]
2255.7.21 by John Arbash Meinel
Get iter_changes working again, by fixing set_parent_trees to
1540
        split = lambda p:p.split('/')
1541
        self.assertEqual(sorted(expected, key=split), expected)
1542
        dirblock_names = [d[0] for d in state._dirblocks]
1543
        self.assertEqual(expected, dirblock_names)
1544
1545
    def test_set_parent_trees_correct_order(self):
1546
        """After calling set_parent_trees() we should maintain the order."""
1547
        dirs = ['a', 'a-a', 'a/a']
1548
        null_sha = ''
1549
        state = dirstate.DirState.initialize('dirstate')
1550
        self.addCleanup(state.unlock)
1551
1552
        fake_stat = os.stat('dirstate')
1553
        for d in dirs:
1554
            d_id = d.replace('/', '_')+'-id'
1555
            file_path = d + '/f'
1556
            file_id = file_path.replace('/', '_')+'-id'
1557
            state.add(d, d_id, 'directory', fake_stat, null_sha)
1558
            state.add(file_path, file_id, 'file', fake_stat, null_sha)
1559
1560
        expected = ['', '', 'a', 'a/a', 'a-a']
1561
        dirblock_names = [d[0] for d in state._dirblocks]
1562
        self.assertEqual(expected, dirblock_names)
1563
1564
        # *really* cheesy way to just get an empty tree
1565
        repo = self.make_repository('repo')
1566
        empty_tree = repo.revision_tree(None)
1567
        state.set_parent_trees([('null:', empty_tree)], [])
1568
2255.8.5 by John Arbash Meinel
Add a test that dirstate adds records in the right order.
1569
        dirblock_names = [d[0] for d in state._dirblocks]
1570
        self.assertEqual(expected, dirblock_names)
1571
1572
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1573
class InstrumentedDirState(dirstate.DirState):
2255.10.1 by John Arbash Meinel
Update WorkingTree4 so that it doesn't use a HashCache,
1574
    """An DirState with instrumented sha1 functionality."""
1575
1576
    def __init__(self, path):
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1577
        super(InstrumentedDirState, self).__init__(path)
2255.10.1 by John Arbash Meinel
Update WorkingTree4 so that it doesn't use a HashCache,
1578
        self._time_offset = 0
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1579
        self._log = []
2872.3.3 by Martin Pool
Fix up test_update_entry to work with -Dhashcache
1580
        # member is dynamically set in DirState.__init__ to turn on trace
1581
        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,
1582
1583
    def _sha_cutoff_time(self):
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1584
        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.
1585
        self._cutoff_time = timestamp + self._time_offset
2255.10.1 by John Arbash Meinel
Update WorkingTree4 so that it doesn't use a HashCache,
1586
2872.3.3 by Martin Pool
Fix up test_update_entry to work with -Dhashcache
1587
    def _sha1_file_and_log(self, abspath):
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1588
        self._log.append(('sha1', abspath))
2872.3.1 by Martin Pool
Add -Dhashcache option; clean up dirstate sha1 code
1589
        return osutils.sha_file_by_name(abspath)
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1590
1591
    def _read_link(self, abspath, old_link):
1592
        self._log.append(('read_link', abspath, old_link))
1593
        return super(InstrumentedDirState, self)._read_link(abspath, old_link)
1594
1595
    def _lstat(self, abspath, entry):
1596
        self._log.append(('lstat', abspath))
1597
        return super(InstrumentedDirState, self)._lstat(abspath, entry)
1598
1599
    def _is_executable(self, mode, old_executable):
1600
        self._log.append(('is_exec', mode, old_executable))
1601
        return super(InstrumentedDirState, self)._is_executable(mode,
1602
                                                                old_executable)
2255.10.1 by John Arbash Meinel
Update WorkingTree4 so that it doesn't use a HashCache,
1603
1604
    def adjust_time(self, secs):
1605
        """Move the clock forward or back.
1606
1607
        :param secs: The amount to adjust the clock by. Positive values make it
1608
        seem as if we are in the future, negative values make it seem like we
1609
        are in the past.
1610
        """
1611
        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.
1612
        self._cutoff_time = None
2255.10.1 by John Arbash Meinel
Update WorkingTree4 so that it doesn't use a HashCache,
1613
1614
1615
class _FakeStat(object):
1616
    """A class with the same attributes as a real stat result."""
1617
1618
    def __init__(self, size, mtime, ctime, dev, ino, mode):
1619
        self.st_size = size
1620
        self.st_mtime = mtime
1621
        self.st_ctime = ctime
1622
        self.st_dev = dev
1623
        self.st_ino = ino
1624
        self.st_mode = mode
1625
1626
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1627
class TestUpdateEntry(TestCaseWithDirState):
1628
    """Test the DirState.update_entry functions"""
2255.10.1 by John Arbash Meinel
Update WorkingTree4 so that it doesn't use a HashCache,
1629
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1630
    def get_state_with_a(self):
1631
        """Create a DirState tracking a single object named 'a'"""
1632
        state = InstrumentedDirState.initialize('dirstate')
2255.10.1 by John Arbash Meinel
Update WorkingTree4 so that it doesn't use a HashCache,
1633
        self.addCleanup(state.unlock)
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1634
        state.add('a', 'a-id', 'file', None, '')
1635
        entry = state._get_entry(0, path_utf8='a')
1636
        return state, entry
1637
1638
    def test_update_entry(self):
1639
        state, entry = self.get_state_with_a()
2255.10.1 by John Arbash Meinel
Update WorkingTree4 so that it doesn't use a HashCache,
1640
        self.build_tree(['a'])
1641
        # Add one where we don't provide the stat or sha already
1642
        self.assertEqual(('', 'a', 'a-id'), entry[0])
1643
        self.assertEqual([('f', '', 0, False, dirstate.DirState.NULLSTAT)],
1644
                         entry[1])
1645
        # Flush the buffers to disk
1646
        state.save()
1647
        self.assertEqual(dirstate.DirState.IN_MEMORY_UNMODIFIED,
1648
                         state._dirblock_state)
1649
1650
        stat_value = os.lstat('a')
2255.10.5 by John Arbash Meinel
Fix a small bug when we have a symlink that does not need to be re-read.
1651
        packed_stat = dirstate.pack_stat(stat_value)
1652
        link_or_sha1 = state.update_entry(entry, abspath='a',
2255.10.1 by John Arbash Meinel
Update WorkingTree4 so that it doesn't use a HashCache,
1653
                                          stat_value=stat_value)
2255.10.5 by John Arbash Meinel
Fix a small bug when we have a symlink that does not need to be re-read.
1654
        self.assertEqual('b50e5406bb5e153ebbeb20268fcf37c87e1ecfb6',
1655
                         link_or_sha1)
2255.10.1 by John Arbash Meinel
Update WorkingTree4 so that it doesn't use a HashCache,
1656
2485.3.14 by John Arbash Meinel
Update the code so that symlinks aren't cached at incorrect times
1657
        # The dirblock entry should not cache the file's sha1
1658
        self.assertEqual([('f', '', 14, False, dirstate.DirState.NULLSTAT)],
2255.10.5 by John Arbash Meinel
Fix a small bug when we have a symlink that does not need to be re-read.
1659
                         entry[1])
2255.10.1 by John Arbash Meinel
Update WorkingTree4 so that it doesn't use a HashCache,
1660
        self.assertEqual(dirstate.DirState.IN_MEMORY_MODIFIED,
1661
                         state._dirblock_state)
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1662
        mode = stat_value.st_mode
1663
        self.assertEqual([('sha1', 'a'), ('is_exec', mode, False)], state._log)
2255.10.1 by John Arbash Meinel
Update WorkingTree4 so that it doesn't use a HashCache,
1664
1665
        state.save()
1666
        self.assertEqual(dirstate.DirState.IN_MEMORY_UNMODIFIED,
1667
                         state._dirblock_state)
1668
1669
        # If we do it again right away, we don't know if the file has changed
1670
        # so we will re-read the file. Roll the clock back so the file is
1671
        # guaranteed to look too new.
1672
        state.adjust_time(-10)
1673
2255.10.5 by John Arbash Meinel
Fix a small bug when we have a symlink that does not need to be re-read.
1674
        link_or_sha1 = state.update_entry(entry, abspath='a',
2255.10.1 by John Arbash Meinel
Update WorkingTree4 so that it doesn't use a HashCache,
1675
                                          stat_value=stat_value)
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1676
        self.assertEqual([('sha1', 'a'), ('is_exec', mode, False),
1677
                          ('sha1', 'a'), ('is_exec', mode, False),
1678
                         ], state._log)
2255.10.5 by John Arbash Meinel
Fix a small bug when we have a symlink that does not need to be re-read.
1679
        self.assertEqual('b50e5406bb5e153ebbeb20268fcf37c87e1ecfb6',
1680
                         link_or_sha1)
2255.10.1 by John Arbash Meinel
Update WorkingTree4 so that it doesn't use a HashCache,
1681
        self.assertEqual(dirstate.DirState.IN_MEMORY_MODIFIED,
1682
                         state._dirblock_state)
2485.3.14 by John Arbash Meinel
Update the code so that symlinks aren't cached at incorrect times
1683
        self.assertEqual([('f', '', 14, False, dirstate.DirState.NULLSTAT)],
1684
                         entry[1])
2255.10.1 by John Arbash Meinel
Update WorkingTree4 so that it doesn't use a HashCache,
1685
        state.save()
1686
1687
        # However, if we move the clock forward so the file is considered
2485.3.14 by John Arbash Meinel
Update the code so that symlinks aren't cached at incorrect times
1688
        # "stable", it should just cache the value.
1689
        state.adjust_time(+20)
1690
        link_or_sha1 = state.update_entry(entry, abspath='a',
1691
                                          stat_value=stat_value)
1692
        self.assertEqual('b50e5406bb5e153ebbeb20268fcf37c87e1ecfb6',
1693
                         link_or_sha1)
1694
        self.assertEqual([('sha1', 'a'), ('is_exec', mode, False),
1695
                          ('sha1', 'a'), ('is_exec', mode, False),
1696
                          ('sha1', 'a'), ('is_exec', mode, False),
1697
                         ], state._log)
1698
        self.assertEqual([('f', link_or_sha1, 14, False, packed_stat)],
1699
                         entry[1])
1700
1701
        # Subsequent calls will just return the cached value
1702
        link_or_sha1 = state.update_entry(entry, abspath='a',
1703
                                          stat_value=stat_value)
1704
        self.assertEqual('b50e5406bb5e153ebbeb20268fcf37c87e1ecfb6',
1705
                         link_or_sha1)
1706
        self.assertEqual([('sha1', 'a'), ('is_exec', mode, False),
1707
                          ('sha1', 'a'), ('is_exec', mode, False),
1708
                          ('sha1', 'a'), ('is_exec', mode, False),
1709
                         ], state._log)
1710
        self.assertEqual([('f', link_or_sha1, 14, False, packed_stat)],
1711
                         entry[1])
2255.10.5 by John Arbash Meinel
Fix a small bug when we have a symlink that does not need to be re-read.
1712
1713
    def test_update_entry_symlink(self):
1714
        """Update entry should read symlinks."""
2949.5.1 by Alexander Belchenko
selftest: use SymlinkFeature instead of TestSkipped where appropriate
1715
        self.requireFeature(SymlinkFeature)
2255.10.5 by John Arbash Meinel
Fix a small bug when we have a symlink that does not need to be re-read.
1716
        state, entry = self.get_state_with_a()
1717
        state.save()
1718
        self.assertEqual(dirstate.DirState.IN_MEMORY_UNMODIFIED,
1719
                         state._dirblock_state)
1720
        os.symlink('target', 'a')
1721
1722
        state.adjust_time(-10) # Make the symlink look new
1723
        stat_value = os.lstat('a')
1724
        packed_stat = dirstate.pack_stat(stat_value)
1725
        link_or_sha1 = state.update_entry(entry, abspath='a',
1726
                                          stat_value=stat_value)
1727
        self.assertEqual('target', link_or_sha1)
1728
        self.assertEqual([('read_link', 'a', '')], state._log)
2485.3.14 by John Arbash Meinel
Update the code so that symlinks aren't cached at incorrect times
1729
        # Dirblock is not updated (the link is too new)
1730
        self.assertEqual([('l', '', 6, False, dirstate.DirState.NULLSTAT)],
2255.10.5 by John Arbash Meinel
Fix a small bug when we have a symlink that does not need to be re-read.
1731
                         entry[1])
1732
        self.assertEqual(dirstate.DirState.IN_MEMORY_MODIFIED,
1733
                         state._dirblock_state)
1734
1735
        # Because the stat_value looks new, we should re-read the target
1736
        link_or_sha1 = state.update_entry(entry, abspath='a',
1737
                                          stat_value=stat_value)
1738
        self.assertEqual('target', link_or_sha1)
1739
        self.assertEqual([('read_link', 'a', ''),
2485.3.14 by John Arbash Meinel
Update the code so that symlinks aren't cached at incorrect times
1740
                          ('read_link', 'a', ''),
2255.10.5 by John Arbash Meinel
Fix a small bug when we have a symlink that does not need to be re-read.
1741
                         ], state._log)
2485.3.14 by John Arbash Meinel
Update the code so that symlinks aren't cached at incorrect times
1742
        self.assertEqual([('l', '', 6, False, dirstate.DirState.NULLSTAT)],
1743
                         entry[1])
2255.10.5 by John Arbash Meinel
Fix a small bug when we have a symlink that does not need to be re-read.
1744
        state.adjust_time(+20) # Skip into the future, all files look old
1745
        link_or_sha1 = state.update_entry(entry, abspath='a',
1746
                                          stat_value=stat_value)
1747
        self.assertEqual('target', link_or_sha1)
2485.3.14 by John Arbash Meinel
Update the code so that symlinks aren't cached at incorrect times
1748
        # We need to re-read the link because only now can we cache it
1749
        self.assertEqual([('read_link', 'a', ''),
1750
                          ('read_link', 'a', ''),
1751
                          ('read_link', 'a', ''),
1752
                         ], state._log)
1753
        self.assertEqual([('l', 'target', 6, False, packed_stat)],
1754
                         entry[1])
1755
1756
        # Another call won't re-read the link
1757
        self.assertEqual([('read_link', 'a', ''),
1758
                          ('read_link', 'a', ''),
1759
                          ('read_link', 'a', ''),
1760
                         ], state._log)
1761
        link_or_sha1 = state.update_entry(entry, abspath='a',
1762
                                          stat_value=stat_value)
1763
        self.assertEqual('target', link_or_sha1)
1764
        self.assertEqual([('l', 'target', 6, False, packed_stat)],
1765
                         entry[1])
2255.10.1 by John Arbash Meinel
Update WorkingTree4 so that it doesn't use a HashCache,
1766
2485.3.3 by John Arbash Meinel
Avoid extra work in inner 'DirState.update_entry' code.
1767
    def do_update_entry(self, state, entry, abspath):
1768
        stat_value = os.lstat(abspath)
1769
        return state.update_entry(entry, abspath, stat_value)
1770
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1771
    def test_update_entry_dir(self):
1772
        state, entry = self.get_state_with_a()
1773
        self.build_tree(['a/'])
2485.3.3 by John Arbash Meinel
Avoid extra work in inner 'DirState.update_entry' code.
1774
        self.assertIs(None, self.do_update_entry(state, entry, 'a'))
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1775
2485.3.1 by John Arbash Meinel
Fix DirState handling of dir records.
1776
    def test_update_entry_dir_unchanged(self):
1777
        state, entry = self.get_state_with_a()
1778
        self.build_tree(['a/'])
2485.3.14 by John Arbash Meinel
Update the code so that symlinks aren't cached at incorrect times
1779
        state.adjust_time(+20)
2485.3.3 by John Arbash Meinel
Avoid extra work in inner 'DirState.update_entry' code.
1780
        self.assertIs(None, self.do_update_entry(state, entry, 'a'))
2485.3.1 by John Arbash Meinel
Fix DirState handling of dir records.
1781
        self.assertEqual(dirstate.DirState.IN_MEMORY_MODIFIED,
1782
                         state._dirblock_state)
1783
        state.save()
1784
        self.assertEqual(dirstate.DirState.IN_MEMORY_UNMODIFIED,
1785
                         state._dirblock_state)
2485.3.3 by John Arbash Meinel
Avoid extra work in inner 'DirState.update_entry' code.
1786
        self.assertIs(None, self.do_update_entry(state, entry, 'a'))
2485.3.1 by John Arbash Meinel
Fix DirState handling of dir records.
1787
        self.assertEqual(dirstate.DirState.IN_MEMORY_UNMODIFIED,
1788
                         state._dirblock_state)
1789
1790
    def test_update_entry_file_unchanged(self):
1791
        state, entry = self.get_state_with_a()
1792
        self.build_tree(['a'])
1793
        sha1sum = 'b50e5406bb5e153ebbeb20268fcf37c87e1ecfb6'
2485.3.14 by John Arbash Meinel
Update the code so that symlinks aren't cached at incorrect times
1794
        state.adjust_time(+20)
2485.3.3 by John Arbash Meinel
Avoid extra work in inner 'DirState.update_entry' code.
1795
        self.assertEqual(sha1sum, self.do_update_entry(state, entry, 'a'))
2485.3.1 by John Arbash Meinel
Fix DirState handling of dir records.
1796
        self.assertEqual(dirstate.DirState.IN_MEMORY_MODIFIED,
1797
                         state._dirblock_state)
1798
        state.save()
1799
        self.assertEqual(dirstate.DirState.IN_MEMORY_UNMODIFIED,
1800
                         state._dirblock_state)
2485.3.3 by John Arbash Meinel
Avoid extra work in inner 'DirState.update_entry' code.
1801
        self.assertEqual(sha1sum, self.do_update_entry(state, entry, 'a'))
2485.3.1 by John Arbash Meinel
Fix DirState handling of dir records.
1802
        self.assertEqual(dirstate.DirState.IN_MEMORY_UNMODIFIED,
1803
                         state._dirblock_state)
1804
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1805
    def create_and_test_file(self, state, entry):
1806
        """Create a file at 'a' and verify the state finds it.
1807
1808
        The state should already be versioning *something* at 'a'. This makes
1809
        sure that state.update_entry recognizes it as a file.
1810
        """
1811
        self.build_tree(['a'])
1812
        stat_value = os.lstat('a')
1813
        packed_stat = dirstate.pack_stat(stat_value)
1814
2485.3.3 by John Arbash Meinel
Avoid extra work in inner 'DirState.update_entry' code.
1815
        link_or_sha1 = self.do_update_entry(state, entry, abspath='a')
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1816
        self.assertEqual('b50e5406bb5e153ebbeb20268fcf37c87e1ecfb6',
1817
                         link_or_sha1)
1818
        self.assertEqual([('f', link_or_sha1, 14, False, packed_stat)],
1819
                         entry[1])
1820
        return packed_stat
1821
1822
    def create_and_test_dir(self, state, entry):
1823
        """Create a directory at 'a' and verify the state finds it.
1824
1825
        The state should already be versioning *something* at 'a'. This makes
1826
        sure that state.update_entry recognizes it as a directory.
1827
        """
1828
        self.build_tree(['a/'])
1829
        stat_value = os.lstat('a')
1830
        packed_stat = dirstate.pack_stat(stat_value)
1831
2485.3.3 by John Arbash Meinel
Avoid extra work in inner 'DirState.update_entry' code.
1832
        link_or_sha1 = self.do_update_entry(state, entry, abspath='a')
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1833
        self.assertIs(None, link_or_sha1)
1834
        self.assertEqual([('d', '', 0, False, packed_stat)], entry[1])
1835
1836
        return packed_stat
1837
1838
    def create_and_test_symlink(self, state, entry):
1839
        """Create a symlink at 'a' and verify the state finds it.
1840
1841
        The state should already be versioning *something* at 'a'. This makes
1842
        sure that state.update_entry recognizes it as a symlink.
1843
1844
        This should not be called if this platform does not have symlink
1845
        support.
1846
        """
2321.3.3 by Alexander Belchenko
test_dirstate: skip tests with symlinks on platforms that don't have symlinks support
1847
        # caller should care about skipping test on platforms without symlinks
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1848
        os.symlink('path/to/foo', 'a')
1849
1850
        stat_value = os.lstat('a')
1851
        packed_stat = dirstate.pack_stat(stat_value)
1852
2485.3.3 by John Arbash Meinel
Avoid extra work in inner 'DirState.update_entry' code.
1853
        link_or_sha1 = self.do_update_entry(state, entry, abspath='a')
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1854
        self.assertEqual('path/to/foo', link_or_sha1)
1855
        self.assertEqual([('l', 'path/to/foo', 11, False, packed_stat)],
1856
                         entry[1])
1857
        return packed_stat
1858
1859
    def test_update_file_to_dir(self):
1860
        """If a file changes to a directory we return None for the sha.
1861
        We also update the inventory record.
1862
        """
1863
        state, entry = self.get_state_with_a()
2485.3.14 by John Arbash Meinel
Update the code so that symlinks aren't cached at incorrect times
1864
        # The file sha1 won't be cached unless the file is old
1865
        state.adjust_time(+10)
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1866
        self.create_and_test_file(state, entry)
1867
        os.remove('a')
1868
        self.create_and_test_dir(state, entry)
1869
1870
    def test_update_file_to_symlink(self):
1871
        """File becomes a symlink"""
2949.5.1 by Alexander Belchenko
selftest: use SymlinkFeature instead of TestSkipped where appropriate
1872
        self.requireFeature(SymlinkFeature)
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1873
        state, entry = self.get_state_with_a()
2485.3.14 by John Arbash Meinel
Update the code so that symlinks aren't cached at incorrect times
1874
        # The file sha1 won't be cached unless the file is old
1875
        state.adjust_time(+10)
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1876
        self.create_and_test_file(state, entry)
1877
        os.remove('a')
1878
        self.create_and_test_symlink(state, entry)
1879
1880
    def test_update_dir_to_file(self):
1881
        """Directory becoming a file updates the entry."""
1882
        state, entry = self.get_state_with_a()
2485.3.14 by John Arbash Meinel
Update the code so that symlinks aren't cached at incorrect times
1883
        # The file sha1 won't be cached unless the file is old
1884
        state.adjust_time(+10)
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1885
        self.create_and_test_dir(state, entry)
1886
        os.rmdir('a')
1887
        self.create_and_test_file(state, entry)
1888
1889
    def test_update_dir_to_symlink(self):
1890
        """Directory becomes a symlink"""
2949.5.1 by Alexander Belchenko
selftest: use SymlinkFeature instead of TestSkipped where appropriate
1891
        self.requireFeature(SymlinkFeature)
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1892
        state, entry = self.get_state_with_a()
2485.3.14 by John Arbash Meinel
Update the code so that symlinks aren't cached at incorrect times
1893
        # The symlink target won't be cached if it isn't old
1894
        state.adjust_time(+10)
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1895
        self.create_and_test_dir(state, entry)
1896
        os.rmdir('a')
1897
        self.create_and_test_symlink(state, entry)
1898
1899
    def test_update_symlink_to_file(self):
1900
        """Symlink becomes a file"""
2949.5.1 by Alexander Belchenko
selftest: use SymlinkFeature instead of TestSkipped where appropriate
1901
        self.requireFeature(SymlinkFeature)
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1902
        state, entry = self.get_state_with_a()
2485.3.14 by John Arbash Meinel
Update the code so that symlinks aren't cached at incorrect times
1903
        # The symlink and file info won't be cached unless old
1904
        state.adjust_time(+10)
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1905
        self.create_and_test_symlink(state, entry)
1906
        os.remove('a')
1907
        self.create_and_test_file(state, entry)
1908
1909
    def test_update_symlink_to_dir(self):
1910
        """Symlink becomes a directory"""
2949.5.1 by Alexander Belchenko
selftest: use SymlinkFeature instead of TestSkipped where appropriate
1911
        self.requireFeature(SymlinkFeature)
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1912
        state, entry = self.get_state_with_a()
2485.3.14 by John Arbash Meinel
Update the code so that symlinks aren't cached at incorrect times
1913
        # The symlink target won't be cached if it isn't old
1914
        state.adjust_time(+10)
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1915
        self.create_and_test_symlink(state, entry)
1916
        os.remove('a')
1917
        self.create_and_test_dir(state, entry)
2255.10.2 by John Arbash Meinel
Update to dirstate locking.
1918
2255.10.7 by John Arbash Meinel
Some updates to how we handle the executable bit. In preparation for supporting Win32
1919
    def test__is_executable_win32(self):
1920
        state, entry = self.get_state_with_a()
1921
        self.build_tree(['a'])
1922
1923
        # Make sure we are using the win32 implementation of _is_executable
1924
        state._is_executable = state._is_executable_win32
1925
1926
        # The file on disk is not executable, but we are marking it as though
1927
        # it is. With _is_executable_win32 we ignore what is on disk.
1928
        entry[1][0] = ('f', '', 0, True, dirstate.DirState.NULLSTAT)
1929
1930
        stat_value = os.lstat('a')
1931
        packed_stat = dirstate.pack_stat(stat_value)
1932
1933
        state.adjust_time(-10) # Make sure everything is new
1934
        state.update_entry(entry, abspath='a', stat_value=stat_value)
1935
1936
        # The row is updated, but the executable bit stays set.
2485.3.14 by John Arbash Meinel
Update the code so that symlinks aren't cached at incorrect times
1937
        self.assertEqual([('f', '', 14, True, dirstate.DirState.NULLSTAT)],
1938
                         entry[1])
1939
1940
        # Make the disk object look old enough to cache
1941
        state.adjust_time(+20)
2255.10.7 by John Arbash Meinel
Some updates to how we handle the executable bit. In preparation for supporting Win32
1942
        digest = 'b50e5406bb5e153ebbeb20268fcf37c87e1ecfb6'
2485.3.14 by John Arbash Meinel
Update the code so that symlinks aren't cached at incorrect times
1943
        state.update_entry(entry, abspath='a', stat_value=stat_value)
2255.10.7 by John Arbash Meinel
Some updates to how we handle the executable bit. In preparation for supporting Win32
1944
        self.assertEqual([('f', digest, 14, True, packed_stat)], entry[1])
1945
2255.10.1 by John Arbash Meinel
Update WorkingTree4 so that it doesn't use a HashCache,
1946
1947
class TestPackStat(TestCaseWithTransport):
1948
1949
    def assertPackStat(self, expected, stat_value):
1950
        """Check the packed and serialized form of a stat value."""
1951
        self.assertEqual(expected, dirstate.pack_stat(stat_value))
1952
1953
    def test_pack_stat_int(self):
1954
        st = _FakeStat(6859L, 1172758614, 1172758617, 777L, 6499538L, 0100644)
1955
        # Make sure that all parameters have an impact on the packed stat.
1956
        self.assertPackStat('AAAay0Xm4FZF5uBZAAADCQBjLNIAAIGk', st)
1957
        st.st_size = 7000L
1958
        #                ay0 => bWE
1959
        self.assertPackStat('AAAbWEXm4FZF5uBZAAADCQBjLNIAAIGk', st)
1960
        st.st_mtime = 1172758620
1961
        #                     4FZ => 4Fx
1962
        self.assertPackStat('AAAbWEXm4FxF5uBZAAADCQBjLNIAAIGk', st)
1963
        st.st_ctime = 1172758630
1964
        #                          uBZ => uBm
1965
        self.assertPackStat('AAAbWEXm4FxF5uBmAAADCQBjLNIAAIGk', st)
1966
        st.st_dev = 888L
1967
        #                                DCQ => DeA
1968
        self.assertPackStat('AAAbWEXm4FxF5uBmAAADeABjLNIAAIGk', st)
1969
        st.st_ino = 6499540L
1970
        #                                     LNI => LNQ
1971
        self.assertPackStat('AAAbWEXm4FxF5uBmAAADeABjLNQAAIGk', st)
1972
        st.st_mode = 0100744
1973
        #                                          IGk => IHk
1974
        self.assertPackStat('AAAbWEXm4FxF5uBmAAADeABjLNQAAIHk', st)
1975
1976
    def test_pack_stat_float(self):
1977
        """On some platforms mtime and ctime are floats.
1978
1979
        Make sure we don't get warnings or errors, and that we ignore changes <
1980
        1s
1981
        """
1982
        st = _FakeStat(7000L, 1172758614.0, 1172758617.0,
1983
                       777L, 6499538L, 0100644)
1984
        # These should all be the same as the integer counterparts
1985
        self.assertPackStat('AAAbWEXm4FZF5uBZAAADCQBjLNIAAIGk', st)
1986
        st.st_mtime = 1172758620.0
1987
        #                     FZF5 => FxF5
1988
        self.assertPackStat('AAAbWEXm4FxF5uBZAAADCQBjLNIAAIGk', st)
1989
        st.st_ctime = 1172758630.0
1990
        #                          uBZ => uBm
1991
        self.assertPackStat('AAAbWEXm4FxF5uBmAAADCQBjLNIAAIGk', st)
1992
        # fractional seconds are discarded, so no change from above
1993
        st.st_mtime = 1172758620.453
1994
        self.assertPackStat('AAAbWEXm4FxF5uBmAAADCQBjLNIAAIGk', st)
1995
        st.st_ctime = 1172758630.228
1996
        self.assertPackStat('AAAbWEXm4FxF5uBmAAADCQBjLNIAAIGk', st)
1997
1998
2323.5.4 by Martin Pool
Move some dirstate test setup methods into the base class
1999
class TestBisect(TestCaseWithDirState):
2255.3.2 by John Arbash Meinel
(broken) some basic work on adding bisect functionality to dirstate.
2000
    """Test the ability to bisect into the disk format."""
2001
2255.2.131 by John Arbash Meinel
Change the return values for bisect functions so they just return
2002
    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.
2003
        """Assert that bisecting for paths returns the right result.
2004
2255.2.131 by John Arbash Meinel
Change the return values for bisect functions so they just return
2005
        :param expected_map: A map from key => entry value
2006
        :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.
2007
        :param state: The DirState object.
2008
        :param paths: A list of paths, these will automatically be split into
2009
                      (dir, name) tuples, and sorted according to how _bisect
2010
                      requires.
2011
        """
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
2012
        result = state._bisect(paths)
2255.2.126 by John Arbash Meinel
Switch the bisect code to support the fact that we can have
2013
        # For now, results are just returned in whatever order we read them.
2014
        # We could sort by (dir, name, file_id) or something like that, but in
2015
        # 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
2016
        # extra overhead if we can avoid it. So sort everything to make sure
2017
        # equality is true
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
2018
        assert len(map_keys) == len(paths)
2255.2.131 by John Arbash Meinel
Change the return values for bisect functions so they just return
2019
        expected = {}
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
2020
        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
2021
            if keys is None:
2022
                # This should not be present in the output
2023
                continue
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
2024
            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
2025
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
2026
        # The returned values are just arranged randomly based on when they
2027
        # were read, for testing, make sure it is properly sorted.
2028
        for path in result:
2029
            result[path].sort()
2255.2.131 by John Arbash Meinel
Change the return values for bisect functions so they just return
2030
2031
        self.assertEqual(expected, result)
2032
2033
    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.
2034
        """Assert that bisecting for dirbblocks returns the right result.
2035
2255.2.132 by John Arbash Meinel
Implement _bisect_recursive, which uses multiple bisect calls to
2036
        :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
2037
        :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.
2038
            Something like [['a', 'b', 'f'], ['b/c', 'b/d']]
2039
        :param state: The DirState object.
2040
        :param paths: A list of directories
2041
        """
2042
        result = state._bisect_dirblocks(paths)
2255.2.131 by John Arbash Meinel
Change the return values for bisect functions so they just return
2043
        assert len(map_keys) == len(paths)
2044
2045
        expected = {}
2046
        for path, keys in zip(paths, map_keys):
2047
            if keys is None:
2048
                # This should not be present in the output
2049
                continue
2050
            expected[path] = sorted(expected_map[k] for k in keys)
2051
        for path in result:
2052
            result[path].sort()
2053
2054
        self.assertEqual(expected, result)
2255.2.130 by John Arbash Meinel
Add a very similar function which grabs everything for a particular directory block.
2055
2255.2.132 by John Arbash Meinel
Implement _bisect_recursive, which uses multiple bisect calls to
2056
    def assertBisectRecursive(self, expected_map, map_keys, state, paths):
2057
        """Assert the return value of a recursive bisection.
2058
2059
        :param expected_map: A map from key => entry value
2060
        :param map_keys: A list of paths we expect to be returned.
2061
            Something like ['a', 'b', 'f', 'b/d', 'b/d2']
2062
        :param state: The DirState object.
2063
        :param paths: A list of files and directories. It will be broken up
2064
            into (dir, name) pairs and sorted before calling _bisect_recursive.
2065
        """
2066
        expected = {}
2067
        for key in map_keys:
2068
            entry = expected_map[key]
2069
            dir_name_id, trees_info = entry
2070
            expected[dir_name_id] = trees_info
2071
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
2072
        result = state._bisect_recursive(paths)
2255.2.132 by John Arbash Meinel
Implement _bisect_recursive, which uses multiple bisect calls to
2073
2074
        self.assertEqual(expected, result)
2075
2255.3.2 by John Arbash Meinel
(broken) some basic work on adding bisect functionality to dirstate.
2076
    def test_bisect_each(self):
2077
        """Find a single record using bisect."""
2255.2.125 by John Arbash Meinel
Initial effort at adding a basic _bisect function to DirState.
2078
        tree, state, expected = self.create_basic_dirstate()
2255.3.2 by John Arbash Meinel
(broken) some basic work on adding bisect functionality to dirstate.
2079
2080
        # 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
2081
        self.assertBisect(expected, [['']], state, [''])
2082
        self.assertBisect(expected, [['a']], state, ['a'])
2083
        self.assertBisect(expected, [['b']], state, ['b'])
2084
        self.assertBisect(expected, [['b/c']], state, ['b/c'])
2085
        self.assertBisect(expected, [['b/d']], state, ['b/d'])
2086
        self.assertBisect(expected, [['b/d/e']], state, ['b/d/e'])
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
2087
        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
2088
        self.assertBisect(expected, [['f']], state, ['f'])
2255.2.125 by John Arbash Meinel
Initial effort at adding a basic _bisect function to DirState.
2089
2090
    def test_bisect_multi(self):
2091
        """Bisect can be used to find multiple records at the same time."""
2092
        tree, state, expected = self.create_basic_dirstate()
2093
        # 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
2094
        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
2095
                          state, ['a', 'b', 'f'])
2255.2.131 by John Arbash Meinel
Change the return values for bisect functions so they just return
2096
        self.assertBisect(expected, [['f'], ['b/d'], ['b/d/e']],
2474.1.61 by John Arbash Meinel
Finish fixing DirState._bisect and the bisect tests
2097
                          state, ['f', 'b/d', 'b/d/e'])
2098
        self.assertBisect(expected, [['b'], ['b-c'], ['b/c']],
2099
                          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
2100
2101
    def test_bisect_one_page(self):
2102
        """Test bisect when there is only 1 page to read"""
2103
        tree, state, expected = self.create_basic_dirstate()
2104
        state._bisect_page_size = 5000
2255.2.131 by John Arbash Meinel
Change the return values for bisect functions so they just return
2105
        self.assertBisect(expected,[['']], state, [''])
2106
        self.assertBisect(expected,[['a']], state, ['a'])
2107
        self.assertBisect(expected,[['b']], state, ['b'])
2108
        self.assertBisect(expected,[['b/c']], state, ['b/c'])
2109
        self.assertBisect(expected,[['b/d']], state, ['b/d'])
2110
        self.assertBisect(expected,[['b/d/e']], state, ['b/d/e'])
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
2111
        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
2112
        self.assertBisect(expected,[['f']], state, ['f'])
2113
        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
2114
                          state, ['a', 'b', 'f'])
2474.1.61 by John Arbash Meinel
Finish fixing DirState._bisect and the bisect tests
2115
        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
2116
                          state, ['b/d', 'b/d/e', 'f'])
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
2117
        self.assertBisect(expected, [['b'], ['b/c'], ['b-c']],
2118
                          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
2119
2120
    def test_bisect_duplicate_paths(self):
2121
        """When bisecting for a path, handle multiple entries."""
2122
        tree, state, expected = self.create_duplicated_dirstate()
2123
2124
        # 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
2125
        self.assertBisect(expected, [['']], state, [''])
2126
        self.assertBisect(expected, [['a', 'a2']], state, ['a'])
2127
        self.assertBisect(expected, [['b', 'b2']], state, ['b'])
2128
        self.assertBisect(expected, [['b/c', 'b/c2']], state, ['b/c'])
2129
        self.assertBisect(expected, [['b/d', 'b/d2']], state, ['b/d'])
2130
        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
2131
                          state, ['b/d/e'])
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
2132
        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
2133
        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
2134
2135
    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.
2136
        """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
2137
        tree, state, expected = self.create_basic_dirstate()
2138
        state._bisect_page_size = 50
2255.2.131 by John Arbash Meinel
Change the return values for bisect functions so they just return
2139
        self.assertBisect(expected, [None], state, ['b/e'])
2140
        self.assertBisect(expected, [['a']], state, ['a'])
2141
        self.assertBisect(expected, [['b']], state, ['b'])
2142
        self.assertBisect(expected, [['b/c']], state, ['b/c'])
2143
        self.assertBisect(expected, [['b/d']], state, ['b/d'])
2144
        self.assertBisect(expected, [['b/d/e']], state, ['b/d/e'])
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
2145
        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
2146
        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
2147
2148
    def test_bisect_missing(self):
2149
        """Test that bisect return None if it cannot find a path."""
2150
        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
2151
        self.assertBisect(expected, [None], state, ['foo'])
2152
        self.assertBisect(expected, [None], state, ['b/foo'])
2153
        self.assertBisect(expected, [None], state, ['bar/foo'])
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
2154
        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
2155
2255.2.131 by John Arbash Meinel
Change the return values for bisect functions so they just return
2156
        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
2157
                          state, ['a', 'foo', 'b/d'])
2255.2.127 by John Arbash Meinel
Expand the test suite to cover more cases.
2158
2159
    def test_bisect_rename(self):
2160
        """Check that we find a renamed row."""
2161
        tree, state, expected = self.create_renamed_dirstate()
2162
2163
        # 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
2164
        self.assertBisect(expected, [['a']], state, ['a'])
2165
        self.assertBisect(expected, [['b/g']], state, ['b/g'])
2255.2.132 by John Arbash Meinel
Implement _bisect_recursive, which uses multiple bisect calls to
2166
        self.assertBisect(expected, [['b/d']], state, ['b/d'])
2167
        self.assertBisect(expected, [['h']], state, ['h'])
2168
2169
        # What about b/d/e? shouldn't that also get 2 directory entries?
2170
        self.assertBisect(expected, [['b/d/e']], state, ['b/d/e'])
2171
        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.
2172
2173
    def test_bisect_dirblocks(self):
2174
        tree, state, expected = self.create_duplicated_dirstate()
2175
        self.assertBisectDirBlocks(expected,
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
2176
            [['', 'a', 'a2', 'b', 'b2', 'b-c', 'b-c2', 'f', 'f2']],
2177
            state, [''])
2255.2.130 by John Arbash Meinel
Add a very similar function which grabs everything for a particular directory block.
2178
        self.assertBisectDirBlocks(expected,
2179
            [['b/c', 'b/c2', 'b/d', 'b/d2']], state, ['b'])
2180
        self.assertBisectDirBlocks(expected,
2181
            [['b/d/e', 'b/d/e2']], state, ['b/d'])
2182
        self.assertBisectDirBlocks(expected,
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
2183
            [['', '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.
2184
             ['b/c', 'b/c2', 'b/d', 'b/d2'],
2185
             ['b/d/e', 'b/d/e2'],
2186
            ], state, ['', 'b', 'b/d'])
2187
2188
    def test_bisect_dirblocks_missing(self):
2189
        tree, state, expected = self.create_basic_dirstate()
2190
        self.assertBisectDirBlocks(expected, [['b/d/e'], None],
2191
            state, ['b/d', 'b/e'])
2192
        # Files don't show up in this search
2193
        self.assertBisectDirBlocks(expected, [None], state, ['a'])
2194
        self.assertBisectDirBlocks(expected, [None], state, ['b/c'])
2195
        self.assertBisectDirBlocks(expected, [None], state, ['c'])
2196
        self.assertBisectDirBlocks(expected, [None], state, ['b/d/e'])
2197
        self.assertBisectDirBlocks(expected, [None], state, ['f'])
2255.2.132 by John Arbash Meinel
Implement _bisect_recursive, which uses multiple bisect calls to
2198
2199
    def test_bisect_recursive_each(self):
2200
        tree, state, expected = self.create_basic_dirstate()
2201
        self.assertBisectRecursive(expected, ['a'], state, ['a'])
2202
        self.assertBisectRecursive(expected, ['b/c'], state, ['b/c'])
2203
        self.assertBisectRecursive(expected, ['b/d/e'], state, ['b/d/e'])
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
2204
        self.assertBisectRecursive(expected, ['b-c'], state, ['b-c'])
2255.2.132 by John Arbash Meinel
Implement _bisect_recursive, which uses multiple bisect calls to
2205
        self.assertBisectRecursive(expected, ['b/d', 'b/d/e'],
2206
                                   state, ['b/d'])
2207
        self.assertBisectRecursive(expected, ['b', 'b/c', 'b/d', 'b/d/e'],
2208
                                   state, ['b'])
2474.1.61 by John Arbash Meinel
Finish fixing DirState._bisect and the bisect tests
2209
        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
2210
                                              'b/d', 'b/d/e'],
2211
                                   state, [''])
2212
2213
    def test_bisect_recursive_multiple(self):
2214
        tree, state, expected = self.create_basic_dirstate()
2215
        self.assertBisectRecursive(expected, ['a', 'b/c'], state, ['a', 'b/c'])
2216
        self.assertBisectRecursive(expected, ['b/d', 'b/d/e'],
2217
                                   state, ['b/d', 'b/d/e'])
2218
2219
    def test_bisect_recursive_missing(self):
2220
        tree, state, expected = self.create_basic_dirstate()
2221
        self.assertBisectRecursive(expected, [], state, ['d'])
2222
        self.assertBisectRecursive(expected, [], state, ['b/e'])
2223
        self.assertBisectRecursive(expected, [], state, ['g'])
2224
        self.assertBisectRecursive(expected, ['a'], state, ['a', 'g'])
2225
2226
    def test_bisect_recursive_renamed(self):
2227
        tree, state, expected = self.create_renamed_dirstate()
2228
2229
        # Looking for either renamed item should find the other
2230
        self.assertBisectRecursive(expected, ['a', 'b/g'], state, ['a'])
2231
        self.assertBisectRecursive(expected, ['a', 'b/g'], state, ['b/g'])
2232
        # Looking in the containing directory should find the rename target,
2233
        # and anything in a subdir of the renamed target.
2234
        self.assertBisectRecursive(expected, ['a', 'b', 'b/c', 'b/d',
2235
                                              'b/d/e', 'b/g', 'h', 'h/e'],
2236
                                   state, ['b'])
2237
2255.8.2 by John Arbash Meinel
Add a helper function, which allows us to store keys as plain paths,
2238
2323.5.4 by Martin Pool
Move some dirstate test setup methods into the base class
2239
class TestDirstateValidation(TestCaseWithDirState):
2240
2241
    def test_validate_correct_dirstate(self):
2242
        state = self.create_complex_dirstate()
2243
        state._validate()
2244
        state.unlock()
2245
        # and make sure we can also validate with a read lock
2246
        state.lock_read()
2247
        try:
2248
            state._validate()
2249
        finally:
2250
            state.unlock()
2323.5.6 by Martin Pool
Add some tests and better messages for DirState._validate
2251
2252
    def test_dirblock_not_sorted(self):
2253
        tree, state, expected = self.create_renamed_dirstate()
2254
        state._read_dirblocks_if_needed()
2255
        last_dirblock = state._dirblocks[-1]
2256
        # we're appending to the dirblock, but this name comes before some of
2257
        # the existing names; that's wrong
2258
        last_dirblock[1].append(
2259
            (('h', 'aaaa', 'a-id'),
2260
             [('a', '', 0, False, ''),
2261
              ('a', '', 0, False, '')]))
2262
        e = self.assertRaises(AssertionError,
2263
            state._validate)
2264
        self.assertContainsRe(str(e), 'not sorted')
2265
2266
    def test_dirblock_name_mismatch(self):
2267
        tree, state, expected = self.create_renamed_dirstate()
2268
        state._read_dirblocks_if_needed()
2269
        last_dirblock = state._dirblocks[-1]
2270
        # add an entry with the wrong directory name
2271
        last_dirblock[1].append(
2272
            (('', 'z', 'a-id'),
2273
             [('a', '', 0, False, ''),
2274
              ('a', '', 0, False, '')]))
2275
        e = self.assertRaises(AssertionError,
2276
            state._validate)
2277
        self.assertContainsRe(str(e),
2278
            "doesn't match directory name")
2279
2323.5.7 by Martin Pool
Better DirState._validate and tests for it.
2280
    def test_dirblock_missing_rename(self):
2281
        tree, state, expected = self.create_renamed_dirstate()
2282
        state._read_dirblocks_if_needed()
2283
        last_dirblock = state._dirblocks[-1]
2323.5.6 by Martin Pool
Add some tests and better messages for DirState._validate
2284
        # make another entry for a-id, without a correct 'r' pointer to
2285
        # the real occurrence in the working tree
2323.5.7 by Martin Pool
Better DirState._validate and tests for it.
2286
        last_dirblock[1].append(
2287
            (('h', 'z', 'a-id'),
2288
             [('a', '', 0, False, ''),
2289
              ('a', '', 0, False, '')]))
2290
        e = self.assertRaises(AssertionError,
2291
            state._validate)
2292
        self.assertContainsRe(str(e),
2293
            '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
2294
2645.2.1 by Wouter van Heyst
The DirState fingerprint for tree-references should be an empty string instead of None
2295
2296
class TestDirstateTreeReference(TestCaseWithDirState):
2297
2298
    def test_reference_revision_is_none(self):
2299
        tree = self.make_branch_and_tree('tree', format='dirstate-with-subtree')
2300
        subtree = self.make_branch_and_tree('tree/subtree',
2301
                            format='dirstate-with-subtree')
2302
        subtree.set_root_id('subtree')
2303
        tree.add_reference(subtree)
2304
        tree.add('subtree')
2305
        state = dirstate.DirState.from_tree(tree, 'dirstate')
2306
        key = ('', 'subtree', 'subtree')
2307
        expected = ('', [(key,
2308
            [('t', '', 0, False, 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')])])
2309
2310
        try:
2311
            self.assertEqual(expected, state._find_block(key))
2312
        finally:
2313
            state.unlock()
2984.1.1 by John Arbash Meinel
Fix bug #161131: Correct DirState._discard_merge_parents logic.
2314
2315
2316
class TestDiscardMergeParents(TestCaseWithDirState):
2317
2318
    def test_discard_no_parents(self):
2319
        # This should be a no-op
2320
        state = self.create_empty_dirstate()
2321
        self.addCleanup(state.unlock)
2322
        state._discard_merge_parents()
2323
        state._validate()
2324
2325
    def test_discard_one_parent(self):
2326
        # No-op
2327
        packed_stat = 'AAAAREUHaIpFB2iKAAADAQAtkqUAAIGk'
2328
        root_entry_direntry = ('', '', 'a-root-value'), [
2329
            ('d', '', 0, False, packed_stat),
2330
            ('d', '', 0, False, packed_stat),
2331
            ]
2332
        dirblocks = []
2333
        dirblocks.append(('', [root_entry_direntry]))
2334
        dirblocks.append(('', []))
2335
2336
        state = self.create_empty_dirstate()
2337
        self.addCleanup(state.unlock)
2338
        state._set_data(['parent-id'], dirblocks[:])
2339
        state._validate()
2340
2341
        state._discard_merge_parents()
2342
        state._validate()
2343
        self.assertEqual(dirblocks, state._dirblocks)
2344
2345
    def test_discard_simple(self):
2346
        # No-op
2347
        packed_stat = 'AAAAREUHaIpFB2iKAAADAQAtkqUAAIGk'
2348
        root_entry_direntry = ('', '', 'a-root-value'), [
2349
            ('d', '', 0, False, packed_stat),
2350
            ('d', '', 0, False, packed_stat),
2351
            ('d', '', 0, False, packed_stat),
2352
            ]
2353
        expected_root_entry_direntry = ('', '', 'a-root-value'), [
2354
            ('d', '', 0, False, packed_stat),
2355
            ('d', '', 0, False, packed_stat),
2356
            ]
2357
        dirblocks = []
2358
        dirblocks.append(('', [root_entry_direntry]))
2359
        dirblocks.append(('', []))
2360
2361
        state = self.create_empty_dirstate()
2362
        self.addCleanup(state.unlock)
2363
        state._set_data(['parent-id', 'merged-id'], dirblocks[:])
2364
        state._validate()
2365
2366
        # This should strip of the extra column
2367
        state._discard_merge_parents()
2368
        state._validate()
2369
        expected_dirblocks = [('', [expected_root_entry_direntry]), ('', [])]
2370
        self.assertEqual(expected_dirblocks, state._dirblocks)
2371
2372
    def test_discard_absent(self):
2373
        """If entries are only in a merge, discard should remove the entries"""
2374
        null_stat = dirstate.DirState.NULLSTAT
2375
        present_dir = ('d', '', 0, False, null_stat)
2376
        present_file = ('f', '', 0, False, null_stat)
2377
        absent = dirstate.DirState.NULL_PARENT_DETAILS
2378
        root_key = ('', '', 'a-root-value')
2379
        file_in_root_key = ('', 'file-in-root', 'a-file-id')
2380
        file_in_merged_key = ('', 'file-in-merged', 'b-file-id')
2381
        dirblocks = [('', [(root_key, [present_dir, present_dir, present_dir])]),
2382
                     ('', [(file_in_merged_key,
2383
                            [absent, absent, present_file]),
2384
                           (file_in_root_key,
2385
                            [present_file, present_file, present_file]),
2386
                          ]),
2387
                    ]
2388
2389
        state = self.create_empty_dirstate()
2390
        self.addCleanup(state.unlock)
2391
        state._set_data(['parent-id', 'merged-id'], dirblocks[:])
2392
        state._validate()
2393
2394
        exp_dirblocks = [('', [(root_key, [present_dir, present_dir])]),
2395
                         ('', [(file_in_root_key,
2396
                                [present_file, present_file]),
2397
                              ]),
2398
                        ]
2399
        state._discard_merge_parents()
2400
        state._validate()
2401
        self.assertEqual(exp_dirblocks, state._dirblocks)
2402
2403
    def test_discard_renamed(self):
2404
        null_stat = dirstate.DirState.NULLSTAT
2405
        present_dir = ('d', '', 0, False, null_stat)
2406
        present_file = ('f', '', 0, False, null_stat)
2407
        absent = dirstate.DirState.NULL_PARENT_DETAILS
2408
        root_key = ('', '', 'a-root-value')
2409
        file_in_root_key = ('', 'file-in-root', 'a-file-id')
2410
        # Renamed relative to parent
2411
        file_rename_s_key = ('', 'file-s', 'b-file-id')
2412
        file_rename_t_key = ('', 'file-t', 'b-file-id')
2413
        # And one that is renamed between the parents, but absent in this
2414
        key_in_1 = ('', 'file-in-1', 'c-file-id')
2415
        key_in_2 = ('', 'file-in-2', 'c-file-id')
2416
2417
        dirblocks = [
2418
            ('', [(root_key, [present_dir, present_dir, present_dir])]),
2419
            ('', [(key_in_1,
2420
                   [absent, present_file, ('r', 'file-in-2', 'c-file-id')]),
2421
                  (key_in_2,
2422
                   [absent, ('r', 'file-in-1', 'c-file-id'), present_file]),
2423
                  (file_in_root_key,
2424
                   [present_file, present_file, present_file]),
2425
                  (file_rename_s_key,
2426
                   [('r', 'file-t', 'b-file-id'), absent, present_file]),
2427
                  (file_rename_t_key,
2428
                   [present_file, absent, ('r', 'file-s', 'b-file-id')]),
2429
                 ]),
2430
        ]
2431
        exp_dirblocks = [
2432
            ('', [(root_key, [present_dir, present_dir])]),
2433
            ('', [(key_in_1, [absent, present_file]),
2434
                  (file_in_root_key, [present_file, present_file]),
2435
                  (file_rename_t_key, [present_file, absent]),
2436
                 ]),
2437
        ]
2438
        state = self.create_empty_dirstate()
2439
        self.addCleanup(state.unlock)
2440
        state._set_data(['parent-id', 'merged-id'], dirblocks[:])
2441
        state._validate()
2442
2443
        state._discard_merge_parents()
2444
        state._validate()
2445
        self.assertEqual(exp_dirblocks, state._dirblocks)
2446
2447
    def test_discard_all_subdir(self):
2448
        null_stat = dirstate.DirState.NULLSTAT
2449
        present_dir = ('d', '', 0, False, null_stat)
2450
        present_file = ('f', '', 0, False, null_stat)
2451
        absent = dirstate.DirState.NULL_PARENT_DETAILS
2452
        root_key = ('', '', 'a-root-value')
2453
        subdir_key = ('', 'sub', 'dir-id')
2454
        child1_key = ('sub', 'child1', 'child1-id')
2455
        child2_key = ('sub', 'child2', 'child2-id')
2456
        child3_key = ('sub', 'child3', 'child3-id')
2457
2458
        dirblocks = [
2459
            ('', [(root_key, [present_dir, present_dir, present_dir])]),
2460
            ('', [(subdir_key, [present_dir, present_dir, present_dir])]),
2461
            ('sub', [(child1_key, [absent, absent, present_file]),
2462
                     (child2_key, [absent, absent, present_file]),
2463
                     (child3_key, [absent, absent, present_file]),
2464
                    ]),
2465
        ]
2466
        exp_dirblocks = [
2467
            ('', [(root_key, [present_dir, present_dir])]),
2468
            ('', [(subdir_key, [present_dir, present_dir])]),
2469
            ('sub', []),
2470
        ]
2471
        state = self.create_empty_dirstate()
2472
        self.addCleanup(state.unlock)
2473
        state._set_data(['parent-id', 'merged-id'], dirblocks[:])
2474
        state._validate()
2475
2476
        state._discard_merge_parents()
2477
        state._validate()
2478
        self.assertEqual(exp_dirblocks, state._dirblocks)