File size: 65,940 Bytes
d086025 | 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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 | diff --git a/afluent/__init__.py b/afluent/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..46e5712ecd0fbfc82db79017d83cee782d123e2b
--- /dev/null
+++ b/afluent/__init__.py
@@ -0,0 +1,3 @@
+"""standard init file."""
+
+__version__ = "0.1.0"
diff --git a/afluent/line.py b/afluent/line.py
new file mode 100644
index 0000000000000000000000000000000000000000..9710fc4ea01b6eeb240cab3023eb693b5b236165
--- /dev/null
+++ b/afluent/line.py
@@ -0,0 +1,211 @@
+"""Create object oriented structure to keep track of line information."""
+
+import math
+from typing import List
+
+# Scores:
+TARAN = "tarantula"
+OCHIAI = "ochiai"
+OCHIAI2 = "ochiai2"
+DSTAR = "dstar"
+
+
+# Tiebreakers
+RANDOM = "random"
+CYCLOMATIC = "cyclomatic"
+LOGICAL = "logical"
+ENHANCED = "enhanced"
+
+
+# pylint: disable=R0902
+class Line:
+ """Implement the line object and suspiciousness calculation."""
+
+ def __init__(self, file_path: str, line_num: int) -> None:
+ """Initialize a line object.
+
+ Args:
+ file_path (str): Path to the file where the line exists
+ line_num (int): number of the line in the file
+ """
+ self.path = file_path
+ self.number = line_num
+ self.passed_by: List[str] = []
+ self.failed_by: List[str] = []
+ self.skipped_by: List[str] = []
+ self.sus_scores = {
+ TARAN: -1.0,
+ OCHIAI: -1.0,
+ DSTAR: -1.0,
+ OCHIAI2: -1.0,
+ }
+ self.tiebreakers = {
+ CYCLOMATIC: 0.0,
+ LOGICAL: 0.0,
+ ENHANCED: 0.0,
+ # *SHOULD ALWAYS STAY ZERO
+ RANDOM: 0.0,
+ }
+
+ def sus(self, method: str, passed_total: int, failed_total: int, power=3):
+ """Calculate the suspiciousness score using the passed method.
+
+ Args:
+ method (str): name of the method to use
+ """
+ if method.lower() == TARAN:
+ self.sus_scores[TARAN] = Line.tarantula(
+ len(self.failed_by),
+ len(self.passed_by),
+ passed_total,
+ failed_total,
+ )
+ elif method.lower() == OCHIAI:
+ self.sus_scores[OCHIAI] = Line.ochiai(
+ len(self.failed_by), len(self.passed_by), failed_total
+ )
+ elif method.lower() == DSTAR:
+ self.sus_scores[DSTAR] = Line.dstar(
+ len(self.failed_by), len(self.passed_by), failed_total, power
+ )
+ elif method.lower() == OCHIAI2:
+ self.sus_scores[OCHIAI2] = Line.ochiai2(
+ len(self.failed_by),
+ len(self.passed_by),
+ passed_total,
+ failed_total,
+ )
+ else:
+ raise Exception("ERROR: unknown suspiciousness method")
+
+ def sus_all(self, passed_total: int, failed_total: int, power=3):
+ """Calculate the suspiciousness score for all available methods."""
+ self.sus(TARAN, passed_total, failed_total)
+ self.sus(OCHIAI, passed_total, failed_total)
+ self.sus(DSTAR, passed_total, failed_total, power=power)
+ self.sus(OCHIAI2, passed_total, failed_total)
+
+ def as_dict(self):
+ """Return line information as json writable dictionary."""
+ return self.__dict__
+
+ def as_csv(self):
+ """Return line information as csv writable list."""
+ return [
+ self.path,
+ self.number,
+ self.sus_scores[TARAN],
+ self.sus_scores[OCHIAI],
+ self.sus_scores[OCHIAI2],
+ self.sus_scores[DSTAR],
+ ]
+
+ def sus_text(self, methods):
+ """Return a tuple of string of line information and score value."""
+ sus_list = []
+ for method_name in methods:
+ sus_list.append(self.sus_scores[method_name])
+ return (self.path, self.number, sus_list)
+
+ @staticmethod
+ def tarantula(
+ failed_cover: int, passed_cover: int, total_passed: int, total_failed: int
+ ) -> float:
+ """Calculate suspiciousness score using the tarantula approach.
+
+ Args:
+ failed_cover (int): total number of failed test cases that cover the line
+ passed_cover (int): total number of passed test cases that cover the line
+ total_passed (int): total number of passed test cases
+ total_failed (int): total number of failed test cases
+
+ Returns:
+ float: suspiciousness score using tarantula
+ """
+ if total_passed == 0:
+ return 1
+ if total_failed == 0:
+ return 0
+ score = (failed_cover / total_failed) / (
+ (passed_cover / total_passed) + (failed_cover / total_failed)
+ )
+ return round(score, 4)
+
+ @staticmethod
+ def ochiai(failed_cover: int, passed_cover: int, total_failed: int) -> float:
+ """Calculate suspiciousness score using the ochiai approach.
+
+ Args:
+ failed_cover (int): total number of failed test cases that cover the line
+ passed_cover (int): total number of passed test cases that cover the line
+ total_failed (int): total number of failed test cases
+
+ Returns:
+ float: suspiciousness score using ochiai
+ """
+ if total_failed == 0 or failed_cover == 0:
+ return 0
+ score = failed_cover / math.sqrt(total_failed * (passed_cover + failed_cover))
+ return round(score, 4)
+
+ @staticmethod
+ def dstar(
+ failed_cover: int, passed_cover: int, total_failed: int, power=3
+ ) -> float:
+ """Calculate suspiciousness score using the dstar approach.
+
+ Args:
+ failed_cover (int): total number of failed test cases that cover the line
+ passed_cover (int): total number of passed test cases that cover the line
+ total_failed (int): total number of failed test cases
+ power (int, optional): Power to use in the equation. Defaults to 3.
+
+ Returns:
+ float: suspiciousness score using dstar
+ """
+ uncovered_failed = total_failed - failed_cover
+ if passed_cover + uncovered_failed == 0:
+ return float("inf")
+ score = math.pow(failed_cover, power) / (passed_cover + uncovered_failed)
+ return round(score, 4)
+
+ @staticmethod
+ def ochiai2(
+ failed_cover: int, passed_cover: int, total_passed: int, total_failed: int
+ ) -> float:
+ """Calculate suspiciousness score using the ochiai2 approach.
+
+ Args:
+ failed_cover (int): total number of failed test cases that cover the line
+ passed_cover (int): total number of passed test cases that cover the line
+ total_passed (int): total number of passed test cases
+ total_failed (int): total number of failed test cases
+
+ Returns:
+ float: suspiciousness score using ochiai2
+ """
+ # !DIVISION BY ZERO WHEN
+ # ?If there are no tests that cover the statement: not happening, we're
+ # only looking at covered statements to begin with
+ # !If there are no tests that do not cover the statement: UNSURE
+ # ?If the total failed is zero: not possible, for AFLuent to run, there
+ # has to be at least one failure
+ # ?If total passed is zero => everything is suspicious, no info really
+ passed_uncover = total_passed - passed_cover
+ failed_uncover = total_failed - failed_cover
+ total_cover = passed_cover + failed_cover
+ total_uncover = passed_uncover + failed_uncover
+ if total_passed == 0:
+ return 1.0
+ if total_uncover == 0:
+ return 0
+ if total_failed == 0:
+ return 0
+ if total_cover == 0:
+ return 0
+ numerator = failed_cover * passed_uncover
+ denominator = math.sqrt(
+ total_cover * total_uncover * total_failed * total_passed
+ )
+ score = numerator / denominator
+ return round(score, 4)
diff --git a/afluent/main.py b/afluent/main.py
new file mode 100644
index 0000000000000000000000000000000000000000..1406bb22adfcb210070af980276ef17a6912687c
--- /dev/null
+++ b/afluent/main.py
@@ -0,0 +1,243 @@
+"""Define Pytest Hooks that run AFLuent."""
+
+import json
+
+from time import time
+import coverage # type: ignore[import]
+import pytest # type: ignore[import]
+from console import bg, fg, fx # type: ignore[import]
+
+from afluent import spectrum_parser
+
+
+WARNING = fx.bold + fg.white + bg.orange
+ERROR = fx.bold + fg.white + bg.red
+VALID = fx.bold + fg.white + bg.green
+
+CONFLICTING_PLUGINS = ["pytest_cov"]
+
+
+def pytest_addoption(parser):
+ """Add AFLuent command line group and arguments to accept."""
+ afluent_group = parser.getgroup("afluent", "Automated Fault Localization (AFLuent)")
+ afluent_group.addoption(
+ "--afl-debug",
+ "--afl",
+ dest="afl_enable",
+ action="store_true",
+ default=False,
+ help="Enable AFLuent",
+ )
+ afluent_group.addoption(
+ "--tarantula",
+ dest="afl_methods",
+ action="append_const",
+ const="tarantula",
+ help="Enable fault localization using Tarantula",
+ )
+ afluent_group.addoption(
+ "--ochiai",
+ dest="afl_methods",
+ action="append_const",
+ const="ochiai",
+ help="Enable fault localization using Ochiai",
+ )
+ afluent_group.addoption(
+ "--ochiai2",
+ dest="afl_methods",
+ action="append_const",
+ const="ochiai2",
+ help="Enable fault localization using Ochiai2",
+ )
+ afluent_group.addoption(
+ "--dstar",
+ dest="afl_methods",
+ action="append_const",
+ const="dstar",
+ help="Enable fault localization using Dstar",
+ )
+ afluent_group.addoption(
+ "--dstar-pow",
+ dest="dstar_pow",
+ default=3,
+ action="store",
+ type=int,
+ help="Power to use when calculating Dstar score, default to 3",
+ )
+ afluent_group.addoption(
+ "--afl-results",
+ dest="results_num",
+ default=20,
+ action="store",
+ type=int,
+ help="Number of results to display in the score report , default to 20",
+ )
+ afluent_group.addoption(
+ "--afl-ignore",
+ dest="afl_ignore",
+ action="extend",
+ nargs="*",
+ type=str,
+ help="File patterns to ignore when calculating coverage for AFLuent (example: tests/*).",
+ )
+ afluent_group.addoption(
+ "--report",
+ dest="report_type",
+ action="store",
+ default=None,
+ type=str,
+ choices=["json", "csv", "eval"],
+ help="Store report after AFLuent run.",
+ )
+ afluent_group.addoption(
+ "--per-test-report",
+ dest="per_test",
+ action="store_true",
+ help="Get per test case coverage report.",
+ )
+ afluent_group.addoption(
+ "--tiebreaker",
+ dest="tiebreaker",
+ action="store",
+ default="random",
+ type=str,
+ choices=["random", "cyclomatic", "logical", "enhanced"],
+ help="Type of tie breaking approach.",
+ )
+
+
+def pytest_cmdline_main(config):
+ """Check if AFLuent is enabled and register the plugin object."""
+ # check if the argument to enable afluent exists and create the object with
+ # the passed configuration
+ for plugin in CONFLICTING_PLUGINS:
+ if config.pluginmanager.hasplugin(plugin):
+ print(
+ WARNING(
+ f"\n{plugin} plugin conflicts with AFLuent, consider disabling\n"
+ + "it for this session to get the most accurate fault localization results.\n\n"
+ )
+ )
+
+ if config.getoption("afl_enable"):
+ # Check if exit after failure is enabled and display warning message
+ if config.getoption("--maxfail"):
+ print(
+ WARNING(
+ "\nExit after failure detected. AFLuent gives more "
+ + "accurate results if the full test suite was ran.\n\n"
+ + "Consider removing `-x` and/or `--maxfail` from CLI arguments."
+ )
+ )
+ print()
+ plugin = Afluent(config)
+ config.pluginmanager.register(plugin, "Afluent")
+ else:
+ print(
+ WARNING(
+ "\nAFLuent is disabled. Enable AFLuent by adding "
+ "--afl or --afl-debug to the test command."
+ )
+ )
+ print()
+
+
+class Afluent:
+ """Contain all the functionalities and hooks of the AFLuent plugin."""
+
+ # pylint: disable=R0913, R0902
+ def __init__(self, pytest_config):
+ """Initialize a plugin object with it's pytest hooks."""
+ self.methods = pytest_config.getoption("afl_methods")
+ # if no methods were passed, include all of them
+ if not self.methods:
+ self.methods = ["dstar", "tarantula", "ochiai", "ochiai2"]
+ self.dstar_pow = pytest_config.getoption("dstar_pow")
+ self.results_num = pytest_config.getoption("results_num")
+ self.ignore = pytest_config.getoption("afl_ignore")
+ self.report = pytest_config.getoption("report_type")
+ self.per_test = pytest_config.getoption("per_test")
+ self.tiebreaker = pytest_config.getoption("tiebreaker")
+ if self.report == "eval":
+ self.eval_mode = True
+ else:
+ self.eval_mode = False
+ self.session_spectrum = {}
+ self.cov = coverage.Coverage(
+ data_file=None,
+ auto_data=False,
+ branch=True,
+ config_file=False,
+ omit=self.ignore,
+ )
+
+ @pytest.hookimpl(hookwrapper=True)
+ def pytest_pyfunc_call(self, pyfuncitem):
+ """Calculate the coverage of each test case and add it to spectrum."""
+ try:
+ self.cov.start()
+ yield
+ self.cov.stop()
+ coverage_data = self.cov.get_data()
+ item_key = f"{pyfuncitem.parent.name}_{pyfuncitem.name}"
+ self.session_spectrum[item_key] = {
+ "coverage": {},
+ "result": "notSet",
+ }
+ for measured_file in coverage_data.measured_files():
+ self.session_spectrum[item_key]["coverage"][
+ measured_file
+ ] = self.cov.get_data().lines(measured_file)
+ except coverage.exceptions.CoverageWarning:
+ pass
+ self.cov.erase()
+
+ @pytest.hookimpl(hookwrapper=True)
+ def pytest_runtest_makereport(self, item):
+ """Store the outcome of the test case as passed, failed, or skipped."""
+ outcome = yield
+ item_key = f"{item.parent.name}_{item.name}"
+ if outcome.get_result().when == "call" and item_key in self.session_spectrum:
+ self.session_spectrum[item_key]["result"] = outcome.get_result().outcome
+
+ def pytest_sessionfinish(self, session, exitstatus):
+ """Perform the spectrum analysis if at least one test fails."""
+ test_end_time = time()
+ reporter = session.config.pluginmanager.get_plugin("terminalreporter")
+ # pylint: disable=W0212
+ test_time = round(test_end_time - reporter._sessionstarttime, 6)
+ localization_time = 0
+ # Store generated json
+ if self.per_test:
+ with open(
+ "afluent_per_test_report.json", "w+", encoding="utf-8"
+ ) as outfile:
+ json.dump(self.session_spectrum, outfile, indent=4)
+ # Tests passed, exit status is 0
+ if exitstatus == 0:
+ exit_message = VALID(
+ "\n\nAll tests passed, no need to diagnose using AFLuent."
+ )
+ print(f"{exit_message}")
+ # some tests failed exit status
+ elif exitstatus == 1:
+ exit_message = ERROR(
+ "\n\nFailing tests detected. Diagnosing using AFLuent..."
+ )
+ print(f"{exit_message}")
+ start_time = time()
+ full_spectrum = spectrum_parser.Spectrum(
+ self.session_spectrum,
+ dstar_pow=self.dstar_pow,
+ tiebreaker=self.tiebreaker,
+ eval_mode=self.eval_mode,
+ )
+ end_time = time()
+ localization_time = round(end_time - start_time, 6)
+ full_spectrum.print_report(self.methods, self.results_num)
+ if self.report:
+ print(f"Storing {self.report} report...")
+ full_spectrum.store_report(self.report)
+ timings = {"test_time": test_time, "localization_time": localization_time}
+ with open("afluent_timings.json", "w+", encoding="utf-8") as outfile:
+ json.dump(timings, outfile, indent=4)
diff --git a/afluent/proj_file.py b/afluent/proj_file.py
new file mode 100644
index 0000000000000000000000000000000000000000..8dc1b3669d0e7b6e01bca2cbb6e40095cc69d519
--- /dev/null
+++ b/afluent/proj_file.py
@@ -0,0 +1,89 @@
+"""Create object oriented structure for files carrying line coverage information."""
+from typing import Dict
+
+from afluent import tiebreak_generator
+
+from afluent import line
+
+
+class ProjFile:
+ """Store coverage information about python files under test."""
+
+ def __init__(self, name: str) -> None:
+ """Initialize a ProjFile object.
+
+ Args:
+ name (str): path of the file under test
+ """
+ self.name = name
+ self.lines: Dict[int, line.Line] = {}
+ self.cyclomatic_complexity_data: Dict[int, int] = {}
+ self.logical_tiebreak_data: Dict[int, int] = {}
+ self.enhanced_tiebreak_data: Dict[int, float] = {}
+
+ def update_file(
+ self, covered_lines: list[int], test_result: str, test_case_name: str
+ ):
+ """Update lines information in a file object.
+
+ Args:
+ covered_lines (list[int]): list of integer values of the lines covered
+ test_result (str): one of three possible values `passed` `failed` or `skipped`
+ test_case_name (str): name of the test case being ran
+
+ Raises:
+ Exception: when a result is not one of the three possible values
+ """
+ for line_number in covered_lines:
+ # Line doesn't exist in the dataset, create new one
+ if line_number not in self.lines:
+ line_obj = line.Line(self.name, line_number)
+ if self.cyclomatic_complexity_data:
+ # get the complexity of the line
+ line_obj.tiebreakers[
+ "cyclomatic"
+ ] = self.cyclomatic_complexity_data[line_number]
+ if self.logical_tiebreak_data:
+ line_obj.tiebreakers["logical"] = self.logical_tiebreak_data[
+ line_number
+ ]
+ if self.enhanced_tiebreak_data:
+ line_obj.tiebreakers["enhanced"] = self.enhanced_tiebreak_data[
+ line_number
+ ]
+
+ self.lines[line_number] = line_obj
+ if test_result == "passed":
+ self.lines[line_number].passed_by.append(test_case_name)
+ elif test_result == "failed":
+ self.lines[line_number].failed_by.append(test_case_name)
+ elif test_result == "skipped":
+ self.lines[line_number].skipped_by.append(test_case_name)
+ else:
+ raise Exception(f"Unknown test result for {test_case_name}")
+
+ def get_cyclomatic_tiebreaker_dataset(self):
+ """Use the file path to calculate cyclomatic complexity and update the data."""
+ # set cyclomatic complexity to be enabled
+ cc_generator = tiebreak_generator.CyclomaticComplexityGenerator(self.name)
+ cc_generator.calculate_syntax_complexity()
+ self.cyclomatic_complexity_data = cc_generator.data
+
+ def get_logical_tiebreaker_dataset(self):
+ """Use tiebreak generator to get the logical tiebreaker dataset."""
+ mutant_density_generator = tiebreak_generator.LogicalTieBreaker(self.name)
+ mutant_density_generator.calculate_mutant_density()
+ self.logical_tiebreak_data = mutant_density_generator.score
+
+ def get_enhanced_tiebreaker_dataset(self):
+ """Use tiebreak generator to get the enhanced tiebreaker dataset."""
+ generator = tiebreak_generator.EnhancedTieBreaker(self.name)
+ generator.calculate_mutant_density()
+ self.enhanced_tiebreak_data = generator.score
+
+ def as_dict(self):
+ """Return lines as a json writable dictionary."""
+ data_dictionary = {}
+ for line_num, line_obj in self.lines.items():
+ data_dictionary[str(line_num)] = line_obj.as_dict()
+ return data_dictionary
diff --git a/afluent/spectrum_parser.py b/afluent/spectrum_parser.py
new file mode 100644
index 0000000000000000000000000000000000000000..6688d20e40de8375639bad05558510ab5643a8ef
--- /dev/null
+++ b/afluent/spectrum_parser.py
@@ -0,0 +1,255 @@
+"""Implement parsing and reassembling functions for coverage data."""
+
+import csv
+import json
+import random
+
+from typing import Any, Dict, List, Tuple
+
+from console import fg, bg, fx # type: ignore[import]
+from tabulate import tabulate
+from afluent import proj_file, line
+
+
+METHOD_NAMES = ["tarantula", "ochiai", "ochiai2", "dstar"]
+TIEBREAKERS = ["random", "cyclomatic", "logical", "enhanced"]
+
+PALETTE = {
+ "severe": fg.white + fx.bold + bg.lightred,
+ "risky": fg.white + fx.bold + bg.i208,
+ "mild": fg.white + fx.bold + bg.yellow,
+ "safe": fg.white + fx.bold + bg.green,
+ "location_line": fg.white,
+}
+
+
+class Spectrum:
+ """Store all the information for individual files and lines coverage."""
+
+ def __init__(
+ self, config, dstar_pow=3, tiebreaker="random", eval_mode=False
+ ) -> None:
+ """Initialize a spectrum object.
+
+ Args:
+ config (dict): per-test coverage information
+ dstar_pow (int): power to use when calculating scores using dstar
+ """
+ self.config = config
+ self.reassembled_data: Dict[str, proj_file.ProjFile] = {}
+ self.sorted_lines: List[line.Line] = []
+ self.totals = {"passed": 0, "failed": 0, "skipped": 0}
+ self.dstar_pow = dstar_pow
+ self.tiebreaker = tiebreaker
+ self.eval_mode = eval_mode
+ self.reassemble()
+ self.calculate_sus()
+
+ def generate_report(
+ self, methods: List[str], max_items=-1
+ ) -> List[Tuple[Any, ...]]:
+ """Generate a list of tuples containing report information."""
+ report_list = []
+ # Gather up all the line objects in one list
+ all_lines: List[line.Line] = []
+ for file_obj in self.reassembled_data.values():
+ all_lines.extend(file_obj.lines.values())
+ # Sort the lines based on the first method name used in the list
+ sorted_lines = Spectrum.generate_rankings(
+ all_lines, methods[0], tiebreaker=self.tiebreaker
+ )
+ # store as an instance variable to generate reports later
+ self.sorted_lines = sorted_lines
+ if max_items > 0:
+ sorted_lines = sorted_lines[:max_items]
+ # pylint: disable=C0200
+ for line_index in range(0, len(sorted_lines)):
+ line_obj = sorted_lines[line_index]
+ line_path, line_number, sus_scores = line_obj.sus_text(methods)
+ line_path = f"{PALETTE['location_line'](line_path)}"
+ line_number = f"{PALETTE['location_line'](str(line_number))}"
+ current_row = [line_path, line_number]
+ format_function = Spectrum.calculate_severity(
+ methods[0], sus_scores[0], line_index, len(sorted_lines)
+ )
+ for method_score in sus_scores:
+ current_row.append(f"{format_function(str(method_score))}")
+ report_list.append(tuple(current_row))
+ return report_list
+
+ def reassemble(self):
+ """Reassemble the coverage information on a file and line basis."""
+ # Config is empty, return nothing
+ if not self.config:
+ return
+ # iterate through every test case in the spectrum report
+ for test_case_name, spectrum_dict in self.config.items():
+ test_result = spectrum_dict["result"]
+ # increment the totals
+ self.totals[test_result] += 1
+ for file_name, lines_covered in spectrum_dict["coverage"].items():
+ if file_name not in self.reassembled_data:
+ # Initialize a new object of one doesn't already exist
+ file_obj = proj_file.ProjFile(file_name)
+ if self.eval_mode:
+ # populate all tieberaker datasets
+ file_obj.get_logical_tiebreaker_dataset()
+ file_obj.get_enhanced_tiebreaker_dataset()
+ file_obj.get_cyclomatic_tiebreaker_dataset()
+ elif self.tiebreaker == "logical":
+ # collect logical tiebreak dataset only
+ file_obj.get_logical_tiebreaker_dataset()
+ elif self.tiebreaker == "enhanced":
+ # collect enhanced tiebreak dataset only
+ file_obj.get_enhanced_tiebreaker_dataset()
+ elif self.tiebreaker == "cyclomatic":
+ # collect cyclometer dataset only
+ file_obj.get_cyclomatic_tiebreaker_dataset()
+ # * Random tiebreaker doesn't need dataset
+ self.reassembled_data[file_name] = file_obj
+ self.reassembled_data[file_name].update_file(
+ lines_covered, test_result, test_case_name
+ )
+
+ def calculate_sus(self):
+ """Iterate through reassembeled data and calculate the suspiciousness of every line."""
+ for _, current_file in self.reassembled_data.items():
+ for _, current_line in current_file.lines.items():
+ current_line.sus_all(
+ self.totals["passed"], self.totals["failed"], power=self.dstar_pow
+ )
+
+ def as_dict(self):
+ """Return the spectrum information as a JSON writable dictionary."""
+ data_dict = {}
+ for file_name, file_obj in self.reassembled_data.items():
+ data_dict[file_name] = file_obj.as_dict()
+
+ return data_dict
+
+ def print_report(self, methods: List[str], items_num: int):
+ """Print a nicely formatted suspiciousness report using the chosen method."""
+ for method_name in methods:
+ if method_name not in METHOD_NAMES:
+ raise Exception(f"ERROR: Invalid method name {method_name}")
+ print()
+ header_text = "============================ AFLuent Report ==============================="
+ table_headers = [
+ PALETTE["location_line"]("File Path"),
+ PALETTE["location_line"]("Line Number"),
+ ]
+ for method_name in methods:
+ table_headers.append(PALETTE["location_line"](f"{method_name} Score"))
+ print(f"{PALETTE['location_line'](header_text)}")
+ print(
+ tabulate(
+ self.generate_report(methods, max_items=items_num),
+ headers=table_headers,
+ tablefmt="rst",
+ )
+ )
+
+ def store_report(self, report_type):
+ """Create and store a report file."""
+ if report_type == "json":
+ data_dict = {}
+ lines_list = list(map(lambda x: x.as_dict(), self.sorted_lines))
+ data_dict["ranking"] = lines_list
+ with open("afluent_report.json", "w+", encoding="utf-8") as outfile:
+ json.dump(data_dict, outfile, indent=4)
+ elif report_type == "csv":
+ header = [
+ "Path",
+ "Line number",
+ "Tarantula Score",
+ "Ochiai Score",
+ "Ochiai2 Score",
+ "Dstar Score",
+ ]
+ with open("afluent_report.csv", "w+", encoding="utf-8") as outfile:
+ csv_writer = csv.writer(outfile)
+ csv_writer.writerow(header)
+ lines_list = list(map(lambda x: x.as_csv(), self.sorted_lines))
+ csv_writer.writerows(lines_list)
+
+ elif report_type == "eval":
+ self.produce_full_eval_report()
+ else:
+ raise Exception(f"Error:Unknown report type {report_type}.")
+
+ # pylint: disable=W0640
+ def produce_full_eval_report(self):
+ """Produce csv reports for all equation tie breaker combinatoins."""
+ for method in METHOD_NAMES:
+ for tiebreaker in TIEBREAKERS:
+ ranked_lines = Spectrum.generate_rankings(
+ self.sorted_lines, method, tiebreaker=tiebreaker
+ )
+ file_to_store = f"{method}_{tiebreaker}_report.csv"
+ header = [
+ "Path",
+ "Line number",
+ f"{method} score",
+ f"{tiebreaker} score",
+ ]
+ with open(file_to_store, "w+", encoding="utf-8") as outfile:
+ csv_writer = csv.writer(outfile)
+ csv_writer.writerow(header)
+ lines_list = list(
+ map(
+ lambda x: [
+ x.path,
+ x.number,
+ x.sus_scores[method],
+ x.tiebreakers[tiebreaker],
+ ],
+ ranked_lines,
+ )
+ )
+ csv_writer.writerows(lines_list)
+
+ @staticmethod
+ def generate_rankings(
+ all_lines: List[line.Line], method: str, tiebreaker="random"
+ ) -> List[line.Line]:
+ """Return a list of line objects ranked from the most to least suspicious.
+
+ Args:
+ method (str): name of the suspiciousness score to use for sorting
+ """
+ # If random, just sort by the sus scores
+ if tiebreaker == "random":
+ # Introduce some randomness before sorting
+ random.shuffle(all_lines)
+ all_lines.sort(
+ key=lambda x: x.sus_scores[method],
+ reverse=True,
+ )
+ # Otherwise, use the tiebreaker scores
+ else:
+ all_lines.sort(
+ key=lambda x: (x.sus_scores[method], x.tiebreakers[tiebreaker]),
+ reverse=True,
+ )
+ # store the sorted list as an attribute
+ return all_lines
+
+ @staticmethod
+ def calculate_severity(method: str, sus_score: float, rank: int, out_of: int):
+ """Return a function to format strings according to score severity.
+
+ Args:
+ method (str): name of the suspiciousness method used
+ sus_score (float): suspiciousness score of the line
+ rank (int): the rank of this line in the sorted list
+ out_of (int): length of the sorted list
+ """
+ if sus_score <= 0:
+ return PALETTE["safe"]
+ if (method in ["tarantula", "ochiai", "ochiai2"]) and sus_score == 1:
+ return PALETTE["severe"]
+ if method == "dstar" and sus_score == float("inf"):
+ return PALETTE["severe"]
+ if rank / out_of <= 0.2:
+ return PALETTE["risky"]
+ return PALETTE["mild"]
diff --git a/afluent/tiebreak_generator.py b/afluent/tiebreak_generator.py
new file mode 100644
index 0000000000000000000000000000000000000000..4c58519841c4cedc1590f778923d1f7907051498
--- /dev/null
+++ b/afluent/tiebreak_generator.py
@@ -0,0 +1,367 @@
+"""Define complexity generators and criteria to calculate complexity."""
+
+from typing import Any, Dict, List
+import libcst as cst
+from libcst import metadata
+from libcst import matchers
+import radon # type: ignore[import]
+import radon.complexity as cc # type: ignore[import]
+
+MUTANTS = [
+ matchers.BitInvert,
+ matchers.Not,
+ matchers.Minus,
+ matchers.Plus,
+ matchers.And,
+ matchers.Or,
+ matchers.Add,
+ matchers.BitAnd,
+ matchers.BitOr,
+ matchers.BitXor,
+ matchers.Divide,
+ matchers.FloorDivide,
+ matchers.LeftShift,
+ matchers.MatrixMultiply,
+ matchers.Modulo,
+ matchers.Multiply,
+ matchers.Power,
+ matchers.RightShift,
+ matchers.Subtract,
+ matchers.Equal,
+ matchers.GreaterThan,
+ matchers.GreaterThanEqual,
+ matchers.In,
+ matchers.Is,
+ matchers.LessThan,
+ matchers.LessThanEqual,
+ matchers.NotEqual,
+ matchers.IsNot,
+ matchers.NotIn,
+ matchers.AddAssign,
+ matchers.BitAndAssign,
+ matchers.BitOrAssign,
+ matchers.BitXorAssign,
+ matchers.DivideAssign,
+ matchers.FloorDivideAssign,
+ matchers.LeftShiftAssign,
+ matchers.MatrixMultiplyAssign,
+ matchers.ModuloAssign,
+ matchers.MultiplyAssign,
+ matchers.PowerAssign,
+ matchers.RightShiftAssign,
+ matchers.SubtractAssign,
+]
+
+ENHANCED_MUTANTS = [
+ matchers.AnnAssign,
+ matchers.Assign,
+ matchers.Call,
+ matchers.Subscript,
+ matchers.Tuple,
+ matchers.List,
+ matchers.SimpleString,
+ matchers.Dict,
+ matchers.Integer,
+ matchers.Float,
+] + MUTANTS
+
+
+class FullVisitor(cst.CSTVisitor):
+ """Locate specific nodes and organize by line number and calculate their complexity."""
+
+ METADATA_DEPENDENCIES = (metadata.PositionProvider,)
+
+ def __init__(self, filler_dict: dict) -> None:
+ """Initialize the class as a visitor.
+
+ Args:
+ filler_dict (dict): empty dictionary containing all line numbers of
+ a file.
+ """
+ super().__init__()
+ self.mutants_by_location = filler_dict
+ self.score: Dict[int, float] = {}
+
+ def visit_If(self, node: cst.If) -> None:
+ """Store the metadata of if statements when visited."""
+ node_metadata = self.get_node_metadata_dict(node)
+ self.fill_locations_range(node_metadata)
+
+ def visit_FunctionDef(self, node: cst.FunctionDef) -> None:
+ """Store the metadata of function definition when visited."""
+ node_metadata = self.get_node_metadata_dict(node)
+ self.fill_locations_range(node_metadata)
+
+ def visit_SimpleStatementLine(self, node: cst.SimpleStatementLine) -> None:
+ """Store the metadata of general statements when visited."""
+ node_metadata = self.get_node_metadata_dict(node)
+ self.fill_locations_range(node_metadata)
+
+ def visit_While(self, node: cst.While) -> None:
+ """Store the metadata of while loops when visited."""
+ node_metadata = self.get_node_metadata_dict(node)
+ self.fill_locations_range(node_metadata)
+
+ def visit_For(self, node: cst.For) -> None:
+ """Store the metadata of for loops when visited."""
+ node_metadata = self.get_node_metadata_dict(node)
+ self.fill_locations_range(node_metadata)
+
+ def visit_With(self, node: cst.With) -> None:
+ """Store the metadata of with statements when visited."""
+ node_metadata = self.get_node_metadata_dict(node)
+ self.fill_locations_range(node_metadata)
+
+ def get_node_metadata_dict(self, node):
+ """Organize the metadata dictionary."""
+ node_type = type(node).__name__
+ metadata_dict = {
+ "start": self.get_metadata(metadata.PositionProvider, node).start.line,
+ "end": self.get_metadata(metadata.PositionProvider, node).end.line,
+ "type": node_type,
+ "complexity": COMPLEXITY_FUNC[node_type](node),
+ }
+ return metadata_dict
+
+ def fill_locations_range(self, node_metadata):
+ """Distribute the metadata for all nodes in the same block."""
+ start = node_metadata["start"]
+ end = node_metadata["end"]
+ for line_num in range(start, end + 1):
+ if line_num in self.mutants_by_location:
+ self.mutants_by_location[line_num].append(node_metadata)
+
+ def calculate_score(self):
+ """Iterate through the collected data and generate a score for each line."""
+ for key, value in self.mutants_by_location.items():
+ self.score[key] = FullVisitor.get_average_score(value)
+
+ @staticmethod
+ def get_average_score(items_list: List[Dict[str, Any]]) -> float:
+ """Calculate the average score for a single line.
+
+ Args:
+ items_list (List[Dict[str, Any]]): List of nodes with their
+ information
+
+ Returns:
+ float: score for the line
+ """
+ statement_sum = 0
+ statement_num = 0
+ other_sum = 0
+ other_num = 0
+ # iterate through the list in a reverse order
+ for item in items_list[::-1]:
+ if item["type"] == "SimpleStatementLine":
+ statement_sum += item["complexity"]
+ statement_num += 1
+ else:
+ other_sum += item["complexity"]
+ other_num += 1
+ # avoid division by zero
+ if statement_num == 0:
+ statement_num += 1
+ if other_num == 0:
+ other_num += 1
+ score = ((statement_sum / statement_num) + (other_sum / other_num)) / 2
+ return round(score, 5)
+
+ @staticmethod
+ def count_mutants(node, mutant_set):
+ """Count the number of possible mutants in a node using the MUTANTS variable."""
+ total = 0
+ for mutant in mutant_set:
+ total += len(matchers.findall(node, mutant()))
+ return total
+
+ @staticmethod
+ def get_funcdef_complexity(node):
+ """Calculate the complexity of a function definition."""
+ return len(node.params.params)
+
+ @staticmethod
+ def get_if_complexity(node):
+ """Calculate the complexity of an if statement."""
+ # complexity of if statement= number of mutants in the test condition
+ if node.test:
+ total = FullVisitor.count_mutants(node.test, ENHANCED_MUTANTS)
+ return total
+ return 0
+
+ @staticmethod
+ def get_statement_complexity(node):
+ """Calculate the complexity of a general statement."""
+ # Complexity of a statement = number of mutants
+ total = FullVisitor.count_mutants(node, ENHANCED_MUTANTS)
+ return total
+
+ @staticmethod
+ def get_while_complexity(node):
+ """Calculate the complexity of a while loop."""
+ if node.test:
+ total = FullVisitor.count_mutants(node.test, ENHANCED_MUTANTS)
+ return total
+ return 0
+
+ @staticmethod
+ def get_for_complexity(node):
+ """Calculate the complexity of a for loop."""
+ target_mutants = 0
+ iterable_mutants = 0
+ if node.target:
+ target_mutants = FullVisitor.count_mutants(node.target, ENHANCED_MUTANTS)
+ if node.iter:
+ iterable_mutants = FullVisitor.count_mutants(node.iter, ENHANCED_MUTANTS)
+ return target_mutants + iterable_mutants
+
+ @staticmethod
+ def get_with_complexity(node):
+ """Calculate the complexity of a with statement."""
+ total = 0
+ if node.items:
+ for with_item in node.items:
+ total += FullVisitor.count_mutants(with_item, ENHANCED_MUTANTS)
+ return 0
+
+
+COMPLEXITY_FUNC = {
+ "FunctionDef": FullVisitor.get_funcdef_complexity,
+ "If": FullVisitor.get_if_complexity,
+ "SimpleStatementLine": FullVisitor.get_statement_complexity,
+ "While": FullVisitor.get_while_complexity,
+ "For": FullVisitor.get_for_complexity,
+ "With": FullVisitor.get_with_complexity,
+}
+
+
+class StatementVisitor(cst.CSTVisitor):
+ """Locate specific nodes and organize by line number and calculate their complexity."""
+
+ METADATA_DEPENDENCIES = (metadata.PositionProvider,)
+
+ def __init__(self, filler_dict: dict) -> None:
+ """Initialize the class as a visitor.
+
+ Args:
+ filler_dict (dict): empty dictionary containing all line numbers of
+ a file.
+ """
+ super().__init__()
+ self.mutants_by_location = filler_dict
+
+ def visit_SimpleStatementLine(self, node: cst.SimpleStatementLine) -> None:
+ """Store the metadata of general statements when visited."""
+ node_metadata = self.get_node_metadata_dict(node)
+ self.fill_locations_range(node_metadata)
+
+ def get_node_metadata_dict(self, node):
+ """Organize the metadata dictionary."""
+ node_type = type(node).__name__
+ metadata_dict = {
+ "start": self.get_metadata(metadata.PositionProvider, node).start.line,
+ "end": self.get_metadata(metadata.PositionProvider, node).end.line,
+ "type": node_type,
+ }
+ if node_type == "SimpleStatementLine":
+ metadata_dict["complexity"] = StatementVisitor.get_statement_complexity(
+ node
+ )
+ return metadata_dict
+
+ def fill_locations_range(self, node_metadata):
+ """Distribute the metadata for all nodes in the same block."""
+ start = node_metadata["start"]
+ end = node_metadata["end"]
+ for line_num in range(start, end + 1):
+ if line_num in self.mutants_by_location:
+ self.mutants_by_location[line_num] = node_metadata["complexity"]
+
+ @staticmethod
+ def get_statement_complexity(node):
+ """Calculate the complexity of a general statement."""
+ # Complexity of a statement = number of mutants
+ total = StatementVisitor.count_mutants(node)
+ return total
+
+ @staticmethod
+ def count_mutants(node):
+ """Count the number of possible mutants in a node using the MUTANTS variable."""
+ total = 0
+ for mutant in MUTANTS:
+ total += len(matchers.findall(node, mutant()))
+ return total
+
+
+# pylint: disable=R0903
+class EnhancedTieBreaker:
+ """Store the full syntax mutant density data set and call the finder."""
+
+ def __init__(self, file_path: str) -> None:
+ """Initialize the generator."""
+ self.path = file_path
+ self.data: Dict[int, List[Dict[str, Any]]] = {}
+ self.score: Dict[int, float] = {}
+
+ def calculate_mutant_density(self):
+ """Get the full file mutant density dataset."""
+ with open(self.path, "r", encoding="utf-8") as infile:
+ file_text = infile.read()
+ module_obj = cst.parse_module(file_text)
+ lines_num = len(file_text.splitlines())
+ filler_dict = {i: [] for i in range(1, lines_num + 1)}
+ wrapper = metadata.MetadataWrapper(module_obj)
+ finder = FullVisitor(filler_dict)
+ wrapper.visit(finder)
+ self.data = finder.mutants_by_location
+ finder.calculate_score()
+ self.score = finder.score
+
+
+# pylint: disable=R0903
+class LogicalTieBreaker:
+ """Store the full syntax mutant density data set and call the finder."""
+
+ def __init__(self, file_path: str) -> None:
+ """Initialize the generator."""
+ self.path = file_path
+ self.score: Dict[int, int] = {}
+
+ def calculate_mutant_density(self):
+ """Get the full file mutant density dataset."""
+ with open(self.path, "r", encoding="utf-8") as infile:
+ file_text = infile.read()
+ module_obj = cst.parse_module(file_text)
+ lines_num = len(file_text.splitlines())
+ filler_dict = {i: 0 for i in range(1, lines_num + 1)}
+ wrapper = metadata.MetadataWrapper(module_obj)
+ finder = StatementVisitor(filler_dict)
+ wrapper.visit(finder)
+ self.score = finder.mutants_by_location
+
+
+# pylint: disable=R0903
+class CyclomaticComplexityGenerator:
+ """Store the dataset for cyclomatic complexity in the file."""
+
+ def __init__(self, file_path) -> None:
+ """Initialize the generator."""
+ self.path = file_path
+ self.data: Dict[int, int] = {}
+
+ def calculate_syntax_complexity(self):
+ """Get the full dataset for cyclomatic complexity."""
+ with open(self.path, "r", encoding="utf-8") as infile:
+ file_string = infile.read()
+ lines_num = len(file_string.splitlines())
+ complexity_data = cc.sorted_results(cc.cc_visit(file_string), cc.LINES)
+ filler_dict = {i: 0 for i in range(1, lines_num + 1)}
+ # reassemble complexity data to follow this format
+ # List(Tuple(line_start:int, line_end:int, complexity_score:int))
+ for item in complexity_data:
+ # Check if the current item is a Function and add it's information
+ if isinstance(item, radon.visitors.Function):
+ # fill the filler_dict with the complexity score
+ for number in range(item.lineno, item.endline + 1):
+ filler_dict[number] = item.complexity
+ self.data = filler_dict
diff --git a/tests/__init__.py b/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..46f591b1d87bf0d23e0167657929425dd693f949
--- /dev/null
+++ b/tests/__init__.py
@@ -0,0 +1 @@
+"""Standard init file."""
diff --git a/tests/conftest.py b/tests/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..2f83b68ba33e86d3233e22f4c2cc0e3ce0108e0a
--- /dev/null
+++ b/tests/conftest.py
@@ -0,0 +1,25 @@
+"""Implement fixtures and hooks for pytest session."""
+
+import json
+import pathlib
+import pytest
+
+# pylint: disable=C0103,W0602
+full_test_data = {}
+
+
+@pytest.hookimpl()
+def pytest_sessionstart():
+ """Read and collect test data as part of the global test data dictionary."""
+ test_data_files = pathlib.Path("./tests/test_data").glob("*.json")
+ for json_data_file in test_data_files:
+ with open(json_data_file, "r", encoding="utf-8") as data_file:
+ current_test_data = json.load(data_file)
+ global full_test_data
+ full_test_data[json_data_file.stem] = current_test_data
+
+
+@pytest.fixture
+def test_data():
+ """Return full_test_data."""
+ return full_test_data
diff --git a/tests/test_data/__init__.py b/tests/test_data/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..46f591b1d87bf0d23e0167657929425dd693f949
--- /dev/null
+++ b/tests/test_data/__init__.py
@@ -0,0 +1 @@
+"""Standard init file."""
diff --git a/tests/test_data/sample_file.py b/tests/test_data/sample_file.py
new file mode 100644
index 0000000000000000000000000000000000000000..54f0724f2fdb862018881cc6ef0121b9f6a5bdfe
--- /dev/null
+++ b/tests/test_data/sample_file.py
@@ -0,0 +1,23 @@
+"""Use module is used for testing purposes only, do not modify."""
+# pylint: disable=C0116, E0602, W0612
+
+
+def some_function(arg1, arg2, arg3, arg4): # noqa
+ print("hello world!")
+ int1 = arg1 * arg3 / 5 - arg4
+ int2 = arg4 ** arg3
+ my_list = [1, 2, 3.6, 4, 5.4, "some string"]
+ my_dictionary = {
+ "first": arg1,
+ "second": arg2,
+ "third": arg3,
+ "fourth": arg4,
+ }
+ my_tuple = ("hello", "world")
+ result = some_other_function(arg2).process_somehow()
+ if not arg3 > arg2 and arg1 < arg4:
+ return arg2 >> 5
+ while my_list[4] > my_dictionary["first"]:
+ my_variable = 54
+ my_variable += arg1 / arg4
+ return my_dictionary["first"] + "something here"
diff --git a/tests/test_data/test_spectrum_init.json b/tests/test_data/test_spectrum_init.json
new file mode 100644
index 0000000000000000000000000000000000000000..4eef5be85f3a01cb23f99a5df36732c61895b4e7
--- /dev/null
+++ b/tests/test_data/test_spectrum_init.json
@@ -0,0 +1,34 @@
+{
+ "input_config": {
+ "test1": {
+ "coverage": {
+ "file1.py": [1, 2, 3, 4],
+ "file2.py": [1, 2, 3, 4, 5, 6]
+ },
+ "result": "passed"
+ },
+ "test2": {
+ "coverage": {
+ "file1.py": [3, 4, 5, 6],
+ "file2.py": [1, 2, 3, 6, 7, 8, 9]
+ },
+ "result": "passed"
+ },
+ "test3": {
+ "coverage": {
+ "file1.py": [5, 6, 7],
+ "file2.py": [9, 3, 5]
+ },
+ "result": "failed"
+ },
+ "test4": {
+ "coverage": {},
+ "result": "skipped"
+ }
+ },
+ "output_reassembled": {
+ "passed": 2,
+ "failed": 1,
+ "skipped": 1
+ }
+}
\ No newline at end of file
diff --git a/tests/test_line.py b/tests/test_line.py
new file mode 100644
index 0000000000000000000000000000000000000000..c7e3ae0038ee8a7b27e74e0ede6cbb9199d92e1a
--- /dev/null
+++ b/tests/test_line.py
@@ -0,0 +1,148 @@
+"""Test the line module and Line class."""
+
+import pytest
+
+from afluent import line
+
+
+def test_globals():
+ """Check that global constants are of specific values."""
+ assert line.TARAN == "tarantula"
+ assert line.OCHIAI == "ochiai"
+ assert line.OCHIAI2 == "ochiai2"
+ assert line.DSTAR == "dstar"
+ assert line.RANDOM == "random"
+ assert line.CYCLOMATIC == "cyclomatic"
+ assert line.LOGICAL == "logical"
+ assert line.ENHANCED == "enhanced"
+
+
+@pytest.mark.parametrize(
+ "failed_cover,passed_cover,total_passed,total_failed,expected_score",
+ [
+ (1, 0, 1, 1, 1),
+ (0, 1, 1, 1, 0),
+ (3, 1, 6, 4, 0.8182),
+ (0, 3, 5, 0, 0),
+ (4, 0, 0, 9, 1),
+ ],
+)
+def test_tarantula(
+ failed_cover, passed_cover, total_passed, total_failed, expected_score
+):
+ """Check that the tarantula formula is correct."""
+ assert (
+ line.Line.tarantula(failed_cover, passed_cover, total_passed, total_failed)
+ == expected_score
+ )
+
+
+@pytest.mark.parametrize(
+ "failed_cover,passed_cover,total_failed,expected_score",
+ [
+ (1, 0, 1, 1),
+ (3, 2, 6, 0.5477),
+ (0, 1, 6, 0),
+ ],
+)
+def test_ohiai(failed_cover, passed_cover, total_failed, expected_score):
+ """Check that the ohiai formula is correct."""
+ assert line.Line.ochiai(failed_cover, passed_cover, total_failed) == expected_score
+
+
+@pytest.mark.parametrize(
+ "failed_cover,passed_cover,total_failed,power,expected_score",
+ [
+ (1, 0, 2, 3, 1),
+ (3, 2, 6, 3, 5.4),
+ (0, 1, 6, 3, 0),
+ (6, 0, 6, 3, float("inf")),
+ ],
+)
+def test_dstar(failed_cover, passed_cover, total_failed, power, expected_score):
+ """Check that the test_dstar formula is correct."""
+ assert (
+ line.Line.dstar(failed_cover, passed_cover, total_failed, power=power)
+ == expected_score
+ )
+
+
+@pytest.mark.parametrize(
+ "failed_cover,passed_cover,total_passed,total_failed,expected_score",
+ [
+ (3, 0, 0, 6, 1),
+ (0, 0, 7, 0, 0),
+ (3, 3, 3, 3, 0),
+ (0, 0, 5, 5, 0),
+ (3, 2, 7, 6, 0.366),
+ ],
+)
+def test_ochiai2(
+ failed_cover, passed_cover, total_passed, total_failed, expected_score
+):
+ """Check that the ochiai2 formula is correct."""
+ assert (
+ line.Line.ochiai2(failed_cover, passed_cover, total_passed, total_failed)
+ == expected_score
+ )
+
+
+def test_line_create():
+ """Check that line object can be instantiated correctly."""
+ test_line = line.Line("sample/path/to/file.py", 14)
+ assert test_line.path == "sample/path/to/file.py"
+ assert test_line.number == 14
+ assert not (test_line.passed_by or test_line.failed_by or test_line.skipped_by)
+ assert list(test_line.sus_scores.values()) == [-1.0, -1.0, -1.0, -1.0]
+ assert list(test_line.tiebreakers.values()) == [0, 0, 0, 0]
+
+
+def test_line_sus_all():
+ """Check that all suspiciousness scores can be calculated."""
+ test_line = line.Line("sample/path/to/file.py", 14)
+ test_line.passed_by = ["test1", "test2"]
+ test_line.failed_by = ["test3", "test4", "test5"]
+ for sus_value in test_line.sus_scores.values():
+ assert sus_value == -1.0
+ test_line.sus_all(4, 6)
+ assert test_line.sus_scores["tarantula"] == 0.5
+ assert test_line.sus_scores["ochiai"] == 0.5477
+ assert test_line.sus_scores["dstar"] == 5.4
+
+
+def test_line_sus_unknown():
+ """Check that an error is thrown when an unknown method is passed."""
+ test_line = line.Line("sample/path/to/file.py", 14)
+ test_line.passed_by = ["test1", "test2"]
+ test_line.failed_by = ["test3", "test4", "test5"]
+ with pytest.raises(Exception):
+ test_line.sus("random", 5, 5)
+
+
+def test_as_csv():
+ """Check that a line is correctly converted to csv format."""
+ test_line = line.Line("sample/path/to/file.py", 14)
+ assert test_line.as_csv() == ["sample/path/to/file.py", 14, -1, -1, -1, -1]
+
+
+def test_sus_text():
+ """Check that the correct tuple is returned."""
+ test_line = line.Line("sample/path/to/file.py", 14)
+ test_line.sus_scores = {
+ "tarantula": 1.0,
+ "ochiai": 1.0,
+ "dstar": 15.0,
+ }
+ assert test_line.sus_text(["tarantula"]) == ("sample/path/to/file.py", 14, [1.0])
+ assert test_line.sus_text(["ochiai"]) == ("sample/path/to/file.py", 14, [1.0])
+ assert test_line.sus_text(["dstar"]) == ("sample/path/to/file.py", 14, [15.0])
+ assert test_line.sus_text(["dstar", "tarantula"]) == (
+ "sample/path/to/file.py",
+ 14,
+ [15.0, 1.0],
+ )
+
+
+# def test_something():
+# """Purposefully fail to check report."""
+# assert False
diff --git a/tests/test_proj_file.py b/tests/test_proj_file.py
new file mode 100644
index 0000000000000000000000000000000000000000..4607c22ac11617c300a0aa0d60025c01899754d2
--- /dev/null
+++ b/tests/test_proj_file.py
@@ -0,0 +1,139 @@
+"""Test the proj_file module and ProjFile class."""
+
+import pytest
+from afluent import line, proj_file
+
+
+def test_projfile_init():
+ """Test that a projFile object can be created."""
+ test_projfile = proj_file.ProjFile("samplename.py")
+ assert test_projfile.name == "samplename.py"
+ assert not test_projfile.lines
+
+
+def test_update_file_new_key():
+ """Check that a line is created and updated in a new file."""
+ test_projfile = proj_file.ProjFile("samplename.py")
+ covered_lines = [3, 6, 7, 9, 13]
+ test_projfile.update_file(covered_lines, "passed", "sample_testcase")
+ for line_num in covered_lines:
+ assert line_num in test_projfile.lines
+ assert isinstance(test_projfile.lines[line_num], line.Line)
+ assert test_projfile.lines[line_num].passed_by == ["sample_testcase"]
+
+
+def test_update_file_existing_key_passed():
+ """Check that a line is created and updated in a new file."""
+ test_projfile = proj_file.ProjFile("samplename.py")
+ test_projfile.lines[5] = line.Line("samplename.py", 5)
+ test_projfile.lines[5].passed_by = [
+ "sample_testcase2",
+ "sample_testcase3",
+ "sample_testcase4",
+ ]
+ covered_lines = [5, 6]
+ test_projfile.update_file(covered_lines, "passed", "sample_testcase")
+ assert test_projfile.lines[5].passed_by == [
+ "sample_testcase2",
+ "sample_testcase3",
+ "sample_testcase4",
+ "sample_testcase",
+ ]
+
+
+def test_update_file_existing_key_failed():
+ """Check that a line is created and updated in a new file."""
+ test_projfile = proj_file.ProjFile("samplename.py")
+ test_projfile.lines[5] = line.Line("samplename.py", 5)
+ test_projfile.lines[5].failed_by = [
+ "sample_testcase2",
+ "sample_testcase3",
+ "sample_testcase4",
+ ]
+ covered_lines = [5, 6]
+ test_projfile.update_file(covered_lines, "failed", "sample_testcase")
+ assert test_projfile.lines[5].failed_by == [
+ "sample_testcase2",
+ "sample_testcase3",
+ "sample_testcase4",
+ "sample_testcase",
+ ]
+
+
+def test_update_file_existing_key_skipped():
+ """Check that a line is created and updated in a new file."""
+ test_projfile = proj_file.ProjFile("samplename.py")
+ test_projfile.lines[5] = line.Line("samplename.py", 5)
+ test_projfile.lines[5].skipped_by = [
+ "sample_testcase2",
+ "sample_testcase3",
+ "sample_testcase4",
+ ]
+ covered_lines = [5, 6]
+ test_projfile.update_file(covered_lines, "skipped", "sample_testcase")
+ assert test_projfile.lines[5].skipped_by == [
+ "sample_testcase2",
+ "sample_testcase3",
+ "sample_testcase4",
+ "sample_testcase",
+ ]
+
+
+def test_update_file_unknown_result():
+ """Check that a line is created and updated in a new file."""
+ test_projfile = proj_file.ProjFile("samplename.py")
+ covered_lines = [5, 6]
+ with pytest.raises(Exception):
+ test_projfile.update_file(covered_lines, "random", "sample_testcase")
+
+
+def test_get_datasets():
+ """Check that all tiebreaker datasets can be populated. Regardless of accuracy."""
+ test_projfile = proj_file.ProjFile("./tests/test_data/sample_file.py")
+ assert not test_projfile.cyclomatic_complexity_data
+ assert not test_projfile.logical_tiebreak_data
+ assert not test_projfile.enhanced_tiebreak_data
+ test_projfile.get_cyclomatic_tiebreaker_dataset()
+ test_projfile.get_logical_tiebreaker_dataset()
+ test_projfile.get_enhanced_tiebreaker_dataset()
+ assert test_projfile.cyclomatic_complexity_data
+ assert test_projfile.logical_tiebreak_data
+ assert test_projfile.enhanced_tiebreak_data
+ covered_lines = [6, 7, 8, 10]
+ test_projfile.update_file(covered_lines, "failed", "sample_testcase")
+ assert test_projfile.lines[6].tiebreakers == {
+ "cyclomatic": 4,
+ "logical": 0.0,
+ "enhanced": 3.0,
+ "random": 0,
+ }
+ assert test_projfile.lines[7].tiebreakers == {
+ "cyclomatic": 4,
+ "logical": 3,
+ "enhanced": 4.5,
+ "random": 0.0,
+ }
+ assert test_projfile.lines[8].tiebreakers == {
+ "cyclomatic": 4,
+ "logical": 1,
+ "enhanced": 3.0,
+ "random": 0.0,
+ }
+ assert test_projfile.lines[10].tiebreakers == {
+ "cyclomatic": 4,
+ "logical": 0.0,
+ "enhanced": 5,
+ "random": 0.0,
+ }
+
+
+# def test_projfile_as_dict():
+# """Check that as_dict() return a correct dictionary."""
+# file_name = "samplename.py"
+# test_projfile = proj_file.ProjFile(file_name)
+# test_projfile.update_file([5], "passed", "sample_test")
+# output_dict = test_projfile.as_dict()
+# expected_line = line.Line(file_name, 5)
+# expected_line.passed_by = ["sample_test"]
+# expected_dict = {"5": expected_line.as_dict()}
+# assert output_dict == expected_dict
diff --git a/tests/test_spectrum_parser.py b/tests/test_spectrum_parser.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ac41d61e501f32ab3785661a2b66e92129e8862
--- /dev/null
+++ b/tests/test_spectrum_parser.py
@@ -0,0 +1,148 @@
+"""Include test cases on spectrum_parser module."""
+import pytest
+from afluent import spectrum_parser
+
+
+def test_spectrum_init(test_data):
+ """Check that spectrum initialization reassembles config and calculates scores."""
+ input_config_dict = test_data["test_spectrum_init"]["input_config"]
+ expected_output_dict = test_data["test_spectrum_init"]["output_reassembled"]
+ spectrum_object = spectrum_parser.Spectrum(input_config_dict)
+ assert spectrum_object.totals == expected_output_dict
+
+
+def test_spectrum_init_empty_config():
+ """Check that nothing will happen when empty config is passed to
+ Spectrum."""
+ spectrum_object = spectrum_parser.Spectrum({})
+ assert not spectrum_object.reassembled_data
+ assert spectrum_object.totals == {"passed": 0, "failed": 0, "skipped": 0}
+
+
+def test_spectrum_generate_report_throws_error(test_data):
+ """Check that error is thrown when unknown method is used."""
+ config_item = test_data["test_spectrum_init"]["input_config"]
+ spectrum_object = spectrum_parser.Spectrum(config_item)
+ with pytest.raises(Exception):
+ spectrum_object.generate_report("random")
+
+
+def test_spectrum_init_eval_mode():
+ """Check that all tiebreaker data is generated in eval mode."""
+ config = {
+ "test1": {
+ "coverage": {"tests/test_data/sample_file.py": [1, 2, 3, 4]},
+ "result": "passed",
+ }
+ }
+ spectrum_object = spectrum_parser.Spectrum(config, eval_mode=True)
+ assert spectrum_object.reassembled_data[
+ "tests/test_data/sample_file.py"
+ ].cyclomatic_complexity_data
+ assert spectrum_object.reassembled_data[
+ "tests/test_data/sample_file.py"
+ ].logical_tiebreak_data
+ assert spectrum_object.reassembled_data[
+ "tests/test_data/sample_file.py"
+ ].enhanced_tiebreak_data
+
+
+def test_spectrum_init_enhanced_tiebreaker():
+ """Check that only the data for the enhanced tiebreaker is calculated for
+ that mode."""
+ config = {
+ "test1": {
+ "coverage": {"tests/test_data/sample_file.py": [1, 2, 3, 4]},
+ "result": "passed",
+ }
+ }
+ spectrum_object = spectrum_parser.Spectrum(config, tiebreaker="enhanced")
+ assert not spectrum_object.reassembled_data[
+ "tests/test_data/sample_file.py"
+ ].cyclomatic_complexity_data
+ assert not spectrum_object.reassembled_data[
+ "tests/test_data/sample_file.py"
+ ].logical_tiebreak_data
+ assert spectrum_object.reassembled_data[
+ "tests/test_data/sample_file.py"
+ ].enhanced_tiebreak_data
+
+
+def test_spectrum_init_logical_tiebreaker():
+ """Check that only the data for the logical tiebreaker is calculated for
+ that mode."""
+ config = {
+ "test1": {
+ "coverage": {"tests/test_data/sample_file.py": [1, 2, 3, 4]},
+ "result": "passed",
+ }
+ }
+ spectrum_object = spectrum_parser.Spectrum(config, tiebreaker="logical")
+ assert not spectrum_object.reassembled_data[
+ "tests/test_data/sample_file.py"
+ ].cyclomatic_complexity_data
+ assert spectrum_object.reassembled_data[
+ "tests/test_data/sample_file.py"
+ ].logical_tiebreak_data
+ assert not spectrum_object.reassembled_data[
+ "tests/test_data/sample_file.py"
+ ].enhanced_tiebreak_data
+
+
+def test_spectrum_init_cyclomatic_tiebreaker():
+ """Check that only the data for the cyclomatic tiebreaker is calculated for
+ that mode."""
+ config = {
+ "test1": {
+ "coverage": {"tests/test_data/sample_file.py": [1, 2, 3, 4]},
+ "result": "passed",
+ }
+ }
+ spectrum_object = spectrum_parser.Spectrum(config, tiebreaker="cyclomatic")
+ assert spectrum_object.reassembled_data[
+ "tests/test_data/sample_file.py"
+ ].cyclomatic_complexity_data
+ assert not spectrum_object.reassembled_data[
+ "tests/test_data/sample_file.py"
+ ].logical_tiebreak_data
+ assert not spectrum_object.reassembled_data[
+ "tests/test_data/sample_file.py"
+ ].enhanced_tiebreak_data
+
+
+def test_spectrum_print_report_throws_error():
+ """Check that an error is thrown when an unknown report is requested."""
+ config = {
+ "test1": {
+ "coverage": {"tests/test_data/sample_file.py": [1, 2, 3, 4]},
+ "result": "passed",
+ }
+ }
+ spectrum_object = spectrum_parser.Spectrum(config, tiebreaker="cyclomatic")
+ with pytest.raises(Exception):
+ spectrum_object.print_report(["something"], items_num=20)
+
+
+@pytest.mark.parametrize(
+ "method,sus_score,rank,out_of,formatting_func",
+ [
+ ("tarantula", 0, 1, 1, spectrum_parser.PALETTE["safe"]),
+ ("tarantula", 0.5, 1, 20, spectrum_parser.PALETTE["risky"]),
+ ("tarantula", 0.5, 16, 20, spectrum_parser.PALETTE["mild"]),
+ ("tarantula", 1, 8, 20, spectrum_parser.PALETTE["severe"]),
+ ("ochiai", 0, 1, 1, spectrum_parser.PALETTE["safe"]),
+ ("ochiai", 0.5, 1, 20, spectrum_parser.PALETTE["risky"]),
+ ("ochiai", 0.5, 16, 20, spectrum_parser.PALETTE["mild"]),
+ ("ochiai", 1, 8, 20, spectrum_parser.PALETTE["severe"]),
+ ("dstar", 0, 1, 1, spectrum_parser.PALETTE["safe"]),
+ ("dstar", 0.5, 1, 20, spectrum_parser.PALETTE["risky"]),
+ ("dstar", 0.5, 16, 20, spectrum_parser.PALETTE["mild"]),
+ ("dstar", float("inf"), 8, 20, spectrum_parser.PALETTE["severe"]),
+ ],
+)
+def test_calculate_severity(method, sus_score, rank, out_of, formatting_func):
+ """Check that severity calculating returns the correct formatting function."""
+ assert (
+ spectrum_parser.Spectrum.calculate_severity(method, sus_score, rank, out_of)
+ == formatting_func
+ )
|