/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to breezy/tests/test__dirstate_helpers.py

  • Committer: Jelmer Vernooij
  • Date: 2017-07-23 15:59:57 UTC
  • mto: This revision was merged to the branch mainline in revision 6740.
  • Revision ID: jelmer@jelmer.uk-20170723155957-rw4kqurf44fqx4x0
Move AlreadyBuilding/NotBuilding errors.

Show diffs side-by-side

added added

removed removed

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