aboutsummaryrefslogtreecommitdiff
path: root/immutables/_testutils.py
blob: 3f174b27e07983080fce2f89dd3ca08b5702d7fe (plain)
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
class HashKey:
    _crasher = None

    def __init__(self, hash, name, *, error_on_eq_to=None):
        assert hash != -1
        self.name = name
        self.hash = hash
        self.error_on_eq_to = error_on_eq_to

    def __repr__(self):
        if self._crasher is not None and self._crasher.error_on_repr:
            raise ReprError
        return '<Key name:{} hash:{}>'.format(self.name, self.hash)

    def __hash__(self):
        if self._crasher is not None and self._crasher.error_on_hash:
            raise HashingError

        return self.hash

    def __eq__(self, other):
        if not isinstance(other, HashKey):
            return NotImplemented

        if self._crasher is not None and self._crasher.error_on_eq:
            raise EqError

        if self.error_on_eq_to is not None and self.error_on_eq_to is other:
            raise ValueError('cannot compare {!r} to {!r}'.format(self, other))
        if other.error_on_eq_to is not None and other.error_on_eq_to is self:
            raise ValueError('cannot compare {!r} to {!r}'.format(other, self))

        return (self.name, self.hash) == (other.name, other.hash)


class KeyStr(str):

    def __hash__(self):
        if HashKey._crasher is not None and HashKey._crasher.error_on_hash:
            raise HashingError
        return super().__hash__()

    def __eq__(self, other):
        if HashKey._crasher is not None and HashKey._crasher.error_on_eq:
            raise EqError
        return super().__eq__(other)

    def __repr__(self, other):
        if HashKey._crasher is not None and HashKey._crasher.error_on_repr:
            raise ReprError
        return super().__eq__(other)


class HashKeyCrasher:

    def __init__(self, *, error_on_hash=False, error_on_eq=False,
                 error_on_repr=False):
        self.error_on_hash = error_on_hash
        self.error_on_eq = error_on_eq
        self.error_on_repr = error_on_repr

    def __enter__(self):
        if HashKey._crasher is not None:
            raise RuntimeError('cannot nest crashers')
        HashKey._crasher = self

    def __exit__(self, *exc):
        HashKey._crasher = None


class HashingError(Exception):
    pass


class EqError(Exception):
    pass


class ReprError(Exception):
    pass