~bzr-pqm/bzr/bzr.dev

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