forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathattr.py
100 lines (69 loc) · 1.79 KB
/
attr.py
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
from testutils import assert_raises
class A:
pass
class B:
x = 50
a = A()
a.b = 10
assert hasattr(a, 'b')
assert a.b == 10
assert B.x == 50
# test delete class attribute with del keyword
del B.x
with assert_raises(AttributeError):
_ = B.x
# test override attribute
setattr(a, 'b', 12)
assert a.b == 12
assert getattr(a, 'b') == 12
# test non-existent attribute
with assert_raises(AttributeError):
_ = a.c
with assert_raises(AttributeError):
getattr(a, 'c')
assert getattr(a, 'c', 21) == 21
# test set attribute
setattr(a, 'c', 20)
assert hasattr(a, 'c')
assert a.c == 20
# test delete attribute
delattr(a, 'c')
assert not hasattr(a, 'c')
with assert_raises(AttributeError):
_ = a.c
# test setting attribute on builtin
with assert_raises(AttributeError):
object().a = 1
with assert_raises(AttributeError):
del object().a
with assert_raises(AttributeError):
setattr(object(), 'a', 2)
with assert_raises(AttributeError):
delattr(object(), 'a')
attrs = {}
class CustomLookup:
def __getattr__(self, item):
return "value_{}".format(item)
def __setattr__(self, key, value):
attrs[key] = value
custom = CustomLookup()
assert custom.attr == "value_attr"
custom.a = 2
custom.b = 5
assert attrs['a'] == 2
assert attrs['b'] == 5
class GetRaise:
def __init__(self, ex):
self.ex = ex
def __getattr__(self, item):
raise self.ex
assert not hasattr(GetRaise(AttributeError()), 'a')
with assert_raises(AttributeError):
getattr(GetRaise(AttributeError()), 'a')
assert getattr(GetRaise(AttributeError()), 'a', 11) == 11
with assert_raises(KeyError):
hasattr(GetRaise(KeyError()), 'a')
with assert_raises(KeyError):
getattr(GetRaise(KeyError()), 'a')
with assert_raises(KeyError):
getattr(GetRaise(KeyError()), 'a', 11)