Example #1
0
    def __getitem__(self, slyce):
        """ Examples:

            self[fname:func_name] -->
              src_code for corresponding test function

            self[fname::func_name] -->
              src_code for function test function was generated from
        """
        from pythoscope.generator import find_method_code
        from pythoscope.astbuilder import parse
        if not isinstance(slyce, slice):
            raise Exception,NotImplementedYet
        fpath,y,z = slyce.start,slyce.stop,slyce.step
        if y:
            out = find_method_code(parse(self>>fpath), y)
        elif z:
            out = find_method_code(parse(open(fpath).read()), z)

        if not out:
            raise Exception,NotImplementedYet
        out = str(out).replace('"""',"'").split('\n')
        def x(line):
            if line.strip(): return INDENTION*2 + line
            else: return INDENTION*2+line
        out = [ x(line) for line in out]
        return '\n'.join(out)
Example #2
0
def get_code_metrics_from_file(code):
    def not_blank_nor_comment(line):
        return not (line.lstrip() == '' or line.lstrip().startswith('#'))

    class ModuleVisitor(ASTVisitor):
        def __init__(self):
            ASTVisitor.__init__(self)
            self.functions = 0
            self.classes = 0
            self.methods = 0

        def visit_class(self, name, bases, body):
            visitor = descend(body.children, ClassVisitor)
            self.methods += visitor.methods
            self.classes += 1

        def visit_function(self, name, args, body):
            self.functions += 1

    class ClassVisitor(ASTVisitor):
        def __init__(self):
            ASTVisitor.__init__(self)
            self.methods = 0

        def visit_function(self, name, args, body):
            self.methods += 1

    try:
        tree = parse(code)
    except ParseError, e:
        notify("Caught parse error: %s." % e)
        raise GatheringError("Failed at code metrics.")
Example #3
0
def get_code_metrics_from_file(code):
    def not_blank_nor_comment(line):
        return not (line.lstrip() == '' or line.lstrip().startswith('#'))
    class ModuleVisitor(ASTVisitor):
        def __init__(self):
            ASTVisitor.__init__(self)
            self.functions = 0
            self.classes = 0
            self.methods = 0
        def visit_class(self, name, bases, body):
            visitor = descend(body.children, ClassVisitor)
            self.methods += visitor.methods
            self.classes += 1
        def visit_function(self, name, args, body):
            self.functions += 1
    class ClassVisitor(ASTVisitor):
        def __init__(self):
            ASTVisitor.__init__(self)
            self.methods = 0
        def visit_function(self, name, args, body):
            self.methods += 1
    try:
        tree = parse(code)
    except ParseError, e:
        notify("Caught parse error: %s." % e)
        raise GatheringError("Failed at code metrics.")
Example #4
0
    def _test_import(self, code, method):
        method_called = [False]
        class TestVisitor(ASTVisitor):
            def visit_import(self, names, import_from, body):
                method(names, import_from)
                method_called[0] = True

        TestVisitor().visit(parse(code))
        assert method_called[0], "visit_import wasn't called at all"
Example #5
0
    def _test_main_snippet(self, code, method):
        method_called = [False]
        class TestVisitor(ASTVisitor):
            def visit_main_snippet(self, body):
                method(regenerate(body))
                method_called[0] = True

        TestVisitor().visit(parse(code))
        assert method_called[0], "visit_main_snippet wasn't called at all"
    def test_replacing_a_test_case_removes_it_from_the_list_of_objects_and_list_of_test_cases(self):
        project = EmptyProject()
        module = project.create_module("module.py", code=parse("# only comments"))
        test_class = create(TestClass, name="TestSomething")
        new_test_class = create(TestClass, name="TestSomethingElse")
        add_test_case(module, test_class)

        replace_test_case(module, test_class, new_test_class)

        assert_equal([new_test_class], module.objects)
        assert_equal([new_test_class], module.test_cases)
    def test_replacing_a_test_case_removes_it_from_the_list_of_objects_and_list_of_test_cases(
            self):
        project = EmptyProject()
        module = project.create_module("module.py",
                                       code=parse("# only comments"))
        test_class = create(TestClass, name="TestSomething")
        new_test_class = create(TestClass, name="TestSomethingElse")
        add_test_case(module, test_class)

        replace_test_case(module, test_class, new_test_class)

        assert_equal([new_test_class], module.objects)
        assert_equal([new_test_class], module.test_cases)
Example #8
0
def inspect_code(project, path, code):
    try:
        tree = parse(code)
    except ParseError as e:
        log.warning("Inspection of module %s failed with error %s" % (path,e))
        return project.create_module(path, errors=[e]) #try to skip
    visitor = descend(tree, ModuleVisitor)

    # We assume that all test classes in this module has dependencies on
    # all imports the module contains.
    for test_class in [o for o in visitor.objects if isinstance(o, TestClass)]:
        # We gathered all imports in a single list, but import lists of those
        # classes may diverge in time, so we don't want to share their
        # structure.
        test_class.imports = visitor.imports[:]

    return project.create_module(path, code=tree, objects=visitor.objects,
        imports=visitor.imports, main_snippet=visitor.main_snippet,
        last_import=visitor.last_import)
Example #9
0
def inspect_code(project, path, code):
    try:
        tree = parse(code)
    except ParseError as e:
        log.warning("Inspection of module %s failed with error %s" % (path,e))
        return project.create_module(path, errors=[e]) #try to skip
    visitor = descend(tree, ModuleVisitor)

    # We assume that all test classes in this module has dependencies on
    # all imports the module contains.
    for test_class in [o for o in visitor.objects if isinstance(o, TestClass)]:
        # We gathered all imports in a single list, but import lists of those
        # classes may diverge in time, so we don't want to share their
        # structure.
        test_class.imports = visitor.imports[:]

    return project.create_module(path, code=tree, objects=visitor.objects,
        imports=visitor.imports, main_snippet=visitor.main_snippet,
        last_import=visitor.last_import)
Example #10
0
        if self.after_callback:
            self.after_callback(obj)
        return obj


########################################################################
## A few handy factories for Pythoscope.
##
from pythoscope.astbuilder import parse
from pythoscope.serializer import UnknownObject, ImmutableObject, SequenceObject
from pythoscope.store import Function, FunctionCall, Definition, TestClass,\
    TestMethod, Module, Project

register_factory(Project, path="/tmp/")
register_factory(Module, project=create(Project), subpath="module")
register_factory(Definition, name="definition")
register_factory(Function, name="function", module=create(Module))
register_factory(UnknownObject, obj=None)
register_factory(ImmutableObject, obj=1)
register_factory(SequenceObject,
                 obj=[],
                 serialize=lambda x: create(UnknownObject, obj=x))
register_dynamic_factory(FunctionCall,
                         lambda:dict(definition=create(Function), args={}, output=create(ImmutableObject))).\
  after(lambda fc: fc.definition.add_call(fc))
register_dynamic_factory(
    TestMethod,
    lambda: dict(name="test_method", code=parse("# a test method")))
register_dynamic_factory(
    TestClass, lambda: dict(name="TestClass", code=parse("# a test class")))
Example #11
0
        return self

    def invoke(self, klass, kwargs):
        args = self.args_callback()
        args.update(kwargs)
        obj = klass(**args)
        if self.after_callback:
            self.after_callback(obj)
        return obj


########################################################################
## A few handy factories for Pythoscope.
##
from pythoscope.astbuilder import parse
from pythoscope.serializer import UnknownObject, ImmutableObject, SequenceObject
from pythoscope.store import Function, FunctionCall, Definition, TestClass, TestMethod, Module, Project

register_factory(Project, path="/tmp/")
register_factory(Module, project=create(Project), subpath="module")
register_factory(Definition, name="definition")
register_factory(Function, name="function", module=create(Module))
register_factory(UnknownObject, obj=None)
register_factory(ImmutableObject, obj=1)
register_factory(SequenceObject, obj=[], serialize=lambda x: create(UnknownObject, obj=x))
register_dynamic_factory(
    FunctionCall, lambda: dict(definition=create(Function), args={}, output=create(ImmutableObject))
).after(lambda fc: fc.definition.add_call(fc))
register_dynamic_factory(TestMethod, lambda: dict(name="test_method", code=parse("# a test method")))
register_dynamic_factory(TestClass, lambda: dict(name="TestClass", code=parse("# a test class")))
Example #12
0
 def test_handles_inputs_without_newline(self):
     tree = parse("42 # answer")
     assert_equal("42 # answer", regenerate(tree))
Example #13
0
def inspect_code(project, path, code):
    try:
        tree = parse(code)
    except ParseError, e:
        log.warning("Inspection of module %s failed." % path)
        return project.create_module(path, errors=[e])
Example #14
0
 def setUp(self):
     self.project = EmptyProject()
     self.module = self.project.create_module("module.py",
                                              code=parse("# only comments"))
     self.test_class = TestClass(name="TestSomething",
                                 code=parse("# some test code"))
Example #15
0
 def setUp(self):
     self.project = EmptyProject()
     self.module = self.project.create_module("module.py", code=parse("# only comments"))
     self.test_class = TestClass(name="TestSomething", code=parse("# some test code"))