3
from sqlalchemy import orm
8
_whitespace = re.compile(r'^(\s+)')
10
def _find_pragma(lines, current):
11
m = _whitespace.match(lines[current])
12
basis = m and m.group() or ''
14
for line in reversed(lines[0:current]):
15
if 'testlib.pragma' in line:
17
m = _whitespace.match(line)
18
indent = m and m.group() or ''
20
# simplistic detection:
22
# >> # testlib.pragma foo
26
# >> # testlib.pragma foo
29
if line.endswith(':'):
33
def _make_blocker(method_name, fallback):
34
"""Creates tripwired variant of a method, raising when called.
36
To excempt an invocation from blockage, there are two options.
38
1) add a pragma in a comment::
40
# testlib.pragma exempt:methodname
43
2) add a magic cookie to the function's namespace::
44
__sa_baremethodname_exempt__ = True
47
another_offending_lines()
49
The second is useful for testing and development.
52
if method_name.startswith('__') and method_name.endswith('__'):
53
frame_marker = '__sa_%s_exempt__' % method_name[2:-2]
55
frame_marker = '__sa_%s_exempt__' % method_name
56
pragma_marker = 'exempt:' + method_name
58
def method(self, *args, **kw):
61
frame = inspect.stack()[1][0]
62
frame_r = inspect.getframeinfo(frame, 9)
64
module = frame.f_globals.get('__name__', '')
68
pragma = _find_pragma(*frame_r[3:5])
71
(not module.startswith('sqlalchemy')) or
72
(pragma and pragma_marker in pragma) or
73
(frame_marker in frame.f_locals) or
74
('self' in frame.f_locals and
75
getattr(frame.f_locals['self'], frame_marker, False)))
78
supermeth = getattr(super(type_, self), method_name, None)
79
if (supermeth is None or
80
getattr(supermeth, 'im_func', None) is method):
81
return fallback(self, *args, **kw)
83
return supermeth(*args, **kw)
86
"%s.%s called in %s, line %s in %s" % (
87
type_.__name__, method_name, module, frame_r[1], frame_r[2]))
90
method.__name__ = method_name
93
def mapper(type_, *args, **kw):
95
('__hash__', 'unhashable', lambda s: id(s)),
96
('__eq__', 'noncomparable', lambda s, o: s is o),
97
('__ne__', 'noncomparable', lambda s, o: s is not o),
98
('__cmp__', 'noncomparable', lambda s, o: object.__cmp__(s, o)),
99
('__le__', 'noncomparable', lambda s, o: object.__le__(s, o)),
100
('__lt__', 'noncomparable', lambda s, o: object.__lt__(s, o)),
101
('__ge__', 'noncomparable', lambda s, o: object.__ge__(s, o)),
102
('__gt__', 'noncomparable', lambda s, o: object.__gt__(s, o)),
103
('__nonzero__', 'truthless', lambda s: 1), ]
105
if isinstance(type_, type) and type_.__bases__ == (object,):
106
for method_name, option, fallback in forbidden:
107
if (getattr(config.options, option, False) and
108
method_name not in type_.__dict__):
109
setattr(type_, method_name, _make_blocker(method_name, fallback))
111
return orm.mapper(type_, *args, **kw)