specificator.py 23.4 KB
Newer Older
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
1
# -*- coding: utf-8 -*-
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
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
# Copyright 2012 GRNET S.A. All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
#   1. Redistributions of source code must retain the above
#      copyright notice, this list of conditions and the following
#      disclaimer.
#
#   2. Redistributions in binary form must reproduce the above
#      copyright notice, this list of conditions and the following
#      disclaimer in the documentation and/or other materials
#      provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.

35
36
from random import random, choice, randint
from math import log
37
from inspect import isclass
38
from .utils.betteron import betteron_decode
39
40
41
42

try:
    from collections import OrderedDict
except ImportError:
43
    from .utils.ordereddict import OrderedDict
44
45
46
47
48
49
50
51
52

def shorts(s):
    if not isinstance(s, unicode):
        s = str(s)

    if len(s) <= 64:
        return s

    return s[:61] + '...'
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
53

54
55
56
57
58
59
60
61
62

class CanonifyException(Exception):
    pass

class SpecifyException(Exception):
    pass


class Canonical(object):
63
64
65

    random_choice = None

66
    def __init__(self, *args, **kw):
67
68
69
70
71
72
73
        self.args = []
        named_args = []
        for a in args:
            if isinstance(a, tuple) and len(a) == 2:
                named_args.append(a)
            else:
                self.args.append(a)
74
        ordered_dict = OrderedDict(named_args)
75

76
        self.name = kw.pop('classname', self.__class__.__name__)
77
78
79
        random_choice = kw.pop('random', None)
        if random_choice is not None:
            self.random_choice = random_choice
80
81
82
        opts = {}
        for k, v in kw.items():
            if not isinstance(v, Canonical):
83
84
85
86
87
                if isclass(v) and issubclass(v, Canonical):
                    m = ("argument '%s': value '%s' is a Canonical _class_. "
                         "Perhaps you meant to specify a Canonical _instance_"
                         % (k, v))
                    raise SpecifyException(m)
88
89
90
91
                opts[k] = v
                del kw[k]

        self.opts = opts
92
93
        ordered_dict.update(kw)
        self.kw = ordered_dict
94
95
96
97
98
99
100
        self.init()

        if 'default' in opts:
            item = opts['default']
            if item is None:
                opts['null'] = 1
            else:
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
101
                opts['default'] = self._check(item)
102
103
104
105
106

    def init(self):
        return

    def __call__(self, item):
107
108
109
        return self.check(item)

    def check(self, item):
110
111
112
113
114
115
116
117
        opts = self.opts
        if item is None and 'default' in opts:
            item = opts['default']

        can_be_null = opts.get('null', False)
        if item is None and can_be_null:
            return None

118
        return self._check(item)
119

120
    def _check(self, item):
121
122
        return item

123
124
125
126
127
128
129
130
131
132
133
134
135
    def parse(self, item):
        opts = self.opts
        if item is None and 'default' in opts:
            item = opts['default']

        can_be_null = opts.get('null', False)
        if item is None and can_be_null:
            return None

        return self._parse(item)

    def _parse(self, item):
        raise NotImplementedError
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
136

137
138
139
    def create(self):
        return None

140
141
142
143
144
145
146
147
148
149
150
151
    def random(self, **kw):
        random_choice = self.random_choice
        if random_choice is None:
            return None

        if callable(random_choice):
            return random_choice(kw)

        if isinstance(random_choice, str):
            return getattr(self, random_choice)(kw)

        return choice(random_choice)
152

153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
    def tostring(self, depth=0, showopts=0, multiline=0):
        depth += 1
        if not multiline:
            argdepth = ''
            owndepth = ''
            joinchar = ','
            padchar = ''
        else:
            argdepth = '    ' * depth
            owndepth = '    ' * (depth - 1)
            joinchar = ',\n'
            padchar = '\n'

        args = [a.tostring( depth=depth,
                            showopts=showopts,
                            multiline=multiline) for a in self.args]
        args += [("%s=%s" %
                    (k, v.tostring( depth=depth,
                                    showopts=showopts,
                                    multiline=multiline)))
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
173

174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
                                    for k, v in self.kw.items()]
        if showopts:
            args += [("%s=%s" % (k, str(v))) for k, v in self.opts.items()]

        if len(args) == 0:
            string = "%s(%s)" % (self.name, ','.join(args))
        else:
            string = "%s(%s" % (self.name, padchar)
            for arg in args:
                string += argdepth + arg + joinchar
            string = string[:-1] + padchar
            string += owndepth + ")"

        return string

    __str__ = tostring

    def __repr__(self):
        return self.tostring(multiline=0, showopts=1)


class Null(Canonical):

197
    def _check(self, item):
198
199
200
201
        return None

Nothing = Null()

202

203
204
class Integer(Canonical):

205
    def _check(self, item):
206
        try:
207
            num = long(item)
208
209
        except ValueError, e:
            try:
210
                num = long(item, 16)
211
            except Exception:
212
                m = "%s: cannot convert '%s' to long" % (self, shorts(item))
213
                raise CanonifyException(m)
214
215
        except TypeError, e:
            m = "%s: cannot convert '%s' to long" % (self, shorts(item))
216
            raise CanonifyException(m)
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231

        optget = self.opts.get
        minimum = optget('minimum', None)
        maximum = optget('maximum', None)

        if minimum is not None and num < minimum:
            m = "%s: %d < minimum=%d" % (self, num, minimum)
            raise CanonifyException(m)

        if maximum is not None and num > maximum:
            m = "%s: %d > maximum=%d" % (self, num, maximum)
            raise CanonifyException(m)

        return num

232
233
234
    def _parse(self, item):
        return self.check(item)

235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
    def random_integer(self, kw):
        optget = self.opts.get
        kwget = kw.get
        minimum = kwget('minimum', optget('minimum', -4294967296L))
        maximum = kwget('maximum', optget('maximum', 4294967295L))
        r = random()
        if r < 0.1:
            return minimum
        if r < 0.2:
            return maximum
        if minimum <= 0 and maximum >= 0 and r < 0.3:
            return 0L
        return long(minimum + r * (maximum - minimum))

    random_choice = random_integer


252

253
254
255
256
257
258
Serial = Integer(
            classname   =   'Serial',
            null        =   True,
)


259
class Text(Canonical):
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280

    re = None
    matcher = None
    choices = None

    def init(self):
        opts = self.opts
        if 'regex' in opts:
            pat = opts['regex']
            re = self.re
            if re is None:
                import re
                self.re = re

            self.matcher = re.compile(pat, re.UNICODE)
            self.pat = pat

        if 'choices' in opts:
            opts['choices'] = dict((unicode(x), unicode(x))
                                    for x in opts['choices'])

281
    def _check(self, item):
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
        if not isinstance(item, unicode):
            # require non-unicode items to be utf8
            item = str(item)
            try:
                item = item.decode('utf8')
            except UnicodeDecodeError, e:
                item = item.decode('latin1')
                m = "%s: non-unicode '%s' is not utf8" % (self, shorts(item))
                raise CanonifyException(m)

        opts = self.opts
        if 'choices' in opts:
            choices = opts['choices']
            try:
                unknown = item not in choices
            except TypeError, e:
                m = "%s: unhashable type '%s'" % (self.name, shorts(item))
                raise CanonifyException(m, e)

            if unknown:
                m = "%s: '%s' not in choices" % (self.name, shorts(item))
                raise CanonifyException(m)

            return choices[item]

        optget = opts.get
        itemlen = len(item)
        maxlen = optget('maxlen', None)
        if maxlen is not None and itemlen > maxlen:
            m = "%s: len('%s') > maxlen=%d" % (self, shorts(item), maxlen)
            raise CanonifyException(m)

        minlen = optget('minlen', None)
        if minlen is not None and itemlen < minlen:
            m = "%s: len('%s') < minlen=%d" % (self, shorts(item), minlen)
            raise CanonifyException(m)
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
318

319
320
321
322
323
324
325
326
327
328
329
330
        matcher = self.matcher
        if matcher is not None:
            match = matcher.match(item)
            if  (       match is None
                    or  (match.start(), match.end()) != (0, itemlen)    ):

                    m = ("%s: '%s' does not match '%s'"
                            % (self, shorts(item), self.pat))
                    raise CanonifyException(m)

        return item

331
332
333
    def _parse(self, item):
        return self.check(item)

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
    default_alphabet = '0123456789αβγδεζ'.decode('utf8')

    def random_string(self, kw):
        opts = self.opts
        if 'regex' in opts:
            m = 'Unfortunately, random for regex strings not supported'
            raise ValueError(m)

        optget = opts.get
        kwget = kw.get
        minlen = kwget('minlen', optget('minlen', 0))
        maxlen = kwget('maxlen', optget('maxlen', 32))
        alphabet = kwget('alphabet', self.default_alphabet)
        z = maxlen - minlen
        if z < 1:
            z = 1

        g = log(z, 2)
        r = random() * g
        z = minlen + int(2**r)

        s = u''
        for _ in xrange(z):
            s += choice(alphabet)

        return s

    random_choice = random_string

363

364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
class Bytes(Canonical):

    re = None
    matcher = None
    choices = None

    def init(self):
        opts = self.opts
        if 'regex' in opts:
            pat = opts['regex']
            re = self.re
            if re is None:
                import re
                self.re = re

            self.matcher = re.compile(pat)
            self.pat = pat

        if 'choices' in opts:
            opts['choices'] = dict((str(x), str(x))
                                    for x in opts['choices'])

386
    def _check(self, item):
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
        if isinstance(item, unicode):
            # convert unicode to utf8
            item = item.encode('utf8')

        opts = self.opts
        if 'choices' in opts:
            choices = opts['choices']
            try:
                unknown = item not in choices
            except TypeError, e:
                m = "%s: unhashable type '%s'" % (self.name, shorts(item))
                raise CanonifyException(m, e)

            if unknown:
                m = "%s: '%s' not in choices" % (self.name, shorts(item))
                raise CanonifyException(m)

            return choices[item]

        optget = opts.get
        itemlen = len(item)
        maxlen = optget('maxlen', None)
        if maxlen is not None and itemlen > maxlen:
            m = "%s: len('%s') > maxlen=%d" % (self, shorts(item), maxlen)
            raise CanonifyException(m)

        minlen = optget('minlen', None)
        if minlen is not None and itemlen < minlen:
            m = "%s: len('%s') < minlen=%d" % (self, shorts(item), minlen)
            raise CanonifyException(m)
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
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
447
448
449
450
451
452
453
454
455
456
457
458
459
        matcher = self.matcher
        if matcher is not None:
            match = matcher.match(item)
            if  (       match is None
                    or  (match.start(), match.end()) != (0, itemlen)    ):

                    m = ("%s: '%s' does not match '%s'"
                            % (self, shorts(item), self.pat))
                    raise CanonifyException(m)

        return item

    default_alphabet = '0123456789abcdef'

    def random_bytes(self, kw):
        opts = self.opts
        if 'regex' in opts:
            m = 'Unfortunately, random for regex strings not supported'
            raise ValueError(m)

        optget = opts.get
        kwget = kw.get
        minlen = kwget('minlen', optget('minlen', 0))
        maxlen = kwget('maxlen', optget('maxlen', 32))
        alphabet = kwget('alphabet', self.default_alphabet)
        z = maxlen - minlen
        if z < 1:
            z = 1

        g = log(z, 2)
        r = random() * g
        z = minlen + int(2**r)

        s = u''
        for _ in xrange(z):
            s += choice(alphabet)

        return s

    random_choice = random_bytes


460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
class ListOf(Canonical):

    def init(self):
        args = self.args
        kw = self.kw

        if not (args or kw):
            raise SpecifyException("ListOf requires one or more arguments")

        if args and kw:
            m = ("ListOf requires either positional "
                 "or keyword arguments, but not both")
            raise SpecifyException(m)

        if args:
            if len(args) > 1:
                self.canonical = Tuple(*args)
            else:
                self.canonical = args[0]
        else:
            self.canonical = Args(**kw)

482
    def _check(self, item):
483
484
485
486
487
488
        if item is None:
            item = ()

        try:
            items = iter(item)
        except TypeError, e:
489
            m = "%s: %s is not iterable" % (self, shorts(item))
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
            raise CanonifyException(m)

        canonical = self.canonical
        canonified = []
        append = canonified.append

        for item in items:
            item = canonical(item)
            append(item)

        if not canonified and self.opts.get('nonempty', False):
            m = "%s: must be nonempty" % (self,)
            raise CanonifyException(m)

        return canonified

506
    def _parse(self, item):
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
        if item is None:
            item = ()

        try:
            items = iter(item)
        except TypeError, e:
            m = "%s: %s is not iterable" % (self, shorts(item))
            raise CanonifyException(m)

        canonical = self.canonical
        canonified = []
        append = canonified.append

        for k, v in items:
            item = canonical.parse(v)
            append(item)

        if not canonified and self.opts.get('nonempty', False):
            m = "%s: must be nonempty" % (self,)
            raise CanonifyException(m)

        return canonified
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
529

530
531
532
533
534
535
536
537
    def random_listof(self, kw):
        z = randint(1, 4)
        get_random = self.canonical.random

        return [get_random() for _ in xrange(z)]

    random_choice = random_listof

538
539
540

class Args(Canonical):

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
541
542
543
544
    def _parse(self, arglist):
        formalslen = len(self.kw)
        arglen = len(arglist)
        if arglen != formalslen:
545
546
            raise Exception('param inconsistent')

547
        parsed = OrderedDict()
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
        keys = self.kw.keys()
        position = 0

        for k, v in arglist:
            if k:
                parsed[k] = self.kw[k].parse(v)
            else:
                # find the right position
                for i in range(position, arglen):
                    key = keys[i]
                    if not key in parsed.keys():
                        position = i + 1
                        break
                else: # exhausted
                    raise Exception("shouldn't happen")
                parsed[key] = self.kw[key].parse(v)

565
        return parsed
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
566

567
    def _check(self, item):
568
        try:
569
            item = OrderedDict(item)
570
        except TypeError, e:
571
            m = "%s: %s is not dict-able" % (self, shorts(item))
572
573
            raise CanonifyException(m)

574
        canonified = OrderedDict()
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
575

576
        try:
577
            for n, c in self.kw.items():
578
                t = item[n] if n in item else None
579
                canonified[n] = c(t)
580
        except KeyError:
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
581
            m = ("%s: Argument '%s' not found in '%s'"
582
                        % (self, shorts(n), shorts(item)))
583
584
585
586
            raise CanonifyException(m)

        return canonified

587
588
    def random_args(self, kw):
        args = {}
589
        for n, c in self.kw.items():
590
591
592
593
594
            args[n] = c.random()
        return args

    random_choice = random_args

595
596
597

class Tuple(Canonical):

598
    def _check(self, item):
599
600
601
        try:
            items = list(item)
        except TypeError, e:
602
            m = "%s: %s is not iterable" % (self, shorts(item))
603
604
605
606
607
608
609
610
611
612
613
614
615
616
            raise CanonifyException(m)

        canonicals = self.args
        zi = len(items)
        zc = len(canonicals)

        if zi != zc:
            m = "%s: expecting %d elements, not %d (%s)" % (self, zc, zi, str(items))
            raise CanonifyException(m)

        g = (canonical(element) for canonical, element in zip(self.args, item))

        return tuple(g)

617
    def _parse(self, item):
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
        try:
            items = list(item)
        except TypeError, e:
            m = "%s: %s is not iterable" % (self, shorts(item))
            raise CanonifyException(m)

        canonicals = self.args
        zi = len(items)
        zc = len(canonicals)

        if zi != zc:
            m = "%s: expecting %d elements, not %d (%s)" % (self, zc, zi, str(items))
            raise CanonifyException(m)

        g = (canonical.parse(element)
             for canonical, (k, element) in zip(self.args, item))
        return tuple(g)
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
635

636
637
638
639
640
    def __add__(self, other):
        oargs = other.args if isinstance(other, Tuple) else (other,)
        args = self.args + oargs
        return self.__class__(*args)

641
642
643
644
645
    def random_tuple(self, kw):
        return tuple(c.random() for c in self.args)

    random_choice = random_tuple

646
647
648

class Dict(Canonical):

649
    def _check(self, item):
650
651
652
653
654
655
656
657

        try:
            item = dict(item)
        except TypeError:
            m = "%s: '%s' is not dict-able" % (self, shorts(item))
            raise CanonifyException(m)

        canonified = {}
658
659
660
661
662
663
        canonical = self.kw

        for n, c in canonical.items():
            if n not in item:
                m = "%s: key '%s' not found" % (self, shorts(n))
                raise CanonifyException(m)
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
664
            canonified[n] = c(item[n])
665

666
        strict = self.opts.get('strict', True)
667
668
669
670
671
672
673
674
        if strict and len(item) != len(canonical):
            for k in sorted(item.keys()):
                if k not in canonical:
                    break

            m = "%s: unexpected key '%s' (strict mode)" % (self, shorts(k))
            raise CanonifyException(m)

675
676
        return canonified

677
    def _parse(self, item):
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703

        try:
            item = dict(item)
        except TypeError:
            m = "%s: '%s' is not dict-able" % (self, shorts(item))
            raise CanonifyException(m)

        canonified = {}
        canonical = self.kw

        for n, c in canonical.items():
            if n not in item:
                m = "%s: key '%s' not found" % (self, shorts(n))
                raise CanonifyException(m)
            canonified[n] = c(item[n])

        strict = self.opts.get('strict', True)
        if strict and len(item) != len(canonical):
            for k in sorted(item.keys()):
                if k not in canonical:
                    break

            m = "%s: unexpected key '%s' (strict mode)" % (self, shorts(k))
            raise CanonifyException(m)

        return canonified
Kostas Papadimitriou's avatar
Kostas Papadimitriou committed
704

705
706
    def random_dict(self, kw):
        item = {}
707
        for n, c in self.canonical.items():
708
709
710
711
712
713
            item[n] = c.random()

        return item

    random_choice = random_dict

714
715

class Canonifier(object):
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
716
    def __init__(self, name, input_canonicals, output_canonicals, doc_strings):
717
718
719
        self.name = name
        self.input_canonicals = dict(input_canonicals)
        self.output_canonicals = dict(output_canonicals)
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
720
        self.doc_strings = dict(doc_strings)
721
722
723
724

    def call_names(self):
        return self.input_canonicals.keys()

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
725
726
727
728
    def call_docs(self):
        for call_name, call_doc in self.doc_strings.iteritems():
            yield call_name, call_doc

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
729
730
731
732
733
734
735
    def get_doc(self, name):
        if name not in self.doc_strings:
            m = "%s: Invalid method name '%s'" % (self.name, name)
            raise CanonifyException(m)

        return self.doc_strings[name]

736
737
738
739
    def call_attrs(self):
        for call_name, canonical in self.input_canonicals.iteritems():
            yield call_name, canonical.tostring(showopts=1, multiline=1)

740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
    def input_canonical(self, name):
        input_canonicals = self.input_canonicals
        if name not in input_canonicals:
            m = "%s: Invalid input call '%s'" % (self.name, name)
            raise CanonifyException(m)

        return input_canonicals[name]

    def canonify_input(self, name, the_input):
        return self.input_canonical(name)(the_input)

    def output_canonical(self, name):
        output_canonicals = self.output_canonicals
        if name not in output_canonicals:
            m = "%s: Output canonical '%s' does not exist" % (self.name, name)
            raise CanonifyException(m)

        return output_canonicals[name]

    def canonify_output(self, name, the_output):
        return self.output_canonical(name)(the_output)

762
763
764
765
766
    def parse(self, method, arglist):
        args, rest = betteron_decode(arglist)
        argdict = self.input_canonical(method).parse(args)
        return argdict

767
768
769
770
771
772
773
774
775
776
777
778

class Specificator(object):

    def __new__(cls):
        if cls is Specificator:
            m = "Specificator classes must be subclassed"
            raise SpecifyException(m)

        import inspect

        canonical_inputs = {}
        canonical_outputs = {}
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
779
        doc_strings = {}
780
781
782
783
784
785

        for name in dir(cls):
            f = getattr(cls, name)
            if not inspect.ismethod(f) or f.__name__.startswith('_'):
                continue

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
786
            doc_strings[name] = f.__doc__
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
            argspec = inspect.getargspec(f)
            defaults = argspec.defaults
            args = argspec.args
            if args and args[0] == 'self':
                args = args[1:]

            if not defaults:
                defaults = ()

            arglen = len(args)
            deflen = len(defaults)

            if arglen != deflen:
                a = (f.__name__, args[:arglen-deflen])
                m = "Unspecified arguments in '%s': %s" % a
                raise SpecifyException(m)

804
805
            args = zip(args, defaults)
            for a, c in args:
806
807
808
809
810
                if not isinstance(c, Canonical):
                    m = ("argument '%s=%s' is not an instance of 'Canonical'"
                         % (a, repr(c)))
                    raise SpecifyException(m)

811
            canonical = Null() if len(args) == 0 else Args(*args)
812
813
814
815
816
            canonical_inputs[name] = canonical

            self = object.__new__(cls)
            canonical = f(self)
            if not isinstance(canonical, Canonical):
817
818
                m = ("method '%s' does not return a Canonical, but a(n) %s "
                                                    % (name, type(canonical)))
819
820
821
                raise SpecifyException(m)
            canonical_outputs[name] = canonical

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
822
823
        return Canonifier(cls.__name__, canonical_inputs, canonical_outputs,
                          doc_strings)
824
825
826
827

    def __call__(self):
        return self