Debian Codegraph @

rdfwriter/utils_test.go

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