File size: 2,521 Bytes
ae83308 | 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 | import json
import sys
import tempfile
import unittest
from pathlib import Path
from codeql_compare import codeql_alert, method_span, metrics, run
class CodeQLComparisonTests(unittest.TestCase):
def test_alert_requires_primary_location_inside_method_and_relevant_tag(self):
side = {
"path": "src/example.py",
"state": {"method": {"source": "L0010| def check():\nL0011| return 1"}},
}
sarif = {
"runs": [{
"tool": {"driver": {"rules": [
{"id": "py/security", "properties": {"tags": ["security"]}},
{"id": "py/style", "properties": {"tags": ["maintainability"]}},
]}},
"results": [
{"ruleId": "py/security", "locations": [{"physicalLocation": {
"artifactLocation": {"uri": "src/example.py"},
"region": {"startLine": 11}}}]},
{"ruleId": "py/security", "locations": [{"physicalLocation": {
"artifactLocation": {"uri": "src/example.py"},
"region": {"startLine": 30}}}]},
{"ruleId": "py/style", "locations": [{"physicalLocation": {
"artifactLocation": {"uri": "src/example.py"},
"region": {"startLine": 10}}}]},
],
}],
}
with tempfile.TemporaryDirectory() as directory:
file = Path(directory) / "result.sarif"
file.write_text(json.dumps(sarif))
self.assertEqual(method_span(side), (10, 11))
self.assertEqual(codeql_alert(file, side, "security"), ["py/security"])
self.assertEqual(codeql_alert(file, side, "bug"), ["py/security"])
def test_counts_include_false_negatives_and_clean_methods(self):
result = metrics(iter([(1, True), (1, False), (0, True), (0, False)]))
self.assertEqual([result[key] for key in ("tp", "fp", "fn", "tn")],
[1, 1, 1, 1])
self.assertEqual(result["f1"], 0.5)
self.assertIsNone(metrics([(1, False), (0, False)])["precision"])
def test_scan_stage_has_bounded_runtime(self):
with tempfile.TemporaryDirectory() as directory:
code, _ = run([sys.executable, "-c", "import time; time.sleep(2)"],
Path(directory) / "stage.log", timeout=0.1)
self.assertEqual(code, 124)
if __name__ == "__main__":
unittest.main()
|