/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/matchers.py

  • Committer: Jelmer Vernooij
  • Date: 2020-02-07 02:14:30 UTC
  • mto: This revision was merged to the branch mainline in revision 7492.
  • Revision ID: jelmer@jelmer.uk-20200207021430-m49iq3x4x8xlib6x
Drop python2 support.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2010 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
"""Matchers for breezy.
 
18
 
 
19
Primarily test support, Matchers are used by self.assertThat in the breezy
 
20
test suite. A matcher is a stateful test helper which can be used to determine
 
21
if a passed object 'matches', much like a regex. If the object does not match
 
22
the mismatch can be described in a human readable fashion. assertThat then
 
23
raises if a mismatch occurs, showing the description as the assertion error.
 
24
 
 
25
Matchers are designed to be more reusable and composable than layered
 
26
assertions in Test Case objects, so they are recommended for new testing work.
 
27
"""
 
28
 
 
29
__all__ = [
 
30
    'HasLayout',
 
31
    'HasPathRelations',
 
32
    'MatchesAncestry',
 
33
    'ContainsNoVfsCalls',
 
34
    'ReturnsUnlockable',
 
35
    'RevisionHistoryMatches',
 
36
    ]
 
37
 
 
38
from .. import (
 
39
    osutils,
 
40
    revision as _mod_revision,
 
41
    )
 
42
from .. import lazy_import
 
43
lazy_import.lazy_import(globals(),
 
44
                        """
 
45
from breezy.bzr.smart.request import request_handlers as smart_request_handlers
 
46
from breezy.bzr.smart import vfs
 
47
""")
 
48
from ..tree import find_previous_path
 
49
 
 
50
from testtools.matchers import Equals, Mismatch, Matcher
 
51
 
 
52
 
 
53
class ReturnsUnlockable(Matcher):
 
54
    """A matcher that checks for the pattern we want lock* methods to have:
 
55
 
 
56
    They should return an object with an unlock() method.
 
57
    Calling that method should unlock the original object.
 
58
 
 
59
    :ivar lockable_thing: The object which can be locked that will be
 
60
        inspected.
 
61
    """
 
62
 
 
63
    def __init__(self, lockable_thing):
 
64
        Matcher.__init__(self)
 
65
        self.lockable_thing = lockable_thing
 
66
 
 
67
    def __str__(self):
 
68
        return ('ReturnsUnlockable(lockable_thing=%s)' %
 
69
                self.lockable_thing)
 
70
 
 
71
    def match(self, lock_method):
 
72
        lock_method().unlock()
 
73
        if self.lockable_thing.is_locked():
 
74
            return _IsLocked(self.lockable_thing)
 
75
        return None
 
76
 
 
77
 
 
78
class _IsLocked(Mismatch):
 
79
    """Something is locked."""
 
80
 
 
81
    def __init__(self, lockable_thing):
 
82
        self.lockable_thing = lockable_thing
 
83
 
 
84
    def describe(self):
 
85
        return "%s is locked" % self.lockable_thing
 
86
 
 
87
 
 
88
class _AncestryMismatch(Mismatch):
 
89
    """Ancestry matching mismatch."""
 
90
 
 
91
    def __init__(self, tip_revision, got, expected):
 
92
        self.tip_revision = tip_revision
 
93
        self.got = got
 
94
        self.expected = expected
 
95
 
 
96
    def describe(self):
 
97
        return "mismatched ancestry for revision %r was %r, expected %r" % (
 
98
            self.tip_revision, self.got, self.expected)
 
99
 
 
100
 
 
101
class MatchesAncestry(Matcher):
 
102
    """A matcher that checks the ancestry of a particular revision.
 
103
 
 
104
    :ivar graph: Graph in which to check the ancestry
 
105
    :ivar revision_id: Revision id of the revision
 
106
    """
 
107
 
 
108
    def __init__(self, repository, revision_id):
 
109
        Matcher.__init__(self)
 
110
        self.repository = repository
 
111
        self.revision_id = revision_id
 
112
 
 
113
    def __str__(self):
 
114
        return ('MatchesAncestry(repository=%r, revision_id=%r)' % (
 
115
            self.repository, self.revision_id))
 
116
 
 
117
    def match(self, expected):
 
118
        with self.repository.lock_read():
 
119
            graph = self.repository.get_graph()
 
120
            got = [r for r, p in graph.iter_ancestry([self.revision_id])]
 
121
            if _mod_revision.NULL_REVISION in got:
 
122
                got.remove(_mod_revision.NULL_REVISION)
 
123
        if sorted(got) != sorted(expected):
 
124
            return _AncestryMismatch(self.revision_id, sorted(got),
 
125
                                     sorted(expected))
 
126
 
 
127
 
 
128
class HasLayout(Matcher):
 
129
    """A matcher that checks if a tree has a specific layout.
 
130
 
 
131
    :ivar entries: List of expected entries, as (path, file_id) pairs.
 
132
    """
 
133
 
 
134
    def __init__(self, entries):
 
135
        Matcher.__init__(self)
 
136
        self.entries = entries
 
137
 
 
138
    def get_tree_layout(self, tree, include_file_ids):
 
139
        """Get the (path, file_id) pairs for the current tree."""
 
140
        with tree.lock_read():
 
141
            for path, ie in tree.iter_entries_by_dir():
 
142
                if path != u'':
 
143
                    path += ie.kind_character()
 
144
                if include_file_ids:
 
145
                    yield (path, ie.file_id)
 
146
                else:
 
147
                    yield path
 
148
 
 
149
    @staticmethod
 
150
    def _strip_unreferenced_directories(entries):
 
151
        """Strip all directories that don't (in)directly contain any files.
 
152
 
 
153
        :param entries: List of path strings or (path, ie) tuples to process
 
154
        """
 
155
        directories = []
 
156
        for entry in entries:
 
157
            if isinstance(entry, str):
 
158
                path = entry
 
159
            else:
 
160
                path = entry[0]
 
161
            if not path or path[-1] == "/":
 
162
                # directory
 
163
                directories.append((path, entry))
 
164
            else:
 
165
                # Yield the referenced parent directories
 
166
                for dirpath, direntry in directories:
 
167
                    if osutils.is_inside(dirpath, path):
 
168
                        yield direntry
 
169
                directories = []
 
170
                yield entry
 
171
 
 
172
    def __str__(self):
 
173
        return 'HasLayout(%r)' % self.entries
 
174
 
 
175
    def match(self, tree):
 
176
        include_file_ids = self.entries and not isinstance(
 
177
            self.entries[0], str)
 
178
        actual = list(self.get_tree_layout(
 
179
            tree, include_file_ids=include_file_ids))
 
180
        if not tree.has_versioned_directories():
 
181
            entries = list(self._strip_unreferenced_directories(self.entries))
 
182
        else:
 
183
            entries = self.entries
 
184
        return Equals(entries).match(actual)
 
185
 
 
186
 
 
187
class HasPathRelations(Matcher):
 
188
    """Matcher verifies that paths have a relation to those in another tree.
 
189
 
 
190
    :ivar previous_tree: tree to compare to
 
191
    :ivar previous_entries: List of expected entries, as (path, previous_path) pairs.
 
192
    """
 
193
 
 
194
    def __init__(self, previous_tree, previous_entries):
 
195
        Matcher.__init__(self)
 
196
        self.previous_tree = previous_tree
 
197
        self.previous_entries = previous_entries
 
198
 
 
199
    def get_path_map(self, tree):
 
200
        """Get the (path, previous_path) pairs for the current tree."""
 
201
        with tree.lock_read(), self.previous_tree.lock_read():
 
202
            for path, ie in tree.iter_entries_by_dir():
 
203
                if tree.supports_rename_tracking():
 
204
                    previous_path = find_previous_path(
 
205
                        tree, self.previous_tree, path)
 
206
                else:
 
207
                    if self.previous_tree.is_versioned(path):
 
208
                        previous_path = path
 
209
                    else:
 
210
                        previous_path = None
 
211
                if previous_path:
 
212
                    kind = self.previous_tree.kind(previous_path)
 
213
                    if kind == 'directory':
 
214
                        previous_path += '/'
 
215
                if path == u'':
 
216
                    yield (u"", previous_path)
 
217
                else:
 
218
                    yield (path + ie.kind_character(), previous_path)
 
219
 
 
220
    @staticmethod
 
221
    def _strip_unreferenced_directories(entries):
 
222
        """Strip all directories that don't (in)directly contain any files.
 
223
 
 
224
        :param entries: List of path strings or (path, previous_path) tuples to process
 
225
        """
 
226
        directory_used = set()
 
227
        directories = []
 
228
        for (path, previous_path) in entries:
 
229
            if not path or path[-1] == "/":
 
230
                # directory
 
231
                directories.append((path, previous_path))
 
232
            else:
 
233
                # Yield the referenced parent directories
 
234
                for direntry in directories:
 
235
                    if osutils.is_inside(direntry[0], path):
 
236
                        directory_used.add(direntry[0])
 
237
        for (path, previous_path) in entries:
 
238
            if (not path.endswith("/")) or path in directory_used:
 
239
                yield (path, previous_path)
 
240
 
 
241
    def __str__(self):
 
242
        return 'HasPathRelations(%r, %r)' % (self.previous_tree, self.previous_entries)
 
243
 
 
244
    def match(self, tree):
 
245
        actual = list(self.get_path_map(tree))
 
246
        if not tree.has_versioned_directories():
 
247
            entries = list(self._strip_unreferenced_directories(
 
248
                self.previous_entries))
 
249
        else:
 
250
            entries = self.previous_entries
 
251
        if not tree.supports_rename_tracking():
 
252
            entries = [
 
253
                (path, path if self.previous_tree.is_versioned(path) else None)
 
254
                for (path, previous_path) in entries]
 
255
        return Equals(entries).match(actual)
 
256
 
 
257
 
 
258
class RevisionHistoryMatches(Matcher):
 
259
    """A matcher that checks if a branch has a specific revision history.
 
260
 
 
261
    :ivar history: Revision history, as list of revisions. Oldest first.
 
262
    """
 
263
 
 
264
    def __init__(self, history):
 
265
        Matcher.__init__(self)
 
266
        self.expected = history
 
267
 
 
268
    def __str__(self):
 
269
        return 'RevisionHistoryMatches(%r)' % self.expected
 
270
 
 
271
    def match(self, branch):
 
272
        with branch.lock_read():
 
273
            graph = branch.repository.get_graph()
 
274
            history = list(graph.iter_lefthand_ancestry(
 
275
                branch.last_revision(), [_mod_revision.NULL_REVISION]))
 
276
            history.reverse()
 
277
        return Equals(self.expected).match(history)
 
278
 
 
279
 
 
280
class _NoVfsCallsMismatch(Mismatch):
 
281
    """Mismatch describing a list of HPSS calls which includes VFS requests."""
 
282
 
 
283
    def __init__(self, vfs_calls):
 
284
        self.vfs_calls = vfs_calls
 
285
 
 
286
    def describe(self):
 
287
        return "no VFS calls expected, got: %s" % ",".join([
 
288
            "%s(%s)" % (c.method,
 
289
                        ", ".join([repr(a) for a in c.args])) for c in self.vfs_calls])
 
290
 
 
291
 
 
292
class ContainsNoVfsCalls(Matcher):
 
293
    """Ensure that none of the specified calls are HPSS calls."""
 
294
 
 
295
    def __str__(self):
 
296
        return 'ContainsNoVfsCalls()'
 
297
 
 
298
    @classmethod
 
299
    def match(cls, hpss_calls):
 
300
        vfs_calls = []
 
301
        for call in hpss_calls:
 
302
            try:
 
303
                request_method = smart_request_handlers.get(call.call.method)
 
304
            except KeyError:
 
305
                # A method we don't know about doesn't count as a VFS method.
 
306
                continue
 
307
            if issubclass(request_method, vfs.VfsRequest):
 
308
                vfs_calls.append(call.call)
 
309
        if len(vfs_calls) == 0:
 
310
            return None
 
311
        return _NoVfsCallsMismatch(vfs_calls)