-
Notifications
You must be signed in to change notification settings - Fork 412
/
test_networkx.py
505 lines (416 loc) · 19.4 KB
/
test_networkx.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import age
import unittest
import argparse
import networkx as nx
from age.models import *
from age.networkx import *
from age.exceptions import *
TEST_GRAPH_NAME = "test_graph"
ORIGINAL_GRAPH = "original_graph"
EXPECTED_GRAPH = "expected_graph"
TEST_HOST = "localhost"
TEST_PORT = 5432
TEST_DB = "postgres"
TEST_USER = "postgres"
TEST_PASSWORD = "agens"
class TestAgeToNetworkx(unittest.TestCase):
ag = None
args: argparse.Namespace = argparse.Namespace(
host=TEST_HOST,
port=TEST_PORT,
database=TEST_DB,
user=TEST_USER,
password=TEST_PASSWORD,
graphName=TEST_GRAPH_NAME
)
def setUp(self):
args = dict(
host=self.args.host,
port=self.args.port,
dbname=self.args.database,
user=self.args.user,
password=self.args.password
)
dsn = "host={host} port={port} dbname={dbname} user={user} password={password}".format(**args)
self.ag = age.connect(dsn, graph=TEST_GRAPH_NAME, **args)
def tearDown(self):
age.deleteGraph(self.ag.connection, TEST_GRAPH_NAME)
self.ag.close()
def compare_networkX(self, G, H):
if G.number_of_nodes() != H.number_of_nodes():
return False
if G.number_of_edges() != H.number_of_edges():
return False
# test nodes
nodes_G, nodes_H = G.number_of_nodes(), H.number_of_nodes()
markG, markH = [0]*nodes_G, [0]*nodes_H
nodes_list_G, nodes_list_H = list(G.nodes), list(H.nodes)
for i in range(0, nodes_G):
for j in range(0, nodes_H):
if markG[i] == 0 and markH[j] == 0:
node_id_G = nodes_list_G[i]
property_G = G.nodes[node_id_G]
node_id_H = nodes_list_H[j]
property_H = H.nodes[node_id_H]
if property_G == property_H:
markG[i] = 1
markH[j] = 1
if any(elem == 0 for elem in markG):
return False
if any(elem == 0 for elem in markH):
return False
# test edges
edges_G, edges_H = G.number_of_edges(), H.number_of_edges()
markG, markH = [0]*edges_G, [0]*edges_H
edges_list_G, edges_list_H = list(G.edges), list(H.edges)
for i in range(0, edges_G):
for j in range(0, edges_H):
if markG[i] == 0 and markH[j] == 0:
source_G, target_G = edges_list_G[i]
property_G = G.edges[source_G, target_G]
source_H, target_H = edges_list_H[j]
property_H = H.edges[source_H, target_H]
if property_G == property_H:
markG[i] = 1
markH[j] = 1
if any(elem == 0 for elem in markG):
return False
if any(elem == 0 for elem in markH):
return False
return True
def test_empty_graph(self):
print('Testing AGE to Networkx for empty graph')
# Expected Graph
# Empty Graph
G = nx.DiGraph()
# Convert Apache AGE to NetworkX
H = age_to_networkx(self.ag.connection, TEST_GRAPH_NAME)
self.assertTrue(self.compare_networkX(G, H))
def test_existing_graph_without_query(self):
print('Testing AGE to Networkx for non empty graph without query')
ag = self.ag
# Create nodes
ag.execCypher("CREATE (n:Person {name: %s}) ", params=('Jack',))
ag.execCypher("CREATE (n:Person {name: %s}) ", params=('Andy',))
ag.execCypher("CREATE (n:Person {name: %s}) ", params=('Smith',))
ag.commit()
# Create Edges
ag.execCypher("""MATCH (a:Person), (b:Person)
WHERE a.name = 'Andy' AND b.name = 'Jack'
CREATE (a)-[r:workWith {weight: 3}]->(b)""")
ag.execCypher("""MATCH (a:Person), (b:Person)
WHERE a.name = %s AND b.name = %s
CREATE p=((a)-[r:workWith {weight: 10}]->(b)) """, params=('Jack', 'Smith',))
ag.commit()
G = age_to_networkx(self.ag.connection, TEST_GRAPH_NAME)
# Check that the G has the expected properties
self.assertIsInstance(G, nx.DiGraph)
# Check that the G has the correct number of nodes and edges
self.assertEqual(len(G.nodes), 3)
self.assertEqual(len(G.edges), 2)
# Check that the node properties are correct
for node in G.nodes:
self.assertEqual(int, type(node))
self.assertEqual(G.nodes[node]['label'], 'Person')
self.assertIn('name', G.nodes[node]['properties'])
self.assertIn('properties', G.nodes[node])
self.assertEqual(str, type(G.nodes[node]['label']))
# Check that the edge properties are correct
for edge in G.edges:
self.assertEqual(tuple, type(edge))
self.assertEqual(int, type(edge[0]) and type(edge[1]))
self.assertEqual(G.edges[edge]['label'], 'workWith')
self.assertIn('weight', G.edges[edge]['properties'])
self.assertEqual(int, type(G.edges[edge]['properties']['weight']))
def test_existing_graph_with_query(self):
print('Testing AGE to Networkx for non empty graph with query')
ag = self.ag
# Create nodes
ag.execCypher("CREATE (n:Person {name: %s}) ", params=('Jack',))
ag.execCypher("CREATE (n:Person {name: %s}) ", params=('Andy',))
ag.execCypher("CREATE (n:Person {name: %s}) ", params=('Smith',))
ag.commit()
# Create Edges
ag.execCypher("""MATCH (a:Person), (b:Person)
WHERE a.name = 'Andy' AND b.name = 'Jack'
CREATE (a)-[r:workWith {weight: 3}]->(b)""")
ag.execCypher("""MATCH (a:Person), (b:Person)
WHERE a.name = %s AND b.name = %s
CREATE p=((a)-[r:workWith {weight: 10}]->(b)) """, params=('Jack', 'Smith',))
ag.commit()
query = """SELECT * FROM cypher('%s', $$ MATCH (a:Person)-[r:workWith]->(b:Person)
WHERE a.name = 'Andy'
RETURN a, r, b $$) AS (a agtype, r agtype, b agtype);
""" % (TEST_GRAPH_NAME)
G = age_to_networkx(self.ag.connection,
graphName=TEST_GRAPH_NAME, query=query)
# Check that the G has the expected properties
self.assertIsInstance(G, nx.DiGraph)
# Check that the G has the correct number of nodes and edges
self.assertEqual(len(G.nodes), 2)
self.assertEqual(len(G.edges), 1)
# Check that the node properties are correct
for node in G.nodes:
self.assertEqual(int, type(node))
self.assertEqual(G.nodes[node]['label'], 'Person')
self.assertIn('name', G.nodes[node]['properties'])
self.assertIn('properties', G.nodes[node])
self.assertEqual(str, type(G.nodes[node]['label']))
# Check that the edge properties are correct
for edge in G.edges:
self.assertEqual(tuple, type(edge))
self.assertEqual(int, type(edge[0]) and type(edge[1]))
self.assertEqual(G.edges[edge]['label'], 'workWith')
self.assertIn('weight', G.edges[edge]['properties'])
self.assertEqual(int, type(G.edges[edge]['properties']['weight']))
def test_existing_graph(self):
print("Testing AGE to NetworkX for non-existing graph")
ag = self.ag
non_existing_graph = "non_existing_graph"
# Check that the function raises an exception for non existing graph
with self.assertRaises(GraphNotFound) as context:
age_to_networkx(ag.connection, graphName=non_existing_graph)
# Check the raised exception has the expected error message
self.assertEqual(str(context.exception), non_existing_graph)
class TestNetworkxToAGE(unittest.TestCase):
ag = None
ag1 = None
ag2 = None
args: argparse.Namespace = argparse.Namespace(
host=TEST_HOST,
port=TEST_PORT,
database=TEST_DB,
user=TEST_USER,
password=TEST_PASSWORD,
graphName=TEST_GRAPH_NAME
)
def setUp(self):
args = dict(
host=self.args.host,
port=self.args.port,
dbname=self.args.database,
user=self.args.user,
password=self.args.password
)
dsn = "host={host} port={port} dbname={dbname} user={user} password={password}".format(**args)
self.ag = age.connect(dsn, graph=TEST_GRAPH_NAME, **args)
self.ag1 = age.connect(dsn, graph=ORIGINAL_GRAPH, **args)
self.ag2 = age.connect(dsn, graph=EXPECTED_GRAPH, **args)
self.graph = nx.DiGraph()
def tearDown(self):
age.deleteGraph(self.ag1.connection, self.ag1.graphName)
age.deleteGraph(self.ag2.connection, self.ag2.graphName)
age.deleteGraph(self.ag.connection, self.ag.graphName)
self.ag.close()
self.ag1.close()
self.ag2.close()
def compare_age(self, age1, age2):
cursor = age1.execCypher("MATCH (v) RETURN v")
g_nodes = cursor.fetchall()
cursor = age1.execCypher("MATCH ()-[r]->() RETURN r")
g_edges = cursor.fetchall()
cursor = age2.execCypher("MATCH (v) RETURN v")
h_nodes = cursor.fetchall()
cursor = age2.execCypher("MATCH ()-[r]->() RETURN r")
h_edges = cursor.fetchall()
if len(g_nodes) != len(h_nodes) or len(g_edges) != len(h_edges):
return False
# test nodes
nodes_G, nodes_H = len(g_nodes), len(h_nodes)
markG, markH = [0]*nodes_G, [0]*nodes_H
# return True
for i in range(0, nodes_G):
for j in range(0, nodes_H):
if markG[i] == 0 and markH[j] == 0:
property_G = g_nodes[i][0].properties
property_G['label'] = g_nodes[i][0].label
property_G.pop('__id__')
property_H = h_nodes[j][0].properties
property_H['label'] = h_nodes[j][0].label
if property_G == property_H:
markG[i] = 1
markH[j] = 1
if any(elem == 0 for elem in markG):
return False
if any(elem == 0 for elem in markH):
return False
# test edges
edges_G, edges_H = len(g_edges), len(h_edges)
markG, markH = [0]*edges_G, [0]*edges_H
for i in range(0, edges_G):
for j in range(0, edges_H):
if markG[i] == 0 and markH[j] == 0:
property_G = g_edges[i][0].properties
property_G['label'] = g_edges[i][0].label
property_H = h_edges[j][0].properties
property_H['label'] = h_edges[j][0].label
if property_G == property_H:
markG[i] = 1
markH[j] = 1
if any(elem == 0 for elem in markG):
return False
if any(elem == 0 for elem in markH):
return False
return True
def test_number_of_nodes_and_edges(self):
print("Testing Networkx To AGE for number of nodes and edges")
ag = self.ag
# Create NetworkX graph
self.graph.add_node(1, label='Person', properties={
'name': 'Moontasir', 'age': '26', 'id': 1})
self.graph.add_node(2, label='Person', properties={
'name': 'Austen', 'age': '26', 'id': 2})
self.graph.add_edge(1, 2, label='KNOWS', properties={
'since': '1997', 'start_id': 1, 'end_id': 2})
self.graph.add_node(3, label='Person', properties={
'name': 'Eric', 'age': '28', 'id': 3})
networkx_to_age(self.ag.connection, self.graph, TEST_GRAPH_NAME)
# Check that node(s) were created
cursor = ag.execCypher('MATCH (n) RETURN n')
result = cursor.fetchall()
# Check number of vertices created
self.assertEqual(len(result), 3)
# Checks if type of property in query output is a Vertex
self.assertEqual(Vertex, type(result[0][0]))
self.assertEqual(Vertex, type(result[1][0]))
# Check that edge(s) was created
cursor = ag.execCypher('MATCH ()-[e]->() RETURN e')
result = cursor.fetchall()
# Check number of edge(s) created
self.assertEqual(len(result), 1)
# Checks if type of property in query output is an Edge
self.assertEqual(Edge, type(result[0][0]))
def test_empty_graph(self):
print("Testing Networkx To AGE for empty Graph")
# Expected Graph
# Empty Graph
# NetworkX Graph
G = nx.DiGraph()
# Convert Apache AGE to NetworkX
networkx_to_age(self.ag1.connection, G, ORIGINAL_GRAPH)
self.assertTrue(self.compare_age(self.ag1, self.ag2))
def test_non_empty_graph(self):
print("Testing Networkx To AGE for non-empty Graph")
# Expected Graph
self.ag2.execCypher("CREATE (:l1 {name: 'n1', weight: '5'})")
self.ag2.execCypher("CREATE (:l1 {name: 'n2', weight: '4'})")
self.ag2.execCypher("CREATE (:l1 {name: 'n3', weight: '9'})")
self.ag2.execCypher("""MATCH (a:l1), (b:l1)
WHERE a.name = 'n1' AND b.name = 'n2'
CREATE (a)-[e:e1 {property:'graph'}]->(b)""")
self.ag2.execCypher("""MATCH (a:l1), (b:l1)
WHERE a.name = 'n2' AND b.name = 'n3'
CREATE (a)-[e:e2 {property:'node'}]->(b)""")
# NetworkX Graph
G = nx.DiGraph()
G.add_node('1',
label='l1',
properties={'name': 'n1',
'weight': '5'})
G.add_node('2',
label='l1',
properties={'name': 'n2',
'weight': '4'})
G.add_node('3',
label='l1',
properties={'name': 'n3',
'weight': '9'})
G.add_edge('1', '2', label='e1', properties={'property': 'graph'})
G.add_edge('2', '3', label='e2', properties={'property': 'node'})
# Convert Apache AGE to NetworkX
networkx_to_age(self.ag1.connection, G, ORIGINAL_GRAPH)
self.assertTrue(self.compare_age(self.ag1, self.ag2))
def test_invalid_node_label(self):
print("Testing Networkx To AGE for invalid node label")
self.graph.add_node(4, label=123, properties={
'name': 'Mason', 'age': '24', 'id': 4})
# Check that the function raises an exception for the invalid node label
with self.assertRaises(Exception) as context:
networkx_to_age(self.ag.connection, G=self.graph,
graphName=TEST_GRAPH_NAME)
# Check the raised exception has the expected error message
self.assertEqual(str(context.exception),
"label of node : 4 must be a string")
def test_invalid_node_properties(self):
print("Testing Networkx To AGE for invalid node properties")
self.graph.add_node(4, label='Person', properties="invalid")
# Check that the function raises an exception for the invalid node properties
with self.assertRaises(Exception) as context:
networkx_to_age(self.ag.connection, G=self.graph,
graphName=TEST_GRAPH_NAME)
# Check the raised exception has the expected error message
self.assertEqual(str(context.exception),
"properties of node : 4 must be a dict")
def test_invalid_edge_label(self):
print("Testing Networkx To AGE for invalid edge label")
self.graph.add_edge(1, 2, label=123, properties={
'since': '1997', 'start_id': 1, 'end_id': 2})
# Check that the function raises an exception for the invalid edge label
with self.assertRaises(Exception) as context:
networkx_to_age(self.ag.connection, G=self.graph,
graphName=TEST_GRAPH_NAME)
# Check the raised exception has the expected error message
self.assertEqual(str(context.exception),
"label of edge : 1->2 must be a string")
def test_invalid_edge_properties(self):
print("Testing Networkx To AGE for invalid edge properties")
self.graph.add_edge(1, 2, label='KNOWS', properties="invalid")
# Check that the function raises an exception for the invalid edge properties
with self.assertRaises(Exception) as context:
networkx_to_age(self.ag.connection, G=self.graph,
graphName=TEST_GRAPH_NAME)
# Check the raised exception has the expected error message
self.assertEqual(str(context.exception),
"properties of edge : 1->2 must be a dict")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-host',
'--host',
help='Optional Host Name. Default Host is "127.0.0.1" ',
default=TEST_HOST)
parser.add_argument('-port',
'--port',
help='Optional Port Number. Default port no is 5432',
default=TEST_PORT)
parser.add_argument('-db',
'--database',
help='Required Database Name',
default=TEST_DB)
parser.add_argument('-u',
'--user',
help='Required Username Name',
default=TEST_USER)
parser.add_argument('-pass',
'--password',
help='Required Password for authentication',
default=TEST_PASSWORD)
args = parser.parse_args()
suite = unittest.TestSuite()
suite.addTest(TestAgeToNetworkx('test_empty_graph'))
suite.addTest(TestAgeToNetworkx('test_existing_graph_without_query'))
suite.addTest(TestAgeToNetworkx('test_existing_graph_with_query'))
suite.addTest(TestAgeToNetworkx('test_existing_graph'))
TestAgeToNetworkx.args = args
suite.addTest(TestNetworkxToAGE('test_number_of_nodes_and_edges'))
suite.addTest(TestNetworkxToAGE('test_empty_graph'))
suite.addTest(TestNetworkxToAGE('test_non_empty_graph'))
suite.addTest(TestNetworkxToAGE('test_invalid_node_label'))
suite.addTest(TestNetworkxToAGE('test_invalid_node_properties'))
suite.addTest(TestNetworkxToAGE('test_invalid_edge_label'))
suite.addTest(TestNetworkxToAGE('test_invalid_edge_properties'))
TestNetworkxToAGE.args = args
unittest.TextTestRunner().run(suite)