Passed
Push — main ( 325744...be7884 )
by Eran
01:17
created

conftest._ast_nodes()   A

Complexity

Conditions 3

Size

Total Lines 5
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 5
nop 1
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
import ast
2
import hashlib
3
import inspect
4
import operator
5
import pickle
6
import random
7
from _ast import AST
8
from collections.abc import Iterable
9
10
import faker
11
import graphinate
12
import pytest
13
14
15
@pytest.fixture()
16
def country_count():
17
    return random.randint(1, 10)
18
19
20
@pytest.fixture()
21
def city_count():
22
    return random.randint(20, 40)
23
24
25
def _ast_nodes(parsed_asts: Iterable[AST]):
26
    for item in parsed_asts:
27
        if not isinstance(item, ast.Load):
28
            yield item
29
            yield from _ast_nodes(ast.iter_child_nodes(item))
30
31
32 View Code Duplication
def _ast_edge(parsed_ast: AST):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
33
    for child_ast in ast.iter_child_nodes(parsed_ast):
34
        if not isinstance(child_ast, ast.Load):
35
            edge = {'source': parsed_ast, 'target': child_ast}
36
            edge_types = (field_name for field_name, value in ast.iter_fields(parsed_ast) if
0 ignored issues
show
introduced by
The variable field_name does not seem to be defined for all execution paths.
Loading history...
37
                          child_ast == value or (child_ast in value if isinstance(value, list) else False))
38
            edge_type = next(edge_types, None)
39
            if edge_type:
40
                edge['type'] = edge_type
41
            yield edge
42
            yield from _ast_edge(child_ast)
43
44
45 View Code Duplication
@pytest.fixture()
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
46
def ast_graph_model():
47
    graph_model = graphinate.model(name='AST Graph')
48
49
    root_ast_node = ast.parse(inspect.getsource(graphinate.builders.D3Builder))
50
51
    def node_type(ast_node):
52
        return ast_node.__class__.__name__
53
54
    def node_label(ast_node) -> str:
55
        label = ast_node.__class__.__name__
56
57
        for field_name in ('name', 'id'):
58
            if field_name in ast_node._fields:
59
                label = f"{label}\n{field_name}: {operator.attrgetter(field_name)(ast_node)}"
60
61
        return label
62
63
    def key(value):
64
        # noinspection InsecureHash
65
        return hashlib.md5(pickle.dumps(value)).hexdigest()
66
67
    def endpoint(value, endpoint_name):
68
        return key(value[endpoint_name])
69
70
    def source(value):
71
        return endpoint(value, 'source')
72
73
    def target(value):
74
        return endpoint(value, 'target')
75
76
    @graph_model.node(_type=node_type, key=key, label=node_label, uniqueness=True)
77
    def ast_node(**kwargs):
78
        yield from _ast_nodes([root_ast_node])
79
80
    @graph_model.edge(_type='edge', source=source, target=target, label=operator.itemgetter('type'))
81
    def ast_edge(**kwargs):
82
        yield from _ast_edge(root_ast_node)
83
84
    return graph_model
85
86
87
@pytest.fixture()
88
def map_graph_model(country_count, city_count):
89
    country_ids = {str(c): None for c in range(1, country_count + 1)}
90
    city_ids = {str(c): random.choice(list(country_ids.keys())) for c in range(1, city_count + 1)}
91
92
    graph_model = graphinate.model(name='Map')
93
94
    faker.Faker.seed(0)
95
    fake = faker.Faker()
96
97
    def country_node_label(value):
98
        return fake.country()
99
100
    def city_node_label(value):
101
        return fake.city()
102
103
    @graph_model.node(label=country_node_label)
104
    def country(country_id=None, **kwargs):
105
106
        if country_id and country_id in country_ids:
107
            yield country_id
108
        else:
109
            yield from country_ids
110
111
    @graph_model.node(parent_type='country', label=city_node_label)
112
    def city(country_id=None, city_id=None, **kwargs):
113
114
        if country_id is None and city_id is None:
115
            yield from city_ids.keys()
116
117
        if country_id is None and city_id is not None and city_id in city_ids:
118
            yield city_id
119
120
        if city_id is not None and country_id is not None and city_ids.get(city_id) == country_id:
121
            yield city_id
122
123
        if country_id is not None and city_id is None:
124
            yield from (k for k, v in city_ids.items() if v == country_id)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable k does not seem to be defined.
Loading history...
125
126
    @graph_model.node(_type=operator.itemgetter('sex'),
127
                      parent_type='city',
128
                      key=operator.itemgetter('username'),
129
                      label=operator.itemgetter('name'))
130
    def person(country_id=None, city_id=None, person_id=None, **kwargs):
131
        yield fake.profile()
132
133
    return country_count, city_count, graph_model
134
135
136
@pytest.fixture()
137
def octagonal_graph_model():
138
    graph_model = graphinate.model(name="Octagonal Graph")
139
    number_of_sides = 8
140
141
    # Register edges supplier function
142
    @graph_model.edge()
143
    def edge():
144
        for i in range(number_of_sides):
145
            yield {'source': i, 'target': i + 1}
146
        yield {'source': number_of_sides, 'target': 0}
147
148
    return graph_model
149
150
151
@pytest.fixture()
152
def graphql_query():
153
    return """
154
    query Graph {
155
      graph {
156
        name
157
        nodeTypeCounts {
158
          name
159
          value
160
        }
161
        edgeTypeCounts {
162
          name
163
          value
164
        }
165
        created
166
        nodeCount
167
        edgeCount
168
        size
169
        order
170
        radius
171
        diameter
172
        averageDegree
173
        hash
174
      }
175
      nodes {
176
        id
177
        ...ElementDetails
178
        neighbors {id type label}
179
        children: neighbors(children: true) {id type label}
180
        edges {id type label}
181
      }
182
      edges {
183
        source {id ...ElementDetails}
184
        target {id ...ElementDetails}
185
        ...ElementDetails
186
        weight
187
      }
188
    }
189
190
    fragment ElementDetails on GraphElement {
191
      label
192
      type
193
      label
194
      color
195
      created
196
      updated
197
    }
198
    """
199