Ejemplo n.º 1
0
def test_serialize(node):
    """Serialized returns the expected dict"""
    obj = ParsedModule(node, DEFAULT_PATH)
    serialized = obj.serialize()
    expected = {
        "name": DEFAULT_NAME,
        "docstring": ast.get_docstring(node),
    }
    assert isinstance(serialized, dict)
    assert serialized == expected
Ejemplo n.º 2
0
class ModuleStructure(CodeStructure):
    """
    Code structure of a Python module
    """
    def __init__(self, module_path):
        """
        Stores information about
        the structure of a module

        :param module_path: str - Filepath of the python module
        """
        self.name = get_python_module_name_from_path(module_path)
        self.path = module_path
        self.module = None
        self.classes = []
        self.functions = []

        self.parsed_references = []

    def parse_module(self, node):
        """
        Parses an ast node creating a ParsedModule object.
        Adds the module to the references

        :param node: ast node
        :returns ParsedModule
        """
        self.module = ParsedModule(node, self.path)
        self.parsed_references.append(node)

    def parse_class(self, node):
        """
        Parses an ast node creating a ParsedClass object.
        Adds the class and its methods to the references

        :param node: ast node
        :returns ParsedModule
        """
        if not node in self.parsed_references:
            parsed_class = ParsedClass(node)
            self.classes.append(parsed_class)
            self.parsed_references.append(node)
            self.parsed_references += [
                func.node for func in parsed_class.functions
            ]

    def parse_function(self, node):
        """
        Parses an ast node creating a ParsedFunction object.
        Adds the function to the references

        :param node: ast node
        :returns ParsedFunction
        """
        if not node in self.parsed_references:
            parsed_function = ParsedFunction(node)
            self.functions.append(parsed_function)
            self.parsed_references.append(node)

    def serialize(self):
        """
        Serializes the library information in a dict

        :returns: dict
        """
        return {
            "module":
            self.module.serialize() if self.module else None,
            "classes":
            [parsed_class.serialize() for parsed_class in self.classes],
            "functions": [
                parsed_function.serialize()
                for parsed_function in self.functions
            ],
        }

    def __str__(self):
        """
        String representation of the instance

        :returns: str
        """
        return "Module '{name}' structure".format(name=self.name, )