File: _basic.py

package info (click to toggle)
python-testtools 2.8.2-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,244 kB
  • sloc: python: 15,086; makefile: 127; sh: 3
file content (446 lines) | stat: -rw-r--r-- 12,993 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
# Copyright (c) 2009-2012 testtools developers. See LICENSE for details.

__all__ = [
    "Contains",
    "EndsWith",
    "Equals",
    "GreaterThan",
    "HasLength",
    "Is",
    "IsInstance",
    "LessThan",
    "MatchesRegex",
    "Nearly",
    "NotEquals",
    "SameMembers",
    "StartsWith",
]

import operator
import re
from collections.abc import Callable
from pprint import pformat
from typing import Any

from ..compat import (
    text_repr,
)
from ..helpers import list_subtract
from ._higherorder import (
    MatchesPredicateWithParams,
    PostfixedMismatch,
)
from ._impl import (
    Matcher,
    Mismatch,
)


def _format(thing):
    """Blocks of text with newlines are formatted as triple-quote
    strings. Everything else is pretty-printed.
    """
    if isinstance(thing, (str, bytes)):
        return text_repr(thing)
    return pformat(thing)


class _BinaryComparison:
    """Matcher that compares an object to another object."""

    mismatch_string: str
    # comparator is defined by subclasses - using Any to allow different signatures
    comparator: Callable[..., Any]

    def __init__(self, expected):
        self.expected = expected

    def __str__(self):
        return f"{self.__class__.__name__}({self.expected!r})"

    def match(self, other):
        if self.comparator(other, self.expected):
            return None
        return _BinaryMismatch(other, self.mismatch_string, self.expected)


class _BinaryMismatch(Mismatch):
    """Two things did not match."""

    def __init__(self, actual, mismatch_string, reference, reference_on_right=True):
        self._actual = actual
        self._mismatch_string = mismatch_string
        self._reference = reference
        self._reference_on_right = reference_on_right

    def describe(self):
        # Special handling for set comparisons
        if (
            self._mismatch_string == "!="
            and isinstance(self._reference, set)
            and isinstance(self._actual, set)
        ):
            return self._describe_set_difference()

        actual = repr(self._actual)
        reference = repr(self._reference)
        if len(actual) + len(reference) > 70:
            return (
                f"{self._mismatch_string}:\n"
                f"reference = {_format(self._reference)}\n"
                f"actual    = {_format(self._actual)}\n"
            )
        else:
            if self._reference_on_right:
                left, right = actual, reference
            else:
                left, right = reference, actual
            return f"{left} {self._mismatch_string} {right}"

    def _describe_set_difference(self):
        """Describe the difference between two sets in a readable format."""
        reference_only = sorted(
            self._reference - self._actual, key=lambda x: (type(x).__name__, x)
        )
        actual_only = sorted(
            self._actual - self._reference, key=lambda x: (type(x).__name__, x)
        )

        lines = ["!=:"]
        if reference_only:
            lines.append(
                f"Items in expected but not in actual:\n{_format(reference_only)}"
            )
        if actual_only:
            lines.append(
                f"Items in actual but not in expected:\n{_format(actual_only)}"
            )

        return "\n".join(lines)


class Equals(_BinaryComparison):
    """Matches if the items are equal."""

    comparator = operator.eq
    mismatch_string = "!="


class _FlippedEquals:
    """Matches if the items are equal.

    Exactly like ``Equals`` except that the short mismatch message is "
    $reference != $actual" rather than "$actual != $reference". This allows
    for ``TestCase.assertEqual`` to use a matcher but still have the order of
    items in the error message align with the order of items in the call to
    the assertion.
    """

    def __init__(self, expected):
        self._expected = expected

    def match(self, other):
        mismatch = Equals(self._expected).match(other)
        if not mismatch:
            return None
        return _BinaryMismatch(other, "!=", self._expected, False)


class NotEquals(_BinaryComparison):
    """Matches if the items are not equal.

    In most cases, this is equivalent to ``Not(Equals(foo))``. The difference
    only matters when testing ``__ne__`` implementations.
    """

    comparator = operator.ne
    mismatch_string = "=="


class Is(_BinaryComparison):
    """Matches if the items are identical."""

    comparator = operator.is_
    mismatch_string = "is not"


class LessThan(_BinaryComparison):
    """Matches if the item is less than the matchers reference object."""

    comparator = operator.lt
    mismatch_string = ">="


class GreaterThan(_BinaryComparison):
    """Matches if the item is greater than the matchers reference object."""

    comparator = operator.gt
    mismatch_string = "<="


class _NotNearlyEqual(Mismatch):
    """Mismatch for Nearly matcher."""

    def __init__(self, actual, expected, delta):
        self.actual = actual
        self.expected = expected
        self.delta = delta

    def describe(self):
        try:
            diff = abs(self.actual - self.expected)
            return (
                f"{self.actual!r} is not nearly equal to {self.expected!r}: "
                f"difference {diff!r} exceeds tolerance {self.delta!r}"
            )
        except (TypeError, AttributeError):
            return (
                f"{self.actual!r} is not nearly equal to {self.expected!r} "
                f"within {self.delta!r}"
            )


class Nearly(Matcher):
    """Matches if a value is nearly equal to the expected value.

    This matcher is useful for comparing floating point values where exact
    equality cannot be relied upon due to precision limitations.

    The matcher checks if the absolute difference between the actual and
    expected values is less than or equal to a specified tolerance (delta).

    This works for any type that supports subtraction and absolute value
    operations (e.g., integers, floats, Decimal, etc.).
    """

    def __init__(self, expected, delta=0.001):
        """Create a Nearly matcher.

        :param expected: The expected value to compare against.
        :param delta: The maximum allowed absolute difference (tolerance).
            Default is 0.001.
        """
        self.expected = expected
        self.delta = delta

    def __str__(self):
        return f"Nearly({self.expected!r}, delta={self.delta!r})"

    def match(self, actual):
        try:
            diff = abs(actual - self.expected)
            if diff <= self.delta:
                return None
        except (TypeError, AttributeError):
            # Can't compute difference - definitely not nearly equal
            pass
        return _NotNearlyEqual(actual, self.expected, self.delta)


class SameMembers(Matcher):
    """Matches if two iterators have the same members.

    This is not the same as set equivalence.  The two iterators must be of the
    same length and have the same repetitions.
    """

    def __init__(self, expected):
        super().__init__()
        self.expected = expected

    def __str__(self):
        return f"{self.__class__.__name__}({self.expected!r})"

    def match(self, observed):
        expected_only = list_subtract(self.expected, observed)
        observed_only = list_subtract(observed, self.expected)
        if expected_only == observed_only == []:
            return
        return PostfixedMismatch(
            (
                f"\nmissing:    {_format(expected_only)}\n"
                f"extra:      {_format(observed_only)}"
            ),
            _BinaryMismatch(observed, "elements differ", self.expected),
        )


class DoesNotStartWith(Mismatch):
    def __init__(self, matchee, expected):
        """Create a DoesNotStartWith Mismatch.

        :param matchee: the string that did not match.
        :param expected: the string that 'matchee' was expected to start with.
        """
        self.matchee = matchee
        self.expected = expected

    def describe(self):
        return (
            f"{text_repr(self.matchee)} does not start with {text_repr(self.expected)}."
        )


class StartsWith(Matcher):
    """Checks whether one string starts with another."""

    def __init__(self, expected):
        """Create a StartsWith Matcher.

        :param expected: the string that matchees should start with.
        """
        self.expected = expected

    def __str__(self):
        return f"StartsWith({self.expected!r})"

    def match(self, matchee):
        if not matchee.startswith(self.expected):
            return DoesNotStartWith(matchee, self.expected)
        return None


class DoesNotEndWith(Mismatch):
    def __init__(self, matchee, expected):
        """Create a DoesNotEndWith Mismatch.

        :param matchee: the string that did not match.
        :param expected: the string that 'matchee' was expected to end with.
        """
        self.matchee = matchee
        self.expected = expected

    def describe(self):
        return (
            f"{text_repr(self.matchee)} does not end with {text_repr(self.expected)}."
        )


class EndsWith(Matcher):
    """Checks whether one string ends with another."""

    def __init__(self, expected):
        """Create a EndsWith Matcher.

        :param expected: the string that matchees should end with.
        """
        self.expected = expected

    def __str__(self):
        return f"EndsWith({self.expected!r})"

    def match(self, matchee):
        if not matchee.endswith(self.expected):
            return DoesNotEndWith(matchee, self.expected)
        return None


class IsInstance:
    """Matcher that wraps isinstance."""

    def __init__(self, *types):
        self.types = tuple(types)

    def __str__(self):
        return "{}({})".format(
            self.__class__.__name__, ", ".join(type.__name__ for type in self.types)
        )

    def match(self, other):
        if isinstance(other, self.types):
            return None
        return NotAnInstance(other, self.types)


class NotAnInstance(Mismatch):
    def __init__(self, matchee, types):
        """Create a NotAnInstance Mismatch.

        :param matchee: the thing which is not an instance of any of types.
        :param types: A tuple of the types which were expected.
        """
        self.matchee = matchee
        self.types = types

    def describe(self):
        if len(self.types) == 1:
            typestr = self.types[0].__name__
        else:
            typestr = "any of ({})".format(
                ", ".join(type.__name__ for type in self.types)
            )
        return f"'{self.matchee}' is not an instance of {typestr}"


class DoesNotContain(Mismatch):
    def __init__(self, matchee, needle):
        """Create a DoesNotContain Mismatch.

        :param matchee: the object that did not contain needle.
        :param needle: the needle that 'matchee' was expected to contain.
        """
        self.matchee = matchee
        self.needle = needle

    def describe(self):
        return f"{self.needle!r} not in {self.matchee!r}"


class Contains(Matcher):
    """Checks whether something is contained in another thing."""

    def __init__(self, needle):
        """Create a Contains Matcher.

        :param needle: the thing that needs to be contained by matchees.
        """
        self.needle = needle

    def __str__(self):
        return f"Contains({self.needle!r})"

    def match(self, matchee):
        try:
            if self.needle not in matchee:
                return DoesNotContain(matchee, self.needle)
        except TypeError:
            # e.g. 1 in 2 will raise TypeError
            return DoesNotContain(matchee, self.needle)
        return None


class MatchesRegex:
    """Matches if the matchee is matched by a regular expression."""

    def __init__(self, pattern, flags=0):
        self.pattern = pattern
        self.flags = flags

    def __str__(self):
        args = [f"{self.pattern!r}"]
        flag_arg = []
        # dir() sorts the attributes for us, so we don't need to do it again.
        for flag in dir(re):
            if len(flag) == 1:
                if self.flags & getattr(re, flag):
                    flag_arg.append(f"re.{flag}")
        if flag_arg:
            args.append("|".join(flag_arg))
        return "{}({})".format(self.__class__.__name__, ", ".join(args))

    def match(self, value):
        if not re.match(self.pattern, value, self.flags):
            pattern = self.pattern
            if not isinstance(pattern, str):
                pattern = pattern.decode("latin1")
            pattern = pattern.encode("unicode_escape").decode("ascii")
            return Mismatch(
                "{!r} does not match /{}/".format(value, pattern.replace("\\\\", "\\"))
            )


def has_len(x, y):
    return len(x) == y


HasLength = MatchesPredicateWithParams(has_len, "len({0}) != {1}", "HasLength")