bebraw
3/14/2010 - 4:56 PM

myclass.py

from __future__ import with_statement

import imp
import yaml

if __name__ == "__main__":
    spec_file = 'spec_myclass.yaml'
    imp_file = 'myclass.py' # this should be derived directly from the spec

    with open(spec_file) as f:
        specs = yaml.safe_load(f)

    module_name = imp_file.split('.')[0]
    module = imp.load_source(module_name, imp_file)

    set_up = specs['set up']

    for k, v in specs.items():
        if k != 'set up':
            def run_test(test_code):
                # TODO: replace this with something nicer :) (ie. expecter or specs)
                test = set_up + ';assert ' + test_code
                exec(test, {module_name: module, })

            if ' raises ' in v:
                test_code, exc = v.split(' raises ')

                try:
                    run_test(test_code)
                except eval(exc):
                    pass
            else:
                run_test(v)
set up:
    c = myclass.MyClass() # this has to match the module name

adds two and two:
    c.add(2,2) == 4

adds negatives:
    c.add(10, -10) == 0

fails adding int and string:
    c.add(10, 'foo') raises TypeError
class MyClass(object):
    def add(self, a, b):
        return a + b