-
Notifications
You must be signed in to change notification settings - Fork 10
/
results_parser.py
executable file
·2507 lines (2159 loc) · 90 KB
/
results_parser.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
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import re
import os
import sys
import tarfile
import tempfile
import sqlite3
import warnings
import string
import keyword
from tqdm import tqdm
# import traceback
import logging
import multiprocessing
import fire # type: ignore
import xml
import yaml
import operator as op
import numpy as np
import pandas as pd # type: ignore
import xml.etree.ElementTree as ET
from typing import (
Callable,
TypeVar,
Type,
Tuple,
List,
Union,
IO,
Optional,
Dict,
Set,
Any,
Iterable,
)
from functools import partial
from itertools import groupby, starmap
from ast import literal_eval
from pathlib import Path
from abc import ABC, abstractmethod
from functools import lru_cache, reduce
import junitparser
from coverage.numbits import register_sqlite_functions
from flapy.utils import try_default
from flapy.sfl_scoring import tarantula, ochiai, dStar, barinel, op2
# Initialize pandas progress bar methods
tqdm.pandas()
FuncDescriptor = Tuple[str, ...]
default_flaky_keywords = [
#
# ASYNC WAIT
"sleep",
#
# CONCURRENCY
"thread",
"threading",
#
# RESOURCE LEAK
#
# IO
"('builtins', '', 'stat')",
"('pathlib', 'Path', 'is_dir')",
#
# NETWORK
"requests",
#
# TIME
"time",
#
# RANDOMNESS
"random",
#
# FLOATING POINT
#
# UNORDERED COLLECTION
"__hash__",
"('builtins', 'set', '__contains__')",
]
logging.getLogger().setLevel(logging.INFO)
# logging.getLogger().setLevel(logging.DEBUG)
FORMAT = "[%(asctime)s][%(levelname)7s][%(filename)20s:%(lineno)4s - %(funcName)20s() ] %(message)s"
logging.basicConfig(format=FORMAT)
proj_cols = ["Project_Name", "Project_URL", "Project_Hash"]
test_cols = ["Test_filename", "Test_classname", "Test_name", "Test_parametrization"]
test_cols_without_parametrization = ["Test_filename", "Test_classname", "Test_name"]
test_cols_without_filename = ["Test_classname", "Test_name", "Test_parametrization"]
def read_junit_testcase(test_case: junitparser.TestCase) -> Dict[str, Union[str, int]]:
"""Transform a Junit test case (xml element under the hood) to a dictionary"""
return {
"file": test_case._elem.get("file"),
"class": test_case.classname,
"name": test_case.name,
"verdict": try_default(
lambda: Verdict.from_junitparser(test_case.result),
junitparser.JUnitXmlError,
Verdict.PARSE_ERROR,
),
"message": (
test_case.result.message
if test_case.result and test_case.result.message
else "NO MESSAGE"
),
"errors_in_stacktrace": (
re.findall(
r"(.*(?:error|exception).*)", test_case.result._elem.text, flags=re.IGNORECASE
)
if (
test_case.result is not None
and test_case.result._elem is not None
and test_case.result._elem.text is not None
)
else None
),
"errors_in_system_err": (
re.findall(r"(.*(?:error|exception).*)", test_case.system_err, flags=re.IGNORECASE)
if test_case.system_err is not None
else None
),
"type": (test_case.result.type if test_case.result is not None else ""),
}
def is_empty(openvia: Callable[[str], IO], path: str):
try:
with openvia(path) as f:
next(f)
except StopIteration:
return True
return False
def junitxml_classname_to_modname_and_actual_classname(classname: str) -> Tuple[List[str], str]:
"""The JUnit-XML attribute 'class' contains both the name of the module and the name of the class -> split them by assuming class names start with capital letters.
EXAMPLE: "tests.test_camera.TestCamera" -> (['tests', 'test_camera'], 'TestCamera')
"""
if classname == "":
return [], ""
split = classname.split(".")
try:
# Case there exists a test-class (assume class names are upper case)
if split[-1][0].isupper():
*mod, class_ = split
# Case there is no test-class, just a test-file
else:
mod = split
class_ = ""
return mod, class_
except IndexError:
logging.warning(
f"junitxml_classname_to_actual_classname: IndexError with classname={classname}"
)
return [], ""
def eval_string_to_set(obj):
if type(obj) == set:
return obj
if obj in ["nan", "", "set()"] or pd.isna(
obj
): # csv (unlike pandas) represents np.NaN as "nan"
return set()
return literal_eval(obj)
class PassedFailed:
columns = [
"Iteration",
"Iteration_status",
#
"Project_Name",
"Project_URL",
"Project_Hash",
"Test_filename",
"Test_classname",
"Test_name",
"Test_parametrization",
#
"Passed_sameOrder",
"Failed_sameOrder",
"Error_sameOrder",
"Skipped_sameOrder",
"Verdict_sameOrder",
"Verdicts_sameOrder",
"numRuns_sameOrder",
#
"Passed_randomOrder",
"Failed_randomOrder",
"Error_randomOrder",
"Skipped_randomOrder",
"Verdict_randomOrder",
"Verdicts_randomOrder",
"numRuns_randomOrder",
]
def __init__(self, df: pd.DataFrame):
self._df = df
# Project_Hash is allowed to be empty, for example for local copies instead of remote repos
self._df["Project_Hash"] = self._df["Project_Hash"].fillna("")
# Some junit-xml files actually had name="" in them
# -> replace by NaN so they get ignored in the groupby
self._df["Test_name"] = self._df["Test_name"].replace("", np.NaN)
# Rows with NaN are ignored by pd.groupby -> fillna
self._df["Test_filename"] = self._df["Test_filename"].fillna("")
self._df["Test_classname"] = self._df["Test_classname"].fillna("")
self._df["Test_parametrization"] = self._df["Test_parametrization"].fillna("")
@classmethod
def load(cls, path: str):
"""Load PassedFailed from CSV file
:file_name: TODO
:returns: TODO
"""
_df = pd.read_csv(
path,
# These converters are disabled, because they cause a lot of memory usage.
# Instead use `eval_string_to_set` on a filtered version.
# converters={
# 'Passed_sameOrder': eval_string_to_set,
# 'Failed_sameOrder': eval_string_to_set,
# 'Error_sameOrder': eval_string_to_set,
# 'Skipped_sameOrder': eval_string_to_set,
# 'Verdicts_sameOrder': eval_string_to_set,
# 'Passed_randomOrder': eval_string_to_set,
# 'Failed_randomOrder': eval_string_to_set,
# 'Error_randomOrder': eval_string_to_set,
# 'Skipped_randomOrder': eval_string_to_set,
# 'Verdicts_randomOrder': eval_string_to_set,
# }
)
return cls(_df)
def add_rerun_column(self) -> pd.DataFrame:
self._df["ids_sameOrder"] = [
p.union(f).union(e).union(s)
for p, f, e, s in zip(
self._df["Passed_sameOrder"],
self._df["Failed_sameOrder"],
self._df["Error_sameOrder"],
self._df["Skipped_sameOrder"],
)
]
return self
def to_tests_overview(self) -> pd.DataFrame:
logging.info("")
self._df["Verdict_sameOrder"] = self._df["Verdicts_sameOrder"].apply(
lambda s: Verdict.decide_overall_verdict(eval_string_to_set(s))
)
self._df["Verdict_randomOrder"] = self._df["Verdicts_randomOrder"].apply(
lambda s: Verdict.decide_overall_verdict(eval_string_to_set(s))
)
self._df["Flaky_sameOrder_withinIteration"] = self._df["Verdict_sameOrder"] == Verdict.FLAKY
self._df["Flaky_randomOrder_withinIteration"] = (
self._df["Verdict_randomOrder"] == Verdict.FLAKY
)
test_overview = self._df.groupby(
[
"Project_Name",
"Project_URL",
"Project_Hash",
"Test_filename",
"Test_classname",
"Test_name",
"Test_parametrization",
],
as_index=False,
).agg(
{
"Verdicts_sameOrder": lambda l: reduce(
set.union, map(lambda s: eval_string_to_set(s), l)
),
"Passed_sameOrder": lambda l: reduce(
op.add, map(lambda s: len(eval_string_to_set(s)), l)
),
"Failed_sameOrder": lambda l: reduce(
op.add, map(lambda s: len(eval_string_to_set(s)), l)
),
"Error_sameOrder": lambda l: reduce(
op.add, map(lambda s: len(eval_string_to_set(s)), l)
),
"Skipped_sameOrder": lambda l: reduce(
op.add, map(lambda s: len(eval_string_to_set(s)), l)
),
"numRuns_sameOrder": sum,
#
"Verdicts_randomOrder": lambda l: reduce(
set.union, map(lambda s: eval_string_to_set(s), l)
),
"Passed_randomOrder": lambda l: reduce(
op.add, map(lambda s: len(eval_string_to_set(s)), l)
),
"Failed_randomOrder": lambda l: reduce(
op.add, map(lambda s: len(eval_string_to_set(s)), l)
),
"Error_randomOrder": lambda l: reduce(
op.add, map(lambda s: len(eval_string_to_set(s)), l)
),
"Skipped_randomOrder": lambda l: reduce(
op.add, map(lambda s: len(eval_string_to_set(s)), l)
),
"numRuns_randomOrder": sum,
"Flaky_sameOrder_withinIteration": any,
"Flaky_randomOrder_withinIteration": any,
}
)
test_overview["Verdict_sameOrder"] = test_overview["Verdicts_sameOrder"].apply(
Verdict.decide_overall_verdict
)
test_overview["Verdict_randomOrder"] = test_overview["Verdicts_randomOrder"].apply(
Verdict.decide_overall_verdict
)
self._df.drop(
["Flaky_sameOrder_withinIteration", "Flaky_randomOrder_withinIteration"],
axis="columns",
inplace=True,
)
# recalculate Order-dependent
test_overview["Order-dependent"] = (~test_overview["Flaky_sameOrder_withinIteration"]) & (
test_overview["Flaky_randomOrder_withinIteration"]
)
# Infrastructure Flakiness
# if a test is order-dependent, it will never be marked as infrastructure flaky,
# even if it would fulfill the requirements in the same order test executions
test_overview["Flaky_Infrastructure"] = (
(
# same order
(test_overview["Verdict_sameOrder"] == Verdict.FLAKY)
& ~test_overview["Flaky_sameOrder_withinIteration"]
)
| (
# random order
(test_overview["Verdict_sameOrder"] != Verdict.FLAKY)
& (test_overview["Verdict_randomOrder"] == Verdict.FLAKY)
& (~test_overview["Order-dependent"])
)
) & ~test_overview["Order-dependent"]
test_overview.insert(
7,
"flaky?",
test_overview.apply(
lambda s: FlakinessType.decide_flakiness_type(
s["Flaky_sameOrder_withinIteration"],
s["Order-dependent"],
s["Flaky_Infrastructure"],
),
axis="columns",
result_type="reduce",
),
)
# modname_classname = test_overview['Test_classname'].apply(
# junitxml_classname_to_modname_and_actual_classname
# )
# test_overview['Test_actual_classname'] = [c for _, c in modname_classname]
# test_overview['Test_modname[-1]'] = [
# m[-1] if len(m) > 0 else '' for m, _ in modname_classname
# ]
test_overview["Test_nodeid"] = test_overview.apply(
lambda s: to_nodeid(s["Test_filename"], s["Test_classname"], s["Test_name"]),
axis=1,
result_type="reduce",
)
test_overview["Test_nodeid_inclPara"] = (
test_overview["Test_nodeid"] + test_overview["Test_parametrization"]
)
return test_overview
def __repr__(self):
return "PassedFailed"
class TestsOverview:
def __init__(self, df: pd.DataFrame):
self._df = df.fillna("")
@classmethod
def load(cls, file_name: str):
"""Load TestsOverview from CSV file"""
_df = pd.read_csv(file_name)
return cls(_df)
def to_classification_template(self) -> pd.DataFrame:
"""Prepare a manual classification template for all flaky tests"""
flaky_tests = self._df[self._df["flaky?"] != FlakinessType.NOT_FLAKY]
classification_template = flaky_tests[
[
"Project_Name",
"Project_URL",
"Project_Hash",
"Test_filename",
"Test_classname",
"Test_name",
"Test_parametrization",
"flaky?",
]
].drop_duplicates()
classification_template["Project Domain"] = ""
classification_template["Category"] = ""
classification_template["Category sure? 1=yes 4=no"] = ""
classification_template["Category comment"] = ""
return classification_template
def to_flapy_input(
self, num_runs: int, *, flakiness_type="ANY", all_tests_in_one_run=True
) -> pd.DataFrame:
"""Filter for all flaky tests and create a new flapy-input, which executes all these (in isolation).
:flakiness_type: see `FlakinessType`
:all_tests_in_one_run: execute all tests within the same project in the same iteration. Tests will still be run separately, but this saves multiple cloning effort.
"""
if flakiness_type == "ANY":
df = self._df
elif flakiness_type == "ANY_FLAKY":
df = self._df[self._df["flaky?"] != FlakinessType.NOT_FLAKY]
else:
df = self._df[self._df["flaky?"] == flakiness_type]
if all_tests_in_one_run:
df = df.groupby(proj_cols)["Test_nodeid"].apply(lambda s: " ".join(s)).reset_index()
else:
df = df[proj_cols + ["Test_nodeid"]]
df["Funcs_to_trace"] = ""
df["Num_runs"] = num_runs
df["PyPi_tag"] = ""
df["Tests_to_be_run"] = df["Test_nodeid"]
return df[
[
"Project_Name",
"Project_URL",
"Project_Hash",
"PyPi_tag",
"Funcs_to_trace",
"Test_nodeid",
"Num_runs",
]
]
class CoverageOverview(object):
"""Output of ResultsDirCollection.get_coverage_overview"""
def __init__(self, df):
self._df = df
self._df["Project_Hash"] = self._df["Project_Hash"].fillna("")
@classmethod
def load(cls, path: str):
return cls(pd.read_csv(path))
def group_by_project(self) -> pd.DataFrame:
"""
Compute the average coverage per project,
taking into account that different iterations
have different numbers of runs (weighted average).
"""
df = self._df.copy()
num_iteration_with_zero_entries = len(df[df["number_of_entries"] < 1])
logging.warning(f"Dropped {num_iteration_with_zero_entries} iteration with zero coverage entries")
df = df[df["number_of_entries"] > 0]
return df.groupby(proj_cols).apply(lambda x: pd.Series({
"number_of_runs": sum(x["number_of_entries"]),
"BranchCoverage": np.average(x["BranchCoverage"], weights=x["number_of_entries"]),
"LineCoverage": np.average(x["LineCoverage"], weights=x["number_of_entries"])
}))
class MyFileWrapper(ABC):
def __init__(
self,
path_: Union[str, Path],
project_name: str,
openvia: Callable[[str], IO] = open,
tarinfo: tarfile.TarInfo = None,
archive: tarfile.TarFile = None,
):
self.p: Path = Path(path_)
self.project_name: str = project_name
self.openvia = openvia
self.archive = archive
self.tarinfo = tarinfo
@classmethod
@abstractmethod
def get_regex(cls, project_name: str) -> str:
"""
Regex should have the run number as the first and only group
:param project_name:
:return:
"""
pass
# TODO is it necessary to check for is empty?
@classmethod
def is_(cls, path: Path, project_name: str, openvia: Callable[[str], IO]) -> bool:
return (
re.match(cls.get_regex(project_name), str(path))
is not None
# and
# (not is_empty(openvia, str(path))
)
@lru_cache()
def get_num(self) -> int:
num = re.findall(self.get_regex(self.project_name), str(self.p))[0][0]
return int(num)
@lru_cache()
def get_test_to_be_run(self) -> str:
return re.findall(self.get_regex(self.project_name), str(self.p))[0][1]
def open(self) -> IO:
f = self.openvia(str(self.p))
if f is None:
raise ValueError("openvia returned None")
return f
def read(self) -> str:
with self.open() as f:
content = f.read()
if isinstance(content, bytes):
content = content.decode()
return content
def __repr__(self) -> str:
return f"{self.__class__.__name__}('{self.p}')"
class CoverageXmlFile(MyFileWrapper):
@classmethod
def get_regex(cls, project_name: str):
return rf".*/{project_name}_coverage(\d+)(.*)\.xml$"
def get_order(self) -> str:
if CoverageXmlFileSameOrder.is_(self.p, self.project_name, self.openvia):
return "same"
if CoverageXmlFileRandomOrder.is_(self.p, self.project_name, self.openvia):
return "random"
return "COULD_NOT_GET_ORDER"
def to_dict(self) -> Dict[str, Union[str, int, float]]:
"""
Transform Junit XML files into a table that shows the verdict and message for each run.
:return:
EXAMPLE:
{
'num': 0,
'order': "same",
"BranchCoverage": 0.7,
"LineCoverage": 0.6
}
"""
try:
with self.open() as f:
root = ET.parse(f).getroot()
return {
"num": self.get_num(),
"order": self.get_order(),
"BranchCoverage": float(root.get("branch-rate")), # type: ignore
"LineCoverage": float(root.get("line-rate")), # type: ignore
}
except Exception as ex:
logging.error(f"{type(ex).__name__} in {self.p}: {ex}")
return {}
class CoverageXmlFileSameOrder(CoverageXmlFile):
@classmethod
def get_regex(cls, project_name: str):
# 'deterministic' was the legacy name sameOrder
return rf".*/(?:deterministic|sameOrder)/tmp/{project_name}_coverage(\d+)(.*)\.xml"
class CoverageXmlFileRandomOrder(CoverageXmlFile):
@classmethod
def get_regex(cls, project_name: str):
# 'non-deterministic' was the legacy name randomOrder
return rf".*/(?:non-deterministic|randomOrder)/tmp/{project_name}_coverage(\d+)(.*)\.xml"
class CoverageSqliteFile(MyFileWrapper):
@classmethod
def get_regex(cls, project_name: str):
return rf".*/{project_name}_coverage(\d+)(.*)\.sqlite$"
def get_order(self) -> str:
if CoverageSqliteFileSameOrder.is_(self.p, self.project_name, self.openvia):
return "same"
if CoverageSqliteFileRandomOrder.is_(self.p, self.project_name, self.openvia):
return "random"
return "COULD_NOT_GET_ORDER"
def get_linebits(self) -> pd.DataFrame:
# -- sqlite cannot open a file handle, but needs a file name -> extract db file first
with tempfile.TemporaryDirectory() as tmpdir:
self.archive.extract(str(self.p), tmpdir)
# -- Querrying database
conn = sqlite3.connect(Path(tmpdir) / self.p)
register_sqlite_functions(conn)
df = pd.read_sql_query(
# "select file_id, context_id, numbits_to_nums(numbits) from line_bits"
"select path, context, numbits_to_nums(numbits) as lines "
"from line_bits "
"join context on context.id=context_id "
"join file on file.id=file_id",
conn,
)
df["lines"] = df["lines"].apply(literal_eval)
df = df.replace("", np.NaN)
return df
def to_table(self, *, drop_empty_context=False, drop_execution_stages=False) -> pd.DataFrame:
"""
drop_execution_stages: e.g. 'test_foo|run' -> 'test_foo'; 'test_bar|setup' -> 'test_bar'
In this case, we also need to group the columns together
that address the same test via an any operator
"""
df = self.get_linebits()
df["context"] = df["context"].fillna("EMPTY_CONTEXT")
df = df.explode("lines")
df = df.dropna(subset="lines")
df["covered"] = True
df = df.pivot(index=["path", "lines"], columns="context", values="covered")
df = df.fillna(False)
if drop_empty_context:
df.drop(columns="EMPTY_CONTEXT", inplace=True, errors="ignore")
if drop_execution_stages:
if not df.empty:
df.rename(columns=lambda col: re.sub("\|.*", "", col), inplace=True)
df = df.groupby(level=0, axis=1).any()
# Groupby somehow removes the index names
df.index.set_names(["path", "lines"], inplace=True)
return df
class CoverageSqliteFileSameOrder(CoverageSqliteFile):
@classmethod
def get_regex(cls, project_name: str):
# 'deterministic' was the legacy name sameOrder
return rf".*/(?:deterministic|sameOrder)/tmp/{project_name}_coverage(\d+)(.*)\.sqlite$"
class CoverageSqliteFileRandomOrder(CoverageSqliteFile):
@classmethod
def get_regex(cls, project_name: str):
# 'non-deterministic' was the legacy name randomOrder
return (
rf".*/(?:non-deterministic|randomOrder)/tmp/{project_name}_coverage(\d+)(.*)\.sqlite$"
)
class JunitXmlFile(MyFileWrapper):
@classmethod
def get_regex(cls, project_name: str):
return rf".*/tmp/{project_name}_output(\d+)(.*)\.xml$"
@lru_cache()
def get_order(self) -> str:
if JunitXmlFileSameOrder.is_(self.p, self.project_name, self.openvia):
return "same"
if JunitXmlFileRandomOrder.is_(self.p, self.project_name, self.openvia):
return "random"
return "COULD_NOT_GET_ORDER"
def parse(self) -> Union[junitparser.JUnitXml, junitparser.TestSuite]:
"""
Read the file and parse it via junitparser.
Some JUnit XML files have three hiearchie levels: testsuites, testsuite, testcase
others skip the first one and start with testsuite
"""
with self.open() as f:
try:
return junitparser.JUnitXml.fromfile(f, ET.parse)
except xml.etree.ElementTree.ParseError as ex:
logging.error(f"ParseError in {self.p}: {ex}")
return junitparser.JUnitXml()
def get_hostname(self) -> str:
return list(self.parse())[0].hostname
def get_testcases(self) -> List[junitparser.TestCase]:
junit_xml = self.parse()
if isinstance(junit_xml, junitparser.TestSuite):
test_cases = [case for case in junit_xml]
else:
test_cases = [case for suite in junit_xml for case in suite]
return test_cases
def to_table(self, include_num_ttbr_order=True) -> List[Dict[str, Union[str, int]]]:
"""
Transform Junit XML files into a table that shows the verdict and message for each run.
:return:
EXAMPLE [
{
'file': 'test_file',
'class': 'test_class',
'func': 'test_func',
'verdict': 'Failed',
'errors': '[AssertionError]'
'contains_no_space_left': False,
'num': 0
},
{ ... }
]
"""
try:
test_cases = self.get_testcases()
# if len(test_cases) == 0:
# logging.warning(f"{self.p} contains no testcases")
if include_num_ttbr_order:
result: List[Dict[str, Union[str, int]]] = [
{
**read_junit_testcase(test_case),
"num": self.get_num(),
"test_to_be_run": self.get_test_to_be_run(),
"order": self.get_order(),
}
for test_case in test_cases
]
else:
result: List[Dict[str, Union[str, int]]] = [
{
**read_junit_testcase(test_case),
}
for test_case in test_cases
]
return result
except Exception as ex:
logging.error(f"{type(ex).__name__} in {self.p}: {ex}")
return []
class JunitXmlFileSameOrder(JunitXmlFile):
@classmethod
def get_regex(cls, project_name: str):
# 'deterministic' was the legacy name sameOrder
return rf".*/(?:deterministic|sameOrder)/tmp/{project_name}_output(\d+)(.*)\.xml"
class JunitXmlFileRandomOrder(JunitXmlFile):
@classmethod
def get_regex(cls, project_name: str):
# 'non-deterministic' was the legacy name randomOrder
return rf".*/(?:non-deterministic|randomOrder)/tmp/{project_name}_output(\d+)(.*)\.xml"
class TraceFile(MyFileWrapper):
"""File containing traces"""
@classmethod
def get_regex(cls, project_name: str):
return rf".*/{project_name}_trace(\d+)_.+\.txt$"
def get_test_funcdescriptor(self) -> FuncDescriptor:
"""Extracts the name of a Test from a given trace-file"""
with self.open() as f:
try:
first_line = next(f)
except StopIteration:
return ("EMPTY_FILE", "", "")
call_return, depth, func, _, _ = parse_trace_line(first_line)
assert call_return == "call"
assert depth == 1
return func
def grep(self, pattern: str) -> Optional[str]:
"""Greps for a string.
:pattern: String, no regex
:returns: First line containing the pattern
"""
with self.open() as f:
for line in f:
line = str(line)
if pattern in line:
return line
return None
T1 = TypeVar("T1", bound=MyFileWrapper)
class Iteration:
"""
Example: flapy-results_20200101/lineflow
"""
archive_name = "results.tar.xz"
meta_file_name = "flapy-iteration-result.yaml"
def __init__(self, path: Union[str, Path]):
self.p = Path(path)
self._archive: Optional[tarfile.TarFile] = None
# Check if this is a valid iteration
if not self.p.is_dir():
raise ValueError(f"{self.p} is not a directory")
if self.p.name == "run":
raise ValueError(f"Folders named 'run' are not considered iterations (legacy)")
if self.p.name.startswith("."):
raise ValueError(f"Folders whose names start with '.' are not considered iterations")
if not (self.p / self.archive_name).is_file():
# TODO: maybe raise this exception later (like inside get_junit_data, or just set
# status). The meta file might still be present and its information might be interesting
raise ValueError(f"{self.p} contains no results archive ({self.archive_name})")
# Read meta info if available (only in newer versions, older versions use separate files)
self.meta_file = self.p / self.meta_file_name
if self.meta_file.is_file():
with open(self.meta_file) as f:
self.meta_info = yaml.safe_load(f)
else:
self.meta_info = None
# Retrieve basic information to raise heat cache and raise possible errors now
self.get_project_name()
self.get_project_url()
self.get_project_git_hash()
# Setup cache
self._results_cache = self.p / "flapy.cache"
if not self._results_cache.is_dir():
self._results_cache.mkdir()
self._junit_cache_file = self._results_cache / "junit_data.csv"
def has_archive(self):
"""If the results have not been written back (e.g., due to a timeout), there is no resultar.tar.xz, however, the directory with the meta infos is still counted as a failed attempt and therefore an iteration."""
return (self.p / self.archive_name).is_file()
@lru_cache()
def get_project_name(self) -> str:
if self.meta_info is not None:
return self.meta_info["project_name"]
elif (self.p / "project-name.txt").is_file():
with open(self.p / "project-name.txt") as file:
return file.read().replace("\n", "")
else:
raise ValueError("Could not retrieve project name")
def get_project_url(self) -> str:
if self.meta_info is not None:
return self.meta_info["project_url"]
elif (self.p / "project-url.txt").is_file():
with open(self.p / "project-url.txt") as file:
return file.read().replace("\n", "")
else:
raise ValueError("Could not retrieve project URL")
def get_project_git_hash(self) -> str:
if self.meta_info is not None:
return self.meta_info["project_git_hash"]
elif (self.p / "project-git-hash.txt").is_file():
with open(self.p / "project-git-hash.txt") as file:
return file.read().replace("\n", "")
else:
raise ValueError("Could not retrieve project hash")
def get_flapy_git_hash(self) -> str:
# Flapy used to be called 'flakyanalysis'
if (self.p / "flakyanalysis-git-hash.txt").is_file():
with open(self.p / "flakyanalysis-git-hash.txt") as file:
return file.read().replace("\n", "")
return "COULD_NOT_GET_FLAKYANALYSIS_GIT_HASH"
def get_iterations_info(self) -> Dict[str, Any]:
return {
"Iteration": self,
"Project_Name": self.get_project_name(),
"Project_URL": self.get_project_url(),
"Project_Hash": self.get_project_git_hash(),
}
def get_lines_of_code(self, languages=["Python"], metrics=["code"]) -> Dict[str, Optional[int]]:
"""Read lines-of-code information
:languages: languages to filter for (Markdown, YAML, Python, ...)
Must be specified as one string carrying a list, e.g. "[Python, Markdown]"
If the project does not use this language, the respective keys are mapped to None
:metrics: type of lines to filter for
Must be a subset of [files, blank, comment, code, total]
Must be specified as one string carrying a list
:returns: Dictionary mapping "language_metric" to the respective number of lines
"""
LOC_METRICS = ["files", "blank", "comment", "code", "total"]
for metric in metrics:
if metric not in LOC_METRICS:
raise ValueError(f"Unknown metric {metric}. Must be in {LOC_METRICS}")
loc_df = pd.read_csv(self.p / "loc.csv").set_index("language")
loc_dict = dict()
for language in languages:
for metric in metrics:
loc_dict[f"{language}_{metric}"] = loc_df[metric].get(language)
return loc_dict
def clear_results_cache(self):
for file_ in self._results_cache.iterdir():
file_.unlink()
def clear_junit_data_cache(self):
if self._junit_cache_file.is_file():
self._junit_cache_file.unlink()
def get_junit_data(
self,
*,
include_project_columns: bool = False,
read_cache=True,
write_cache=True,
return_nothing=False,
) -> pd.DataFrame:
did_read_cache = False
if read_cache and self._junit_cache_file.is_file():
junit_data: pd.DataFrame = pd.read_csv(self._junit_cache_file)
did_read_cache = True
else:
columns = list(read_junit_testcase(junitparser.TestCase()).keys()) + ["num", "order"]
junitxml_files = self.get_files(JunitXmlFile)
junit_data = pd.DataFrame(
[
test_case
for junit_xml_file in junitxml_files
for test_case in junit_xml_file.to_table()
]
)
if len(junit_data) == 0:
junit_data = pd.DataFrame(columns=columns)
if write_cache and not did_read_cache and len(junit_data) > 0:
junit_data.to_csv(self._junit_cache_file, index=False)
if include_project_columns:
junit_data.insert(
0,
"Project_Hash",
try_default(lambda: self.get_project_git_hash(), Exception, "error"),
)
junit_data.insert(0, "Project_URL", self.get_project_url())
junit_data.insert(0, "Project_Name", self.get_project_name())
junit_data.insert(0, "Iteration", self.p.name)
self.close_archive()
if return_nothing:
return None
return junit_data.fillna("")
def get_passed_failed(
self, *, read_cache=True, write_cache=True, verdict_cols_to_strings=True
) -> pd.DataFrame:
try:
junit_data = self.get_junit_data(
include_project_columns=False, read_cache=read_cache, write_cache=write_cache
)
except Exception as e:
logging.error(f"{type(e).__name__}: {e} in {self.p}")
return pd.DataFrame(columns=PassedFailed.columns)
junit_data.insert(0, "Iteration", self.p.name)
junit_data.insert(1, "Project_Name", self.get_project_name())
junit_data.insert(2, "Project_URL", self.get_project_url())
junit_data.insert(3, "Project_Hash", self.get_project_git_hash())
junit_data["Test_filename"] = junit_data["file"]
junit_data["Test_classname"] = junit_data["class"]
junit_data["Test_name"] = [re.sub(r"\[.*\]", "", name) for name in junit_data["name"]]
junit_data["Test_parametrization"] = [
re.findall(r"(\[.*\])", name)[0] if len(re.findall(r"(\[.*\])", name)) > 0 else ""
for name in junit_data["name"]