Skip to content
Newer
Older
100644 73 lines (61 sloc) 2.38 KB
83d44dc @airportyh A proof-of-concept for smart parameter checking in Python.
authored Mar 22, 2011
1 import inspect
2
3 class Args(object):
4 def __init__(self, kwargs, vargs):
5 self.kwargs = kwargs
6 self.vargs = vargs
7
8 def keys(self):
9 return self.kwargs.keys()
10
11 def __eq__(one, other):
12 return one.kwargs == other.kwargs and \
13 one.vargs == other.vargs
14
15 def __ne__(one, other):
16 return not one.__eq__(other)
17
18 def __repr__(self):
19 return "Args(%s, %s)" % (self.kwargs, self.vargs)
20
21 @classmethod
22 def combine(clz, sig, args, kwds):
23 args_by_key = dict()
24 extra = []
25 for i in xrange(len(args)):
26 try:
27 argname = sig.args[i]
28 args_by_key[argname] = args[i]
29 except IndexError:
30 extra.append(args[i])
31 for key, val in kwds.items():
32 if key in args_by_key:
33 raise Exception('TODO')
34 args_by_key[key] = val
35 return Args(args_by_key, extra)
36
37 class Mock(object):
38 def __init__(self, func):
39 self.func = func
40 self.sig = inspect.getargspec(self.func)
41 self.required_args = self.get_required_args()
42 self.named_args = self.get_named_args()
43 self.call_args = []
44
45 def __call__(self, *args, **kwds):
46 args = self.combine_args(args, kwds)
47 self.call_args.append(args)
48 if not set(self.required_args).issubset(set(args.keys())):
49 raise Exception('Not all required args are given')
50 if self.sig.keywords is None and \
51 not set(args.keys()).issubset(set(self.named_args)):
52 raise Exception('Unexpected args were given')
53 if len(args.vargs) > 0 and self.sig.varargs is None:
54 raise Exception('Unexpected positional args were given')
55
56 def get_required_args(self):
57 ret = list(self.sig.args)
58 if self.sig.defaults:
59 for df in self.sig.defaults:
60 ret.pop()
61 return ret
62
63 def get_named_args(self):
64 return list(self.sig.args)
65
66 def combine_args(self, args, kwds):
67 return Args.combine(self.sig, args, kwds)
68
69 def assert_called_with(self, *args, **kwds):
70 args = self.combine_args(args, kwds)
71 if self.call_args[0] != args:
72 raise Exception('Expected call with %s but called with %s' %
73 (args, self.call_args[0]))
Something went wrong with that request. Please try again.