Debian Codegraph @

rdfwriter/utils_test.go

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 package rdfwriter
2
3 import (
4 "github.com/spdx/gordf/rdfloader/parser"
5 "github.com/spdx/gordf/uri"
6 "reflect"
7 "testing"
8 )
9
10 func max(n1, n2 int) int {
11 if n1 > n2 {
12 return n1
13 }
14 return n2
15 }
16
17 func getInvSchema() map[string]string {
18 return map[string]string{
19 "http://spdx.org/rdf/terms": "spdx",
20 "http://www.w3.org/1999/02/22-rdf-syntax-ns": "rdf",
21 "http://www.w3.org/2000/01/rdf-schema": "rdfs",
22 }
23 }
24
25 // returns a slice of n blank nodes.
26 // n > 0
27 func getNBlankNodes(n int) (blankNodes []*parser.Node) {
28 blankNodes = make([]*parser.Node, max(0, n))
29 // first blank nodes start with N1
30 blankNodeGetter := parser.BlankNodeGetter{}
31 for i := 0; i < n; i++ {
32 newBlankNode := blankNodeGetter.Get()
33 blankNodes[i] = &newBlankNode
34 }
35 return
36 }
37
38 func Test_getAdjacencyList(t *testing.T) {
39 // TestCase 1
40 // empty list of triples should have empty map as an output
41 adjList := GetAdjacencyList([]*parser.Triple{})
42 recoveryDS := GetNodeToTriples([]*parser.Triple{})
43 if len(adjList) > 0 || len(recoveryDS) > 0 {
44 t.Errorf("empty input is having non-empty output. Adjacency List: %v, recoveryDS: %v", adjList, recoveryDS)
45 }
46
47 // TestCase 2
48 // modelling a simple graph depicted as follows:
49 // (N1)
50 // (N0) ---------> (N2)
51 // |
52 // (N3) |
53 // |
54 // v
55 // (N4)
56 //
57 // Triples for the above graph will be:
58 // 1. N0 -> N1 -> N2
59 // 2. N0 -> N3 -> N4
60 blankNodes := getNBlankNodes(5)
61 triples := []*parser.Triple{
62 {
63 Subject: blankNodes[0],
64 Predicate: blankNodes[1],
65 Object: blankNodes[2],
66 }, {
67 Subject: blankNodes[0],
68 Predicate: blankNodes[3],
69 Object: blankNodes[4],
70 },
71 }
72 adjList = GetAdjacencyList(triples)
73 // adjList must have exactly 3 keys (N0, N2, N4)
74 if len(adjList) != 3 {
75 t.Errorf("adjacency list for the given graph should've only one key. Found %v keys", len(adjList))
76 }
77 if nChildren := len(adjList[blankNodes[0]]); nChildren != 2 {
78 t.Errorf("Node 0 should've exactly 2 children. Found %v children", nChildren)
79 }
80 // there aren't any neighbors for other nodes.
81 for i := 1; i < len(blankNodes); i++ {
82 if nChildren := len(adjList[blankNodes[i]]); nChildren > 0 {
83 t.Errorf("N%v should have no neighbors. Found %v neighbors", i+1, nChildren)
84 }
85 }
86 }
87
88 func TestTopologicalSortTriples(t *testing.T) {
89 nodes := getNBlankNodes(5)
90
91 // TestCase 1: only a single triple in the list
92 // The graph is as follows:
93 // (N1)
94 // (N0) --------> (N2)
95 triples := []*parser.Triple{
96 {nodes[0], nodes[1], nodes[2]},
97 }
98 // but it doesn't exist in the keys of the map.
99 sortedTriples, err := TopologicalSortTriples(triples)
100 if err != nil {
101 t.Errorf("unexpected parsing a single triple list. Error: %v", err)
102 }
103 if len(sortedTriples) != len(triples) {
104 t.Errorf("sorted triples doesn't have a proper dimension. Expected %v triples, found %v triples", len(triples), len(sortedTriples))
105 }
106
107 // TestCase 2: another valid test-case where the input is a cyclic graph.
108 /*
109 (N0)
110 / ^ \
111 (N1)/ | \(N2)
112 \ | /
113 v | v
114 (N3)
115 Triples:
116 1. N0 -> N1 -> N3
117 2. N0 -> N2 -> N3
118 3. N3 -> N4 -> N0 // couldn't show N4 in the graph.
119 */
120 nodes = getNBlankNodes(5)
121 triples = []*parser.Triple{
122 {Subject: nodes[0], Predicate: nodes[1], Object: nodes[3]},
123 {Subject: nodes[0], Predicate: nodes[2], Object: nodes[3]},
124 {Subject: nodes[3], Predicate: nodes[4], Object: nodes[0]},
125 }
126 sortedTriples, err = TopologicalSortTriples(triples)
127
128 // since we have a cycle here, we can expect two configurations.
129 expectedTriples := []*parser.Triple{
130 {Subject: nodes[3], Predicate: nodes[4], Object: nodes[0]},
131 {Subject: nodes[0], Predicate: nodes[1], Object: nodes[3]},
132 {Subject: nodes[0], Predicate: nodes[2], Object: nodes[3]},
133 }
134 anotherConfig := []*parser.Triple{
135 {Subject: nodes[0], Predicate: nodes[1], Object: nodes[3]},
136 {Subject: nodes[0], Predicate: nodes[2], Object: nodes[3]},
137 {Subject: nodes[3], Predicate: nodes[4], Object: nodes[0]},
138 }
139 if !reflect.DeepEqual(sortedTriples, expectedTriples) && !reflect.DeepEqual(sortedTriples, anotherConfig) {
140 t.Errorf("sorted triples are not in correct order")
141 }
142 }
143
144 func Test_topologicalSort(t *testing.T) {
145 nodes := getNBlankNodes(5)
146
147 // TestCase 1: invalid adjacency matrix with nodes which not in
148 // the keys but exists in the children lists.
149 // The graph is as follows:
150 // (N1)
151 // (N0) --------> (N2)
152 adjList := map[*parser.Node][]*parser.Node{
153 nodes[0]: {nodes[2]},
154 } // here, nodes[2] is child of nodes[0]
155 // but it doesn't exist in the keys of the map.
156 _, err := topologicalSort(adjList)
157 if err == nil {
158 t.Error("expected an error reporting \"extra nodes found\"")
159 }
160
161 // TestCase 2: Valid case
162 adjList = map[*parser.Node][]*parser.Node{
163 nodes[0]: {nodes[2]},
164 nodes[2]: {},
165 }
166 sortedNodes, err := topologicalSort(adjList)
167 if err != nil {
168 t.Errorf("unexpected error: %v", err)
169 }
170 expectedOutput := []*parser.Node{nodes[2], nodes[0]}
171 if !reflect.DeepEqual(sortedNodes, expectedOutput) {
172 t.Errorf("nodes are not sorted correctly. \nExpected: %v, \nFound: %v", sortedNodes, expectedOutput)
173 }
174 }
175
176 func Test_topologicalSortHelper(t *testing.T) {
177 // declaring satellite field required by the function
178 var lastIndex int
179 var adjList map[*parser.Node][]*parser.Node
180 var visited map[*parser.Node]bool
181 var resultList []*parser.Node
182
183 reinitializeSatellites := func(nNodes int) {
184 // nNodes := number of nodes.
185 lastIndex = 0
186 visited = make(map[*parser.Node]bool, nNodes)
187 resultList = make([]*parser.Node, nNodes)
188 }
189
190 /*
191 Graph that we will be using for all the testcases in this function:
192 It is a simple three staged input with a single source and sink pair.
193
194 (N1)
195 (N0) ------------> (N2)
196 | |
197 | |
198 (N3)| |(N6)
199 | |
200 v v
201 (N4) ------------> (N7)
202 (N5)
203 Triples that exists in the above graph:
204 1. N0 -> N1 -> N2
205 2. N2 -> N6 -> N7
206 3. N0 -> N3 -> N4
207 4. N3 -> N5 -> N7
208 */
209 numberNodes := 8
210 nodes := getNBlankNodes(numberNodes)
211 triples := []*parser.Triple{
212 {Subject: nodes[0], Predicate: nodes[1], Object: nodes[2]},
213 {Subject: nodes[2], Predicate: nodes[6], Object: nodes[7]},
214 {Subject: nodes[0], Predicate: nodes[3], Object: nodes[4]},
215 {Subject: nodes[3], Predicate: nodes[5], Object: nodes[7]},
216 }
217 adjList = GetAdjacencyList(triples)
218
219 // TestCase 1: trying to traverse on a node which doesn't exist in the graph.
220 // function should raise an error.
221 reinitializeSatellites(numberNodes)
222 inexistentNode := parser.Node{NodeType: parser.BLANK, ID: "sample node"}
223 err := topologicalSortHelper(&inexistentNode, &lastIndex, adjList, &visited, &resultList)
224 if err == nil {
225 t.Errorf("inexistent node should've raised an error")
226 }
227
228 // TestCase 2: traversing node with no children
229 reinitializeSatellites(numberNodes)
230 err = topologicalSortHelper(nodes[7], &lastIndex, adjList, &visited, &resultList)
231 if err != nil {
232 t.Errorf("unexpected error: %v", err)
233 }
234 // if a node without a child is traversed, the number of nodes added to the
235 // resultList should be exactly 1. That is the node itself.
236 if lastIndex != 1 {
237 t.Errorf("Expected exactly 1 node in the result list. Found %v nodes", lastIndex)
238 }
239
240 // TestCase 3: traversing a node with 1 child
241 // if we are traversing node N2, N7 is the only child.
242 reinitializeSatellites(numberNodes)
243 _ = topologicalSortHelper(nodes[2], &lastIndex, adjList, &visited, &resultList)
244 if lastIndex != 2 {
245 t.Errorf("Expected exactly 1 node in the result list. Found %v nodes", lastIndex)
246 }
247 // since N7 is the child of N2,
248 // resultList must have N7 before N2.
249 if resultList[0] != nodes[7] || resultList[1] != nodes[2] {
250 t.Error("resultList is not set properly")
251 }
252
253 // TestCase 4: Final Case when all the nodes will be traversed.
254 reinitializeSatellites(numberNodes)
255 _ = topologicalSortHelper(nodes[0], &lastIndex, adjList, &visited, &resultList)
256 if lastIndex != 4 {
257 t.Errorf("after parsing all nodes, resultList must've 4 nodes. Found %v nodes", lastIndex)
258 }
259 // after traversing all the nodes, (N0) should be the last node
260 // to be added to the list and (N7) should be the first node.
261 if resultList[0] != nodes[7] || resultList[lastIndex-1] != nodes[0] {
262 t.Error("order of resultList if not correct")
263 }
264 }
265
266 func TestDisjointSet(t *testing.T) {
267
268 // TestCase 1: two distinct sets
269 /* Modelling the following graph:
270 (N5) (N6)
271 (N0) ---------> (N1) ---------> (N2)
272
273 (N7)
274 (N3) --------> (N4)
275 */
276 // Clear enough, there are two different sets in the depicted graph.
277 nodes := getNBlankNodes(8)
278 triples := []*parser.Triple{
279 {Subject: nodes[0], Predicate: nodes[5], Object: nodes[1]},
280 {Subject: nodes[1], Predicate: nodes[6], Object: nodes[2]},
281 {Subject: nodes[3], Predicate: nodes[7], Object: nodes[4]},
282 }
283 parent := DisjointSet(triples)
284 nSets := 0
285 for subject := range parent {
286 if parent[subject] == nil {
287 nSets++
288 }
289 }
290 if nSets != 2 {
291 t.Errorf("Expected Graph to have exactly %d disjoint sets. Found %d sets", 2, nSets)
292 }
293
294 // TestCase 2: All Independent Triples:
295 /*
296 (N8) (N9)
297 (N0) -----------> (N1) (N2) -----------> (N3)
298
299 (N10) (N11)
300 (N4) -----------> (N5) (N6) -----------> (N7)
301 */
302 nodes = getNBlankNodes(12)
303 triples = []*parser.Triple{
304 {Subject: nodes[0], Predicate: nodes[8], Object: nodes[1]},
305 {Subject: nodes[2], Predicate: nodes[9], Object: nodes[3]},
306 {Subject: nodes[4], Predicate: nodes[10], Object: nodes[5]},
307 {Subject: nodes[6], Predicate: nodes[11], Object: nodes[7]},
308 }
309 parent = DisjointSet(triples)
310 nSets = 0
311 for node := range parent {
312 if parent[node] == nil {
313 nSets++
314 }
315 }
316 if nSets != len(triples) {
317 t.Errorf("Mismatch in the number of sets. expected %v disjoint sets, found %v sets", len(triples), nSets)
318 }
319 }
320
321 func Test_any(t *testing.T) {
322 // any function checks if the target is in the given list of strings
323
324 listStrings := []string{"c", "b", "a"}
325
326 // case when the target string is present in the strings
327 targetString := "a"
328 if !any(targetString, listStrings) {
329 // targetString wasn't found even though it exits in the list
330 t.Errorf("couldn't find %v in %v. even though it exits in the list", targetString, listStrings)
331 }
332
333 // case when the target is not present in the strings
334 targetString = "z"
335 if any(targetString, listStrings) {
336 // targetString was found even though it doesn't exist in the list.
337 t.Errorf("found %v in the list: %v. even though it doesn't exist in the list", targetString, listStrings)
338 }
339 }
340
341 func Test_invertSchemaDefinition(t *testing.T) {
342 // no special variations to test for.
343 spdxString := "http://spdx.org/rdf/terms"
344 spdxURI, _ := uri.NewURIRef(parser.RDFNS)
345 schemaDefinition := map[string]uri.URIRef{
346 "spdx": spdxURI,
347 }
348
349 inv := invertSchemaDefinition(schemaDefinition)
350 expected := map[string]string{spdxString: "spdx"}
351 if reflect.DeepEqual(inv, expected) {
352 t.Errorf("expected %v, found %v", expected, inv)
353 }
354 }
355
356 func Test_getRDFNSAbbreviation(t *testing.T) {
357 invSchemaDefinition := make(map[string]string)
358
359 // TestCase 1: Default prefix of the rdf namespace should be "rdf"
360 abbrev := getRDFNSAbbreviation(invSchemaDefinition)
361 if abbrev != "rdf" {
362 t.Errorf("by default, the rdf namespace should be abbreviated by rdf and not %s", abbrev)
363 }
364
365 // TestCase 2: Case when the rdf namespace exists in the invSchemaDefinition.
366 expectedAbbrev := "rdfNS"
367 invSchemaDefinition[parser.RDFNS] = expectedAbbrev
368 abbrev = getRDFNSAbbreviation(invSchemaDefinition)
369 if abbrev != expectedAbbrev {
370 t.Errorf("expected %s abbreviation, found %v", expectedAbbrev, abbrev)
371 }
372 }
373
374 func Test_getRestTriples(t *testing.T) {
375 nodes := getNBlankNodes(7)
376
377 // TestCase 1: Base Case where all the triples have predicate
378 // of rdf attributes
379 triples := []*parser.Triple{
380 {
381 Subject: nodes[0],
382 Predicate: &parser.Node{NodeType: parser.IRI, ID: parser.RDFNS + "type"},
383 Object: nodes[1]},
384 {
385 Subject: nodes[2],
386 Predicate: &parser.Node{NodeType: parser.IRI, ID: parser.RDFNS + "nodeID"},
387 Object: nodes[3],
388 },
389 }
390 restTriples := getRestTriples(triples)
391 if n := len(restTriples); n != 0 {
392 t.Errorf("expected empty output. got %d nodes", n)
393 }
394
395 // TestCase 2: Case where the output has at least one node which is not a
396 // rdf attribute
397 triples = append(triples, &parser.Triple{
398 Subject: nodes[4],
399 Predicate: nodes[5],
400 Object: nodes[6],
401 })
402 restTriples = getRestTriples(triples)
403 if n := len(restTriples); n != 1 {
404 t.Errorf("expected only one extra triple. found %d triples", n)
405 }
406 }
407
408 func Test_shortenURI(t *testing.T) {
409 invSchema := getInvSchema()
410
411 // TestCase 1: uri doesn't have two fragments
412 // Must raise an error
413 uriref := "http://spdx.org/rdf/terms#"
414 _, err := shortenURI(uriref, invSchema)
415 if err == nil {
416 t.Errorf("didn't raise any error for url with no fragment")
417 }
418
419 // TestCase 2: uri with inexistent baseURI
420 // Must raise an error
421 uriref = "https://www.googlge.com/terms#website"
422 _, err = shortenURI(uriref, invSchema)
423 if err == nil {
424 t.Errorf("expected an error stating baseURI doesn't exist in the given schema")
425 }
426
427 // TestCase 3: valid uri
428 uriref = "http://spdx.org/rdf/terms#Snippet"
429 expectedOP := "spdx:Snippet"
430 shortURI, err := shortenURI(uriref, invSchema)
431 if err != nil {
432 t.Errorf("unexpected error converting a valid URI")
433 }
434 if shortURI != expectedOP {
435 t.Errorf("expected output: %v, found: %v", expectedOP, shortURI)
436 }
437 }
438
439 func Test_getRootNodes(t *testing.T) {
440 nodes := getNBlankNodes(10)
441
442 // TestCase 1: self loop
443 triples := []*parser.Triple{
444 {Subject: nodes[0], Predicate: nodes[1], Object: nodes[0]},
445 }
446 roots := GetRootNodes(triples)
447 if len(roots) != 0 {
448 t.Errorf("expected no roots as output. found %v", roots)
449 }
450
451 // TestCase 2: Disjoint Triples with distinct root elements
452 /*
453 Graph: 3 disjoint triplets
454
455 (N1)
456 (N0) ---------> (N2)
457
458 (N4)
459 (N3) ---------> (N5)
460
461 (N7)
462 (N6) ---------> (N8)
463 */
464 triples = []*parser.Triple{
465 {Subject: nodes[0], Predicate: nodes[1], Object: nodes[2]},
466 {Subject: nodes[3], Predicate: nodes[4], Object: nodes[5]},
467 {Subject: nodes[6], Predicate: nodes[7], Object: nodes[8]},
468 }
469 roots = GetRootNodes(triples)
470 if len(roots) != len(triples) {
471 t.Errorf("expected %v root nodes, found %v nodes", len(roots), len(triples))
472 }
473 }