def extract_verdict(scan: 'ScanResult') -> 'Optional[Verdict]': """Try to parse ``scan.metadata`` as a Verdict""" meta = getattr(scan, 'metadata', None) if isinstance(meta, str): return Verdict.parse_raw(meta) elif isinstance(meta, Mapping): return Verdict.parse_obj(meta) return meta
def test_scanalytics(statsd, engine_info, use_async, scan_result, verbose_metrics, artifact_kind): is_error = isinstance(scan_result, Exception) args = (None, str(uuid4()), artifact_kind, b'content', {}, 'home') type_tag = 'type:%s' % ArtifactType.to_string(artifact_kind) if use_async: @scanalytics(statsd=statsd, engine_info=engine_info, verbose=verbose_metrics) async def scanfn(self, guid, artifact_type, content, metadata, chain): if is_error: raise scan_result return scan_result result = asyncio.run(scanfn(*args)) else: @scanalytics(statsd=statsd, engine_info=engine_info, verbose=verbose_metrics) def scanfn(self, guid, artifact_type, content, metadata, chain): if is_error: raise scan_result return scan_result result = scanfn(*args) statsd.timing.assert_called_once() assert isinstance(result.metadata, str) result_meta = Verdict.parse_raw(result.metadata) assert result_meta.scanner.signatures_version == engine_info.definitions_version assert result_meta.scanner.vendor_version == engine_info.engine_version if is_error: assert result_meta.__dict__['scan_error'] == scan_result.event_name assert result.bit is False statsd.increment.assert_called_once_with( SCAN_FAIL, tags=[type_tag, f'scan_error:{scan_result.event_name}'] ) else: assert result.verdict is scan_result.verdict assert result.bit is scan_result.bit verdict_tag = 'verdict:malicious' if scan_result.verdict else 'verdict:benign' if scan_result.bit is True: statsd.increment.assert_any_call(SCAN_SUCCESS, tags=[type_tag, verdict_tag]) if verbose_metrics: statsd.increment.assert_any_call( SCAN_VERDICT, tags=[type_tag, verdict_tag], ) assert statsd.increment.call_count == 2 else: assert statsd.increment.call_count == 1 elif scan_result.bit is False: if verbose_metrics: statsd.increment.assert_called_once_with(SCAN_NO_RESULT, tags=[type_tag])