Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
227 changes: 226 additions & 1 deletion test/tools/donate_cpu_server_rest_test.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from importlib import import_module
import json
import time
import warnings

Expand Down Expand Up @@ -233,7 +234,7 @@ def test_html_pages(client):
client.post('/api/v1/results', content=RESULT_CRASH)
client.post('/api/v1/info', content=INFO)
pages = ['/', '/crash.html', '/timeout.html', '/stale.html', '/diff.html', '/diff-knownConditionTrueFalse',
'/head.html', '/headinfo.html', '/head-syntaxError', '/headtoday-syntaxError', '/headinfo-checkLibraryFunction',
'/head.html', '/headinfo.html', '/head-syntaxError', '/headtoday-syntaxError', '/headinfo-checkLibraryFunction', '/triage.html',
'/latest.html', '/time_lt.html', '/time_gt.html', '/time_slow.html', '/clients.html',
'/check_library_function_report.html', '/check_library_check_type_report.html', '/unknown_macro.html',
'/value_flow_bailout_incomplete_var.html']
Expand Down Expand Up @@ -295,3 +296,227 @@ def test_raw_files(client):
assert client.get('/info_output/aaa').status_code == 200
assert client.get('/nonexistent').status_code == 404
assert client.get('/..%2F..%2Fetc%2Fpasswd').status_code == 404


WARNING_OOB = "ccc/a.c:1:2: error: Array 'a[2]' accessed at index 2, which is out of bounds. [arrayIndexOutOfBounds]"
WARNING_MACRO = 'ccc/b.c:4:1: error: There is an unknown macro here somewhere. Configuration is required. ' \
'If FOO is a macro then please configure it. [unknownMacro]'
WARNING_OLD = server.OLD_VERSION + ' ccc/c.c:1:2: style: blah [knownConditionTrueFalse]'


def triage(warning, verdict, url=PKG_C):
return {'url': url, 'warning': warning, 'verdict': verdict}


def triage_warnings(work_path):
return [item['warning'] for item in json.loads((work_path / 'triage.json').read_text())]


def upload_triage(client):
r = client.post('/api/v1/triage', json=[
triage('head ' + WARNING_OOB, 'Unintentional ; True positive - not a False positive \u00e5'),
triage(WARNING_MACRO, 'Intentional ; False positive - x'),
triage(WARNING_OLD, 'False positive'),
triage(WARNING_OOB + '\n' + WARNING_OLD, 'rephrazed')])
assert r.status_code == 200
assert r.json() == {'added': 4, 'updated': 0, 'unchanged': 0, 'skipped': 0}


def test_triage_report(client):
upload_triage(client)
data = client.get('/api/v1/reports/triage').json()
assert data['head']['message_ids'] == {
'arrayIndexOutOfBounds': {'tp': 1, 'fp': 0, 'other': 1, 'tp_ratio': 1.0, 'fp_ratio': 0.0},
'unknownMacro': {'tp': 0, 'fp': 1, 'other': 0, 'tp_ratio': 0.0, 'fp_ratio': 1.0},
}
assert data['head']['total'] == {'tp': 1, 'fp': 1, 'other': 1, 'tp_ratio': 0.5, 'fp_ratio': 0.5}
assert list(data['old']['message_ids']) == ['knownConditionTrueFalse']
html = client.get('/triage.html').text
assert '/head-arrayIndexOutOfBounds' in html and '/diff-knownConditionTrueFalse' in html and '50%' in html


def test_triage_merge(client, work_path):
upload_triage(client)
# with and without 'head' is the same warning, and notes are ignored
r = client.post('/api/v1/triage', json=[
triage(WARNING_OOB + '\nccc/a.c:1:1: note: array a [arrayIndexOutOfBounds]', 'False positive'),
triage(WARNING_OLD, 'False positive'),
triage('ccc/a.c:1:1: note: array a', 'True positive'),
triage('no message id', 'True positive'),
triage(WARNING_OOB, 'True positive', PKG_C.replace('ccc_1.0', 'ccc_9.0')),
triage(WARNING_OOB, 'True positive', 'http://example.com/x.tar.gz')])
assert r.json() == {'added': 0, 'updated': 1, 'unchanged': 1, 'skipped': 4}
assert len(triage_warnings(work_path)) == 4
assert client.get('/api/v1/reports/triage').json()['head']['total']['fp'] == 2

# the triage results are loaded after a restart
with TestClient(server.create_app(str(work_path), rescan_interval=0.2)) as client2:
assert client2.get('/api/v1/reports/triage').json()['head']['total']['fp'] == 2


def test_triage_upload_errors(client, work_path, monkeypatch):
for data in ('', '{}', '[{"url": "x"}]', '[{"url": "x", "warning": 1, "verdict": "x"}]', '[1'):
assert client.post('/api/v1/triage', content=data).status_code == 422
monkeypatch.setattr(server, 'MAX_TRIAGE_SIZE', 10)
assert client.post('/api/v1/triage', json=[triage(WARNING_OOB, 'True positive')]).status_code == 413
assert not (work_path / 'triage.json').exists()


def test_triage_broken_file(work_path):
for text in ('[{', '[1]', '[{"url": "x"}]', '{"a": 1}'):
(work_path / 'triage.json').write_text(text)
with pytest.raises(RuntimeError):
server.create_app(str(work_path))
assert (work_path / 'triage.json').read_text() == text


def test_triage_removed_when_results_are_uploaded(client, work_path):
upload_triage(client)
results = RESULT_FILE_C.split('\n', 1)[1]

# results for another package, or same results => nothing is removed
assert client.post('/api/v1/results', content=RESULT_CRASH).status_code == 201
assert client.post('/api/v1/results', content=results).status_code == 201
assert len(triage_warnings(work_path)) == 4

# a missing warning says nothing if there was a crash or a timeout
for count in ('Crash! 2', '3 TO!'):
data = results.replace('count: 3 2', 'count: ' + count).replace(WARNING_OOB, '')
assert client.post('/api/v1/results', content=data).status_code == 201
assert len(triage_warnings(work_path)) == 4

# the old warning is not in the diff anymore
data = results.replace(WARNING_OLD + '\n', '')
assert client.post('/api/v1/results', content=data).status_code == 201
assert triage_warnings(work_path) == [WARNING_OOB, WARNING_MACRO]

data = data.replace(WARNING_OOB, WARNING_OOB.replace(':1:2:', ':2:2:'))
assert client.post('/api/v1/results', content=data).status_code == 201
assert triage_warnings(work_path) == [WARNING_MACRO]
assert client.get('/api/v1/reports/triage').json()['head']['total']['fp'] == 1


def test_triage_removed_when_old_server_stores_results(client, work_path):
upload_triage(client)
(work_path / 'donated-results' / 'ccc').write_text(RESULT_FILE_C.replace(WARNING_MACRO, ''))
for _ in range(100):
if len(triage_warnings(work_path)) == 3:
break
time.sleep(0.05)
assert WARNING_MACRO not in triage_warnings(work_path)
assert len(triage_warnings(work_path)) == 3


def test_triage_removed_when_package_url_changes(work_path):
new_url = PKG_C.replace('ccc_1.0', 'ccc_1.1')
with open(str(work_path / 'packages.txt'), 'at') as f:
f.write(new_url + '\n')
with TestClient(server.create_app(str(work_path), rescan_interval=0.2)) as client:
upload_triage(client)
results = RESULT_FILE_C.split('\n', 1)[1].replace(PKG_C, new_url)
assert client.post('/api/v1/results', content=results).status_code == 201
assert triage_warnings(work_path) == []


def suggestions(client):
r = client.get('/api/v1/triage/suggestions')
assert r.status_code == 200
assert r.json()['complete'] is True
return r.json()['warnings']


def result_file(head, diff, count='3 2', url=PKG_C):
return '2026-11-01 10:00\n{}\ncppcheck: head {}\ncount: {}\nelapsed-time: 1.0 1.0\nhead results:\n{}\n\ndiff:\n{}\n'.format(
url, server.OLD_VERSION, count, '\n'.join(head), '\n'.join(diff))


def style(line, message_id='id1'):
return 'ccc/a.c:{}:1: style: x [{}]'.format(line, message_id)


def test_triage_suggestions(client):
assert suggestions(client) == [
{'message_id': 'arrayIndexOutOfBounds', 'section': 'diff', 'package': 'ccc', 'url': PKG_C, 'warning': 'head ' + WARNING_OOB},
{'message_id': 'knownConditionTrueFalse', 'section': 'diff', 'package': 'ccc', 'url': PKG_C, 'warning': WARNING_OLD},
{'message_id': 'unknownMacro', 'section': 'head', 'package': 'ccc', 'url': PKG_C, 'warning': WARNING_MACRO},
]
# the suggestions can be uploaded when there is a verdict; after that they are not suggested anymore
items = [dict(w, verdict='True positive') for w in suggestions(client)]
assert client.post('/api/v1/triage', json=items[:1]).json()['added'] == 1
assert [w['warning'] for w in suggestions(client)] == [WARNING_OLD, WARNING_MACRO]
assert client.post('/api/v1/triage', json=items[1:]).json()['added'] == 2
assert suggestions(client) == []


def test_triage_suggestions_triaged(client):
upload_triage(client)
assert suggestions(client) == []


def test_triage_suggestions_selection(client, work_path, monkeypatch):
head = [style(n) for n in range(1, 31)] + [style(n, 'id2') for n in range(1, 31)] + [style(7, 'id2')]
head += ['ccc/a.c:1:1: debug: x [dbg]', 'ccc/a.c:9:1: note: x [id1]']
diff = ['head ' + style(n) for n in (1, 2)] + [server.OLD_VERSION + ' ' + style(99)]
diff += ['head ' + style(n, 'id2') for n in range(1, 21)]
client.post('/api/v1/results', content=result_file(head, diff).split('\n', 1)[1])
client.post('/api/v1/triage', json=[triage(style(2), 'False positive')])

first = suggestions(client)
id1 = [w for w in first if w['message_id'] == 'id1']
id2 = [w for w in first if w['message_id'] == 'id2']
assert len(first) == 10 and len(id1) == 5 and len(id2) == 5
# all the diff warnings without triage result, and then head warnings. No duplicates.
assert {w['warning'] for w in id1 if w['section'] == 'diff'} == {'head ' + style(1), server.OLD_VERSION + ' ' + style(99)}
assert len({w['warning'] for w in id1 if w['section'] == 'head'} - {style(1), style(2)}) == 3
# enough warnings in the diff
assert {w['section'] for w in id2} == {'diff'}
assert len({w['warning'] for w in id2}) == 5

# same list the same day, new random list the next day
assert suggestions(client) == first
monkeypatch.setattr(server, 'today_str', lambda: '2100-01-01')
lists = [suggestions(client)]
assert suggestions(client) == lists[0]
for day in range(2, 7):
monkeypatch.setattr(server, 'today_str', lambda day=day: '2100-01-0{}'.format(day))
lists.append(suggestions(client))
assert any(x != first for x in lists)


@pytest.mark.parametrize('old,new', [
('count: 3 2', 'count: Crash! 2'),
('count: 3 2', 'count: 3 TO!'),
('cppcheck: head ' + server.OLD_VERSION, 'cppcheck: head 1.0'),
('ccc_1.0', 'ccc_9.0')])
def test_triage_suggestions_ignored_results(work_path, old, new):
# incomplete results, results for another old version, unknown package url
assert old in RESULT_FILE_C
(work_path / 'donated-results' / 'ccc').write_text(RESULT_FILE_C.replace(old, new))
with TestClient(server.create_app(str(work_path), rescan_interval=0.2)) as client:
for _ in range(100):
if client.get('/api/v1/status').json()['index_ready']:
break
time.sleep(0.05)
assert client.get('/api/v1/status').json()['results'] == 1
assert suggestions(client) == []


def test_triage_suggestions_index_not_ready(work_path):
# without lifespan the index is not built => incomplete and not reused
client = TestClient(server.create_app(str(work_path)))
data = client.get('/api/v1/triage/suggestions').json()
assert data['complete'] is False and data['warnings'] == []
with client:
for _ in range(100):
if client.get('/api/v1/status').json()['index_ready']:
break
time.sleep(0.05)
assert len(suggestions(client)) == 3


def test_random_order():
rng = server.random.Random(1)
assert list(server.random_order(0, rng)) == []
orders = {tuple(server.random_order(4, rng)) for _ in range(1000)}
assert len(orders) == 24
assert all(sorted(order) == [0, 1, 2, 3] for order in orders)
Loading
Loading