forked from FiorelaCiroku/XDTestingDemo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.py
920 lines (781 loc) · 42.9 KB
/
script.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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
import json
import os
import re
import sys
import subprocess
from urllib import response
import requests as issue
from urllib.request import urlopen
import rdflib
from rdflib.plugins.sparql import prepareQuery
from rdflib.namespace import FOAF
from rdflib.namespace import RDF
from rdflib.namespace import RDFS
from rdflib.namespace import DC
from rdflib.namespace import OWL
from rdflib.namespace import XSD
from pytablewriter import MarkdownTableWriter
from datetime import date
# Load data from a JSON file
def loadDataFromJsonFile(filename):
with open(filename, 'r') as f:
data = json.load(f)
return data
# Get the ontology name
def getOntologiesName(data):
name = data.get("ontologies")[0]['name']
# Removing space
return name.replace(" ", "")
# Create ontology directory
def createOntologiesDirectory(name):
# Directory
directory = name
# Parent Directory path
parent_dir = "./XDTesting"
try:
# Path
path = os.path.join(parent_dir, directory)
if not os.path.exists(path):
os.makedirs(path)
print("Directory '% s' created" % directory)
if not os.path.exists(path + '/IntegrationRegressionTestDocumentation'):
os.mkdir(path + '/IntegrationRegressionTestDocumentation')
path = path + '/IntegrationRegressionTestDocumentation'
if not os.path.exists(path + '/TestDocumentation'):
os.mkdir(path + '/TestDocumentation')
if not os.path.exists(path + '/CompetencyQuestionVerificationTest'):
os.mkdir(path + '/CompetencyQuestionVerificationTest')
if not os.path.exists(path + '/InferenceVerificationTest'):
os.mkdir(path + '/InferenceVerificationTest')
if not os.path.exists(path + '/ErrorProvocationTest'):
os.mkdir(path + '/ErrorProvocationTest')
if not os.path.exists(path + '/TestDocumentation/PassedTests'):
os.mkdir(path + '/TestDocumentation/PassedTests')
file = open(
path + "/TestDocumentation/PassedTests/README.md", "w+")
file.write("This directory stores successfully passed tests.")
file.close()
if not os.path.exists(path + '/TestDocumentation/FailedTests'):
os.mkdir(path + '/TestDocumentation/FailedTests')
file = open(
path + "/TestDocumentation/FailedTests/README.md", "w+")
file.write("This directory stores failed tests.")
file.close()
if not os.path.exists(path + '/CompetencyQuestionVerificationTest/CQTestCase'):
os.mkdir(path + '/CompetencyQuestionVerificationTest/CQTestCase')
file = open(
path + "/CompetencyQuestionVerificationTest/CQTestCase/README.md", "w+")
file.write(
"This directory stores Competency Question Verification test cases.")
file.close()
if not os.path.exists(path + '/CompetencyQuestionVerificationTest/CQDataSet'):
os.mkdir(path + '/CompetencyQuestionVerificationTest/CQDataSet')
file = open(
path + "/CompetencyQuestionVerificationTest/CQDataSet/README.md", "w+")
file.write(
"This directory stores the sample dataset for the Competency Question Verification test cases.")
file.close()
if not os.path.exists(path + '/InferenceVerificationTest/IVTestCase'):
os.mkdir(path + '/InferenceVerificationTest/IVTestCase')
file = open(
path + "/InferenceVerificationTest/IVTestCase/README.md", "w+")
file.write(
"This directory stores Inference Verification test cases.")
file.close()
if not os.path.exists(path + '/InferenceVerificationTest/IVDataSet'):
os.mkdir(path + '/InferenceVerificationTest/IVDataSet')
file = open(
path + "/InferenceVerificationTest/IVDataSet/README.md", "w+")
file.write(
"This directory stores the sample dataset for the Inference Verification test cases.")
file.close()
if not os.path.exists(path + '/ErrorProvocationTest/EPTestCase'):
os.mkdir(path + '/ErrorProvocationTest/EPTestCase')
file = open(
path + "/ErrorProvocationTest/EPTestCase/README.md", "w+")
file.write(
"This directory stores Error Provocation test cases.")
file.close()
if not os.path.exists(path + '/ErrorProvocationTest/EPDataSet'):
os.mkdir(path + '/ErrorProvocationTest/EPDataSet')
file = open(
path + "/ErrorProvocationTest/EPDataSet/README.md", "w+")
file.write(
"This directory stores the sample dataset for the Error Provocation test cases.")
file.close()
except OSError as error:
print(error)
# Get fragment name
def getFragmentsName(data):
listOfFragmentName = []
for fragment in data['fragments']:
fragmentDetail = []
fragmentDetail.append(fragment['name'].replace(" ", ""))
fragmentDetail.append(fragment.get('ontologyName').replace(" ", ""))
listOfFragmentName.append(fragmentDetail)
return listOfFragmentName
# Create fragment directory
def createFragmentDirectory(fragmentName, name):
# Directory
directory = fragmentName
# Parent Directory path
parent_dir = "./XDTesting/" + name
# Path
try:
# Path
path = os.path.join(parent_dir, directory)
if not os.path.exists(path):
os.makedirs(path)
file = open(
path + "/README.md", "w+")
file.write(
"Fragment testing documentation")
file.close()
# os.makedirs()
if not os.path.exists(path + '/TestDocumentation'):
os.mkdir(path + '/TestDocumentation')
if not os.path.exists(path + '/CompetencyQuestionVerificationTest'):
os.mkdir(path + '/CompetencyQuestionVerificationTest')
if not os.path.exists(path + '/InferenceVerificationTest'):
os.mkdir(path + '/InferenceVerificationTest')
if not os.path.exists(path + '/ErrorProvocationTest'):
os.mkdir(path + '/ErrorProvocationTest')
if not os.path.exists(path + '/TestDocumentation/PassedTests'):
os.mkdir(path + '/TestDocumentation/PassedTests')
file = open(
path + "/TestDocumentation/PassedTests/README.md", "w+")
file.write("This directory stores successfully passed tests.")
file.close()
if not os.path.exists(path + '/TestDocumentation/FailedTests'):
os.mkdir(path + '/TestDocumentation/FailedTests')
file = open(
path + "/TestDocumentation/FailedTests/README.md", "w+")
file.write("This directory stores failed tests.")
file.close()
if not os.path.exists(path + '/CompetencyQuestionVerificationTest/CQTestCase'):
os.mkdir(path + '/CompetencyQuestionVerificationTest/CQTestCase')
file = open(
path + "/CompetencyQuestionVerificationTest/CQTestCase/README.md", "w+")
file.write(
"# Competency Question Verification Test \n")
file.write(
"This directory stores Competency Question Verification test cases.\n")
file.write(
"Competency Question Verification tests allow to verify if the ontology can answer the competency questions that have been collected during the requirement collection.")
file.close()
if not os.path.exists(path + '/CompetencyQuestionVerificationTest/CQDataSet'):
os.mkdir(path + '/CompetencyQuestionVerificationTest/CQDataSet')
file = open(
path + "/CompetencyQuestionVerificationTest/CQDataSet/README.md", "w+")
file.write(
"This directory stores the sample data for the Competency Question Verification test cases.")
file.close()
if not os.path.exists(path + '/InferenceVerificationTest/IVTestCase'):
os.mkdir(path + '/InferenceVerificationTest/IVTestCase')
file = open(
path + "/InferenceVerificationTest/IVTestCase/README.md", "w+")
file.write(
"This directory stores Inference Verification test cases.")
file.close()
if not os.path.exists(path + '/InferenceVerificationTest/IVDataSet'):
os.mkdir(path + '/InferenceVerificationTest/IVDataSet')
file = open(
path + "/InferenceVerificationTest/IVDataSet/README.md", "w+")
file.write(
"This directory stores the sample data for the Inference Verification test cases.")
file.close()
if not os.path.exists(path + '/ErrorProvocationTest/EPTestCase'):
os.mkdir(path + '/ErrorProvocationTest/EPTestCase')
file = open(
path + "/ErrorProvocationTest/EPTestCase/README.md", "w+")
file.write(
"This directory stores Error Provocation test cases.")
file.close()
if not os.path.exists(path + '/ErrorProvocationTest/EPDataSet'):
os.mkdir(path + '/ErrorProvocationTest/EPDataSet')
file = open(
path + "/ErrorProvocationTest/EPDataSet/README.md", "w+")
file.write(
"This directory stores the sample data for the Error Provocation test cases.")
file.close()
os.mkdir(path)
except OSError as error:
print(error)
print("Directory '% s' created" % directory)
# Validate the expected result by loading JSON
def validateJSON(jsonData):
try:
json.loads(jsonData)
print("Success!")
return true
except ValueError as error:
print("Error - " + error)
return error
# Validate SPARQL by preparing query
def validateSPARQL(query):
print("The variable is ", query)
try:
q = prepareQuery(query, initNs={
"foaf": FOAF, "rdfs": RDFS, "rdf": RDF, "owl": OWL, "xsd": XSD}, )
print("Success!")
return true
except Exception as error:
print("Error - " + error)
return error
# Get test type
def getTestType(test):
return test.get('type')
# Get content (competency question)
def getContent(test):
return test.get('content')
# Get query content
def getQueryContent(test):
if test.get('query') is None:
queryPath = '.xd-testing/' + test.get('queryFileName')
file = open(queryPath, "r")
return file.read()
else:
# return urlopen(test.get('query')).read()
return test.get('query')
# Get expected result
def getExpectedResultsContent(test):
if test.get('expectedResults') == "":
testPath = '.xd-testing/' + test.get('expectedResultsFileName')
file = open(testPath, "r")
return file.read()
else:
return test.get('expectedResults')
# return urlopen(test.get('expectedResults')).read()
# Get data
def getData(test):
if test.get('data') == "":
dataPath = '.xd-testing/' + test.get('dataFileName')
file = open(dataPath, "r")
return file.read()
else:
return test.get('data')
# return urlopen(test.get('data')).read()
# Get test ID
def getID(test):
return test.get('id')
# Get reasoner
def getReasoner(test):
return test.get('reasoner')
# Get ontology url
def getOntologyUrl(test):
return test.get("ontologies")[0]['url']
# Update test status
def setCheckValue(filename, value, indexFragment, indexTest):
data = loadDataFromJsonFile(filename)
data['fragments'][indexFragment]['tests'][indexTest]['check'] = value
with open(filename, 'w') as json_file:
json.dump(data, json_file,
indent=4,
separators=(',', ': '))
json_file.close()
# Get check value
def getCheckValue(data, indexFragment, indexTest):
try:
return data['fragments'][indexFragment]['tests'][indexTest]['check']
except:
return None
# Set status value
def setStatusValue(filename, value, indexFragment, indexTest):
data = loadDataFromJsonFile(filename)
data['fragments'][indexFragment]['tests'][indexTest]['status'] = value
with open(filename, 'w') as json_file:
json.dump(data, json_file,
indent=4,
separators=(',', ': '))
json_file.close()
# Get status value
def getStatusValue(data, indexFragment, indexTest):
try:
return data['fragments'][indexFragment]['tests'][indexTest]['status']
except:
return None
# Set status notes
def setStatusNotesValue(filename, value, indexFragment, indexTest):
data = loadDataFromJsonFile(filename)
data['fragments'][indexFragment]['tests'][indexTest]['statusNotes'] = str(
value)
with open(filename, 'w') as json_file:
json.dump(data, json_file,
indent=4,
separators=(',', ': '))
json_file.close()
# Create versioned files
def createVersionedDocumentation(file_name):
if os.path.isfile(file_name):
# Get the file name and extension
base_name, file_ext = os.path.splitext(file_name)
# Create a new file name with the same name but a different version
new_file_name = base_name + "-v2" + file_ext
# Check if the new file already exists
i = 2
while os.path.isfile(new_file_name):
new_file_name = base_name + "-v" + str(i) + file_ext
i += 1
# Create the new file
with open(new_file_name, "w") as new_file:
new_file.write("")
return new_file_name
else:
with open(file_name, "w") as new_file:
new_file.write("")
return file_name
# Validate dataset file
def validateDatasetSyntax(filepath):
try:
g = rdflib.Graph()
g.parse(filepath, format="turtle")
return True
except Exception as error:
print("Error - " + error)
return error
# Create test case and data set file
def createTestCaseAndDataSetFile(fileData, fileName, repoName):
for indexFragment in range(len(fileData['fragments'])):
if 'tests' in fileData['fragments'][indexFragment]:
for indexTest in range(len(fileData['fragments'][indexFragment]['tests'])):
if (getCheckValue(fileData, indexFragment, indexTest) is None or getCheckValue(fileData, indexFragment,
indexTest) == 0):
testData = fileData['fragments'][indexFragment]['tests'][indexTest]
print(testData)
if (getTestType(testData) == 'COMPETENCY_QUESTION'):
try:
# validateSPARQL(getQueryContent(testData))
# validateJSON(getExpectedResultsContent(testData))
testFileLink = "https://raw.githubusercontent.com/" + repoName + "/main/XDTesting/" + \
fileData['fragments'][indexFragment]['ontologyName'].replace(
" ", "") + "/" + fileData['fragments'][indexFragment]['name'].replace(" ",
"") + "/CompetencyQuestionVerificationTest/"
testFilePath = "./XDTesting/" + fileData['fragments'][indexFragment]['ontologyName'].replace(
" ", "") + "/" + fileData['fragments'][indexFragment]['name'].replace(" ",
"") + "/CompetencyQuestionVerificationTest/"
with open(testFilePath + '/CQTestCase/' + getID(testData) + '.ttl', 'w') as f:
f.write(
'@prefix owlunit: <https://w3id.org/OWLunit/ontology/> .\n')
f.write(
'@prefix ns: <' + 'https://raw.githubusercontent.com/' + repoName + '/main/.xd-testing/' +
fileData['fragments'][indexFragment]['fileName'] + '> .\n')
f.write('@prefix td: <' +
testFileLink + 'CQDataSet/> .\n')
f.write('@prefix tc: <' + testFileLink +
'CQTestCase/> .\n\n')
f.write('tc:' + getID(testData) + '.ttl' +
' a owlunit:CompetencyQuestionVerification ;\n')
f.write('\towlunit:hasCompetencyQuestion \"' +
getContent(testData) + '\" ;\n')
f.write('\towlunit:hasSPARQLUnitTest \"' +
getQueryContent(testData) + '\" ;\n')
f.write('\towlunit:hasInputData td:' +
getID(testData) + 'TD.ttl ;\n')
f.write(
'\towlunit:hasInputTestDataCategory owlunit:ToyDataset ;\n')
f.write(
'\towlunit:hasExpectedResult \"' +
getExpectedResultsContent(testData).replace("\n", "") + '\"; \n')
f.write(
'\towlunit:testsOntology ns: .\n')
f.close()
print(testFilePath + 'CQDataSet/' + getID(testData) + 'TD.ttl')
with open(testFilePath + 'CQDataSet/' + getID(testData) + 'TD.ttl', 'w') as f:
f.write(
getData(testData))
f.close()
except Exception as error:
setStatusValue(fileName, 'warning',
indexFragment, indexTest)
setStatusNotesValue(fileName, error,
indexFragment, indexTest)
elif (getTestType(testData) == 'INFERENCE_VERIFICATION'):
try:
# validateSPARQL(getQueryContent(testData))
testFileLink = "https://raw.githubusercontent.com/" + repoName + "/main/XDTesting/" + \
fileData['fragments'][indexFragment]['ontologyName'].replace(
" ", "") + "/" + fileData['fragments'][indexFragment]['name'].replace(" ",
"") + "/InferenceVerificationTest/"
testFilePath = "./XDTesting/" + fileData['fragments'][indexFragment]['ontologyName'].replace(
" ", "") + "/" + fileData['fragments'][indexFragment]['name'].replace(" ",
"") + "/InferenceVerificationTest/"
with open(testFilePath + '/IVTestCase/' + getID(testData) + '.ttl', 'w') as f:
f.write(
'@prefix owlunit: <https://w3id.org/OWLunit/ontology/> .\n')
f.write(
'@prefix ns: <' + 'https://raw.githubusercontent.com/' + repoName + '/main/.xd-testing/' +
fileData['fragments'][indexFragment]['fileName'] + '> .\n')
f.write('@prefix td: <' +
testFileLink + 'IVDataSet/> .\n')
f.write('@prefix tc: <' + testFileLink +
'IVTestCase/> .\n\n')
f.write('tc:' + getID(testData) + '.ttl' +
' a owlunit:InferenceVerification ;\n')
f.write('\towlunit:hasSPARQLUnitTest \"' +
getQueryContent(testData) + '\" ;\n')
f.write('\towlunit:hasInputData td:' +
getID(testData) + 'TD.ttl ;\n')
f.write(
'\towlunit:hasExpectedResult true ;\n')
f.write(
'\towlunit:hasReasoner owlunit:HermiT ;\n') # '\towlunit:hasReasoner owlunit:'+getReasoner(testData)+' ;\n')
f.write(
'\towlunit:testsOntology ns: .\n')
f.close()
with open(testFilePath + 'IVDataSet/' + getID(testData) + 'TD.ttl', 'w') as f:
f.write(
getData(testData))
f.close()
except Exception as error:
setStatusValue(fileName, 'warning',
indexFragment, indexTest)
setStatusNotesValue(fileName, error,
indexFragment, indexTest)
elif (getTestType(testData) == 'ERROR_PROVOCATION'):
try:
testFileLink = "https://raw.githubusercontent.com/" + repoName + "/main/XDTesting/" + \
fileData['fragments'][indexFragment]['ontologyName'].replace(
" ", "") + "/" + fileData['fragments'][indexFragment]['name'].replace(" ",
"") + "/ErrorProvocationTest/"
testFilePath = "./XDTesting/" + fileData['fragments'][indexFragment]['ontologyName'].replace(
" ", "") + "/" + fileData['fragments'][indexFragment]['name'].replace(" ",
"") + "/ErrorProvocationTest/"
with open(testFilePath + 'EPTestCase/' + getID(testData) + '.ttl', 'w') as f:
f.write(
'@prefix owlunit: <https://w3id.org/OWLunit/ontology/> .\n')
f.write(
'@prefix ns: <' + 'https://raw.githubusercontent.com/' + repoName + '/main/.xd-testing/' +
fileData['fragments'][indexFragment]['fileName'] + '> .\n')
f.write('@prefix td: <' +
testFileLink + 'EPDataSet/> .\n')
f.write('@prefix tc: <' + testFileLink +
'EPTestCase/> .\n\n')
f.write('tc:' + getID(testData) + '.ttl' +
' a owlunit:ErrorProvocation ;\n')
f.write('\towlunit:hasInputData td:' +
getID(testData) + 'TD.ttl ;\n')
f.write(
'\towlunit:testsOntology ns: .\n')
f.close()
with open(testFilePath + 'EPDataSet/' + getID(testData) + 'TD.ttl', 'w') as f:
f.write(
getData(testData))
f.close()
except Exception as error:
setStatusValue(fileName, 'warning',
indexFragment, indexTest)
setStatusNotesValue(fileName, error,
indexFragment, indexTest)
else:
print('Test Case and Data Set already Created ')
def createTestDocumentation(testFilePath, result, testData, folderName, error="Error"):
if result == "PASSED":
if (getTestType(testData) == 'COMPETENCY_QUESTION'):
writer = MarkdownTableWriter(
headers=["Test case documentation",
"Information"],
value_matrix=[
["Test case ID", getID(testData)],
["Test category", getTestType(testData)],
["Requirement", getContent(testData)],
["Test", getQueryContent(testData)],
["Input test data", str(folderName) +
str(getID(testData)) + 'TD.ttl'],
["Expected result", getExpectedResultsContent(testData)],
["Actual result", getExpectedResultsContent(testData)],
["Executed on", date.today()],
["Environment", "GITHUB"],
["Execution result", result],
["Execution comment", ""],
],
margin=1 # add a whitespace for both sides of each cell
)
elif (getTestType(testData) == 'INFERENCE_VERIFICATION'):
writer = MarkdownTableWriter(
headers=["Test case documentation",
"Information"],
value_matrix=[
["Test case ID", getID(testData)],
["Test category", getTestType(testData)],
["Test", getQueryContent(testData)],
["Input test data", str(folderName) +
str(getID(testData)) + 'TD.ttl'],
["Expected result", True],
["Actual result", True],
["Executed on", date.today()],
["Environment", "GITHUB"],
["Execution result", result],
["Execution comment", ""],
],
margin=1 # add a whitespace for both sides of each cell
)
elif (getTestType(testData) == 'ERROR_PROVOCATION'):
writer = MarkdownTableWriter(
headers=["Test case documentation",
"Information"],
value_matrix=[
["Test case ID", getID(testData)],
["Test category", getTestType(testData)],
["Input test data", str(folderName) +
str(getID(testData)) + 'TD.ttl'],
["Expected result", False],
["Actual result", False],
["Executed on", date.today()],
["Environment", "GITHUB"],
["Execution result", result],
["Execution comment", ""],
],
margin=1 # add a whitespace for both sides of each cell
)
writer.dump(str(testFilePath) + 'PassedTests/' + str(getID(testData)) + '.md')
elif result == "FAILED":
if (getTestType(testData) == 'COMPETENCY_QUESTION'):
writer = MarkdownTableWriter(
headers=["Test case documentation",
"Information"],
value_matrix=[
["Test case ID", getID(testData)],
["Test category", getTestType(testData)],
["Requirement", getContent(testData)],
["Test", getQueryContent(testData)],
["Input test data", str(folderName) +
str(getID(testData)) + 'TD.ttl'],
["Expected result", getExpectedResultsContent(testData)],
["Actual result", error],
["Executed on", date.today()],
["Environment", "GITHUB"],
["Execution result", result],
["Execution comment", ""],
],
margin=1 # add a whitespace for both sides of each cell
)
elif (getTestType(testData) == 'INFERENCE_VERIFICATION'):
writer = MarkdownTableWriter(
headers=["Test case documentation",
"Information"],
value_matrix=[
["Test case ID", getID(testData)],
["Test category", getTestType(testData)],
["Test", getQueryContent(testData)],
["Input test data", str(folderName) +
str(getID(testData)) + 'TD.ttl'],
["Expected result", True],
["Actual result", False],
["Executed on", date.today()],
["Environment", "GITHUB"],
["Execution result", result],
["Execution comment", ""],
],
margin=1 # add a whitespace for both sides of each cell
)
elif (getTestType(testData) == 'ERROR_PROVOCATION'):
writer = MarkdownTableWriter(
headers=["Test case documentation",
"Information"],
value_matrix=[
["Test case ID", getID(testData)],
["Test category", getTestType(testData)],
["Input test data", str(folderName) +
str(getID(testData)) + 'TD.ttl'],
["Expected result", False],
["Actual result", True],
["Executed on", date.today()],
["Environment", "GITHUB"],
["Execution result", result],
["Execution comment", ""],
],
margin=1 # add a whitespace for both sides of each cell
)
newFilePath = str(testFilePath) + 'FailedTests/' + str(getID(testData)) + '.md'
newFilePath = createVersionedDocumentation(newFilePath)
writer.dump(newFilePath)
# writer.dump(str(testFilePath)+'FailedTests/' + str(getID(testData))+'.md')
def executeTestCase(fileData, fileName, repoName, token):
headers = {"Authorization": "token {}".format(token)}
url = "https://api.github.com/repos/{}/issues".format(
repoName)
for indexFragment in range(len(fileData['fragments'])):
if 'tests' in fileData['fragments'][indexFragment]:
for indexTest in range(len(fileData['fragments'][indexFragment]['tests'])):
# if getStatusValue(fileData, indexFragment, indexTest) != "warning":
if (getCheckValue(fileData, indexFragment, indexTest) is None or getCheckValue(fileData, indexFragment,
indexTest) == 0):
testData = fileData['fragments'][indexFragment]['tests'][indexTest]
if (getTestType(testData) == 'COMPETENCY_QUESTION'):
try:
testFileLink = "https://raw.githubusercontent.com/" + repoName + "/main/XDTesting/" + \
fileData['fragments'][indexFragment]['ontologyName'].replace(
" ", "") + "/" + fileData['fragments'][indexFragment]['name'].replace(" ",
"") + "/CompetencyQuestionVerificationTest/"
testFilePath = "./XDTesting/" + fileData['fragments'][indexFragment]['ontologyName'].replace(
" ", "") + "/" + fileData['fragments'][indexFragment]['name'].replace(" ",
"") + "/TestDocumentation/"
print('---- Executing Test ----')
os.system(
"java -jar OWLUnit-0.3.2.jar --test-case " + testFileLink + "CQTestCase/" + getID(
testData) + ".ttl")
testOutcome = subprocess.check_output(
"java -jar OWLUnit-0.3.2.jar --test-case " + testFileLink + "CQTestCase/" + getID(
testData) + ".ttl", shell=True)
if "PASSED" in testOutcome.decode("utf-8"):
print('---- PASSED ----')
createTestDocumentation(
testFilePath, "PASSED", testData, "CQDataSet/")
setCheckValue(fileName, 1,
indexFragment, indexTest)
setStatusValue(fileName, 'success',
indexFragment, indexTest)
setStatusNotesValue(fileName, "Executed",
indexFragment, indexTest)
elif "FAILED" in testOutcome.decode("utf-8"):
print('---- FAILED----')
createTestDocumentation(
testFilePath, "FAILED", testData,
"CQDataSet/") # testFilePath, "FAILED", testData, "CQDataSet/", error)
setStatusValue(fileName, 'failed',
indexFragment, indexTest)
setStatusNotesValue(fileName, "Executed",
indexFragment, indexTest)
except Exception as error:
print('---- ERROR----')
data = {"title": getID(fileData), "body": error}
try:
createTestDocumentation(
testFilePath, "FAILED", testData, "CQDataSet/", error)
response = issue.post(url, data, headers=headers)
print(response)
setStatusValue(fileName, 'failed',
indexFragment, indexTest)
setCheckValue(
fileName, 0, indexFragment, indexTest)
setStatusNotesValue(fileName, response,
indexFragment, indexTest)
except Exception as error:
print("Error : " + error)
elif (getTestType(testData) == 'INFERENCE_VERIFICATION'):
try:
testFileLink = "https://raw.githubusercontent.com/" + repoName + "/main/XDTesting/" + \
fileData['fragments'][indexFragment]['ontologyName'].replace(
" ", "") + "/" + fileData['fragments'][indexFragment]['name'].replace(" ",
"") + "/InferenceVerificationTest/"
testFilePath = "./XDTesting/" + fileData['fragments'][indexFragment]['ontologyName'].replace(
" ", "") + "/" + fileData['fragments'][indexFragment]['name'].replace(" ",
"") + "/TestDocumentation/"
print('---- Executing Test ----')
os.system(
"java -jar OWLUnit-0.3.2.jar --test-case " + testFileLink + "IVTestCase/" + getID(
testData) + ".ttl")
testOutcome = subprocess.check_output(
"java -jar OWLUnit-0.3.2.jar --test-case " + testFileLink + "IVTestCase/" + getID(
testData) + ".ttl", shell=True)
if "PASSED" in testOutcome.decode("utf-8"):
print('---- PASSED ----')
createTestDocumentation(
testFilePath, "PASSED", testData, "IVDataSet/")
setCheckValue(fileName, 1,
indexFragment, indexTest)
setStatusValue(fileName, 'success',
indexFragment, indexTest)
setStatusNotesValue(fileName, "Executed",
indexFragment, indexTest)
elif "FAILED" in testOutcome.decode("utf-8"):
print('---- FAILED----')
createTestDocumentation(
testFilePath, "FAILED", testData, "IVDataSet/")
setStatusValue(fileName, 'failed',
indexFragment, indexTest)
setStatusNotesValue(fileName, "Executed",
indexFragment, indexTest)
except Exception as error:
print('---- ERROR----')
data = {"title": getID(fileData), "body": error}
try:
createTestDocumentation(
testFilePath, "FAILED", testData, "IVDataSet/", error)
response = issue.post(url, data, headers=headers)
print(response)
setStatusValue(fileName, 'failed',
indexFragment, indexTest)
setCheckValue(
fileName, 0, indexFragment, indexTest)
setStatusNotesValue(fileName, response,
indexFragment, indexTest)
except Exception as error:
print("Error : " + error)
elif (getTestType(testData) == 'ERROR_PROVOCATION'):
try:
testFileLink = "https://raw.githubusercontent.com/" + repoName + "/main/XDTesting/" + \
fileData['fragments'][indexFragment]['ontologyName'].replace(
" ", "") + "/" + fileData['fragments'][indexFragment]['name'].replace(" ",
"") + "/ErrorProvocationTest/"
testFilePath = "./XDTesting/" + fileData['fragments'][indexFragment]['ontologyName'].replace(
" ", "") + "/" + fileData['fragments'][indexFragment]['name'].replace(" ",
"") + "/TestDocumentation/"
print(
"Execution command: java -jar OWLUnit-0.3.2.jar --test-case " + testFileLink + "EPTestCase/" + getID(
testData) + ".ttl")
print('---- Executing Test ----')
os.system(
"java -jar OWLUnit-0.3.2.jar --test-case " + testFileLink + "EPTestCase/" + getID(
testData) + ".ttl") # fileData
testOutcome = subprocess.check_output(
"java -jar OWLUnit-0.3.2.jar --test-case " + testFileLink + "EPTestCase/" + getID(
testData) + ".ttl", shell=True)
if "PASSED" in testOutcome.decode("utf-8"):
print('---- PASSED ----')
createTestDocumentation(
testFilePath, "PASSED", testData, "EPDataSet/")
setCheckValue(fileName, 1,
indexFragment, indexTest)
setStatusValue(fileName, 'success',
indexFragment, indexTest)
setStatusNotesValue(fileName, "Executed",
indexFragment, indexTest)
elif "FAILED" in testOutcome.decode("utf-8"):
print('---- FAILED----')
createTestDocumentation(
testFilePath, "FAILED", testData, "EPDataSet/")
setStatusValue(fileName, 'failed',
indexFragment, indexTest)
setStatusNotesValue(fileName, "Executed",
indexFragment, indexTest)
except Exception as error:
print('---- ERROR----')
data = {"title": getID(fileData), "body": error}
try:
createTestDocumentation(
testFilePath, "FAILED", testData, "EPDataSet/", error)
response = issue.post(url, data, headers=headers)
print(response)
setStatusValue(fileName, 'failed',
indexFragment, indexTest)
setCheckValue(
fileName, 0, indexFragment, indexTest)
setStatusNotesValue(fileName, response,
indexFragment, indexTest)
except Exception as error:
print("Error : " + error)
else:
print('Test already Executed')
# ---------------- Start---------------#
repoName = sys.argv[1]
arg = sys.argv[2]
token = sys.argv[3]
fileName = '.xd-testing/UserInput.json'
fileData = loadDataFromJsonFile(fileName)
if arg == "create":
# Step 1 - Get ontology name
ontologyName = getOntologiesName(fileData)
# Step 2 - Create the GitHub directories for the ontology
createOntologiesDirectory(ontologyName)
# Step 3 - Get fragment name
listOfFragmentName = getFragmentsName(fileData)
print(listOfFragmentName)
# Step 4 - Create the GitHub directories for the module
for fragment, ontology in listOfFragmentName:
createFragmentDirectory(fragment, ontology)
# Step 5 - Create test cases and dataset files
createTestCaseAndDataSetFile(fileData, fileName, repoName)
elif arg == "test":
# Step 6 - Execute test cases
executeTestCase(fileData, fileName, repoName, token)