fastest.code_assets.function.get_functions()   A
last analyzed

Complexity

Conditions 2

Size

Total Lines 31
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 31
rs 9.9
c 0
b 0
f 0
cc 2
nop 1
1
import ast
2
from fastest.code_assets.naive_case_detector import get_test_from_example_passage
3
from fastest.logger.logger import logger
4
5
6
def get_functions_from_node(node):
7
    """
8
    Extract functions from ast node
9
    :param node:
10
    :return: list
11
    """
12
    return [{
13
        'name': n.name,
14
        'tests': get_test_from_example_passage(ast.get_docstring(n))
15
    } for n in node.body if isinstance(n, ast.FunctionDef)]
16
17
18
def get_functions(page):
19
    """
20
    Read a python script and extract functions and class methods
21
    and add them to a list
22
    ------
23
    examples:
24
25
    @need
26
    from fastest.constants import TestBodies
27
    @end
28
29
    @let
30
    page = TestBodies.GET_FUNCTIONS_TEST_CASE_1
31
    page_with_syntax_error = TestBodies.PAGE_WITH_SYNTAX_ERRORS
32
    @end
33
34
    1) get_functions(page) -> TestBodies.GET_FUNCTIONS_TEST_CASE_1_EXPECT
35
    2) get_functions(page_with_syntax_error) -> []
36
    ------
37
    :param page: str
38
    :return: list
39
    """
40
    try:
41
        node = ast.parse(page)
42
        functions = get_functions_from_node(node)
43
        classes = [n for n in node.body if isinstance(n, ast.ClassDef)]
44
        methods = [get_functions_from_node(class_) for class_ in classes]
45
        return functions + methods
46
    except SyntaxError as error:
47
        logger.error(error)
48
        return []
49
50