~bzr-pqm/bzr/bzr.dev

5557.1.7 by John Arbash Meinel
Merge in the bzr.dev 5582
1
# Copyright (C) 2007-2011 Canonical Ltd
2474.1.7 by John Arbash Meinel
Add some tests for a helper function that lets us
2
#
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2474.1.7 by John Arbash Meinel
Add some tests for a helper function that lets us
16
17
"""Tests for the compiled dirstate helpers."""
18
2474.1.57 by John Arbash Meinel
Move code around to refactor according to our pyrex extension design.
19
import bisect
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
20
import os
3696.5.1 by Robert Collins
Integrate in stat-cache-updates-during-commit with faster iter-changes.
21
import time
2474.1.57 by John Arbash Meinel
Move code around to refactor according to our pyrex extension design.
22
2474.1.7 by John Arbash Meinel
Add some tests for a helper function that lets us
23
from bzrlib import (
2474.1.63 by John Arbash Meinel
Found a small bug in the python version of _read_dirblocks.
24
    dirstate,
3640.2.5 by John Arbash Meinel
Change from using AssertionError to using DirstateCorrupt in a few places
25
    errors,
4132.2.4 by Ian Clatworthy
John's enhancements/fixes to the tests
26
    osutils,
2474.1.7 by John Arbash Meinel
Add some tests for a helper function that lets us
27
    tests,
6169.2.2 by Martin Packman
Merge fix for overflow issues in pack_stat from 2.4
28
    _dirstate_helpers_py,
2474.1.7 by John Arbash Meinel
Add some tests for a helper function that lets us
29
    )
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
30
from bzrlib.tests import (
4241.14.12 by Vincent Ladeuil
Far too many modifications for a single commit, need to restart.
31
    test_dirstate,
5559.2.2 by Martin Pool
Change to using standard load_tests_apply_scenarios.
32
    )
33
from bzrlib.tests.test_osutils import dir_reader_scenarios
34
from bzrlib.tests.scenarios import (
35
    load_tests_apply_scenarios,
36
    multiply_scenarios,
37
    )
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
38
from bzrlib.tests import (
39
    features,
40
    )
5559.2.2 by Martin Pool
Change to using standard load_tests_apply_scenarios.
41
42
43
load_tests = load_tests_apply_scenarios
4241.14.19 by Vincent Ladeuil
Modernize dirstate helpers tests parametrization.
44
45
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
46
compiled_dirstate_helpers_feature = features.ModuleAvailableFeature(
5559.2.2 by Martin Pool
Change to using standard load_tests_apply_scenarios.
47
    'bzrlib._dirstate_helpers_pyx')
48
49
50
# FIXME: we should also parametrize against SHA1Provider !
51
52
ue_scenarios = [('dirstate_Python',
53
    {'update_entry': dirstate.py_update_entry})]
54
if compiled_dirstate_helpers_feature.available():
55
    update_entry = compiled_dirstate_helpers_feature.module.update_entry
56
    ue_scenarios.append(('dirstate_Pyrex', {'update_entry': update_entry}))
57
58
pe_scenarios = [('dirstate_Python',
59
    {'_process_entry': dirstate.ProcessEntryPython})]
60
if compiled_dirstate_helpers_feature.available():
61
    process_entry = compiled_dirstate_helpers_feature.module.ProcessEntryC
62
    pe_scenarios.append(('dirstate_Pyrex', {'_process_entry': process_entry}))
2474.1.7 by John Arbash Meinel
Add some tests for a helper function that lets us
63
6169.2.3 by Martin Packman
Parametrise TestPackStat against both py and pyx implementations
64
helper_scenarios = [('dirstate_Python', {'helpers': _dirstate_helpers_py})]
65
if compiled_dirstate_helpers_feature.available():
66
    helper_scenarios.append(('dirstate_Pyrex',
67
        {'helpers': compiled_dirstate_helpers_feature.module}))
68
2474.1.7 by John Arbash Meinel
Add some tests for a helper function that lets us
69
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
70
class TestBisectPathMixin(object):
2474.1.66 by John Arbash Meinel
Some restructuring.
71
    """Test that _bisect_path_*() returns the expected values.
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
72
2474.1.66 by John Arbash Meinel
Some restructuring.
73
    _bisect_path_* is intended to work like bisect.bisect_*() except it
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
74
    knows it is working on paths that are sorted by ('path', 'to', 'foo')
75
    chunks rather than by raw 'path/to/foo'.
2474.1.68 by John Arbash Meinel
Review feedback from Martin, mostly documentation updates.
76
77
    Test Cases should inherit from this and override ``get_bisect_path`` return
78
    their implementation, and ``get_bisect`` to return the matching
79
    bisect.bisect_* function.
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
80
    """
81
82
    def get_bisect_path(self):
2474.1.66 by John Arbash Meinel
Some restructuring.
83
        """Return an implementation of _bisect_path_*"""
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
84
        raise NotImplementedError
85
86
    def get_bisect(self):
87
        """Return a version of bisect.bisect_*.
88
89
        Also, for the 'exists' check, return the offset to the real values.
90
        For example bisect_left returns the index of an entry, while
91
        bisect_right returns the index *after* an entry
92
93
        :return: (bisect_func, offset)
94
        """
95
        raise NotImplementedError
96
97
    def assertBisect(self, paths, split_paths, path, exists=True):
98
        """Assert that bisect_split works like bisect_left on the split paths.
99
100
        :param paths: A list of path names
101
        :param split_paths: A list of path names that are already split up by directory
102
            ('path/to/foo' => ('path', 'to', 'foo'))
103
        :param path: The path we are indexing.
104
        :param exists: The path should be present, so make sure the
105
            final location actually points to the right value.
106
107
        All other arguments will be passed along.
108
        """
109
        bisect_path = self.get_bisect_path()
110
        self.assertIsInstance(paths, list)
111
        bisect_path_idx = bisect_path(paths, path)
112
        split_path = self.split_for_dirblocks([path])[0]
113
        bisect_func, offset = self.get_bisect()
114
        bisect_split_idx = bisect_func(split_paths, split_path)
115
        self.assertEqual(bisect_split_idx, bisect_path_idx,
116
                         '%s disagreed. %s != %s'
117
                         ' for key %r'
118
                         % (bisect_path.__name__,
119
                            bisect_split_idx, bisect_path_idx, path)
120
                         )
121
        if exists:
122
            self.assertEqual(path, paths[bisect_path_idx+offset])
123
124
    def split_for_dirblocks(self, paths):
125
        dir_split_paths = []
126
        for path in paths:
127
            dirname, basename = os.path.split(path)
128
            dir_split_paths.append((dirname.split('/'), basename))
129
        dir_split_paths.sort()
130
        return dir_split_paths
131
132
    def test_simple(self):
133
        """In the simple case it works just like bisect_left"""
134
        paths = ['', 'a', 'b', 'c', 'd']
135
        split_paths = self.split_for_dirblocks(paths)
136
        for path in paths:
137
            self.assertBisect(paths, split_paths, path, exists=True)
138
        self.assertBisect(paths, split_paths, '_', exists=False)
139
        self.assertBisect(paths, split_paths, 'aa', exists=False)
140
        self.assertBisect(paths, split_paths, 'bb', exists=False)
141
        self.assertBisect(paths, split_paths, 'cc', exists=False)
142
        self.assertBisect(paths, split_paths, 'dd', exists=False)
143
        self.assertBisect(paths, split_paths, 'a/a', exists=False)
144
        self.assertBisect(paths, split_paths, 'b/b', exists=False)
145
        self.assertBisect(paths, split_paths, 'c/c', exists=False)
146
        self.assertBisect(paths, split_paths, 'd/d', exists=False)
147
148
    def test_involved(self):
149
        """This is where bisect_path_* diverges slightly."""
150
        # This is the list of paths and their contents
151
        # a/
152
        #   a/
153
        #     a
154
        #     z
155
        #   a-a/
156
        #     a
157
        #   a-z/
158
        #     z
159
        #   a=a/
160
        #     a
161
        #   a=z/
162
        #     z
163
        #   z/
164
        #     a
165
        #     z
166
        #   z-a
167
        #   z-z
168
        #   z=a
169
        #   z=z
170
        # a-a/
171
        #   a
172
        # a-z/
173
        #   z
174
        # a=a/
175
        #   a
176
        # a=z/
177
        #   z
178
        # This is the exact order that is stored by dirstate
179
        # All children in a directory are mentioned before an children of
180
        # children are mentioned.
181
        # So all the root-directory paths, then all the
182
        # first sub directory, etc.
183
        paths = [# content of '/'
184
                 '', 'a', 'a-a', 'a-z', 'a=a', 'a=z',
185
                 # content of 'a/'
186
                 'a/a', 'a/a-a', 'a/a-z',
187
                 'a/a=a', 'a/a=z',
188
                 'a/z', 'a/z-a', 'a/z-z',
189
                 'a/z=a', 'a/z=z',
190
                 # content of 'a/a/'
191
                 'a/a/a', 'a/a/z',
192
                 # content of 'a/a-a'
193
                 'a/a-a/a',
194
                 # content of 'a/a-z'
195
                 'a/a-z/z',
196
                 # content of 'a/a=a'
197
                 'a/a=a/a',
198
                 # content of 'a/a=z'
199
                 'a/a=z/z',
200
                 # content of 'a/z/'
201
                 'a/z/a', 'a/z/z',
202
                 # content of 'a-a'
203
                 'a-a/a',
204
                 # content of 'a-z'
205
                 'a-z/z',
206
                 # content of 'a=a'
207
                 'a=a/a',
208
                 # content of 'a=z'
209
                 'a=z/z',
210
                ]
211
        split_paths = self.split_for_dirblocks(paths)
212
        sorted_paths = []
213
        for dir_parts, basename in split_paths:
214
            if dir_parts == ['']:
215
                sorted_paths.append(basename)
216
            else:
217
                sorted_paths.append('/'.join(dir_parts + [basename]))
218
219
        self.assertEqual(sorted_paths, paths)
220
221
        for path in paths:
222
            self.assertBisect(paths, split_paths, path, exists=True)
223
224
225
class TestBisectPathLeft(tests.TestCase, TestBisectPathMixin):
4459.2.3 by Vincent Ladeuil
Fix failing benchmarks for dirstate helpers.
226
    """Run all Bisect Path tests against _bisect_path_left."""
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
227
228
    def get_bisect_path(self):
4459.2.2 by Vincent Ladeuil
Use the same method or function names for _dirstate_helpers in pyrex and
229
        from bzrlib._dirstate_helpers_py import _bisect_path_left
230
        return _bisect_path_left
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
231
232
    def get_bisect(self):
233
        return bisect.bisect_left, 0
234
235
236
class TestCompiledBisectPathLeft(TestBisectPathLeft):
4459.2.3 by Vincent Ladeuil
Fix failing benchmarks for dirstate helpers.
237
    """Run all Bisect Path tests against _bisect_path_lect"""
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
238
4913.2.20 by John Arbash Meinel
Change all of the compiled_foo to compiled_foo_feature
239
    _test_needs_features = [compiled_dirstate_helpers_feature]
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
240
241
    def get_bisect_path(self):
4459.2.2 by Vincent Ladeuil
Use the same method or function names for _dirstate_helpers in pyrex and
242
        from bzrlib._dirstate_helpers_pyx import _bisect_path_left
243
        return _bisect_path_left
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
244
245
246
class TestBisectPathRight(tests.TestCase, TestBisectPathMixin):
4459.2.3 by Vincent Ladeuil
Fix failing benchmarks for dirstate helpers.
247
    """Run all Bisect Path tests against _bisect_path_right"""
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
248
249
    def get_bisect_path(self):
4459.2.2 by Vincent Ladeuil
Use the same method or function names for _dirstate_helpers in pyrex and
250
        from bzrlib._dirstate_helpers_py import _bisect_path_right
251
        return _bisect_path_right
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
252
253
    def get_bisect(self):
254
        return bisect.bisect_right, -1
255
256
257
class TestCompiledBisectPathRight(TestBisectPathRight):
4459.2.3 by Vincent Ladeuil
Fix failing benchmarks for dirstate helpers.
258
    """Run all Bisect Path tests against _bisect_path_right"""
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
259
4913.2.20 by John Arbash Meinel
Change all of the compiled_foo to compiled_foo_feature
260
    _test_needs_features = [compiled_dirstate_helpers_feature]
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
261
262
    def get_bisect_path(self):
4459.2.2 by Vincent Ladeuil
Use the same method or function names for _dirstate_helpers in pyrex and
263
        from bzrlib._dirstate_helpers_pyx import _bisect_path_right
264
        return _bisect_path_right
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
265
266
267
class TestBisectDirblock(tests.TestCase):
268
    """Test that bisect_dirblock() returns the expected values.
269
270
    bisect_dirblock is intended to work like bisect.bisect_left() except it
271
    knows it is working on dirblocks and that dirblocks are sorted by ('path',
272
    'to', 'foo') chunks rather than by raw 'path/to/foo'.
2474.1.68 by John Arbash Meinel
Review feedback from Martin, mostly documentation updates.
273
274
    This test is parameterized by calling get_bisect_dirblock(). Child test
275
    cases can override this function to test against a different
276
    implementation.
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
277
    """
278
279
    def get_bisect_dirblock(self):
280
        """Return an implementation of bisect_dirblock"""
4459.2.2 by Vincent Ladeuil
Use the same method or function names for _dirstate_helpers in pyrex and
281
        from bzrlib._dirstate_helpers_py import bisect_dirblock
282
        return bisect_dirblock
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
283
284
    def assertBisect(self, dirblocks, split_dirblocks, path, *args, **kwargs):
285
        """Assert that bisect_split works like bisect_left on the split paths.
286
287
        :param dirblocks: A list of (path, [info]) pairs.
288
        :param split_dirblocks: A list of ((split, path), [info]) pairs.
289
        :param path: The path we are indexing.
290
291
        All other arguments will be passed along.
292
        """
293
        bisect_dirblock = self.get_bisect_dirblock()
294
        self.assertIsInstance(dirblocks, list)
295
        bisect_split_idx = bisect_dirblock(dirblocks, path, *args, **kwargs)
296
        split_dirblock = (path.split('/'), [])
297
        bisect_left_idx = bisect.bisect_left(split_dirblocks, split_dirblock,
298
                                             *args)
299
        self.assertEqual(bisect_left_idx, bisect_split_idx,
300
                         'bisect_split disagreed. %s != %s'
301
                         ' for key %r'
302
                         % (bisect_left_idx, bisect_split_idx, path)
303
                         )
304
305
    def paths_to_dirblocks(self, paths):
306
        """Convert a list of paths into dirblock form.
307
308
        Also, ensure that the paths are in proper sorted order.
309
        """
310
        dirblocks = [(path, []) for path in paths]
311
        split_dirblocks = [(path.split('/'), []) for path in paths]
312
        self.assertEqual(sorted(split_dirblocks), split_dirblocks)
313
        return dirblocks, split_dirblocks
314
315
    def test_simple(self):
316
        """In the simple case it works just like bisect_left"""
317
        paths = ['', 'a', 'b', 'c', 'd']
318
        dirblocks, split_dirblocks = self.paths_to_dirblocks(paths)
319
        for path in paths:
320
            self.assertBisect(dirblocks, split_dirblocks, path)
321
        self.assertBisect(dirblocks, split_dirblocks, '_')
322
        self.assertBisect(dirblocks, split_dirblocks, 'aa')
323
        self.assertBisect(dirblocks, split_dirblocks, 'bb')
324
        self.assertBisect(dirblocks, split_dirblocks, 'cc')
325
        self.assertBisect(dirblocks, split_dirblocks, 'dd')
326
        self.assertBisect(dirblocks, split_dirblocks, 'a/a')
327
        self.assertBisect(dirblocks, split_dirblocks, 'b/b')
328
        self.assertBisect(dirblocks, split_dirblocks, 'c/c')
329
        self.assertBisect(dirblocks, split_dirblocks, 'd/d')
330
331
    def test_involved(self):
332
        """This is where bisect_left diverges slightly."""
333
        paths = ['', 'a',
334
                 'a/a', 'a/a/a', 'a/a/z', 'a/a-a', 'a/a-z',
335
                 'a/z', 'a/z/a', 'a/z/z', 'a/z-a', 'a/z-z',
336
                 'a-a', 'a-z',
337
                 'z', 'z/a/a', 'z/a/z', 'z/a-a', 'z/a-z',
338
                 'z/z', 'z/z/a', 'z/z/z', 'z/z-a', 'z/z-z',
339
                 'z-a', 'z-z',
340
                ]
341
        dirblocks, split_dirblocks = self.paths_to_dirblocks(paths)
342
        for path in paths:
343
            self.assertBisect(dirblocks, split_dirblocks, path)
344
345
    def test_involved_cached(self):
346
        """This is where bisect_left diverges slightly."""
347
        paths = ['', 'a',
348
                 'a/a', 'a/a/a', 'a/a/z', 'a/a-a', 'a/a-z',
349
                 'a/z', 'a/z/a', 'a/z/z', 'a/z-a', 'a/z-z',
350
                 'a-a', 'a-z',
351
                 'z', 'z/a/a', 'z/a/z', 'z/a-a', 'z/a-z',
352
                 'z/z', 'z/z/a', 'z/z/z', 'z/z-a', 'z/z-z',
353
                 'z-a', 'z-z',
354
                ]
355
        cache = {}
356
        dirblocks, split_dirblocks = self.paths_to_dirblocks(paths)
357
        for path in paths:
358
            self.assertBisect(dirblocks, split_dirblocks, path, cache=cache)
359
360
361
class TestCompiledBisectDirblock(TestBisectDirblock):
362
    """Test that bisect_dirblock() returns the expected values.
363
364
    bisect_dirblock is intended to work like bisect.bisect_left() except it
365
    knows it is working on dirblocks and that dirblocks are sorted by ('path',
366
    'to', 'foo') chunks rather than by raw 'path/to/foo'.
367
368
    This runs all the normal tests that TestBisectDirblock did, but uses the
369
    compiled version.
370
    """
371
4913.2.20 by John Arbash Meinel
Change all of the compiled_foo to compiled_foo_feature
372
    _test_needs_features = [compiled_dirstate_helpers_feature]
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
373
374
    def get_bisect_dirblock(self):
4459.2.2 by Vincent Ladeuil
Use the same method or function names for _dirstate_helpers in pyrex and
375
        from bzrlib._dirstate_helpers_pyx import bisect_dirblock
376
        return bisect_dirblock
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
377
378
2474.1.57 by John Arbash Meinel
Move code around to refactor according to our pyrex extension design.
379
class TestCmpByDirs(tests.TestCase):
2474.1.68 by John Arbash Meinel
Review feedback from Martin, mostly documentation updates.
380
    """Test an implementation of cmp_by_dirs()
381
382
    cmp_by_dirs() compares 2 paths by their directory sections, rather than as
383
    plain strings.
384
385
    Child test cases can override ``get_cmp_by_dirs`` to test a specific
386
    implementation.
387
    """
2474.1.57 by John Arbash Meinel
Move code around to refactor according to our pyrex extension design.
388
389
    def get_cmp_by_dirs(self):
390
        """Get a specific implementation of cmp_by_dirs."""
4459.2.2 by Vincent Ladeuil
Use the same method or function names for _dirstate_helpers in pyrex and
391
        from bzrlib._dirstate_helpers_py import cmp_by_dirs
392
        return cmp_by_dirs
2474.1.57 by John Arbash Meinel
Move code around to refactor according to our pyrex extension design.
393
394
    def assertCmpByDirs(self, expected, str1, str2):
395
        """Compare the two strings, in both directions.
396
397
        :param expected: The expected comparison value. -1 means str1 comes
398
            first, 0 means they are equal, 1 means str2 comes first
399
        :param str1: string to compare
400
        :param str2: string to compare
401
        """
402
        cmp_by_dirs = self.get_cmp_by_dirs()
403
        if expected == 0:
404
            self.assertEqual(str1, str2)
405
            self.assertEqual(0, cmp_by_dirs(str1, str2))
406
            self.assertEqual(0, cmp_by_dirs(str2, str1))
407
        elif expected > 0:
408
            self.assertPositive(cmp_by_dirs(str1, str2))
409
            self.assertNegative(cmp_by_dirs(str2, str1))
410
        else:
411
            self.assertNegative(cmp_by_dirs(str1, str2))
412
            self.assertPositive(cmp_by_dirs(str2, str1))
413
414
    def test_cmp_empty(self):
415
        """Compare against the empty string."""
416
        self.assertCmpByDirs(0, '', '')
417
        self.assertCmpByDirs(1, 'a', '')
418
        self.assertCmpByDirs(1, 'ab', '')
419
        self.assertCmpByDirs(1, 'abc', '')
420
        self.assertCmpByDirs(1, 'abcd', '')
421
        self.assertCmpByDirs(1, 'abcde', '')
422
        self.assertCmpByDirs(1, 'abcdef', '')
423
        self.assertCmpByDirs(1, 'abcdefg', '')
424
        self.assertCmpByDirs(1, 'abcdefgh', '')
425
        self.assertCmpByDirs(1, 'abcdefghi', '')
426
        self.assertCmpByDirs(1, 'test/ing/a/path/', '')
427
428
    def test_cmp_same_str(self):
429
        """Compare the same string"""
430
        self.assertCmpByDirs(0, 'a', 'a')
431
        self.assertCmpByDirs(0, 'ab', 'ab')
432
        self.assertCmpByDirs(0, 'abc', 'abc')
433
        self.assertCmpByDirs(0, 'abcd', 'abcd')
434
        self.assertCmpByDirs(0, 'abcde', 'abcde')
435
        self.assertCmpByDirs(0, 'abcdef', 'abcdef')
436
        self.assertCmpByDirs(0, 'abcdefg', 'abcdefg')
437
        self.assertCmpByDirs(0, 'abcdefgh', 'abcdefgh')
438
        self.assertCmpByDirs(0, 'abcdefghi', 'abcdefghi')
439
        self.assertCmpByDirs(0, 'testing a long string', 'testing a long string')
440
        self.assertCmpByDirs(0, 'x'*10000, 'x'*10000)
441
        self.assertCmpByDirs(0, 'a/b', 'a/b')
442
        self.assertCmpByDirs(0, 'a/b/c', 'a/b/c')
443
        self.assertCmpByDirs(0, 'a/b/c/d', 'a/b/c/d')
444
        self.assertCmpByDirs(0, 'a/b/c/d/e', 'a/b/c/d/e')
445
446
    def test_simple_paths(self):
447
        """Compare strings that act like normal string comparison"""
448
        self.assertCmpByDirs(-1, 'a', 'b')
449
        self.assertCmpByDirs(-1, 'aa', 'ab')
450
        self.assertCmpByDirs(-1, 'ab', 'bb')
451
        self.assertCmpByDirs(-1, 'aaa', 'aab')
452
        self.assertCmpByDirs(-1, 'aab', 'abb')
453
        self.assertCmpByDirs(-1, 'abb', 'bbb')
454
        self.assertCmpByDirs(-1, 'aaaa', 'aaab')
455
        self.assertCmpByDirs(-1, 'aaab', 'aabb')
456
        self.assertCmpByDirs(-1, 'aabb', 'abbb')
457
        self.assertCmpByDirs(-1, 'abbb', 'bbbb')
458
        self.assertCmpByDirs(-1, 'aaaaa', 'aaaab')
459
        self.assertCmpByDirs(-1, 'a/a', 'a/b')
460
        self.assertCmpByDirs(-1, 'a/b', 'b/b')
461
        self.assertCmpByDirs(-1, 'a/a/a', 'a/a/b')
462
        self.assertCmpByDirs(-1, 'a/a/b', 'a/b/b')
463
        self.assertCmpByDirs(-1, 'a/b/b', 'b/b/b')
464
        self.assertCmpByDirs(-1, 'a/a/a/a', 'a/a/a/b')
465
        self.assertCmpByDirs(-1, 'a/a/a/b', 'a/a/b/b')
466
        self.assertCmpByDirs(-1, 'a/a/b/b', 'a/b/b/b')
467
        self.assertCmpByDirs(-1, 'a/b/b/b', 'b/b/b/b')
468
        self.assertCmpByDirs(-1, 'a/a/a/a/a', 'a/a/a/a/b')
469
470
    def test_tricky_paths(self):
471
        self.assertCmpByDirs(1, 'ab/cd/ef', 'ab/cc/ef')
472
        self.assertCmpByDirs(1, 'ab/cd/ef', 'ab/c/ef')
473
        self.assertCmpByDirs(-1, 'ab/cd/ef', 'ab/cd-ef')
474
        self.assertCmpByDirs(-1, 'ab/cd', 'ab/cd-')
475
        self.assertCmpByDirs(-1, 'ab/cd', 'ab-cd')
476
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
477
    def test_cmp_unicode_not_allowed(self):
478
        cmp_by_dirs = self.get_cmp_by_dirs()
479
        self.assertRaises(TypeError, cmp_by_dirs, u'Unicode', 'str')
480
        self.assertRaises(TypeError, cmp_by_dirs, 'str', u'Unicode')
481
        self.assertRaises(TypeError, cmp_by_dirs, u'Unicode', u'Unicode')
482
483
    def test_cmp_non_ascii(self):
484
        self.assertCmpByDirs(-1, '\xc2\xb5', '\xc3\xa5') # u'\xb5', u'\xe5'
485
        self.assertCmpByDirs(-1, 'a', '\xc3\xa5') # u'a', u'\xe5'
486
        self.assertCmpByDirs(-1, 'b', '\xc2\xb5') # u'b', u'\xb5'
487
        self.assertCmpByDirs(-1, 'a/b', 'a/\xc3\xa5') # u'a/b', u'a/\xe5'
488
        self.assertCmpByDirs(-1, 'b/a', 'b/\xc2\xb5') # u'b/a', u'b/\xb5'
489
2474.1.57 by John Arbash Meinel
Move code around to refactor according to our pyrex extension design.
490
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
491
class TestCompiledCmpByDirs(TestCmpByDirs):
492
    """Test the pyrex implementation of cmp_by_dirs"""
2474.1.7 by John Arbash Meinel
Add some tests for a helper function that lets us
493
4913.2.20 by John Arbash Meinel
Change all of the compiled_foo to compiled_foo_feature
494
    _test_needs_features = [compiled_dirstate_helpers_feature]
2474.1.7 by John Arbash Meinel
Add some tests for a helper function that lets us
495
2474.1.41 by John Arbash Meinel
Change the name of cmp_dirblock_strings to cmp_by_dirs
496
    def get_cmp_by_dirs(self):
4459.2.2 by Vincent Ladeuil
Use the same method or function names for _dirstate_helpers in pyrex and
497
        from bzrlib._dirstate_helpers_pyx import cmp_by_dirs
498
        return cmp_by_dirs
2474.1.57 by John Arbash Meinel
Move code around to refactor according to our pyrex extension design.
499
500
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
501
class TestCmpPathByDirblock(tests.TestCase):
2474.1.68 by John Arbash Meinel
Review feedback from Martin, mostly documentation updates.
502
    """Test an implementation of _cmp_path_by_dirblock()
503
504
    _cmp_path_by_dirblock() compares two paths using the sort order used by
505
    DirState. All paths in the same directory are sorted together.
506
507
    Child test cases can override ``get_cmp_path_by_dirblock`` to test a specific
508
    implementation.
509
    """
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
510
511
    def get_cmp_path_by_dirblock(self):
2474.1.66 by John Arbash Meinel
Some restructuring.
512
        """Get a specific implementation of _cmp_path_by_dirblock."""
4459.2.2 by Vincent Ladeuil
Use the same method or function names for _dirstate_helpers in pyrex and
513
        from bzrlib._dirstate_helpers_py import _cmp_path_by_dirblock
514
        return _cmp_path_by_dirblock
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
515
516
    def assertCmpPathByDirblock(self, paths):
517
        """Compare all paths and make sure they evaluate to the correct order.
518
519
        This does N^2 comparisons. It is assumed that ``paths`` is properly
520
        sorted list.
521
522
        :param paths: a sorted list of paths to compare
523
        """
524
        # First, make sure the paths being passed in are correct
525
        def _key(p):
526
            dirname, basename = os.path.split(p)
527
            return dirname.split('/'), basename
528
        self.assertEqual(sorted(paths, key=_key), paths)
529
530
        cmp_path_by_dirblock = self.get_cmp_path_by_dirblock()
531
        for idx1, path1 in enumerate(paths):
532
            for idx2, path2 in enumerate(paths):
533
                cmp_val = cmp_path_by_dirblock(path1, path2)
534
                if idx1 < idx2:
535
                    self.assertTrue(cmp_val < 0,
536
                        '%s did not state that %r came before %r, cmp=%s'
537
                        % (cmp_path_by_dirblock.__name__,
538
                           path1, path2, cmp_val))
539
                elif idx1 > idx2:
540
                    self.assertTrue(cmp_val > 0,
541
                        '%s did not state that %r came after %r, cmp=%s'
542
                        % (cmp_path_by_dirblock.__name__,
543
                           path1, path2, cmp_val))
544
                else: # idx1 == idx2
545
                    self.assertTrue(cmp_val == 0,
546
                        '%s did not state that %r == %r, cmp=%s'
547
                        % (cmp_path_by_dirblock.__name__,
548
                           path1, path2, cmp_val))
549
550
    def test_cmp_simple_paths(self):
551
        """Compare against the empty string."""
552
        self.assertCmpPathByDirblock(['', 'a', 'ab', 'abc', 'a/b/c', 'b/d/e'])
553
        self.assertCmpPathByDirblock(['kl', 'ab/cd', 'ab/ef', 'gh/ij'])
554
555
    def test_tricky_paths(self):
556
        self.assertCmpPathByDirblock([
557
            # Contents of ''
558
            '', 'a', 'a-a', 'a=a', 'b',
559
            # Contents of 'a'
560
            'a/a', 'a/a-a', 'a/a=a', 'a/b',
561
            # Contents of 'a/a'
562
            'a/a/a', 'a/a/a-a', 'a/a/a=a',
563
            # Contents of 'a/a/a'
564
            'a/a/a/a', 'a/a/a/b',
565
            # Contents of 'a/a/a-a',
566
            'a/a/a-a/a', 'a/a/a-a/b',
567
            # Contents of 'a/a/a=a',
568
            'a/a/a=a/a', 'a/a/a=a/b',
569
            # Contents of 'a/a-a'
570
            'a/a-a/a',
571
            # Contents of 'a/a-a/a'
572
            'a/a-a/a/a', 'a/a-a/a/b',
573
            # Contents of 'a/a=a'
574
            'a/a=a/a',
575
            # Contents of 'a/b'
576
            'a/b/a', 'a/b/b',
577
            # Contents of 'a-a',
578
            'a-a/a', 'a-a/b',
579
            # Contents of 'a=a',
580
            'a=a/a', 'a=a/b',
581
            # Contents of 'b',
582
            'b/a', 'b/b',
583
            ])
584
        self.assertCmpPathByDirblock([
585
                 # content of '/'
586
                 '', 'a', 'a-a', 'a-z', 'a=a', 'a=z',
587
                 # content of 'a/'
588
                 'a/a', 'a/a-a', 'a/a-z',
589
                 'a/a=a', 'a/a=z',
590
                 'a/z', 'a/z-a', 'a/z-z',
591
                 'a/z=a', 'a/z=z',
592
                 # content of 'a/a/'
593
                 'a/a/a', 'a/a/z',
594
                 # content of 'a/a-a'
595
                 'a/a-a/a',
596
                 # content of 'a/a-z'
597
                 'a/a-z/z',
598
                 # content of 'a/a=a'
599
                 'a/a=a/a',
600
                 # content of 'a/a=z'
601
                 'a/a=z/z',
602
                 # content of 'a/z/'
603
                 'a/z/a', 'a/z/z',
604
                 # content of 'a-a'
605
                 'a-a/a',
606
                 # content of 'a-z'
607
                 'a-z/z',
608
                 # content of 'a=a'
609
                 'a=a/a',
610
                 # content of 'a=z'
611
                 'a=z/z',
612
                ])
613
2474.1.70 by John Arbash Meinel
Lot's of fixes from Martin's comments.
614
    def test_unicode_not_allowed(self):
615
        cmp_path_by_dirblock = self.get_cmp_path_by_dirblock()
616
        self.assertRaises(TypeError, cmp_path_by_dirblock, u'Uni', 'str')
617
        self.assertRaises(TypeError, cmp_path_by_dirblock, 'str', u'Uni')
618
        self.assertRaises(TypeError, cmp_path_by_dirblock, u'Uni', u'Uni')
619
        self.assertRaises(TypeError, cmp_path_by_dirblock, u'x/Uni', 'x/str')
620
        self.assertRaises(TypeError, cmp_path_by_dirblock, 'x/str', u'x/Uni')
621
        self.assertRaises(TypeError, cmp_path_by_dirblock, u'x/Uni', u'x/Uni')
622
623
    def test_nonascii(self):
624
        self.assertCmpPathByDirblock([
625
            # content of '/'
626
            '', 'a', '\xc2\xb5', '\xc3\xa5',
627
            # content of 'a'
628
            'a/a', 'a/\xc2\xb5', 'a/\xc3\xa5',
629
            # content of 'a/a'
630
            'a/a/a', 'a/a/\xc2\xb5', 'a/a/\xc3\xa5',
631
            # content of 'a/\xc2\xb5'
632
            'a/\xc2\xb5/a', 'a/\xc2\xb5/\xc2\xb5', 'a/\xc2\xb5/\xc3\xa5',
633
            # content of 'a/\xc3\xa5'
634
            'a/\xc3\xa5/a', 'a/\xc3\xa5/\xc2\xb5', 'a/\xc3\xa5/\xc3\xa5',
635
            # content of '\xc2\xb5'
636
            '\xc2\xb5/a', '\xc2\xb5/\xc2\xb5', '\xc2\xb5/\xc3\xa5',
637
            # content of '\xc2\xe5'
638
            '\xc3\xa5/a', '\xc3\xa5/\xc2\xb5', '\xc3\xa5/\xc3\xa5',
639
            ])
640
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
641
642
class TestCompiledCmpPathByDirblock(TestCmpPathByDirblock):
2474.1.66 by John Arbash Meinel
Some restructuring.
643
    """Test the pyrex implementation of _cmp_path_by_dirblock"""
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
644
4913.2.20 by John Arbash Meinel
Change all of the compiled_foo to compiled_foo_feature
645
    _test_needs_features = [compiled_dirstate_helpers_feature]
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
646
647
    def get_cmp_by_dirs(self):
4459.2.2 by Vincent Ladeuil
Use the same method or function names for _dirstate_helpers in pyrex and
648
        from bzrlib._dirstate_helpers_pyx import _cmp_path_by_dirblock
649
        return _cmp_path_by_dirblock
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
650
651
652
class TestMemRChr(tests.TestCase):
2474.1.66 by John Arbash Meinel
Some restructuring.
653
    """Test memrchr functionality"""
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
654
4913.2.20 by John Arbash Meinel
Change all of the compiled_foo to compiled_foo_feature
655
    _test_needs_features = [compiled_dirstate_helpers_feature]
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
656
657
    def assertMemRChr(self, expected, s, c):
4459.2.1 by Vincent Ladeuil
Use a consistent scheme for naming pyrex source files.
658
        from bzrlib._dirstate_helpers_pyx import _py_memrchr
2474.1.58 by John Arbash Meinel
(broken) Try to properly implement DirState._bisect*
659
        self.assertEqual(expected, _py_memrchr(s, c))
660
661
    def test_missing(self):
662
        self.assertMemRChr(None, '', 'a')
663
        self.assertMemRChr(None, '', 'c')
664
        self.assertMemRChr(None, 'abcdefghijklm', 'q')
665
        self.assertMemRChr(None, 'aaaaaaaaaaaaaaaaaaaaaaa', 'b')
666
667
    def test_single_entry(self):
668
        self.assertMemRChr(0, 'abcdefghijklm', 'a')
669
        self.assertMemRChr(1, 'abcdefghijklm', 'b')
670
        self.assertMemRChr(2, 'abcdefghijklm', 'c')
671
        self.assertMemRChr(10, 'abcdefghijklm', 'k')
672
        self.assertMemRChr(11, 'abcdefghijklm', 'l')
673
        self.assertMemRChr(12, 'abcdefghijklm', 'm')
674
675
    def test_multiple(self):
676
        self.assertMemRChr(10, 'abcdefjklmabcdefghijklm', 'a')
677
        self.assertMemRChr(11, 'abcdefjklmabcdefghijklm', 'b')
678
        self.assertMemRChr(12, 'abcdefjklmabcdefghijklm', 'c')
679
        self.assertMemRChr(20, 'abcdefjklmabcdefghijklm', 'k')
680
        self.assertMemRChr(21, 'abcdefjklmabcdefghijklm', 'l')
681
        self.assertMemRChr(22, 'abcdefjklmabcdefghijklm', 'm')
682
        self.assertMemRChr(22, 'aaaaaaaaaaaaaaaaaaaaaaa', 'a')
683
684
    def test_with_nulls(self):
685
        self.assertMemRChr(10, 'abc\0\0\0jklmabc\0\0\0ghijklm', 'a')
686
        self.assertMemRChr(11, 'abc\0\0\0jklmabc\0\0\0ghijklm', 'b')
687
        self.assertMemRChr(12, 'abc\0\0\0jklmabc\0\0\0ghijklm', 'c')
688
        self.assertMemRChr(20, 'abc\0\0\0jklmabc\0\0\0ghijklm', 'k')
689
        self.assertMemRChr(21, 'abc\0\0\0jklmabc\0\0\0ghijklm', 'l')
690
        self.assertMemRChr(22, 'abc\0\0\0jklmabc\0\0\0ghijklm', 'm')
691
        self.assertMemRChr(22, 'aaa\0\0\0aaaaaaa\0\0\0aaaaaaa', 'a')
692
        self.assertMemRChr(9, '\0\0\0\0\0\0\0\0\0\0', '\0')
2474.1.63 by John Arbash Meinel
Found a small bug in the python version of _read_dirblocks.
693
694
695
class TestReadDirblocks(test_dirstate.TestCaseWithDirState):
2474.1.68 by John Arbash Meinel
Review feedback from Martin, mostly documentation updates.
696
    """Test an implementation of _read_dirblocks()
697
698
    _read_dirblocks() reads in all of the dirblock information from the disk
699
    file.
700
701
    Child test cases can override ``get_read_dirblocks`` to test a specific
702
    implementation.
703
    """
2474.1.63 by John Arbash Meinel
Found a small bug in the python version of _read_dirblocks.
704
5559.2.2 by Martin Pool
Change to using standard load_tests_apply_scenarios.
705
    # inherits scenarios from test_dirstate
706
2474.1.63 by John Arbash Meinel
Found a small bug in the python version of _read_dirblocks.
707
    def get_read_dirblocks(self):
4459.2.2 by Vincent Ladeuil
Use the same method or function names for _dirstate_helpers in pyrex and
708
        from bzrlib._dirstate_helpers_py import _read_dirblocks
709
        return _read_dirblocks
2474.1.63 by John Arbash Meinel
Found a small bug in the python version of _read_dirblocks.
710
711
    def test_smoketest(self):
712
        """Make sure that we can create and read back a simple file."""
713
        tree, state, expected = self.create_basic_dirstate()
714
        del tree
715
        state._read_header_if_needed()
716
        self.assertEqual(dirstate.DirState.NOT_IN_MEMORY,
717
                         state._dirblock_state)
718
        read_dirblocks = self.get_read_dirblocks()
719
        read_dirblocks(state)
720
        self.assertEqual(dirstate.DirState.IN_MEMORY_UNMODIFIED,
721
                         state._dirblock_state)
722
3640.2.1 by John Arbash Meinel
More safety checks around PyString_FromStringAndSize,
723
    def test_trailing_garbage(self):
724
        tree, state, expected = self.create_basic_dirstate()
5278.1.2 by Martin Pool
Don't say 'Linux' except when specifically talking about the kernel
725
        # On Unix, we can write extra data as long as we haven't read yet, but
4789.21.1 by John Arbash Meinel
It seems that on Win32, if you open a file with FILE_SHARE_READ
726
        # on Win32, if you've opened the file with FILE_SHARE_READ, trying to
727
        # open it in append mode will fail.
728
        state.unlock()
3640.2.1 by John Arbash Meinel
More safety checks around PyString_FromStringAndSize,
729
        f = open('dirstate', 'ab')
730
        try:
731
            # Add bogus trailing garbage
732
            f.write('bogus\n')
733
        finally:
734
            f.close()
4789.21.1 by John Arbash Meinel
It seems that on Win32, if you open a file with FILE_SHARE_READ
735
            state.lock_read()
3640.2.5 by John Arbash Meinel
Change from using AssertionError to using DirstateCorrupt in a few places
736
        e = self.assertRaises(errors.DirstateCorrupt,
737
                              state._read_dirblocks_if_needed)
3640.2.1 by John Arbash Meinel
More safety checks around PyString_FromStringAndSize,
738
        # Make sure we mention the bogus characters in the error
739
        self.assertContainsRe(str(e), 'bogus')
740
2474.1.63 by John Arbash Meinel
Found a small bug in the python version of _read_dirblocks.
741
742
class TestCompiledReadDirblocks(TestReadDirblocks):
2474.1.68 by John Arbash Meinel
Review feedback from Martin, mostly documentation updates.
743
    """Test the pyrex implementation of _read_dirblocks"""
2474.1.63 by John Arbash Meinel
Found a small bug in the python version of _read_dirblocks.
744
4913.2.20 by John Arbash Meinel
Change all of the compiled_foo to compiled_foo_feature
745
    _test_needs_features = [compiled_dirstate_helpers_feature]
2474.1.63 by John Arbash Meinel
Found a small bug in the python version of _read_dirblocks.
746
747
    def get_read_dirblocks(self):
4459.2.2 by Vincent Ladeuil
Use the same method or function names for _dirstate_helpers in pyrex and
748
        from bzrlib._dirstate_helpers_pyx import _read_dirblocks
749
        return _read_dirblocks
2474.1.66 by John Arbash Meinel
Some restructuring.
750
751
752
class TestUsingCompiledIfAvailable(tests.TestCase):
753
    """Check that any compiled functions that are available are the default.
754
755
    It is possible to have typos, etc in the import line, such that
4459.2.1 by Vincent Ladeuil
Use a consistent scheme for naming pyrex source files.
756
    _dirstate_helpers_pyx is actually available, but the compiled functions are
2474.1.66 by John Arbash Meinel
Some restructuring.
757
    not being used.
758
    """
759
760
    def test_bisect_dirblock(self):
4913.2.20 by John Arbash Meinel
Change all of the compiled_foo to compiled_foo_feature
761
        if compiled_dirstate_helpers_feature.available():
4459.2.2 by Vincent Ladeuil
Use the same method or function names for _dirstate_helpers in pyrex and
762
            from bzrlib._dirstate_helpers_pyx import bisect_dirblock
2474.1.66 by John Arbash Meinel
Some restructuring.
763
        else:
4459.2.2 by Vincent Ladeuil
Use the same method or function names for _dirstate_helpers in pyrex and
764
            from bzrlib._dirstate_helpers_py import bisect_dirblock
765
        self.assertIs(bisect_dirblock, dirstate.bisect_dirblock)
2474.1.66 by John Arbash Meinel
Some restructuring.
766
767
    def test__bisect_path_left(self):
4913.2.20 by John Arbash Meinel
Change all of the compiled_foo to compiled_foo_feature
768
        if compiled_dirstate_helpers_feature.available():
4459.2.2 by Vincent Ladeuil
Use the same method or function names for _dirstate_helpers in pyrex and
769
            from bzrlib._dirstate_helpers_pyx import _bisect_path_left
2474.1.66 by John Arbash Meinel
Some restructuring.
770
        else:
4459.2.2 by Vincent Ladeuil
Use the same method or function names for _dirstate_helpers in pyrex and
771
            from bzrlib._dirstate_helpers_py import _bisect_path_left
772
        self.assertIs(_bisect_path_left, dirstate._bisect_path_left)
2474.1.66 by John Arbash Meinel
Some restructuring.
773
774
    def test__bisect_path_right(self):
4913.2.20 by John Arbash Meinel
Change all of the compiled_foo to compiled_foo_feature
775
        if compiled_dirstate_helpers_feature.available():
4459.2.2 by Vincent Ladeuil
Use the same method or function names for _dirstate_helpers in pyrex and
776
            from bzrlib._dirstate_helpers_pyx import _bisect_path_right
2474.1.66 by John Arbash Meinel
Some restructuring.
777
        else:
4459.2.2 by Vincent Ladeuil
Use the same method or function names for _dirstate_helpers in pyrex and
778
            from bzrlib._dirstate_helpers_py import _bisect_path_right
779
        self.assertIs(_bisect_path_right, dirstate._bisect_path_right)
2474.1.66 by John Arbash Meinel
Some restructuring.
780
781
    def test_cmp_by_dirs(self):
4913.2.20 by John Arbash Meinel
Change all of the compiled_foo to compiled_foo_feature
782
        if compiled_dirstate_helpers_feature.available():
4459.2.2 by Vincent Ladeuil
Use the same method or function names for _dirstate_helpers in pyrex and
783
            from bzrlib._dirstate_helpers_pyx import cmp_by_dirs
2474.1.66 by John Arbash Meinel
Some restructuring.
784
        else:
4459.2.2 by Vincent Ladeuil
Use the same method or function names for _dirstate_helpers in pyrex and
785
            from bzrlib._dirstate_helpers_py import cmp_by_dirs
786
        self.assertIs(cmp_by_dirs, dirstate.cmp_by_dirs)
2474.1.66 by John Arbash Meinel
Some restructuring.
787
788
    def test__read_dirblocks(self):
4913.2.20 by John Arbash Meinel
Change all of the compiled_foo to compiled_foo_feature
789
        if compiled_dirstate_helpers_feature.available():
4459.2.2 by Vincent Ladeuil
Use the same method or function names for _dirstate_helpers in pyrex and
790
            from bzrlib._dirstate_helpers_pyx import _read_dirblocks
2474.1.66 by John Arbash Meinel
Some restructuring.
791
        else:
4459.2.2 by Vincent Ladeuil
Use the same method or function names for _dirstate_helpers in pyrex and
792
            from bzrlib._dirstate_helpers_py import _read_dirblocks
793
        self.assertIs(_read_dirblocks, dirstate._read_dirblocks)
2474.1.66 by John Arbash Meinel
Some restructuring.
794
3696.4.11 by Robert Collins
Some Cification of iter_changes, and making the python one actually work.
795
    def test_update_entry(self):
4913.2.20 by John Arbash Meinel
Change all of the compiled_foo to compiled_foo_feature
796
        if compiled_dirstate_helpers_feature.available():
4459.2.1 by Vincent Ladeuil
Use a consistent scheme for naming pyrex source files.
797
            from bzrlib._dirstate_helpers_pyx import update_entry
3696.4.11 by Robert Collins
Some Cification of iter_changes, and making the python one actually work.
798
        else:
4459.2.2 by Vincent Ladeuil
Use the same method or function names for _dirstate_helpers in pyrex and
799
            from bzrlib.dirstate import update_entry
800
        self.assertIs(update_entry, dirstate.update_entry)
3696.4.11 by Robert Collins
Some Cification of iter_changes, and making the python one actually work.
801
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
802
    def test_process_entry(self):
4913.2.20 by John Arbash Meinel
Change all of the compiled_foo to compiled_foo_feature
803
        if compiled_dirstate_helpers_feature.available():
4459.2.1 by Vincent Ladeuil
Use a consistent scheme for naming pyrex source files.
804
            from bzrlib._dirstate_helpers_pyx import ProcessEntryC
3696.4.5 by Robert Collins
Simple 'compiled with pyrex' ProcessEntry class. faster.
805
            self.assertIs(ProcessEntryC, dirstate._process_entry)
806
        else:
807
            from bzrlib.dirstate import ProcessEntryPython
808
            self.assertIs(ProcessEntryPython, dirstate._process_entry)
809
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
810
811
class TestUpdateEntry(test_dirstate.TestCaseWithDirState):
812
    """Test the DirState.update_entry functions"""
813
5559.2.2 by Martin Pool
Change to using standard load_tests_apply_scenarios.
814
    scenarios = multiply_scenarios(
815
        dir_reader_scenarios(), ue_scenarios)
816
4241.14.19 by Vincent Ladeuil
Modernize dirstate helpers tests parametrization.
817
    # Set by load_tests
818
    update_entry = None
819
820
    def setUp(self):
821
        super(TestUpdateEntry, self).setUp()
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
822
        self.overrideAttr(dirstate, 'update_entry', self.update_entry)
4241.14.19 by Vincent Ladeuil
Modernize dirstate helpers tests parametrization.
823
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
824
    def get_state_with_a(self):
825
        """Create a DirState tracking a single object named 'a'"""
826
        state = test_dirstate.InstrumentedDirState.initialize('dirstate')
827
        self.addCleanup(state.unlock)
828
        state.add('a', 'a-id', 'file', None, '')
829
        entry = state._get_entry(0, path_utf8='a')
830
        return state, entry
831
3696.5.1 by Robert Collins
Integrate in stat-cache-updates-during-commit with faster iter-changes.
832
    def test_observed_sha1_cachable(self):
833
        state, entry = self.get_state_with_a()
5807.4.4 by John Arbash Meinel
Assert the transition from _observed_sha1.
834
        state.save()
3696.5.1 by Robert Collins
Integrate in stat-cache-updates-during-commit with faster iter-changes.
835
        atime = time.time() - 10
836
        self.build_tree(['a'])
5807.4.4 by John Arbash Meinel
Assert the transition from _observed_sha1.
837
        statvalue = test_dirstate._FakeStat.from_stat(os.lstat('a'))
838
        statvalue.st_mtime = statvalue.st_ctime = atime
839
        self.assertEqual(dirstate.DirState.IN_MEMORY_UNMODIFIED,
840
                         state._dirblock_state)
3696.5.1 by Robert Collins
Integrate in stat-cache-updates-during-commit with faster iter-changes.
841
        state._observed_sha1(entry, "foo", statvalue)
842
        self.assertEqual('foo', entry[1][0][1])
843
        packed_stat = dirstate.pack_stat(statvalue)
844
        self.assertEqual(packed_stat, entry[1][0][4])
5807.4.4 by John Arbash Meinel
Assert the transition from _observed_sha1.
845
        self.assertEqual(dirstate.DirState.IN_MEMORY_HASH_MODIFIED,
846
                         state._dirblock_state)
3696.5.1 by Robert Collins
Integrate in stat-cache-updates-during-commit with faster iter-changes.
847
848
    def test_observed_sha1_not_cachable(self):
849
        state, entry = self.get_state_with_a()
5807.4.4 by John Arbash Meinel
Assert the transition from _observed_sha1.
850
        state.save()
3696.5.1 by Robert Collins
Integrate in stat-cache-updates-during-commit with faster iter-changes.
851
        oldval = entry[1][0][1]
852
        oldstat = entry[1][0][4]
853
        self.build_tree(['a'])
854
        statvalue = os.lstat('a')
5807.4.4 by John Arbash Meinel
Assert the transition from _observed_sha1.
855
        self.assertEqual(dirstate.DirState.IN_MEMORY_UNMODIFIED,
856
                         state._dirblock_state)
3696.5.1 by Robert Collins
Integrate in stat-cache-updates-during-commit with faster iter-changes.
857
        state._observed_sha1(entry, "foo", statvalue)
858
        self.assertEqual(oldval, entry[1][0][1])
859
        self.assertEqual(oldstat, entry[1][0][4])
5807.4.4 by John Arbash Meinel
Assert the transition from _observed_sha1.
860
        self.assertEqual(dirstate.DirState.IN_MEMORY_UNMODIFIED,
861
                         state._dirblock_state)
3696.5.1 by Robert Collins
Integrate in stat-cache-updates-during-commit with faster iter-changes.
862
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
863
    def test_update_entry(self):
3696.5.2 by Robert Collins
Integrate less aggressive sha logic with C iter-changes.
864
        state, _ = self.get_state_with_a()
865
        tree = self.make_branch_and_tree('tree')
866
        tree.lock_write()
867
        empty_revid = tree.commit('empty')
868
        self.build_tree(['tree/a'])
869
        tree.add(['a'], ['a-id'])
870
        with_a_id = tree.commit('with_a')
871
        self.addCleanup(tree.unlock)
872
        state.set_parent_trees(
873
            [(empty_revid, tree.branch.repository.revision_tree(empty_revid))],
874
            [])
875
        entry = state._get_entry(0, path_utf8='a')
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
876
        self.build_tree(['a'])
877
        # Add one where we don't provide the stat or sha already
878
        self.assertEqual(('', 'a', 'a-id'), entry[0])
3696.5.2 by Robert Collins
Integrate less aggressive sha logic with C iter-changes.
879
        self.assertEqual(('f', '', 0, False, dirstate.DirState.NULLSTAT),
880
                         entry[1][0])
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
881
        # Flush the buffers to disk
882
        state.save()
883
        self.assertEqual(dirstate.DirState.IN_MEMORY_UNMODIFIED,
884
                         state._dirblock_state)
885
886
        stat_value = os.lstat('a')
887
        packed_stat = dirstate.pack_stat(stat_value)
888
        link_or_sha1 = self.update_entry(state, entry, abspath='a',
889
                                          stat_value=stat_value)
3696.5.2 by Robert Collins
Integrate less aggressive sha logic with C iter-changes.
890
        self.assertEqual(None, link_or_sha1)
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
891
5802.3.1 by John Arbash Meinel
Fix bug #765881. Having a file added on disk was skipping
892
        # The dirblock entry should not have computed or cached the file's
893
        # sha1, but it did update the files' st_size. However, this is not
894
        # worth writing a dirstate file for, so we leave the state UNMODIFIED
3696.5.2 by Robert Collins
Integrate less aggressive sha logic with C iter-changes.
895
        self.assertEqual(('f', '', 14, False, dirstate.DirState.NULLSTAT),
896
                         entry[1][0])
5802.3.1 by John Arbash Meinel
Fix bug #765881. Having a file added on disk was skipping
897
        self.assertEqual(dirstate.DirState.IN_MEMORY_UNMODIFIED,
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
898
                         state._dirblock_state)
899
        mode = stat_value.st_mode
3696.5.2 by Robert Collins
Integrate less aggressive sha logic with C iter-changes.
900
        self.assertEqual([('is_exec', mode, False)], state._log)
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
901
902
        state.save()
903
        self.assertEqual(dirstate.DirState.IN_MEMORY_UNMODIFIED,
904
                         state._dirblock_state)
905
5802.3.1 by John Arbash Meinel
Fix bug #765881. Having a file added on disk was skipping
906
        # Roll the clock back so the file is guaranteed to look too new. We
907
        # should still not compute the sha1.
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
908
        state.adjust_time(-10)
3696.5.2 by Robert Collins
Integrate less aggressive sha logic with C iter-changes.
909
        del state._log[:]
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
910
911
        link_or_sha1 = self.update_entry(state, entry, abspath='a',
912
                                          stat_value=stat_value)
3696.5.2 by Robert Collins
Integrate less aggressive sha logic with C iter-changes.
913
        self.assertEqual([('is_exec', mode, False)], state._log)
914
        self.assertEqual(None, link_or_sha1)
5802.3.1 by John Arbash Meinel
Fix bug #765881. Having a file added on disk was skipping
915
        self.assertEqual(dirstate.DirState.IN_MEMORY_UNMODIFIED,
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
916
                         state._dirblock_state)
3696.5.2 by Robert Collins
Integrate less aggressive sha logic with C iter-changes.
917
        self.assertEqual(('f', '', 14, False, dirstate.DirState.NULLSTAT),
918
                         entry[1][0])
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
919
        state.save()
920
3696.5.2 by Robert Collins
Integrate less aggressive sha logic with C iter-changes.
921
        # If it is cachable (the clock has moved forward) but new it still
922
        # won't calculate the sha or cache it.
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
923
        state.adjust_time(+20)
3696.5.2 by Robert Collins
Integrate less aggressive sha logic with C iter-changes.
924
        del state._log[:]
925
        link_or_sha1 = dirstate.update_entry(state, entry, abspath='a',
926
                                          stat_value=stat_value)
927
        self.assertEqual(None, link_or_sha1)
928
        self.assertEqual([('is_exec', mode, False)], state._log)
929
        self.assertEqual(('f', '', 14, False, dirstate.DirState.NULLSTAT),
930
                         entry[1][0])
5802.3.1 by John Arbash Meinel
Fix bug #765881. Having a file added on disk was skipping
931
        self.assertEqual(dirstate.DirState.IN_MEMORY_UNMODIFIED,
932
                         state._dirblock_state)
3696.5.2 by Robert Collins
Integrate less aggressive sha logic with C iter-changes.
933
934
        # If the file is no longer new, and the clock has been moved forward
935
        # sufficiently, it will cache the sha.
936
        del state._log[:]
937
        state.set_parent_trees(
938
            [(with_a_id, tree.branch.repository.revision_tree(with_a_id))],
939
            [])
940
        entry = state._get_entry(0, path_utf8='a')
941
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
942
        link_or_sha1 = self.update_entry(state, entry, abspath='a',
943
                                          stat_value=stat_value)
944
        self.assertEqual('b50e5406bb5e153ebbeb20268fcf37c87e1ecfb6',
945
                         link_or_sha1)
3696.5.2 by Robert Collins
Integrate less aggressive sha logic with C iter-changes.
946
        self.assertEqual([('is_exec', mode, False), ('sha1', 'a')],
947
                          state._log)
948
        self.assertEqual(('f', link_or_sha1, 14, False, packed_stat),
949
                         entry[1][0])
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
950
951
        # Subsequent calls will just return the cached value
3696.5.2 by Robert Collins
Integrate less aggressive sha logic with C iter-changes.
952
        del state._log[:]
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
953
        link_or_sha1 = self.update_entry(state, entry, abspath='a',
954
                                          stat_value=stat_value)
955
        self.assertEqual('b50e5406bb5e153ebbeb20268fcf37c87e1ecfb6',
956
                         link_or_sha1)
3696.5.2 by Robert Collins
Integrate less aggressive sha logic with C iter-changes.
957
        self.assertEqual([], state._log)
958
        self.assertEqual(('f', link_or_sha1, 14, False, packed_stat),
959
                         entry[1][0])
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
960
961
    def test_update_entry_symlink(self):
962
        """Update entry should read symlinks."""
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
963
        self.requireFeature(features.SymlinkFeature)
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
964
        state, entry = self.get_state_with_a()
965
        state.save()
966
        self.assertEqual(dirstate.DirState.IN_MEMORY_UNMODIFIED,
967
                         state._dirblock_state)
968
        os.symlink('target', 'a')
969
970
        state.adjust_time(-10) # Make the symlink look new
971
        stat_value = os.lstat('a')
972
        packed_stat = dirstate.pack_stat(stat_value)
973
        link_or_sha1 = self.update_entry(state, entry, abspath='a',
974
                                          stat_value=stat_value)
975
        self.assertEqual('target', link_or_sha1)
976
        self.assertEqual([('read_link', 'a', '')], state._log)
977
        # Dirblock is not updated (the link is too new)
978
        self.assertEqual([('l', '', 6, False, dirstate.DirState.NULLSTAT)],
979
                         entry[1])
5807.4.6 by John Arbash Meinel
Merge newer bzr.dev and resolve conflicts.
980
        # The file entry turned into a symlink, that is considered
981
        # HASH modified worthy.
5807.4.3 by John Arbash Meinel
Get the test suite to run clean for bt.test_dirstate bt.test__dirstate bt.test_workingtree
982
        self.assertEqual(dirstate.DirState.IN_MEMORY_HASH_MODIFIED,
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
983
                         state._dirblock_state)
984
985
        # Because the stat_value looks new, we should re-read the target
5807.4.6 by John Arbash Meinel
Merge newer bzr.dev and resolve conflicts.
986
        del state._log[:]
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
987
        link_or_sha1 = self.update_entry(state, entry, abspath='a',
988
                                          stat_value=stat_value)
989
        self.assertEqual('target', link_or_sha1)
5807.4.6 by John Arbash Meinel
Merge newer bzr.dev and resolve conflicts.
990
        self.assertEqual([('read_link', 'a', '')], state._log)
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
991
        self.assertEqual([('l', '', 6, False, dirstate.DirState.NULLSTAT)],
992
                         entry[1])
5807.4.6 by John Arbash Meinel
Merge newer bzr.dev and resolve conflicts.
993
        state.save()
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
994
        state.adjust_time(+20) # Skip into the future, all files look old
5807.4.6 by John Arbash Meinel
Merge newer bzr.dev and resolve conflicts.
995
        del state._log[:]
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
996
        link_or_sha1 = self.update_entry(state, entry, abspath='a',
997
                                          stat_value=stat_value)
5807.4.6 by John Arbash Meinel
Merge newer bzr.dev and resolve conflicts.
998
        # The symlink stayed a symlink. So while it is new enough to cache, we
999
        # don't bother setting the flag, because it is not really worth saving
1000
        # (when we stat the symlink, we'll have paged in the target.)
1001
        self.assertEqual(dirstate.DirState.IN_MEMORY_UNMODIFIED,
1002
                         state._dirblock_state)
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
1003
        self.assertEqual('target', link_or_sha1)
1004
        # We need to re-read the link because only now can we cache it
5807.4.6 by John Arbash Meinel
Merge newer bzr.dev and resolve conflicts.
1005
        self.assertEqual([('read_link', 'a', '')], state._log)
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
1006
        self.assertEqual([('l', 'target', 6, False, packed_stat)],
1007
                         entry[1])
1008
5807.4.6 by John Arbash Meinel
Merge newer bzr.dev and resolve conflicts.
1009
        del state._log[:]
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
1010
        # Another call won't re-read the link
5807.4.6 by John Arbash Meinel
Merge newer bzr.dev and resolve conflicts.
1011
        self.assertEqual([], state._log)
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
1012
        link_or_sha1 = self.update_entry(state, entry, abspath='a',
1013
                                          stat_value=stat_value)
1014
        self.assertEqual('target', link_or_sha1)
1015
        self.assertEqual([('l', 'target', 6, False, packed_stat)],
1016
                         entry[1])
1017
1018
    def do_update_entry(self, state, entry, abspath):
1019
        stat_value = os.lstat(abspath)
1020
        return self.update_entry(state, entry, abspath, stat_value)
1021
1022
    def test_update_entry_dir(self):
1023
        state, entry = self.get_state_with_a()
1024
        self.build_tree(['a/'])
1025
        self.assertIs(None, self.do_update_entry(state, entry, 'a'))
1026
1027
    def test_update_entry_dir_unchanged(self):
1028
        state, entry = self.get_state_with_a()
1029
        self.build_tree(['a/'])
1030
        state.adjust_time(+20)
1031
        self.assertIs(None, self.do_update_entry(state, entry, 'a'))
5802.3.1 by John Arbash Meinel
Fix bug #765881. Having a file added on disk was skipping
1032
        # a/ used to be a file, but is now a directory, worth saving
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
1033
        self.assertEqual(dirstate.DirState.IN_MEMORY_MODIFIED,
1034
                         state._dirblock_state)
1035
        state.save()
1036
        self.assertEqual(dirstate.DirState.IN_MEMORY_UNMODIFIED,
1037
                         state._dirblock_state)
5802.3.1 by John Arbash Meinel
Fix bug #765881. Having a file added on disk was skipping
1038
        # No changes to a/ means not worth saving.
1039
        self.assertIs(None, self.do_update_entry(state, entry, 'a'))
1040
        self.assertEqual(dirstate.DirState.IN_MEMORY_UNMODIFIED,
1041
                         state._dirblock_state)
1042
        # Change the last-modified time for the directory
1043
        t = time.time() - 100.0
5813.2.1 by John Arbash Meinel
On babune, the test fails because we can't set mtime on a dir.
1044
        try:
1045
            os.utime('a', (t, t))
1046
        except OSError:
1047
            # It looks like Win32 + FAT doesn't allow to change times on a dir.
1048
            raise tests.TestSkipped("can't update mtime of a dir on FAT")
5802.3.1 by John Arbash Meinel
Fix bug #765881. Having a file added on disk was skipping
1049
        saved_packed_stat = entry[1][0][-1]
1050
        self.assertIs(None, self.do_update_entry(state, entry, 'a'))
1051
        # We *do* go ahead and update the information in the dirblocks, but we
1052
        # don't bother setting IN_MEMORY_MODIFIED because it is trivial to
1053
        # recompute.
1054
        self.assertNotEqual(saved_packed_stat, entry[1][0][-1])
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
1055
        self.assertEqual(dirstate.DirState.IN_MEMORY_UNMODIFIED,
1056
                         state._dirblock_state)
1057
1058
    def test_update_entry_file_unchanged(self):
3696.5.2 by Robert Collins
Integrate less aggressive sha logic with C iter-changes.
1059
        state, _ = self.get_state_with_a()
1060
        tree = self.make_branch_and_tree('tree')
1061
        tree.lock_write()
1062
        self.build_tree(['tree/a'])
1063
        tree.add(['a'], ['a-id'])
1064
        with_a_id = tree.commit('witha')
1065
        self.addCleanup(tree.unlock)
1066
        state.set_parent_trees(
1067
            [(with_a_id, tree.branch.repository.revision_tree(with_a_id))],
1068
            [])
1069
        entry = state._get_entry(0, path_utf8='a')
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
1070
        self.build_tree(['a'])
1071
        sha1sum = 'b50e5406bb5e153ebbeb20268fcf37c87e1ecfb6'
1072
        state.adjust_time(+20)
1073
        self.assertEqual(sha1sum, self.do_update_entry(state, entry, 'a'))
1074
        self.assertEqual(dirstate.DirState.IN_MEMORY_MODIFIED,
1075
                         state._dirblock_state)
1076
        state.save()
1077
        self.assertEqual(dirstate.DirState.IN_MEMORY_UNMODIFIED,
1078
                         state._dirblock_state)
1079
        self.assertEqual(sha1sum, self.do_update_entry(state, entry, 'a'))
1080
        self.assertEqual(dirstate.DirState.IN_MEMORY_UNMODIFIED,
1081
                         state._dirblock_state)
1082
4100.2.6 by Aaron Bentley
Add tests for update_entry with tree references
1083
    def test_update_entry_tree_reference(self):
1084
        state = test_dirstate.InstrumentedDirState.initialize('dirstate')
1085
        self.addCleanup(state.unlock)
1086
        state.add('r', 'r-id', 'tree-reference', None, '')
1087
        self.build_tree(['r/'])
1088
        entry = state._get_entry(0, path_utf8='r')
1089
        self.do_update_entry(state, entry, 'r')
1090
        entry = state._get_entry(0, path_utf8='r')
1091
        self.assertEqual('t', entry[1][0][0])
1092
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
1093
    def create_and_test_file(self, state, entry):
3696.5.2 by Robert Collins
Integrate less aggressive sha logic with C iter-changes.
1094
        """Create a file at 'a' and verify the state finds it during update.
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
1095
1096
        The state should already be versioning *something* at 'a'. This makes
1097
        sure that state.update_entry recognizes it as a file.
1098
        """
1099
        self.build_tree(['a'])
1100
        stat_value = os.lstat('a')
1101
        packed_stat = dirstate.pack_stat(stat_value)
1102
1103
        link_or_sha1 = self.do_update_entry(state, entry, abspath='a')
3696.5.2 by Robert Collins
Integrate less aggressive sha logic with C iter-changes.
1104
        self.assertEqual(None, link_or_sha1)
1105
        self.assertEqual([('f', '', 14, False, dirstate.DirState.NULLSTAT)],
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
1106
                         entry[1])
1107
        return packed_stat
1108
1109
    def create_and_test_dir(self, state, entry):
1110
        """Create a directory at 'a' and verify the state finds it.
1111
1112
        The state should already be versioning *something* at 'a'. This makes
1113
        sure that state.update_entry recognizes it as a directory.
1114
        """
1115
        self.build_tree(['a/'])
1116
        stat_value = os.lstat('a')
1117
        packed_stat = dirstate.pack_stat(stat_value)
1118
1119
        link_or_sha1 = self.do_update_entry(state, entry, abspath='a')
1120
        self.assertIs(None, link_or_sha1)
1121
        self.assertEqual([('d', '', 0, False, packed_stat)], entry[1])
1122
1123
        return packed_stat
1124
4241.14.19 by Vincent Ladeuil
Modernize dirstate helpers tests parametrization.
1125
    # FIXME: Add unicode version
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
1126
    def create_and_test_symlink(self, state, entry):
1127
        """Create a symlink at 'a' and verify the state finds it.
1128
1129
        The state should already be versioning *something* at 'a'. This makes
1130
        sure that state.update_entry recognizes it as a symlink.
1131
1132
        This should not be called if this platform does not have symlink
1133
        support.
1134
        """
1135
        # caller should care about skipping test on platforms without symlinks
1136
        os.symlink('path/to/foo', 'a')
1137
1138
        stat_value = os.lstat('a')
1139
        packed_stat = dirstate.pack_stat(stat_value)
1140
1141
        link_or_sha1 = self.do_update_entry(state, entry, abspath='a')
1142
        self.assertEqual('path/to/foo', link_or_sha1)
1143
        self.assertEqual([('l', 'path/to/foo', 11, False, packed_stat)],
1144
                         entry[1])
1145
        return packed_stat
1146
1147
    def test_update_file_to_dir(self):
1148
        """If a file changes to a directory we return None for the sha.
1149
        We also update the inventory record.
1150
        """
1151
        state, entry = self.get_state_with_a()
1152
        # The file sha1 won't be cached unless the file is old
1153
        state.adjust_time(+10)
1154
        self.create_and_test_file(state, entry)
1155
        os.remove('a')
1156
        self.create_and_test_dir(state, entry)
1157
1158
    def test_update_file_to_symlink(self):
1159
        """File becomes a symlink"""
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
1160
        self.requireFeature(features.SymlinkFeature)
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
1161
        state, entry = self.get_state_with_a()
1162
        # The file sha1 won't be cached unless the file is old
1163
        state.adjust_time(+10)
1164
        self.create_and_test_file(state, entry)
1165
        os.remove('a')
1166
        self.create_and_test_symlink(state, entry)
1167
1168
    def test_update_dir_to_file(self):
1169
        """Directory becoming a file updates the entry."""
1170
        state, entry = self.get_state_with_a()
1171
        # The file sha1 won't be cached unless the file is old
1172
        state.adjust_time(+10)
1173
        self.create_and_test_dir(state, entry)
1174
        os.rmdir('a')
1175
        self.create_and_test_file(state, entry)
1176
1177
    def test_update_dir_to_symlink(self):
1178
        """Directory becomes a symlink"""
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
1179
        self.requireFeature(features.SymlinkFeature)
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
1180
        state, entry = self.get_state_with_a()
1181
        # The symlink target won't be cached if it isn't old
1182
        state.adjust_time(+10)
1183
        self.create_and_test_dir(state, entry)
1184
        os.rmdir('a')
1185
        self.create_and_test_symlink(state, entry)
1186
1187
    def test_update_symlink_to_file(self):
1188
        """Symlink becomes a file"""
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
1189
        self.requireFeature(features.SymlinkFeature)
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
1190
        state, entry = self.get_state_with_a()
1191
        # The symlink and file info won't be cached unless old
1192
        state.adjust_time(+10)
1193
        self.create_and_test_symlink(state, entry)
1194
        os.remove('a')
1195
        self.create_and_test_file(state, entry)
1196
1197
    def test_update_symlink_to_dir(self):
1198
        """Symlink becomes a directory"""
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
1199
        self.requireFeature(features.SymlinkFeature)
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
1200
        state, entry = self.get_state_with_a()
1201
        # The symlink target won't be cached if it isn't old
1202
        state.adjust_time(+10)
1203
        self.create_and_test_symlink(state, entry)
1204
        os.remove('a')
1205
        self.create_and_test_dir(state, entry)
1206
1207
    def test__is_executable_win32(self):
1208
        state, entry = self.get_state_with_a()
1209
        self.build_tree(['a'])
1210
1211
        # Make sure we are using the win32 implementation of _is_executable
1212
        state._is_executable = state._is_executable_win32
1213
1214
        # The file on disk is not executable, but we are marking it as though
1215
        # it is. With _is_executable_win32 we ignore what is on disk.
1216
        entry[1][0] = ('f', '', 0, True, dirstate.DirState.NULLSTAT)
1217
1218
        stat_value = os.lstat('a')
1219
        packed_stat = dirstate.pack_stat(stat_value)
1220
1221
        state.adjust_time(-10) # Make sure everything is new
1222
        self.update_entry(state, entry, abspath='a', stat_value=stat_value)
1223
1224
        # The row is updated, but the executable bit stays set.
1225
        self.assertEqual([('f', '', 14, True, dirstate.DirState.NULLSTAT)],
1226
                         entry[1])
1227
4241.14.19 by Vincent Ladeuil
Modernize dirstate helpers tests parametrization.
1228
        # Make the disk object look old enough to cache (but it won't cache the
1229
        # sha as it is a new file).
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
1230
        state.adjust_time(+20)
1231
        digest = 'b50e5406bb5e153ebbeb20268fcf37c87e1ecfb6'
1232
        self.update_entry(state, entry, abspath='a', stat_value=stat_value)
3696.5.2 by Robert Collins
Integrate less aggressive sha logic with C iter-changes.
1233
        self.assertEqual([('f', '', 14, True, dirstate.DirState.NULLSTAT)],
1234
            entry[1])
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
1235
4132.2.4 by Ian Clatworthy
John's enhancements/fixes to the tests
1236
    def _prepare_tree(self):
1237
        # Create a tree
1238
        text = 'Hello World\n'
1239
        tree = self.make_branch_and_tree('tree')
1240
        self.build_tree_contents([('tree/a file', text)])
1241
        tree.add('a file', 'a-file-id')
1242
        # Note: dirstate does not sha prior to the first commit
1243
        # so commit now in order for the test to work
1244
        tree.commit('first')
1245
        return tree, text
1246
1247
    def test_sha1provider_sha1_used(self):
1248
        tree, text = self._prepare_tree()
1249
        state = dirstate.DirState.from_tree(tree, 'dirstate',
4132.2.5 by Ian Clatworthy
feedback from poolie - use SHA, not Sha, in class names
1250
            UppercaseSHA1Provider())
4132.2.4 by Ian Clatworthy
John's enhancements/fixes to the tests
1251
        self.addCleanup(state.unlock)
1252
        expected_sha = osutils.sha_string(text.upper() + "foo")
1253
        entry = state._get_entry(0, path_utf8='a file')
1254
        state._sha_cutoff_time()
1255
        state._cutoff_time += 10
4241.14.19 by Vincent Ladeuil
Modernize dirstate helpers tests parametrization.
1256
        sha1 = self.update_entry(state, entry, 'tree/a file',
1257
                                 os.lstat('tree/a file'))
4132.2.4 by Ian Clatworthy
John's enhancements/fixes to the tests
1258
        self.assertEqual(expected_sha, sha1)
1259
1260
    def test_sha1provider_stat_and_sha1_used(self):
1261
        tree, text = self._prepare_tree()
1262
        tree.lock_write()
1263
        self.addCleanup(tree.unlock)
1264
        state = tree._current_dirstate()
4132.2.5 by Ian Clatworthy
feedback from poolie - use SHA, not Sha, in class names
1265
        state._sha1_provider = UppercaseSHA1Provider()
4132.2.4 by Ian Clatworthy
John's enhancements/fixes to the tests
1266
        # If we used the standard provider, it would look like nothing has
1267
        # changed
4241.14.19 by Vincent Ladeuil
Modernize dirstate helpers tests parametrization.
1268
        file_ids_changed = [change[0] for change
1269
                            in tree.iter_changes(tree.basis_tree())]
4132.2.4 by Ian Clatworthy
John's enhancements/fixes to the tests
1270
        self.assertEqual(['a-file-id'], file_ids_changed)
1271
1272
4159.1.2 by Ian Clatworthy
make sha1_provider a parameter to DirState() - tweak tests
1273
class UppercaseSHA1Provider(dirstate.SHA1Provider):
4132.2.5 by Ian Clatworthy
feedback from poolie - use SHA, not Sha, in class names
1274
    """A custom SHA1Provider."""
4132.2.4 by Ian Clatworthy
John's enhancements/fixes to the tests
1275
1276
    def sha1(self, abspath):
1277
        return self.stat_and_sha1(abspath)[1]
1278
1279
    def stat_and_sha1(self, abspath):
1280
        file_obj = file(abspath, 'rb')
1281
        try:
1282
            statvalue = os.fstat(file_obj.fileno())
1283
            text = ''.join(file_obj.readlines())
1284
            sha1 = osutils.sha_string(text.upper() + "foo")
1285
        finally:
1286
            file_obj.close()
1287
        return statvalue, sha1
1288
3696.4.1 by Robert Collins
Refactor to allow a pluggable dirstate update_entry with interface tests.
1289
4241.14.19 by Vincent Ladeuil
Modernize dirstate helpers tests parametrization.
1290
class TestProcessEntry(test_dirstate.TestCaseWithDirState):
1291
5559.2.2 by Martin Pool
Change to using standard load_tests_apply_scenarios.
1292
    scenarios = multiply_scenarios(dir_reader_scenarios(), pe_scenarios)
1293
4241.14.19 by Vincent Ladeuil
Modernize dirstate helpers tests parametrization.
1294
    # Set by load_tests
1295
    _process_entry = None
4132.2.4 by Ian Clatworthy
John's enhancements/fixes to the tests
1296
1297
    def setUp(self):
4241.14.19 by Vincent Ladeuil
Modernize dirstate helpers tests parametrization.
1298
        super(TestProcessEntry, self).setUp()
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
1299
        self.overrideAttr(dirstate, '_process_entry', self._process_entry)
4132.2.4 by Ian Clatworthy
John's enhancements/fixes to the tests
1300
1301
    def assertChangedFileIds(self, expected, tree):
1302
        tree.lock_read()
1303
        try:
1304
            file_ids = [info[0] for info
1305
                        in tree.iter_changes(tree.basis_tree())]
1306
        finally:
1307
            tree.unlock()
1308
        self.assertEqual(sorted(expected), sorted(file_ids))
1309
4634.117.1 by John Arbash Meinel
Fix bug #495023, _update_current_block should not supress exceptions.
1310
    def test_exceptions_raised(self):
1311
        # This is a direct test of bug #495023, it relies on osutils.is_inside
1312
        # getting called in an inner function. Which makes it a bit brittle,
1313
        # but at least it does reproduce the bug.
1314
        tree = self.make_branch_and_tree('tree')
1315
        self.build_tree(['tree/file', 'tree/dir/', 'tree/dir/sub',
1316
                         'tree/dir2/', 'tree/dir2/sub2'])
1317
        tree.add(['file', 'dir', 'dir/sub', 'dir2', 'dir2/sub2'])
1318
        tree.commit('first commit')
1319
        tree.lock_read()
1320
        self.addCleanup(tree.unlock)
1321
        basis_tree = tree.basis_tree()
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
1322
        def is_inside_raises(*args, **kwargs):
1323
            raise RuntimeError('stop this')
1324
        self.overrideAttr(osutils, 'is_inside', is_inside_raises)
4634.117.1 by John Arbash Meinel
Fix bug #495023, _update_current_block should not supress exceptions.
1325
        self.assertListRaises(RuntimeError, tree.iter_changes, basis_tree)
1326
4132.2.4 by Ian Clatworthy
John's enhancements/fixes to the tests
1327
    def test_simple_changes(self):
1328
        tree = self.make_branch_and_tree('tree')
1329
        self.build_tree(['tree/file'])
1330
        tree.add(['file'], ['file-id'])
1331
        self.assertChangedFileIds([tree.get_root_id(), 'file-id'], tree)
1332
        tree.commit('one')
1333
        self.assertChangedFileIds([], tree)
1334
1335
    def test_sha1provider_stat_and_sha1_used(self):
1336
        tree = self.make_branch_and_tree('tree')
1337
        self.build_tree(['tree/file'])
1338
        tree.add(['file'], ['file-id'])
1339
        tree.commit('one')
1340
        tree.lock_write()
1341
        self.addCleanup(tree.unlock)
1342
        state = tree._current_dirstate()
4132.2.5 by Ian Clatworthy
feedback from poolie - use SHA, not Sha, in class names
1343
        state._sha1_provider = UppercaseSHA1Provider()
4132.2.4 by Ian Clatworthy
John's enhancements/fixes to the tests
1344
        self.assertChangedFileIds(['file-id'], tree)
1345
6015.37.1 by Martin Packman
Add failing tests for pack_stat overflow issues
1346
1347
class TestPackStat(tests.TestCase):
1348
    """Check packed representaton of stat values is robust on all inputs"""
1349
6169.2.3 by Martin Packman
Parametrise TestPackStat against both py and pyx implementations
1350
    scenarios = helper_scenarios
6015.37.1 by Martin Packman
Add failing tests for pack_stat overflow issues
1351
6169.2.3 by Martin Packman
Parametrise TestPackStat against both py and pyx implementations
1352
    def pack(self, statlike_tuple):
1353
        return self.helpers.pack_stat(os.stat_result(statlike_tuple))
6015.37.1 by Martin Packman
Add failing tests for pack_stat overflow issues
1354
1355
    @staticmethod
1356
    def unpack_field(packed_string, stat_field):
6169.2.2 by Martin Packman
Merge fix for overflow issues in pack_stat from 2.4
1357
        return _dirstate_helpers_py._unpack_stat(packed_string)[stat_field]
6015.37.1 by Martin Packman
Add failing tests for pack_stat overflow issues
1358
1359
    def test_result(self):
1360
        self.assertEqual("AAAQAAAAABAAAAARAAAAAgAAAAEAAIHk",
1361
            self.pack((33252, 1, 2, 0, 0, 0, 4096, 15.5, 16.5, 17.5)))
1362
1363
    def test_giant_inode(self):
1364
        packed = self.pack((33252, 0xF80000ABC, 0, 0, 0, 0, 0, 0, 0, 0))
1365
        self.assertEqual(0x80000ABC, self.unpack_field(packed, "st_ino"))
1366
1367
    def test_giant_size(self):
6015.37.3 by Martin Packman
Change tests to always expect truncation not clamping for times
1368
        packed = self.pack((33252, 0, 0, 0, 0, 0, (1 << 33) + 4096, 0, 0, 0))
1369
        self.assertEqual(4096, self.unpack_field(packed, "st_size"))
6015.37.1 by Martin Packman
Add failing tests for pack_stat overflow issues
1370
1371
    def test_fractional_mtime(self):
1372
        packed = self.pack((33252, 0, 0, 0, 0, 0, 0, 0, 16.9375, 0))
1373
        self.assertEqual(16, self.unpack_field(packed, "st_mtime"))
1374
1375
    def test_ancient_mtime(self):
1376
        packed = self.pack((33252, 0, 0, 0, 0, 0, 0, 0, -11644473600.0, 0))
6015.37.3 by Martin Packman
Change tests to always expect truncation not clamping for times
1377
        self.assertEqual(1240428288, self.unpack_field(packed, "st_mtime"))
6015.37.1 by Martin Packman
Add failing tests for pack_stat overflow issues
1378
1379
    def test_distant_mtime(self):
1380
        packed = self.pack((33252, 0, 0, 0, 0, 0, 0, 0, 64060588800.0, 0))
6015.37.3 by Martin Packman
Change tests to always expect truncation not clamping for times
1381
        self.assertEqual(3931046656, self.unpack_field(packed, "st_mtime"))
6015.37.1 by Martin Packman
Add failing tests for pack_stat overflow issues
1382
1383
    def test_fractional_ctime(self):
1384
        packed = self.pack((33252, 0, 0, 0, 0, 0, 0, 0, 0, 17.5625))
1385
        self.assertEqual(17, self.unpack_field(packed, "st_ctime"))
1386
1387
    def test_ancient_ctime(self):
1388
        packed = self.pack((33252, 0, 0, 0, 0, 0, 0, 0, 0, -11644473600.0))
6015.37.3 by Martin Packman
Change tests to always expect truncation not clamping for times
1389
        self.assertEqual(1240428288, self.unpack_field(packed, "st_ctime"))
6015.37.1 by Martin Packman
Add failing tests for pack_stat overflow issues
1390
1391
    def test_distant_ctime(self):
1392
        packed = self.pack((33252, 0, 0, 0, 0, 0, 0, 0, 0, 64060588800.0))
6015.37.3 by Martin Packman
Change tests to always expect truncation not clamping for times
1393
        self.assertEqual(3931046656, self.unpack_field(packed, "st_ctime"))
6015.37.1 by Martin Packman
Add failing tests for pack_stat overflow issues
1394
6015.37.2 by Martin Packman
Add test for negative st_dev field that may be an issue on cygwin
1395
    def test_negative_dev(self):
1396
        packed = self.pack((33252, 0, -0xFFFFFCDE, 0, 0, 0, 0, 0, 0, 0))
1397
        self.assertEqual(0x322, self.unpack_field(packed, "st_dev"))