diff --git "a/PythonDataset/test/quality-time-task-instances.jsonl.all" "b/PythonDataset/test/quality-time-task-instances.jsonl.all" new file mode 100644--- /dev/null +++ "b/PythonDataset/test/quality-time-task-instances.jsonl.all" @@ -0,0 +1 @@ +{"repo": "ICTU/quality-time", "pull_number": 1102, "instance_id": "ICTU__quality-time-1102", "issue_numbers": "", "base_commit": "6df08864df270b6956cc78502aa3d9c0446038d5", "patch": "diff --git a/components/collector/src/base_collectors/__init__.py b/components/collector/src/base_collectors/__init__.py\nnew file mode 100644\n--- /dev/null\n+++ b/components/collector/src/base_collectors/__init__.py\n@@ -0,0 +1,8 @@\n+\"\"\"Metric collectors.\"\"\"\n+\n+from .api_source_collector import JenkinsPluginSourceUpToDatenessCollector\n+from .file_source_collector import CSVFileSourceCollector, HTMLFileSourceCollector, JSONFileSourceCollector, \\\n+ XMLFileSourceCollector\n+from .metrics_collector import MetricsCollector\n+from .source_collector import SourceCollector, LocalSourceCollector, UnmergedBranchesSourceCollector, \\\n+ SourceUpToDatenessCollector\ndiff --git a/components/collector/src/base_collectors/api_source_collector.py b/components/collector/src/base_collectors/api_source_collector.py\nnew file mode 100644\n--- /dev/null\n+++ b/components/collector/src/base_collectors/api_source_collector.py\n@@ -0,0 +1,16 @@\n+\"\"\"API source collector base classes.\"\"\"\n+\n+from datetime import datetime\n+\n+from collector_utilities.type import Response, URL\n+from .source_collector import SourceUpToDatenessCollector\n+\n+\n+class JenkinsPluginSourceUpToDatenessCollector(SourceUpToDatenessCollector):\n+ \"\"\"Base class for Jenkins plugin source up-to-dateness collectors.\"\"\"\n+\n+ async def _api_url(self) -> URL:\n+ return URL(f\"{await super()._api_url()}/lastSuccessfulBuild/api/json\")\n+\n+ async def _parse_source_response_date_time(self, response: Response) -> datetime:\n+ return datetime.fromtimestamp(float((await response.json())[\"timestamp\"]) / 1000.)\ndiff --git a/components/collector/src/base_collectors/cached_client_session.py b/components/collector/src/base_collectors/cached_client_session.py\nnew file mode 100644\n--- /dev/null\n+++ b/components/collector/src/base_collectors/cached_client_session.py\n@@ -0,0 +1,29 @@\n+\"\"\"Cached client session.\"\"\"\n+\n+import asyncio\n+from typing import Any, cast\n+\n+import aiohttp\n+from aiohttp.client import _RequestContextManager\n+from aiohttp.typedefs import StrOrURL\n+\n+\n+class CachedClientSession(aiohttp.ClientSession):\n+ \"\"\"Cached version of client session.\"\"\"\n+ def __init__(self, *args, **kwargs):\n+ super().__init__(*args, **kwargs)\n+ # We don't need a fancy cache with time-to-live or a max size because a new session is created every time the\n+ # collector wakes up (once every minute by default).\n+ self.__cache = dict()\n+\n+ async def get( # type: ignore\n+ self, url: StrOrURL, *, allow_redirects: bool = True, **kwargs: Any) -> '_RequestContextManager':\n+ \"\"\"Retrieve the url, using a cache.\"\"\"\n+ if url in self.__cache:\n+ if isinstance(self.__cache[url], asyncio.Event):\n+ await self.__cache[url].wait() # URL is being retrieved, wait for it\n+ else:\n+ event = self.__cache[url] = asyncio.Event() # Make other callers wait until the URL is retrieved\n+ self.__cache[url] = await super().get(url, allow_redirects=allow_redirects, **kwargs)\n+ event.set() # Signal other callers the URL has been retrieved\n+ return cast(_RequestContextManager, self.__cache[url])\ndiff --git a/components/collector/src/base_collectors/file_source_collector.py b/components/collector/src/base_collectors/file_source_collector.py\nnew file mode 100644\n--- /dev/null\n+++ b/components/collector/src/base_collectors/file_source_collector.py\n@@ -0,0 +1,64 @@\n+\"\"\"File source collector base classes.\"\"\"\n+\n+import asyncio\n+import io\n+import itertools\n+import zipfile\n+from abc import ABC\n+from typing import cast, Dict, List\n+\n+from collector_utilities.type import Response, Responses, URL\n+from .source_collector import FakeResponse, SourceCollector\n+\n+\n+class FileSourceCollector(SourceCollector, ABC): # pylint: disable=abstract-method\n+ \"\"\"Base class for source collectors that retrieve files.\"\"\"\n+\n+ file_extensions: List[str] = [] # Subclass responsibility\n+\n+ async def _get_source_responses(self, *urls: URL) -> Responses:\n+ responses = await super()._get_source_responses(*urls)\n+ if not urls[0].endswith(\".zip\"):\n+ return responses\n+ unzipped_responses = await asyncio.gather(*[self.__unzip(response) for response in responses])\n+ return list(itertools.chain(*unzipped_responses))\n+\n+ def _headers(self) -> Dict[str, str]:\n+ headers = super()._headers()\n+ if token := cast(str, self._parameter(\"private_token\")):\n+ # GitLab needs this header, see\n+ # https://docs.gitlab.com/ee/api/jobs.html#download-a-single-artifact-file-by-job-id\n+ headers[\"Private-Token\"] = token\n+ return headers\n+\n+ @classmethod\n+ async def __unzip(cls, response: Response) -> Responses:\n+ \"\"\"Unzip the response content and return a (new) response for each applicable file in the zip archive.\"\"\"\n+ with zipfile.ZipFile(io.BytesIO(await response.read())) as response_zipfile:\n+ names = [name for name in response_zipfile.namelist() if name.split(\".\")[-1].lower() in cls.file_extensions]\n+ responses = [FakeResponse(response_zipfile.read(name)) for name in names]\n+ return cast(Responses, responses)\n+\n+\n+class CSVFileSourceCollector(FileSourceCollector, ABC): # pylint: disable=abstract-method\n+ \"\"\"Base class for source collectors that retrieve CSV files.\"\"\"\n+\n+ file_extensions = [\"csv\"]\n+\n+\n+class HTMLFileSourceCollector(FileSourceCollector, ABC): # pylint: disable=abstract-method\n+ \"\"\"Base class for source collectors that retrieve HTML files.\"\"\"\n+\n+ file_extensions = [\"html\", \"htm\"]\n+\n+\n+class JSONFileSourceCollector(FileSourceCollector, ABC): # pylint: disable=abstract-method\n+ \"\"\"Base class for source collectors that retrieve JSON files.\"\"\"\n+\n+ file_extensions = [\"json\"]\n+\n+\n+class XMLFileSourceCollector(FileSourceCollector, ABC): # pylint: disable=abstract-method\n+ \"\"\"Base class for source collectors that retrieve XML files.\"\"\"\n+\n+ file_extensions = [\"xml\"]\ndiff --git a/components/collector/src/base_collectors/metrics_collector.py b/components/collector/src/base_collectors/metrics_collector.py\nnew file mode 100644\n--- /dev/null\n+++ b/components/collector/src/base_collectors/metrics_collector.py\n@@ -0,0 +1,136 @@\n+\"\"\"Metrics collector.\"\"\"\n+\n+from datetime import datetime, timedelta\n+import asyncio\n+import logging\n+import os\n+import traceback\n+from typing import cast, Any, Dict, Final, NoReturn\n+\n+import aiohttp\n+\n+from collector_utilities.functions import timer\n+from collector_utilities.type import JSON, URL\n+from .cached_client_session import CachedClientSession\n+from .source_collector import SourceCollector\n+\n+\n+async def get(session: aiohttp.ClientSession, api: URL) -> JSON:\n+ \"\"\"Get data from the API url.\"\"\"\n+ try:\n+ response = await session.get(api)\n+ return cast(JSON, await response.json())\n+ except Exception as reason: # pylint: disable=broad-except\n+ logging.error(\"Getting data from %s failed: %s\", api, reason)\n+ logging.error(traceback.format_exc())\n+ return {}\n+\n+\n+async def post(session: aiohttp.ClientSession, api: URL, data) -> None:\n+ \"\"\"Post the JSON data to the api url.\"\"\"\n+ try:\n+ await session.post(api, json=data)\n+ except Exception as reason: # pylint: disable=broad-except\n+ logging.error(\"Posting %s to %s failed: %s\", data, api, reason)\n+ logging.error(traceback.format_exc())\n+\n+\n+class MetricsCollector:\n+ \"\"\"Collect measurements for all metrics.\"\"\"\n+ def __init__(self) -> None:\n+ self.server_url: Final[URL] = \\\n+ URL(f\"http://{os.environ.get('SERVER_HOST', 'localhost')}:{os.environ.get('SERVER_PORT', '5001')}\")\n+ self.data_model: JSON = dict()\n+ self.next_fetch: Dict[str, datetime] = dict()\n+ self.last_parameters: Dict[str, Any] = dict()\n+\n+ @staticmethod\n+ def record_health(filename: str = \"/tmp/health_check.txt\") -> None:\n+ \"\"\"Record the current date and time in a file to allow for health checks.\"\"\"\n+ try:\n+ with open(filename, \"w\") as health_check:\n+ health_check.write(datetime.now().isoformat())\n+ except OSError as reason:\n+ logging.error(\"Could not write health check time stamp to %s: %s\", filename, reason)\n+\n+ async def start(self) -> NoReturn:\n+ \"\"\"Start fetching measurements indefinitely.\"\"\"\n+ max_sleep_duration = int(os.environ.get(\"COLLECTOR_SLEEP_DURATION\", 60))\n+ measurement_frequency = int(os.environ.get(\"COLLECTOR_MEASUREMENT_FREQUENCY\", 15 * 60))\n+ timeout = aiohttp.ClientTimeout(total=120)\n+ async with CachedClientSession(timeout=timeout, raise_for_status=True) as session:\n+ self.data_model = await self.fetch_data_model(session, max_sleep_duration)\n+ while True:\n+ self.record_health()\n+ logging.info(\"Collecting...\")\n+ async with CachedClientSession(\n+ timeout=timeout, connector=aiohttp.TCPConnector(limit_per_host=20),\n+ raise_for_status=True) as session:\n+ with timer() as collection_timer:\n+ await self.collect_metrics(session, measurement_frequency)\n+ sleep_duration = max(0, max_sleep_duration - collection_timer.duration)\n+ logging.info(\n+ \"Collecting took %.1f seconds. Sleeping %.1f seconds...\", collection_timer.duration, sleep_duration)\n+ await asyncio.sleep(sleep_duration)\n+\n+ async def fetch_data_model(self, session: aiohttp.ClientSession, sleep_duration: int) -> JSON:\n+ \"\"\"Fetch the data model.\"\"\"\n+ while True:\n+ self.record_health()\n+ logging.info(\"Loading data model...\")\n+ if data_model := await get(session, URL(f\"{self.server_url}/api/v2/datamodel\")):\n+ return data_model\n+ logging.warning(\"Loading data model failed, trying again in %ss...\", sleep_duration)\n+ await asyncio.sleep(sleep_duration)\n+\n+ async def collect_metrics(self, session: aiohttp.ClientSession, measurement_frequency: int) -> None:\n+ \"\"\"Collect measurements for all metrics.\"\"\"\n+ metrics = await get(session, URL(f\"{self.server_url}/api/v2/metrics\"))\n+ next_fetch = datetime.now() + timedelta(seconds=measurement_frequency)\n+ tasks = [self.collect_metric(session, metric_uuid, metric, next_fetch)\n+ for metric_uuid, metric in metrics.items() if self.__can_and_should_collect(metric_uuid, metric)]\n+ await asyncio.gather(*tasks)\n+\n+ async def collect_metric(\n+ self, session: aiohttp.ClientSession, metric_uuid, metric, next_fetch: datetime) -> None:\n+ \"\"\"Collect measurements for the metric and post it to the server.\"\"\"\n+ self.last_parameters[metric_uuid] = metric\n+ self.next_fetch[metric_uuid] = next_fetch\n+ measurement = await self.collect_sources(session, metric)\n+ measurement[\"metric_uuid\"] = metric_uuid\n+ await post(session, URL(f\"{self.server_url}/api/v2/measurements\"), measurement)\n+\n+ async def collect_sources(self, session: aiohttp.ClientSession, metric):\n+ \"\"\"Collect the measurements from the metric's sources.\"\"\"\n+ collectors = []\n+ for source in metric[\"sources\"].values():\n+ collector_class = SourceCollector.get_subclass(source[\"type\"], metric[\"type\"])\n+ collectors.append(collector_class(session, source, self.data_model).get())\n+ measurements = await asyncio.gather(*collectors)\n+ for measurement, source_uuid in zip(measurements, metric[\"sources\"]):\n+ measurement[\"source_uuid\"] = source_uuid\n+ return dict(sources=measurements)\n+\n+ def __can_and_should_collect(self, metric_uuid: str, metric) -> bool:\n+ \"\"\"Return whether the metric can and needs to be measured.\"\"\"\n+ if not self.__can_collect(metric):\n+ return False\n+ return self.__should_collect(metric_uuid, metric)\n+\n+ def __can_collect(self, metric) -> bool:\n+ \"\"\"Return whether the user has specified all mandatory parameters for all sources.\"\"\"\n+ sources = metric.get(\"sources\")\n+ for source in sources.values():\n+ parameters = self.data_model.get(\"sources\", {}).get(source[\"type\"], {}).get(\"parameters\", {})\n+ for parameter_key, parameter in parameters.items():\n+ if parameter.get(\"mandatory\") and metric[\"type\"] in parameter.get(\"metrics\") and \\\n+ not source.get(\"parameters\", {}).get(parameter_key):\n+ return False\n+ return bool(sources)\n+\n+ def __should_collect(self, metric_uuid: str, metric) -> bool:\n+ \"\"\"Return whether the metric should be collected, either because the user changed the configuration or because\n+ it has been collected too long ago.\"\"\"\n+ if self.last_parameters.get(metric_uuid) != metric:\n+ return True\n+ return self.next_fetch.get(metric_uuid, datetime.min) <= datetime.now()\ndiff --git a/components/collector/src/source_collectors/source_collector.py b/components/collector/src/base_collectors/source_collector.py\nsimilarity index 60%\nrename from components/collector/src/source_collectors/source_collector.py\nrename to components/collector/src/base_collectors/source_collector.py\n--- a/components/collector/src/source_collectors/source_collector.py\n+++ b/components/collector/src/base_collectors/source_collector.py\n@@ -1,32 +1,32 @@\n \"\"\"Source collector base classes.\"\"\"\n \n-import io\n+import asyncio\n+import json\n import logging\n import traceback\n import urllib\n-import zipfile\n from abc import ABC, abstractmethod\n from datetime import datetime\n from http import HTTPStatus\n-from typing import cast, Dict, Final, List, Optional, Set, Tuple, Type, Union\n+from typing import cast, Any, Dict, Final, List, Optional, Set, Tuple, Type, Union\n \n-import requests\n+import aiohttp\n \n from collector_utilities.functions import days_ago, tokenless, stable_traceback\n-from collector_utilities.type import ErrorMessage, Entities, Measurement, Response, Responses, URL, Value\n+from collector_utilities.type import ErrorMessage, Entities, JSON, Measurement, Response, Responses, URL, Value\n \n \n class SourceCollector(ABC):\n \"\"\"Base class for source collectors. Source collectors are subclasses of this class that know how to collect the\n measurement data for one specific metric from one specific source.\"\"\"\n \n- TIMEOUT = 10 # Default timeout of 10 seconds\n MAX_ENTITIES = 100 # The maximum number of entities (e.g. violations, warnings) to send to the server\n API_URL_PARAMETER_KEY = \"url\"\n source_type = \"\" # The source type is set on the subclass, when the subclass is registered\n subclasses: Set[Type[\"SourceCollector\"]] = set()\n \n- def __init__(self, source, datamodel) -> None:\n+ def __init__(self, session: aiohttp.ClientSession, source, datamodel) -> None:\n+ self._session = session\n self._datamodel: Final = datamodel\n self.__parameters: Final[Dict[str, Union[str, List[str]]]] = source.get(\"parameters\", {})\n \n@@ -45,30 +45,22 @@ def get_subclass(cls, source_type: str, metric_type: str) -> Type[\"SourceCollect\n return matching_subclasses[0]\n raise LookupError(f\"Couldn't find collector subclass for source {source_type} and metric {metric_type}\")\n \n- def get(self) -> Measurement:\n+ async def get(self) -> Measurement:\n \"\"\"Return the measurement from this source.\"\"\"\n- responses, api_url, connection_error = self.__safely_get_source_responses()\n- value, total, entities, parse_error = self.__safely_parse_source_responses(responses)\n- landing_url = self._landing_url(responses)\n+ responses, api_url, connection_error = await self.__safely_get_source_responses()\n+ value, total, entities, parse_error = await self.__safely_parse_source_responses(responses)\n+ landing_url = await self.__safely_parse_landing_url(responses)\n return dict(api_url=api_url, landing_url=landing_url, value=value, total=total, entities=entities,\n connection_error=connection_error, parse_error=parse_error)\n \n- def _landing_url(self, responses: Responses) -> URL: # pylint: disable=unused-argument\n- \"\"\"Return the user supplied landing url parameter if there is one, otherwise translate the url parameter into\n- a default landing url.\"\"\"\n- if landing_url := cast(str, self.__parameters.get(\"landing_url\", \"\")).rstrip(\"/\"):\n- return URL(landing_url)\n- url = cast(str, self.__parameters.get(self.API_URL_PARAMETER_KEY, \"\")).rstrip(\"/\")\n- return URL(url[:-(len(\"xml\"))] + \"html\" if url.endswith(\".xml\") else url)\n-\n- def _api_url(self) -> URL:\n+ async def _api_url(self) -> URL:\n \"\"\"Translate the url parameter into the API url.\"\"\"\n return URL(cast(str, self.__parameters.get(self.API_URL_PARAMETER_KEY, \"\")).rstrip(\"/\"))\n \n def _parameter(self, parameter_key: str, quote: bool = False) -> Union[str, List[str]]:\n \"\"\"Return the parameter value.\"\"\"\n \n- def quote_if_needed(parameter_value):\n+ def quote_if_needed(parameter_value: str) -> str:\n \"\"\"Quote the string if needed.\"\"\"\n return urllib.parse.quote(parameter_value, safe=\"\") if quote else parameter_value\n \n@@ -84,30 +76,30 @@ def quote_if_needed(parameter_value):\n value = cast(str, value).rstrip(\"/\")\n return quote_if_needed(value) if isinstance(value, str) else [quote_if_needed(v) for v in value]\n \n- def __safely_get_source_responses(self) -> Tuple[Responses, URL, ErrorMessage]:\n+ async def __safely_get_source_responses(self) -> Tuple[Responses, URL, ErrorMessage]:\n \"\"\"Connect to the source and get the data, without failing. This method should not be overridden\n because it makes sure the collection of source data never causes the collector to fail.\"\"\"\n responses: Responses = []\n api_url = URL(\"\")\n error = None\n try:\n- responses = self._get_source_responses(api_url := self._api_url())\n- for response in responses:\n- response.raise_for_status()\n+ responses = await self._get_source_responses(api_url := await self._api_url())\n logging.info(\"Retrieved %s\", tokenless(api_url) or self.__class__.__name__)\n except Exception as reason: # pylint: disable=broad-except\n error = stable_traceback(traceback.format_exc())\n logging.warning(\"Failed to retrieve %s: %s\", tokenless(api_url) or self.__class__.__name__, reason)\n return responses, api_url, error\n \n- def _get_source_responses(self, api_url: URL) -> Responses:\n- \"\"\"Open the url. Can be overridden if a post request is needed or multiple requests need to be made.\"\"\"\n- return [\n- requests.get(api_url, timeout=self.TIMEOUT, auth=self._basic_auth_credentials(), headers=self._headers())]\n-\n- def _headers(self) -> Dict[str, str]: # pylint: disable=no-self-use\n- \"\"\"Return the headers for the request.\"\"\"\n- return dict()\n+ async def _get_source_responses(self, *urls: URL) -> Responses:\n+ \"\"\"Open the url. Can be overridden if a post request is needed or serial requests need to be made.\"\"\"\n+ kwargs: Dict[str, Any] = dict()\n+ credentials = self._basic_auth_credentials()\n+ if credentials is not None:\n+ kwargs[\"auth\"] = aiohttp.BasicAuth(credentials[0], credentials[1])\n+ if headers := self._headers():\n+ kwargs[\"headers\"] = headers\n+ tasks = [self._session.get(url, **kwargs) for url in urls]\n+ return list(await asyncio.gather(*tasks))\n \n def _basic_auth_credentials(self) -> Optional[Tuple[str, str]]:\n \"\"\"Return the basic authentication credentials, if any.\"\"\"\n@@ -117,7 +109,11 @@ def _basic_auth_credentials(self) -> Optional[Tuple[str, str]]:\n password = cast(str, self.__parameters.get(\"password\", \"\"))\n return (username, password) if username and password else None\n \n- def __safely_parse_source_responses(\n+ def _headers(self) -> Dict[str, str]: # pylint: disable=no-self-use\n+ \"\"\"Return the headers for the get request.\"\"\"\n+ return {}\n+\n+ async def __safely_parse_source_responses(\n self, responses: Responses) -> Tuple[Value, Value, Entities, ErrorMessage]:\n \"\"\"Parse the data from the responses, without failing. This method should not be overridden because it\n makes sure that the parsing of source data never causes the collector to fail.\"\"\"\n@@ -125,95 +121,72 @@ def __safely_parse_source_responses(\n value, total, error = None, None, None\n if responses:\n try:\n- value, total, entities = self._parse_source_responses(responses)\n+ value, total, entities = await self._parse_source_responses(responses)\n except Exception: # pylint: disable=broad-except\n error = stable_traceback(traceback.format_exc())\n return value, total, entities[:self.MAX_ENTITIES], error\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n \"\"\"Parse the responses to get the measurement value, the total value, and the entities for the metric.\n This method can be overridden by collectors to parse the retrieved sources data.\"\"\"\n # pylint: disable=assignment-from-none,no-self-use,unused-argument\n return None, \"100\", [] # pragma nocover\n \n+ async def __safely_parse_landing_url(self, responses: Responses) -> URL:\n+ \"\"\"Parse the responses to get the landing url, without failing. This method should not be overridden because\n+ it makes sure that the parsing of source data never causes the collector to fail.\"\"\"\n+ try:\n+ return await self._landing_url(responses)\n+ except Exception: # pylint: disable=broad-except\n+ return await self._api_url()\n \n-class FileSourceCollector(SourceCollector, ABC): # pylint: disable=abstract-method\n- \"\"\"Base class for source collectors that retrieve files.\"\"\"\n-\n- file_extensions: List[str] = [] # Subclass responsibility\n-\n- def _get_source_responses(self, api_url: URL) -> Responses:\n- responses = super()._get_source_responses(api_url)\n- if not api_url.endswith(\".zip\"):\n- return responses\n- unzipped_responses = []\n- for response in responses:\n- unzipped_responses.extend(self.__unzip(response))\n- return unzipped_responses\n-\n- def _headers(self) -> Dict[str, str]:\n- headers = super()._headers()\n- if token := cast(str, self._parameter(\"private_token\")):\n- # GitLab needs this header, see\n- # https://docs.gitlab.com/ee/api/jobs.html#download-a-single-artifact-file-by-job-id\n- headers[\"Private-Token\"] = token\n- return headers\n-\n- @classmethod\n- def __unzip(cls, response: Response) -> Responses:\n- \"\"\"Unzip the response content and return a (new) response for each applicable file in the zip archive.\"\"\"\n- responses = []\n- with zipfile.ZipFile(io.BytesIO(response.content)) as response_zipfile:\n- names = [name for name in response_zipfile.namelist() if name.split(\".\")[-1].lower() in cls.file_extensions]\n- for name in names:\n- unzipped_response = requests.Response()\n- unzipped_response.raw = io.BytesIO(response_zipfile.read(name))\n- unzipped_response.status_code = HTTPStatus.OK\n- responses.append(unzipped_response)\n- return responses\n-\n-\n-class HTMLFileSourceCollector(FileSourceCollector, ABC): # pylint: disable=abstract-method\n- \"\"\"Base class for source collectors that retrieve HTML files.\"\"\"\n-\n- file_extensions = [\"html\", \"htm\"]\n-\n+ async def _landing_url(self, responses: Responses) -> URL: # pylint: disable=unused-argument\n+ \"\"\"Return the user supplied landing url parameter if there is one, otherwise translate the url parameter into\n+ a default landing url.\"\"\"\n+ if landing_url := cast(str, self.__parameters.get(\"landing_url\", \"\")).rstrip(\"/\"):\n+ return URL(landing_url)\n+ url = cast(str, self.__parameters.get(self.API_URL_PARAMETER_KEY, \"\")).rstrip(\"/\")\n+ return URL(url[:-(len(\"xml\"))] + \"html\" if url.endswith(\".xml\") else url)\n \n-class JSONFileSourceCollector(FileSourceCollector, ABC): # pylint: disable=abstract-method\n- \"\"\"Base class for source collectors that retrieve JSON files.\"\"\"\n \n- file_extensions = [\"json\"]\n+class FakeResponse: # pylint: disable=too-few-public-methods\n+ \"\"\"Fake a response because aiohttp.ClientResponse can not easily be instantiated directly. \"\"\"\n+ status = HTTPStatus.OK\n \n+ def __init__(self, contents: bytes = bytes()) -> None:\n+ super().__init__()\n+ self.contents = contents\n \n-class XMLFileSourceCollector(FileSourceCollector, ABC): # pylint: disable=abstract-method\n- \"\"\"Base class for source collectors that retrieve XML files.\"\"\"\n+ async def json(self) -> JSON:\n+ \"\"\"Return the JSON version of the contents.\"\"\"\n+ return cast(JSON, json.loads(self.contents))\n \n- file_extensions = [\"xml\"]\n+ async def text(self) -> str:\n+ \"\"\"Return the text version of the contents.\"\"\"\n+ return str(self.contents.decode())\n \n \n class LocalSourceCollector(SourceCollector, ABC): # pylint: disable=abstract-method\n \"\"\"Base class for source collectors that do not need to access the network but return static or user-supplied\n data.\"\"\"\n \n- def _get_source_responses(self, api_url: URL) -> Responses:\n- fake_response = requests.Response()\n- fake_response.status_code = HTTPStatus.OK\n- return [fake_response] # Return a fake response so that the parse methods will be called\n+ async def _get_source_responses(self, *urls: URL) -> Responses:\n+ return [cast(Response, FakeResponse())] # Return a fake response so that the parse methods will be called\n \n \n class UnmergedBranchesSourceCollector(SourceCollector, ABC): # pylint: disable=abstract-method\n \"\"\"Base class for unmerged branches source collectors.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n entities = [\n dict(key=branch[\"name\"], name=branch[\"name\"], commit_age=str(days_ago(self._commit_datetime(branch))),\n commit_date=str(self._commit_datetime(branch).date()))\n- for branch in self._unmerged_branches(responses)]\n+ for branch in await self._unmerged_branches(responses)]\n return str(len(entities)), \"100\", entities\n \n @abstractmethod\n- def _unmerged_branches(self, responses: Responses) -> List:\n- \"\"\"Return the list of unmerged branch.\"\"\"\n+ async def _unmerged_branches(self, responses: Responses) -> List[Dict[str, Any]]:\n+ \"\"\"Return the list of unmerged branches.\"\"\"\n \n @abstractmethod\n def _commit_datetime(self, branch) -> datetime:\n@@ -223,9 +196,10 @@ def _commit_datetime(self, branch) -> datetime:\n class SourceUpToDatenessCollector(SourceCollector):\n \"\"\"Base class for source up-to-dateness collectors.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- return str(days_ago(min(self._parse_source_response_date_time(response) for response in responses))), \"100\", []\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ date_times = await asyncio.gather(*[self._parse_source_response_date_time(response) for response in responses])\n+ return str(days_ago(min(date_times))), \"100\", []\n \n- def _parse_source_response_date_time(self, response: Response) -> datetime:\n+ async def _parse_source_response_date_time(self, response: Response) -> datetime:\n \"\"\"Parse the date time from the source.\"\"\"\n raise NotImplementedError # pragma: nocover\ndiff --git a/components/collector/src/collector_utilities/functions.py b/components/collector/src/collector_utilities/functions.py\n--- a/components/collector/src/collector_utilities/functions.py\n+++ b/components/collector/src/collector_utilities/functions.py\n@@ -4,8 +4,8 @@\n import hashlib\n import re\n import urllib\n-from datetime import datetime, timedelta\n-from typing import cast, Collection, Pattern, Tuple\n+from datetime import datetime\n+from typing import cast, Collection, Generator, Pattern, Tuple\n from xml.etree.ElementTree import Element # nosec, Element is not available from defusedxml, but only used as type\n \n from defusedxml import ElementTree\n@@ -13,24 +13,24 @@\n from .type import Namespaces, Response, URL\n \n \n-def parse_source_response_xml(response: Response, allowed_root_tags: Collection[str] = None) -> Element:\n+async def parse_source_response_xml(response: Response, allowed_root_tags: Collection[str] = None) -> Element:\n \"\"\"Parse the XML from the source response.\"\"\"\n- tree = cast(Element, ElementTree.fromstring(response.text))\n+ tree = cast(Element, ElementTree.fromstring(await response.text()))\n if allowed_root_tags and tree.tag not in allowed_root_tags:\n raise AssertionError(f'The XML root element should be one of \"{allowed_root_tags}\" but is \"{tree.tag}\"')\n return tree\n \n \n-def parse_source_response_xml_with_namespace(\n+async def parse_source_response_xml_with_namespace(\n response: Response, allowed_root_tags: Collection[str] = None) -> Tuple[Element, Namespaces]:\n \"\"\"Parse the XML with namespace from the source response.\"\"\"\n- tree = parse_source_response_xml(response, allowed_root_tags)\n+ tree = await parse_source_response_xml(response, allowed_root_tags)\n # ElementTree has no API to get the namespace so we extract it from the root tag:\n namespaces = dict(ns=tree.tag.split('}')[0][1:])\n return tree, namespaces\n \n \n-Substitution = Tuple[Pattern, str]\n+Substitution = Tuple[Pattern[str], str]\n MEMORY_ADDRESS_SUB: Substitution = (re.compile(r\" at 0x[0-9abcdef]+>\"), \">\")\n TOKEN_SUB: Substitution = (re.compile(r\"token=[0-9a-zA-Z]+\"), \"token=\")\n KEY_SUB: Substitution = (re.compile(r\"key=[0-9abcdef]+\"), \"key=\")\n@@ -92,17 +92,17 @@ def match_string_or_regular_expression(string: str, strings_and_or_regular_expre\n \n class Clock: # pylint: disable=too-few-public-methods\n \"\"\"Class to keep track of time.\"\"\"\n- def __init__(self):\n+ def __init__(self) -> None:\n self.start = datetime.now()\n- self.duration = timedelta()\n+ self.duration = 0.0\n \n- def stop(self):\n+ def stop(self) -> None:\n \"\"\"Stop the clock.\"\"\"\n self.duration = (datetime.now() - self.start).total_seconds()\n \n \n @contextlib.contextmanager\n-def timer():\n+def timer() -> Generator[Clock, None, None]:\n \"\"\"Timer context manager.\"\"\"\n clock = Clock()\n yield clock\ndiff --git a/components/collector/src/collector_utilities/type.py b/components/collector/src/collector_utilities/type.py\n--- a/components/collector/src/collector_utilities/type.py\n+++ b/components/collector/src/collector_utilities/type.py\n@@ -2,7 +2,8 @@\n \n from typing import Any, Dict, List, NewType, Optional, Union\n \n-import requests\n+import aiohttp\n+\n \n Entity = Dict[str, Union[int, float, str]] # pylint: disable=invalid-name\n Entities = List[Entity]\n@@ -12,7 +13,7 @@\n JSON = Dict[str, Any]\n Namespaces = Dict[str, str] # Namespace prefix to Namespace URI mapping\n Measurement = Dict[str, Any]\n-Response = requests.Response\n+Response = aiohttp.ClientResponse\n Responses = List[Response]\n URL = NewType(\"URL\", str)\n Value = Optional[str]\ndiff --git a/components/collector/src/metric_collectors/__init__.py b/components/collector/src/metric_collectors/__init__.py\ndeleted file mode 100644\n--- a/components/collector/src/metric_collectors/__init__.py\n+++ /dev/null\n@@ -1,4 +0,0 @@\n-\"\"\"Metric collectors.\"\"\"\n-\n-from .metric_collector import MetricCollector\n-from .metrics_collector import MetricsCollector\ndiff --git a/components/collector/src/metric_collectors/metric_collector.py b/components/collector/src/metric_collectors/metric_collector.py\ndeleted file mode 100644\n--- a/components/collector/src/metric_collectors/metric_collector.py\n+++ /dev/null\n@@ -1,33 +0,0 @@\n-\"\"\"Collector base class.\"\"\"\n-\n-from typing import Dict, Final\n-\n-from source_collectors.source_collector import SourceCollector\n-from collector_utilities.type import Measurement\n-\n-\n-class MetricCollector:\n- \"\"\"Base class for collecting measurements from multiple sources for a metric.\"\"\"\n-\n- def __init__(self, metric, datamodel=None) -> None:\n- self.metric: Final = metric\n- self.datamodel: Final = datamodel\n- self.collectors: Dict[str, SourceCollector] = dict()\n- for source_uuid, source in self.metric[\"sources\"].items():\n- collector_class = SourceCollector.get_subclass(source['type'], self.metric['type'])\n- self.collectors[source_uuid] = collector_class(source, datamodel)\n-\n- def can_collect(self) -> bool:\n- \"\"\"Return whether the user has specified all mandatory parameters for all sources.\"\"\"\n- sources = self.metric.get(\"sources\")\n- for source in sources.values():\n- parameters = self.datamodel.get(\"sources\", {}).get(source[\"type\"], {}).get(\"parameters\", {})\n- for parameter_key, parameter in parameters.items():\n- if parameter.get(\"mandatory\") and self.metric[\"type\"] in parameter.get(\"metrics\") and \\\n- not source.get(\"parameters\", {}).get(parameter_key):\n- return False\n- return bool(sources)\n-\n- def get(self) -> Measurement:\n- \"\"\"Connect to the sources to get and parse the measurements for the metric.\"\"\"\n- return dict(sources=[{**self.collectors[uuid].get(), \"source_uuid\": uuid} for uuid in self.metric[\"sources\"]])\ndiff --git a/components/collector/src/metric_collectors/metrics_collector.py b/components/collector/src/metric_collectors/metrics_collector.py\ndeleted file mode 100644\n--- a/components/collector/src/metric_collectors/metrics_collector.py\n+++ /dev/null\n@@ -1,94 +0,0 @@\n-\"\"\"Metrics collector.\"\"\"\n-\n-from datetime import datetime, timedelta\n-import logging\n-import os\n-import time\n-from typing import cast, Any, Dict, Final, NoReturn\n-\n-import requests\n-\n-from collector_utilities.functions import timer\n-from collector_utilities.type import JSON, URL\n-from .metric_collector import MetricCollector\n-\n-\n-def get(api: URL) -> JSON:\n- \"\"\"Get data from the API url.\"\"\"\n- try:\n- return cast(JSON, requests.get(api).json())\n- except Exception as reason: # pylint: disable=broad-except\n- logging.error(\"Getting data from %s failed: %s\", api, reason)\n- return {}\n-\n-\n-def post(api: URL, data) -> None:\n- \"\"\"Post the JSON data to the api url.\"\"\"\n- try:\n- requests.post(api, json=data)\n- except Exception as reason: # pylint: disable=broad-except\n- logging.error(\"Posting %s to %s failed: %s\", data, api, reason)\n-\n-\n-class MetricsCollector:\n- \"\"\"Collect measurements for all metrics.\"\"\"\n- def __init__(self) -> None:\n- self.server_url: Final[URL] = \\\n- URL(f\"http://{os.environ.get('SERVER_HOST', 'localhost')}:{os.environ.get('SERVER_PORT', '5001')}\")\n- self.data_model: JSON = dict()\n- self.next_fetch: Dict[str, datetime] = dict()\n- self.last_parameters: Dict[str, Any] = dict()\n-\n- @staticmethod\n- def record_health(filename: str = \"/tmp/health_check.txt\") -> None:\n- \"\"\"Record the current date and time in a file to allow for health checks.\"\"\"\n- try:\n- with open(filename, \"w\") as health_check:\n- health_check.write(datetime.now().isoformat())\n- except OSError as reason:\n- logging.error(\"Could not write health check time stamp to %s: %s\", filename, reason)\n-\n- def start(self) -> NoReturn:\n- \"\"\"Start fetching measurements indefinitely.\"\"\"\n- max_sleep_duration = int(os.environ.get(\"COLLECTOR_SLEEP_DURATION\", 60))\n- measurement_frequency = int(os.environ.get(\"COLLECTOR_MEASUREMENT_FREQUENCY\", 15 * 60))\n- self.data_model = self.fetch_data_model(max_sleep_duration)\n- while True:\n- self.record_health()\n- logging.info(\"Collecting...\")\n- with timer() as collection_timer:\n- self.fetch_measurements(measurement_frequency)\n- sleep_duration = max(0, max_sleep_duration - collection_timer.duration)\n- logging.info(\n- \"Collecting took %.1f seconds. Sleeping %.1f seconds...\", collection_timer.duration, sleep_duration)\n- time.sleep(sleep_duration)\n-\n- def fetch_data_model(self, sleep_duration: int) -> JSON:\n- \"\"\"Fetch the data model.\"\"\"\n- while True:\n- self.record_health()\n- logging.info(\"Loading data model...\")\n- if data_model := get(URL(f\"{self.server_url}/api/v2/datamodel\")):\n- return data_model\n- logging.warning(\"Loading data model failed, trying again in %ss...\", sleep_duration)\n- time.sleep(sleep_duration)\n-\n- def fetch_measurements(self, measurement_frequency: int) -> None:\n- \"\"\"Fetch the metrics and their measurements.\"\"\"\n- metrics = get(URL(f\"{self.server_url}/api/v2/metrics\"))\n- for metric_uuid, metric in metrics.items():\n- if not (collector := MetricCollector(metric, self.data_model)).can_collect():\n- continue\n- if self.__skip(metric_uuid, metric):\n- continue\n- measurement = collector.get()\n- self.last_parameters[metric_uuid] = metric\n- self.next_fetch[metric_uuid] = datetime.now() + timedelta(seconds=measurement_frequency)\n- measurement[\"metric_uuid\"] = metric_uuid\n- post(URL(f\"{self.server_url}/api/v2/measurements\"), measurement)\n-\n- def __skip(self, metric_uuid: str, metric) -> bool:\n- \"\"\"Return whether the metric needs to be measured.\"\"\"\n- if self.last_parameters.get(metric_uuid) != metric:\n- return False # Don't skip if metric parameters changed\n- return self.next_fetch.get(metric_uuid, datetime.min) > datetime.now()\ndiff --git a/components/collector/src/quality_time_collector.py b/components/collector/src/quality_time_collector.py\n--- a/components/collector/src/quality_time_collector.py\n+++ b/components/collector/src/quality_time_collector.py\n@@ -1,18 +1,18 @@\n \"\"\"Measurement collector.\"\"\"\n \n+import asyncio\n import logging\n-from typing import NoReturn\n \n-from metric_collectors import MetricsCollector\n+from base_collectors import MetricsCollector\n # Make sure subclasses are registered\n from source_collectors import * # lgtm [py/polluting-import] pylint: disable=unused-wildcard-import,wildcard-import\n \n \n-def collect(log_level: int = None) -> NoReturn:\n+async def collect(log_level: int = None) -> None:\n \"\"\"Collect the measurements indefinitely.\"\"\"\n logging.getLogger().setLevel(log_level or logging.ERROR)\n- MetricsCollector().start()\n+ await MetricsCollector().start()\n \n \n if __name__ == \"__main__\":\n- collect(logging.INFO) # pragma: nocover\n+ asyncio.run(collect(logging.INFO)) # pragma: nocover\ndiff --git a/components/collector/src/source_collectors/__init__.py b/components/collector/src/source_collectors/__init__.py\n--- a/components/collector/src/source_collectors/__init__.py\n+++ b/components/collector/src/source_collectors/__init__.py\n@@ -1,39 +1,44 @@\n \"\"\"Metric collectors per source.\"\"\"\n \n-from .anchore import AnchoreSecurityWarnings, AnchoreSourceUpToDateness\n-from .axe_csv import AxeCSVAccessibility\n-from .azure_devops import AzureDevopsIssues, AzureDevopsReadyUserStoryPoints\n-from .bandit import BanditSecurityWarnings, BanditSourceUpToDateness\n-from .calendar import CalendarSourceUpToDateness\n-from .composer import ComposerDependencies\n-from .cxsast import CxSASTSecurityWarnings, CxSASTSourceUpToDateness\n-from .gitlab import GitLabFailedJobs, GitLabUnusedJobs, GitLabSourceUpToDateness, GitLabUnmergedBranches\n-from .jacoco import JacocoSourceUpToDateness, JacocoUncoveredBranches, JacocoUncoveredLines\n-from .jacoco_jenkins_plugin import (\n+from .api_source_collectors.azure_devops import AzureDevopsIssues, AzureDevopsReadyUserStoryPoints\n+from .api_source_collectors.cxsast import CxSASTSecurityWarnings, CxSASTSourceUpToDateness\n+from .api_source_collectors.gitlab import (\n+ GitLabFailedJobs, GitLabUnusedJobs, GitLabSourceUpToDateness, GitLabUnmergedBranches)\n+from .api_source_collectors.jacoco_jenkins_plugin import (\n JacocoJenkinsPluginUncoveredBranches, JacocoJenkinsPluginUncoveredLines, JacocoJenkinsPluginSourceUpToDateness)\n-from .jenkins import JenkinsFailedJobs, JenkinsJobs\n-from .jenkins_test_report import JenkinsTestReportSourceUpToDateness, JenkinsTestReportTests\n-from .jira import JiraIssues, JiraManualTestDuration, JiraManualTestExecution, JiraReadyUserStoryPoints\n-from .junit import JUnitSourceUpToDateness, JUnitTests\n-from .manual_number import ManualNumber\n-from .ncover import NCoverSourceUpToDateness\n-from .ojaudit import OJAuditViolations\n-from .openvas import OpenVASSecurityWarnings, OpenVASSourceUpToDateness\n-from .owasp_dependency_check import OWASPDependencyCheckSecurityWarnings, OWASPDependencyCheckSourceUpToDateness\n-from .owasp_dependency_check_jenkins_plugin import (\n+from .api_source_collectors.jenkins import JenkinsFailedJobs, JenkinsJobs\n+from .api_source_collectors.jenkins_test_report import JenkinsTestReportSourceUpToDateness, JenkinsTestReportTests\n+from .api_source_collectors.jira import (\n+ JiraIssues, JiraManualTestDuration, JiraManualTestExecution, JiraReadyUserStoryPoints)\n+from .api_source_collectors.owasp_dependency_check_jenkins_plugin import (\n OWASPDependencyCheckJenkinsPluginSecurityWarnings, OWASPDependencyCheckJenkinsPluginSourceUpToDateness)\n-from .owasp_zap import OWASPZAPSecurityWarnings, OWASPZAPSourceUpToDateness\n-from .performancetest_runner import (\n+from .api_source_collectors.quality_time import QualityTimeMetrics\n+from .api_source_collectors.sonarqube import (\n+ SonarQubeDuplicatedLines, SonarQubeComplexUnits, SonarQubeCommentedOutCode, SonarQubeLOC, SonarQubeLongUnits,\n+ SonarQubeManyParameters, SonarQubeSourceUpToDateness, SonarQubeSuppressedViolations, SonarQubeTests,\n+ SonarQubeUncoveredBranches, SonarQubeUncoveredLines, SonarQubeViolations)\n+from .api_source_collectors.trello import TrelloIssues, TrelloSourceUpToDateness\n+from .api_source_collectors.wekan import WekanIssues, WekanSourceUpToDateness\n+\n+from .file_source_collectors.anchore import AnchoreSecurityWarnings, AnchoreSourceUpToDateness\n+from .file_source_collectors.axe_csv import AxeCSVAccessibility\n+from .file_source_collectors.bandit import BanditSecurityWarnings, BanditSourceUpToDateness\n+from .file_source_collectors.composer import ComposerDependencies\n+from .file_source_collectors.jacoco import JacocoSourceUpToDateness, JacocoUncoveredBranches, JacocoUncoveredLines\n+from .file_source_collectors.junit import JUnitSourceUpToDateness, JUnitTests\n+from .file_source_collectors.ncover import NCoverSourceUpToDateness\n+from .file_source_collectors.ojaudit import OJAuditViolations\n+from .file_source_collectors.openvas import OpenVASSecurityWarnings, OpenVASSourceUpToDateness\n+from .file_source_collectors.owasp_dependency_check import (\n+ OWASPDependencyCheckSecurityWarnings, OWASPDependencyCheckSourceUpToDateness)\n+from .file_source_collectors.owasp_zap import OWASPZAPSecurityWarnings, OWASPZAPSourceUpToDateness\n+from .file_source_collectors.performancetest_runner import (\n PerformanceTestRunnerPerformanceTestDuration, PerformanceTestRunnerPerformanceTestStability,\n PerformanceTestRunnerScalability, PerformanceTestRunnerSlowTransactions, PerformanceTestRunnerSourceUpToDateness,\n PerformanceTestRunnerTests)\n-from .pyupio_safety import PyupioSafetySecurityWarnings\n-from .quality_time import QualityTimeMetrics\n-from .random_number import Random\n-from .robot_framework import RobotFrameworkTests, RobotFrameworkSourceUpToDateness\n-from .sonarqube import (\n- SonarQubeDuplicatedLines, SonarQubeComplexUnits, SonarQubeCommentedOutCode, SonarQubeLOC,\n- SonarQubeLongUnits, SonarQubeManyParameters, SonarQubeSourceUpToDateness, SonarQubeSuppressedViolations,\n- SonarQubeTests, SonarQubeUncoveredBranches, SonarQubeUncoveredLines, SonarQubeViolations)\n-from .trello import TrelloIssues, TrelloSourceUpToDateness\n-from .wekan import WekanIssues, WekanSourceUpToDateness\n+from .file_source_collectors.pyupio_safety import PyupioSafetySecurityWarnings\n+from .file_source_collectors.robot_framework import RobotFrameworkTests, RobotFrameworkSourceUpToDateness\n+\n+from .local_source_collectors.calendar import CalendarSourceUpToDateness\n+from .local_source_collectors.manual_number import ManualNumber\n+from .local_source_collectors.random_number import Random\ndiff --git a/components/collector/src/source_collectors/azure_devops.py b/components/collector/src/source_collectors/api_source_collectors/azure_devops.py\nsimilarity index 63%\nrename from components/collector/src/source_collectors/azure_devops.py\nrename to components/collector/src/source_collectors/api_source_collectors/azure_devops.py\n--- a/components/collector/src/source_collectors/azure_devops.py\n+++ b/components/collector/src/source_collectors/api_source_collectors/azure_devops.py\n@@ -6,14 +6,14 @@\n \n from abc import ABC\n from datetime import datetime\n-from typing import cast, Final, List, Tuple\n+from typing import cast, Any, Dict, Final, List, Tuple\n \n from dateutil.parser import parse\n-import requests\n+import aiohttp\n \n from collector_utilities.functions import days_ago, match_string_or_regular_expression\n from collector_utilities.type import Entities, Job, Response, Responses, URL, Value\n-from .source_collector import SourceCollector, SourceUpToDatenessCollector, UnmergedBranchesSourceCollector\n+from base_collectors import SourceCollector, SourceUpToDatenessCollector, UnmergedBranchesSourceCollector\n \n \n class AzureDevopsIssues(SourceCollector):\n@@ -22,43 +22,44 @@ class AzureDevopsIssues(SourceCollector):\n MAX_IDS_PER_WORK_ITEMS_API_CALL: Final[int] = 200 # See\n # https://docs.microsoft.com/en-us/rest/api/azure/devops/wit/work%20items/list?view=azure-devops-rest-5.1\n \n- def _api_url(self) -> URL:\n- return URL(f\"{super()._api_url()}/_apis/wit/wiql?api-version=4.1\")\n+ async def _api_url(self) -> URL:\n+ return URL(f\"{await super()._api_url()}/_apis/wit/wiql?api-version=4.1\")\n \n- def _get_source_responses(self, api_url: URL) -> Responses:\n+ async def _get_source_responses(self, *urls: URL) -> Responses:\n \"\"\"Override because we need to do a post request and need to separately get the entities.\"\"\"\n- auth = self._basic_auth_credentials()\n- response = requests.post(api_url, timeout=self.TIMEOUT, auth=auth, json=dict(query=self._parameter(\"wiql\")))\n- ids = [str(work_item[\"id\"]) for work_item in response.json().get(\"workItems\", [])]\n+ auth = aiohttp.BasicAuth(str(self._parameter(\"private_token\")))\n+ response = await self._session.post(urls[0], auth=auth, json=dict(query=self._parameter(\"wiql\")))\n+ ids = [str(work_item[\"id\"]) for work_item in (await response.json()).get(\"workItems\", [])]\n if not ids:\n return [response]\n ids_string = \",\".join(ids[:min(self.MAX_IDS_PER_WORK_ITEMS_API_CALL, self.MAX_ENTITIES)])\n- work_items_url = URL(f\"{super()._api_url()}/_apis/wit/workitems?ids={ids_string}&api-version=4.1\")\n- return [response, requests.get(work_items_url, timeout=self.TIMEOUT, auth=auth)]\n+ work_items_url = URL(f\"{await super()._api_url()}/_apis/wit/workitems?ids={ids_string}&api-version=4.1\")\n+ work_items = await super()._get_source_responses(work_items_url)\n+ return [response] + work_items\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- value = str(len(responses[0].json()[\"workItems\"]))\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ value = str(len((await responses[0].json())[\"workItems\"]))\n entities = [\n dict(\n key=str(work_item[\"id\"]), project=work_item[\"fields\"][\"System.TeamProject\"],\n title=work_item[\"fields\"][\"System.Title\"], work_item_type=work_item[\"fields\"][\"System.WorkItemType\"],\n state=work_item[\"fields\"][\"System.State\"], url=work_item[\"url\"])\n- for work_item in self._work_items(responses)]\n+ for work_item in await self._work_items(responses)]\n return value, \"100\", entities\n \n @staticmethod\n- def _work_items(responses: Responses):\n+ async def _work_items(responses: Responses):\n \"\"\"Return the work items, if any.\"\"\"\n- return responses[1].json()[\"value\"] if len(responses) > 1 else []\n+ return (await responses[1].json())[\"value\"] if len(responses) > 1 else []\n \n \n class AzureDevopsReadyUserStoryPoints(AzureDevopsIssues):\n \"\"\"Collector to get ready user story points from Azure Devops Server.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- _, total, entities = super()._parse_source_responses(responses)\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ _, total, entities = await super()._parse_source_responses(responses)\n value = 0\n- for entity, work_item in zip(entities, self._work_items(responses)):\n+ for entity, work_item in zip(entities, await self._work_items(responses)):\n entity[\"story_points\"] = story_points = work_item[\"fields\"].get(\"Microsoft.VSTS.Scheduling.StoryPoints\")\n value += 0 if story_points is None else story_points\n return str(round(value)), total, entities\n@@ -67,30 +68,29 @@ def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, E\n class AzureDevopsRepositoryBase(SourceCollector, ABC): # pylint: disable=abstract-method\n \"\"\"Base class for Azure DevOps collectors that work with repositories.\"\"\"\n \n- def _repository_id(self) -> str:\n+ async def _repository_id(self) -> str:\n \"\"\"Return the repository id belonging to the repository.\"\"\"\n- api_url = str(super()._api_url())\n+ api_url = str(await super()._api_url())\n repository = self._parameter(\"repository\") or api_url.rsplit(\"/\", 1)[-1]\n- repositories_url = f\"{api_url}/_apis/git/repositories?api-version=4.1\"\n- repositories = requests.get(repositories_url, timeout=self.TIMEOUT, auth=self._basic_auth_credentials())\n- repositories.raise_for_status()\n- return str([r for r in repositories.json()[\"value\"] if repository in (r[\"name\"], r[\"id\"])][0][\"id\"])\n+ repositories_url = URL(f\"{api_url}/_apis/git/repositories?api-version=4.1\")\n+ repositories = (await (await super()._get_source_responses(repositories_url))[0].json())[\"value\"]\n+ return str([r for r in repositories if repository in (r[\"name\"], r[\"id\"])][0][\"id\"])\n \n \n class AzureDevopsUnmergedBranches(UnmergedBranchesSourceCollector, AzureDevopsRepositoryBase):\n \"\"\"Collector for unmerged branches.\"\"\"\n \n- def _api_url(self) -> URL:\n- api_url = str(super()._api_url())\n- return URL(f\"{api_url}/_apis/git/repositories/{self._repository_id()}/stats/branches?api-version=4.1\")\n+ async def _api_url(self) -> URL:\n+ api_url = str(await super()._api_url())\n+ return URL(f\"{api_url}/_apis/git/repositories/{await self._repository_id()}/stats/branches?api-version=4.1\")\n \n- def _landing_url(self, responses: Responses) -> URL:\n- landing_url = str(super()._landing_url(responses))\n+ async def _landing_url(self, responses: Responses) -> URL:\n+ landing_url = str(await super()._landing_url(responses))\n repository = self._parameter(\"repository\") or landing_url.rsplit(\"/\", 1)[-1]\n return URL(f\"{landing_url}/_git/{repository}/branches\")\n \n- def _unmerged_branches(self, responses: Responses) -> List:\n- return [branch for branch in responses[0].json()[\"value\"] if not branch[\"isBaseVersion\"] and\n+ async def _unmerged_branches(self, responses: Responses) -> List[Dict[str, Any]]:\n+ return [branch for branch in (await responses[0].json())[\"value\"] if not branch[\"isBaseVersion\"] and\n int(branch[\"aheadCount\"]) > 0 and\n days_ago(self._commit_datetime(branch)) > int(cast(str, self._parameter(\"inactive_days\"))) and\n not match_string_or_regular_expression(branch[\"name\"], self._parameter(\"branches_to_ignore\"))]\n@@ -102,35 +102,36 @@ def _commit_datetime(self, branch) -> datetime:\n class AzureDevopsSourceUpToDateness(SourceUpToDatenessCollector, AzureDevopsRepositoryBase):\n \"\"\"Collector class to measure the up-to-dateness of a repo or folder/file in a repo.\"\"\"\n \n- def _api_url(self) -> URL:\n- api_url = str(super()._api_url())\n- repository_id = self._repository_id()\n+ async def _api_url(self) -> URL:\n+ api_url = str(await super()._api_url())\n+ repository_id = await self._repository_id()\n path = self._parameter(\"file_path\", quote=True)\n branch = self._parameter(\"branch\", quote=True)\n search_criteria = \\\n f\"searchCriteria.itemPath={path}&searchCriteria.itemVersion.version={branch}&searchCriteria.$top=1\"\n return URL(f\"{api_url}/_apis/git/repositories/{repository_id}/commits?{search_criteria}&api-version=4.1\")\n \n- def _landing_url(self, responses: Responses) -> URL:\n- landing_url = str(super()._landing_url(responses))\n+ async def _landing_url(self, responses: Responses) -> URL:\n+ landing_url = str(await super()._landing_url(responses))\n repository = self._parameter(\"repository\") or landing_url.rsplit(\"/\", 1)[-1]\n path = self._parameter(\"file_path\", quote=True)\n branch = self._parameter(\"branch\", quote=True)\n return URL(f\"{landing_url}/_git/{repository}?path={path}&version=GB{branch}\")\n \n- def _parse_source_response_date_time(self, response: Response) -> datetime:\n- return parse(response.json()[\"value\"][0][\"committer\"][\"date\"])\n+ async def _parse_source_response_date_time(self, response: Response) -> datetime:\n+ return parse((await response.json())[\"value\"][0][\"committer\"][\"date\"])\n \n \n class AzureDevopsTests(SourceCollector):\n \"\"\"Collector for the tests metric.\"\"\"\n \n- def _api_url(self) -> URL:\n- return URL(f\"{super()._api_url()}/_apis/test/runs?automated=true&includeRunDetails=true&$top=1&api-version=5.1\")\n+ async def _api_url(self) -> URL:\n+ api_url = await super()._api_url()\n+ return URL(f\"{api_url}/_apis/test/runs?automated=true&includeRunDetails=true&$top=1&api-version=5.1\")\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n test_results = cast(List[str], self._parameter(\"test_result\"))\n- runs = responses[0].json().get(\"value\", [])\n+ runs = (await responses[0].json()).get(\"value\", [])\n test_count, highest_build_nr_seen = 0, 0\n for run in runs:\n build_nr = int(run.get(\"build\", {}).get(\"id\", \"-1\"))\n@@ -143,18 +144,18 @@ def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, E\n return str(test_count), \"100\", []\n \n \n-class AxureDevopsJobs(SourceCollector):\n+class AzureDevopsJobs(SourceCollector):\n \"\"\"Base class for job collectors.\"\"\"\n \n- def _api_url(self) -> URL:\n- return URL(f\"{super()._api_url()}/_apis/build/definitions?includeLatestBuilds=true&api-version=4.1\")\n+ async def _api_url(self) -> URL:\n+ return URL(f\"{await super()._api_url()}/_apis/build/definitions?includeLatestBuilds=true&api-version=4.1\")\n \n- def _landing_url(self, responses: Responses) -> URL:\n- return URL(f\"{super()._api_url()}/_build\")\n+ async def _landing_url(self, responses: Responses) -> URL:\n+ return URL(f\"{await super()._api_url()}/_build\")\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n entities: Entities = []\n- for job in responses[0].json()[\"value\"]:\n+ for job in (await responses[0].json())[\"value\"]:\n if self._ignore_job(job):\n continue\n name = self.__job_name(job)\n@@ -190,7 +191,7 @@ def __job_name(job: Job) -> str:\n return \"/\".join(job[\"path\"].strip(r\"\\\\\").split(r\"\\\\\") + [job[\"name\"]]).strip(\"/\")\n \n \n-class AzureDevopsFailedJobs(AxureDevopsJobs):\n+class AzureDevopsFailedJobs(AzureDevopsJobs):\n \"\"\"Collector for the failed jobs metric.\"\"\"\n \n def _ignore_job(self, job: Job) -> bool:\n@@ -199,7 +200,7 @@ def _ignore_job(self, job: Job) -> bool:\n return self._latest_build_result(job) not in self._parameter(\"failure_type\")\n \n \n-class AzureDevopsUnusedJobs(AxureDevopsJobs):\n+class AzureDevopsUnusedJobs(AzureDevopsJobs):\n \"\"\"Collector for the unused jobs metric.\"\"\"\n \n def _ignore_job(self, job: Job) -> bool:\ndiff --git a/components/collector/src/source_collectors/api_source_collectors/cxsast.py b/components/collector/src/source_collectors/api_source_collectors/cxsast.py\nnew file mode 100644\n--- /dev/null\n+++ b/components/collector/src/source_collectors/api_source_collectors/cxsast.py\n@@ -0,0 +1,85 @@\n+\"\"\"Collectors for the Checkmarx CxSAST product.\"\"\"\n+\n+from abc import ABC\n+from typing import cast, Dict, Optional, Tuple\n+\n+from dateutil.parser import parse\n+import aiohttp\n+\n+from collector_utilities.type import Entities, Response, Responses, URL, Value\n+from collector_utilities.functions import days_ago\n+from base_collectors import SourceCollector\n+\n+\n+class CxSASTBase(SourceCollector, ABC): # pylint: disable=abstract-method\n+ \"\"\"Base class for CxSAST collectors.\"\"\"\n+\n+ def __init__(self, *args, **kwargs) -> None:\n+ self.__token: Optional[str] = None\n+ self.__project_id: Optional[str] = None\n+ self._scan_id: Optional[str] = None\n+ super().__init__(*args, **kwargs)\n+\n+ def _headers(self) -> Dict[str, str]:\n+ headers = super()._headers()\n+ headers[\"Authorization\"] = f\"Bearer {self.__token}\"\n+ return headers\n+\n+ def _basic_auth_credentials(self) -> Optional[Tuple[str, str]]:\n+ return None\n+\n+ async def _landing_url(self, responses: Responses) -> URL:\n+ api_url = await self._api_url()\n+ return URL(f\"{api_url}/CxWebClient/ViewerMain.aspx?scanId={self._scan_id}&ProjectID={self.__project_id}\") \\\n+ if responses else api_url\n+\n+ async def _get_source_responses(self, *urls: URL) -> Responses:\n+ \"\"\"Override because we need to do multiple requests to get all the data we need.\"\"\"\n+ # See https://checkmarx.atlassian.net/wiki/spaces/KC/pages/1187774721/Using+the+CxSAST+REST+API+v8.6.0+and+up\n+ credentials = dict( # nosec, The client secret is not really secret, see previous url\n+ username=cast(str, self._parameter(\"username\")),\n+ password=cast(str, self._parameter(\"password\")),\n+ grant_type=\"password\", scope=\"sast_rest_api\", client_id=\"resource_owner_client\",\n+ client_secret=\"014DF517-39D1-4453-B7B3-9930C563627C\")\n+ token_response = await self.__api_post(\"auth/identity/connect/token\", credentials)\n+ self.__token = (await token_response.json())['access_token']\n+ project_api = URL(f\"{await self._api_url()}/cxrestapi/projects\")\n+ project_response = (await super()._get_source_responses(project_api))[0]\n+ self.__project_id = await self.__get_project_id(project_response)\n+ scan_api = URL(\n+ f\"{await self._api_url()}/cxrestapi/sast/scans?projectId={self.__project_id}&scanStatus=Finished&last=1\")\n+ scan_response = (await super()._get_source_responses(scan_api))[0]\n+ self._scan_id = (await scan_response.json())[0][\"id\"]\n+ return [scan_response]\n+\n+ async def __get_project_id(self, project_response: Response) -> str:\n+ \"\"\"Return the project id that belongs to the project parameter.\"\"\"\n+ project_name_or_id = self._parameter(\"project\")\n+ projects = await project_response.json()\n+ return str([project for project in projects if project_name_or_id in (project[\"name\"], project[\"id\"])][0][\"id\"])\n+\n+ async def __api_post(self, api: str, data) -> aiohttp.ClientResponse:\n+ \"\"\"Post to the API and return the response.\"\"\"\n+ return await self._session.post(f\"{await self._api_url()}/cxrestapi/{api}\", data=data)\n+\n+\n+class CxSASTSourceUpToDateness(CxSASTBase):\n+ \"\"\"Collector class to measure the up-to-dateness of a Checkmarx CxSAST scan.\"\"\"\n+\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ scan = (await responses[0].json())[0]\n+ return str(days_ago(parse(scan[\"dateAndTime\"][\"finishedOn\"]))), \"100\", []\n+\n+\n+class CxSASTSecurityWarnings(CxSASTBase):\n+ \"\"\"Collector class to measure the number of security warnings in a Checkmarx CxSAST scan.\"\"\"\n+\n+ async def _get_source_responses(self, *urls: URL) -> Responses:\n+ await super()._get_source_responses(*urls) # Get token\n+ stats_api = URL(f\"{await self._api_url()}/cxrestapi/sast/scans/{self._scan_id}/resultsStatistics\")\n+ return await SourceCollector._get_source_responses(self, stats_api) # pylint: disable=protected-access\n+\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ stats = await responses[0].json()\n+ severities = self._parameter(\"severities\")\n+ return str(sum(stats.get(f\"{severity.lower()}Severity\", 0) for severity in severities)), \"100\", []\ndiff --git a/components/collector/src/source_collectors/gitlab.py b/components/collector/src/source_collectors/api_source_collectors/gitlab.py\nsimilarity index 56%\nrename from components/collector/src/source_collectors/gitlab.py\nrename to components/collector/src/source_collectors/api_source_collectors/gitlab.py\n--- a/components/collector/src/source_collectors/gitlab.py\n+++ b/components/collector/src/source_collectors/api_source_collectors/gitlab.py\n@@ -1,24 +1,25 @@\n \"\"\"GitLab metric source.\"\"\"\n \n+import asyncio\n+import itertools\n from abc import ABC\n from datetime import datetime\n-from typing import cast, Iterator, List, Optional, Set, Tuple\n+from typing import cast, Any, Dict, List, Optional, Set, Sequence, Tuple\n from urllib.parse import quote\n \n from dateutil.parser import parse\n-import requests\n \n from collector_utilities.functions import days_ago, match_string_or_regular_expression\n-from collector_utilities.type import Job, Entities, Response, Responses, URL, Value\n-from .source_collector import SourceCollector, UnmergedBranchesSourceCollector\n+from collector_utilities.type import Job, Entities, Responses, URL, Value\n+from base_collectors import SourceCollector, UnmergedBranchesSourceCollector\n \n \n class GitLabBase(SourceCollector, ABC): # pylint: disable=abstract-method\n \"\"\"Base class for GitLab collectors.\"\"\"\n \n- def _gitlab_api_url(self, api: str) -> URL:\n+ async def _gitlab_api_url(self, api: str) -> URL:\n \"\"\"Return a GitLab API url with private token, if present in the parameters.\"\"\"\n- url = super()._api_url()\n+ url = await super()._api_url()\n project = self._parameter(\"project\", quote=True)\n api_url = f\"{url}/api/v4/projects/{project}/{api}\"\n sep = \"&\" if \"?\" in api_url else \"?\"\n@@ -34,29 +35,32 @@ def _basic_auth_credentials(self) -> Optional[Tuple[str, str]]:\n class GitLabJobsBase(GitLabBase):\n \"\"\"Base class for GitLab job collectors.\"\"\"\n \n- def _api_url(self) -> URL:\n- return self._gitlab_api_url(\"jobs\")\n+ async def _api_url(self) -> URL:\n+ return await self._gitlab_api_url(\"jobs\")\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ jobs = await self.__jobs(responses)\n entities = [\n dict(\n key=job[\"id\"], name=job[\"name\"], url=job[\"web_url\"], build_status=job[\"status\"], branch=job[\"ref\"],\n stage=job[\"stage\"], build_date=str((build_date := parse(job[\"created_at\"])).date()),\n build_age=str(days_ago(build_date)))\n- for job in self.__jobs(responses)]\n+ for job in jobs]\n return str(len(entities)), \"100\", entities\n \n- def __jobs(self, responses: Responses) -> Iterator[Job]:\n+ async def __jobs(self, responses: Responses) -> Sequence[Job]:\n \"\"\"Return the jobs to count.\"\"\"\n+ jobs: List[Job] = []\n jobs_seen: Set[Tuple[str, str, str]] = set()\n for response in responses:\n- for job in response.json():\n+ for job in await response.json():\n job_fingerprint = job[\"name\"], job[\"stage\"], job[\"ref\"]\n if job_fingerprint in jobs_seen:\n continue\n jobs_seen.add(job_fingerprint)\n if self._count_job(job):\n- yield job\n+ jobs.append(job)\n+ return jobs\n \n def _count_job(self, job: Job) -> bool: # pylint: disable=no-self-use,unused-argument\n \"\"\"Return whether to count the job.\"\"\"\n@@ -84,66 +88,67 @@ def _count_job(self, job: Job) -> bool:\n class GitLabSourceUpToDateness(GitLabBase):\n \"\"\"Collector class to measure the up-to-dateness of a repo or folder/file in a repo.\"\"\"\n \n- def _api_url(self) -> URL:\n- return self._gitlab_api_url(\"\")\n+ async def _api_url(self) -> URL:\n+ return await self._gitlab_api_url(\"\")\n \n- def _landing_url(self, responses: Responses) -> URL:\n- return URL(\n- f\"{responses[0].json()['web_url']}/blob/{self._parameter('branch', quote=True)}/\"\n- f\"{self._parameter('file_path', quote=True)}\") if responses else super()._landing_url(responses)\n+ async def _landing_url(self, responses: Responses) -> URL:\n+ if not responses:\n+ return await super()._landing_url(responses)\n+ web_url = (await responses[0].json())[\"web_url\"]\n+ branch = self._parameter('branch', quote=True)\n+ file_path = self._parameter('file_path', quote=True)\n+ return URL(f\"{web_url}/blob/{branch}/{file_path}\")\n \n- def _get_source_responses(self, api_url: URL) -> Responses:\n+ async def _get_source_responses(self, *urls: URL) -> Responses:\n \"\"\"Override to get the last commit metadata of the file or, if the file is a folder, of the files in the folder,\n recursively.\"\"\"\n \n- def get_commits_recursively(file_path: str, first_call: bool = True) -> Responses:\n+ async def get_commits_recursively(file_path: str, first_call: bool = True) -> Responses:\n \"\"\"Get the commits of files recursively.\"\"\"\n- tree_api = self._gitlab_api_url(\n+ tree_api = await self._gitlab_api_url(\n f\"repository/tree?path={file_path}&ref={self._parameter('branch', quote=True)}\")\n- tree_response = super(GitLabSourceUpToDateness, self)._get_source_responses(tree_api)[0]\n- tree_response.raise_for_status()\n- tree = tree_response.json()\n+ tree_response = (await super(GitLabSourceUpToDateness, self)._get_source_responses(tree_api))[0]\n+ tree = await tree_response.json()\n file_paths = [quote(item[\"path\"], safe=\"\") for item in tree if item[\"type\"] == \"blob\"]\n folder_paths = [quote(item[\"path\"], safe=\"\") for item in tree if item[\"type\"] == \"tree\"]\n if not tree and first_call:\n file_paths = [file_path]\n- commit_responses = [self.__last_commit(file_path) for file_path in file_paths]\n- for folder_path in folder_paths:\n- commit_responses.extend(get_commits_recursively(folder_path, first_call=False))\n- return commit_responses\n+ commits = [self.__last_commit(file_path) for file_path in file_paths] + \\\n+ [get_commits_recursively(folder_path, first_call=False) for folder_path in folder_paths]\n+ return list(itertools.chain(*(await asyncio.gather(*commits))))\n \n # First, get the project info so we can use the web url as landing url\n- responses = super()._get_source_responses(api_url)\n- responses[0].raise_for_status()\n+ responses = await super()._get_source_responses(*urls)\n # Then, collect the commits\n- responses.extend(get_commits_recursively(str(self._parameter(\"file_path\", quote=True))))\n+ responses.extend(await get_commits_recursively(str(self._parameter(\"file_path\", quote=True))))\n return responses\n \n- def __last_commit(self, file_path: str) -> Response:\n- files_api_url = self._gitlab_api_url(\n+ async def __last_commit(self, file_path: str) -> Responses:\n+ files_api_url = await self._gitlab_api_url(\n f\"repository/files/{file_path}?ref={self._parameter('branch', quote=True)}\")\n- response = requests.head(files_api_url)\n+ response = await self._session.head(files_api_url)\n last_commit_id = response.headers[\"X-Gitlab-Last-Commit-Id\"]\n- commit_api_url = self._gitlab_api_url(f\"repository/commits/{last_commit_id}\")\n- return requests.get(commit_api_url, timeout=self.TIMEOUT, auth=self._basic_auth_credentials())\n+ commit_api_url = await self._gitlab_api_url(f\"repository/commits/{last_commit_id}\")\n+ return await super()._get_source_responses(commit_api_url)\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n commit_responses = responses[1:]\n- value = str(days_ago(max(parse(response.json()[\"committed_date\"]) for response in commit_responses)))\n+ value = str(days_ago(max([parse((await response.json())[\"committed_date\"]) for response in commit_responses])))\n return value, \"100\", []\n \n \n class GitLabUnmergedBranches(GitLabBase, UnmergedBranchesSourceCollector):\n \"\"\"Collector class to measure the number of unmerged branches.\"\"\"\n \n- def _api_url(self) -> URL:\n- return self._gitlab_api_url(\"repository/branches\")\n+ async def _api_url(self) -> URL:\n+ return await self._gitlab_api_url(\"repository/branches\")\n \n- def _landing_url(self, responses: Responses) -> URL:\n- return URL(f\"{str(super()._landing_url(responses))}/{self._parameter('project')}/-/branches\")\n+ async def _landing_url(self, responses: Responses) -> URL:\n+ return URL(f\"{str(await super()._landing_url(responses))}/{self._parameter('project')}/-/branches\")\n \n- def _unmerged_branches(self, responses: Responses) -> List:\n- return [branch for branch in responses[0].json() if not branch[\"default\"] and not branch[\"merged\"] and\n+ async def _unmerged_branches(self, responses: Responses) -> List[Dict[str, Any]]:\n+ branches = await responses[0].json()\n+ return [branch for branch in branches if not branch[\"default\"] and not branch[\"merged\"] and\n days_ago(self._commit_datetime(branch)) > int(cast(str, self._parameter(\"inactive_days\"))) and\n not match_string_or_regular_expression(branch[\"name\"], self._parameter(\"branches_to_ignore\"))]\n \ndiff --git a/components/collector/src/source_collectors/jacoco_jenkins_plugin.py b/components/collector/src/source_collectors/api_source_collectors/jacoco_jenkins_plugin.py\nsimilarity index 51%\nrename from components/collector/src/source_collectors/jacoco_jenkins_plugin.py\nrename to components/collector/src/source_collectors/api_source_collectors/jacoco_jenkins_plugin.py\n--- a/components/collector/src/source_collectors/jacoco_jenkins_plugin.py\n+++ b/components/collector/src/source_collectors/api_source_collectors/jacoco_jenkins_plugin.py\n@@ -1,18 +1,17 @@\n \"\"\"Jacoco Jenkins plugin coverage report collector.\"\"\"\n \n-from datetime import datetime\n from typing import Tuple\n \n-from collector_utilities.type import Entities, Response, Responses, URL, Value\n+from collector_utilities.type import Entities, Responses, URL, Value\n \n-from .source_collector import SourceCollector, SourceUpToDatenessCollector\n+from base_collectors import JenkinsPluginSourceUpToDatenessCollector, SourceCollector\n \n \n class JacocoJenkinsPluginBaseClass(SourceCollector):\n \"\"\"Base class for Jacoco Jenkins plugin collectors.\"\"\"\n \n- def _landing_url(self, responses: Responses) -> URL:\n- return URL(f\"{super()._api_url()}/lastSuccessfulBuild/jacoco\")\n+ async def _landing_url(self, responses: Responses) -> URL:\n+ return URL(f\"{await super()._api_url()}/lastSuccessfulBuild/jacoco\")\n \n \n class JacocoJenkinsPluginCoverageBaseClass(JacocoJenkinsPluginBaseClass):\n@@ -20,11 +19,11 @@ class JacocoJenkinsPluginCoverageBaseClass(JacocoJenkinsPluginBaseClass):\n \n coverage_type = \"subclass responsibility\"\n \n- def _api_url(self) -> URL:\n- return URL(f\"{super()._api_url()}/lastSuccessfulBuild/jacoco/api/json\")\n+ async def _api_url(self) -> URL:\n+ return URL(f\"{await super()._api_url()}/lastSuccessfulBuild/jacoco/api/json\")\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- line_coverage = responses[0].json()[f\"{self.coverage_type}Coverage\"]\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ line_coverage = (await responses[0].json())[f\"{self.coverage_type}Coverage\"]\n return str(line_coverage[\"missed\"]), str(line_coverage[\"total\"]), []\n \n \n@@ -40,11 +39,5 @@ class JacocoJenkinsPluginUncoveredBranches(JacocoJenkinsPluginCoverageBaseClass)\n coverage_type = \"branch\"\n \n \n-class JacocoJenkinsPluginSourceUpToDateness(JacocoJenkinsPluginBaseClass, SourceUpToDatenessCollector):\n+class JacocoJenkinsPluginSourceUpToDateness(JacocoJenkinsPluginBaseClass, JenkinsPluginSourceUpToDatenessCollector):\n \"\"\"Collector for the up to dateness of the Jacoco Jenkins plugin coverage report.\"\"\"\n-\n- def _api_url(self) -> URL:\n- return URL(f\"{super()._api_url()}/lastSuccessfulBuild/api/json\")\n-\n- def _parse_source_response_date_time(self, response: Response) -> datetime:\n- return datetime.fromtimestamp(float(response.json()[\"timestamp\"]) / 1000.)\ndiff --git a/components/collector/src/source_collectors/jenkins.py b/components/collector/src/source_collectors/api_source_collectors/jenkins.py\nsimilarity index 91%\nrename from components/collector/src/source_collectors/jenkins.py\nrename to components/collector/src/source_collectors/api_source_collectors/jenkins.py\n--- a/components/collector/src/source_collectors/jenkins.py\n+++ b/components/collector/src/source_collectors/api_source_collectors/jenkins.py\n@@ -5,24 +5,24 @@\n \n from collector_utilities.functions import days_ago, match_string_or_regular_expression\n from collector_utilities.type import Job, Jobs, Entities, Responses, URL, Value\n-from .source_collector import SourceCollector\n+from base_collectors import SourceCollector\n \n \n class JenkinsJobs(SourceCollector):\n \"\"\"Collector to get job counts from Jenkins.\"\"\"\n \n- def _api_url(self) -> URL:\n- url = super()._api_url()\n+ async def _api_url(self) -> URL:\n+ url = await super()._api_url()\n job_attrs = \"buildable,color,url,name,builds[result,timestamp]\"\n return URL(f\"{url}/api/json?tree=jobs[{job_attrs},jobs[{job_attrs},jobs[{job_attrs}]]]\")\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n entities = [\n dict(\n key=job[\"name\"], name=job[\"name\"], url=job[\"url\"], build_status=self._build_status(job),\n build_age=str(days_ago(self._build_datetime(job))) if self._build_datetime(job) > datetime.min else \"\",\n build_date=str(self._build_datetime(job).date()) if self._build_datetime(job) > datetime.min else \"\")\n- for job in self.__jobs(responses[0].json()[\"jobs\"])]\n+ for job in self.__jobs((await responses[0].json())[\"jobs\"])]\n return str(len(entities)), \"100\", entities\n \n def __jobs(self, jobs: Jobs, parent_job_name: str = \"\") -> Iterator[Job]:\ndiff --git a/components/collector/src/source_collectors/jira.py b/components/collector/src/source_collectors/api_source_collectors/jira.py\nsimilarity index 82%\nrename from components/collector/src/source_collectors/jira.py\nrename to components/collector/src/source_collectors/api_source_collectors/jira.py\n--- a/components/collector/src/source_collectors/jira.py\n+++ b/components/collector/src/source_collectors/api_source_collectors/jira.py\n@@ -6,7 +6,7 @@\n \n from collector_utilities.functions import days_ago\n from collector_utilities.type import Entity, Entities, Responses, URL, Value\n-from .source_collector import SourceCollector\n+from base_collectors import SourceCollector\n \n \n class JiraIssues(SourceCollector):\n@@ -16,14 +16,14 @@ def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._field_ids = {}\n \n- def _api_url(self) -> URL:\n- url = super()._api_url()\n+ async def _api_url(self) -> URL:\n+ url = await super()._api_url()\n jql = str(self._parameter(\"jql\", quote=True))\n fields = self._fields()\n return URL(f\"{url}/rest/api/2/search?jql={jql}&fields={fields}&maxResults=500\")\n \n- def _landing_url(self, responses: Responses) -> URL:\n- url = super()._landing_url(responses)\n+ async def _landing_url(self, responses: Responses) -> URL:\n+ url = await super()._landing_url(responses)\n jql = str(self._parameter(\"jql\", quote=True))\n return URL(f\"{url}/issues/?jql={jql}\")\n \n@@ -33,16 +33,15 @@ def _parameter(self, parameter_key: str, quote: bool = False) -> Union[str, List\n parameter_value = self._field_ids.get(parameter_value, parameter_value)\n return parameter_value\n \n- def _get_source_responses(self, api_url: URL) -> Responses:\n- fields_url = URL(f\"{super()._api_url()}/rest/api/2/field\")\n- response = super()._get_source_responses(fields_url)[0]\n- response.raise_for_status()\n- self._field_ids = dict((field[\"name\"], field[\"id\"]) for field in response.json())\n- return super()._get_source_responses(api_url)\n+ async def _get_source_responses(self, *urls: URL) -> Responses:\n+ fields_url = URL(f\"{await super()._api_url()}/rest/api/2/field\")\n+ response = (await super()._get_source_responses(fields_url))[0]\n+ self._field_ids = dict((field[\"name\"], field[\"id\"]) for field in await response.json())\n+ return await super()._get_source_responses(*urls)\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n url = URL(str(self._parameter(\"url\")))\n- json = responses[0].json()\n+ json = await responses[0].json()\n entities = [self._create_entity(issue, url) for issue in json.get(\"issues\", []) if self._include_issue(issue)]\n return str(json.get(\"total\", 0)), \"100\", entities\n \n@@ -62,8 +61,8 @@ def _fields(self) -> str: # pylint: disable=no-self-use\n class JiraManualTestExecution(JiraIssues):\n \"\"\"Collector for the number of manual test cases that have not been executed recently enough.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- _, total, entities = super()._parse_source_responses(responses)\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ _, total, entities = await super()._parse_source_responses(responses)\n return str(len(entities)), total, entities\n \n def _create_entity(self, issue: Dict, url: URL) -> Entity:\n@@ -97,8 +96,8 @@ class JiraFieldSumBase(JiraIssues):\n field_parameter = \"subclass responsibility\"\n entity_key = \"subclass responsibility\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- _, total, entities = super()._parse_source_responses(responses)\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ _, total, entities = await super()._parse_source_responses(responses)\n value = str(round(sum(float(entity[self.entity_key]) for entity in entities)))\n return value, total, entities\n \ndiff --git a/components/collector/src/source_collectors/owasp_dependency_check_jenkins_plugin.py b/components/collector/src/source_collectors/api_source_collectors/owasp_dependency_check_jenkins_plugin.py\nsimilarity index 61%\nrename from components/collector/src/source_collectors/owasp_dependency_check_jenkins_plugin.py\nrename to components/collector/src/source_collectors/api_source_collectors/owasp_dependency_check_jenkins_plugin.py\n--- a/components/collector/src/source_collectors/owasp_dependency_check_jenkins_plugin.py\n+++ b/components/collector/src/source_collectors/api_source_collectors/owasp_dependency_check_jenkins_plugin.py\n@@ -1,23 +1,23 @@\n \"\"\"OWASP Dependency Check Jenkins plugin metric collector.\"\"\"\n \n-from datetime import datetime\n from typing import Dict, Tuple\n \n-from collector_utilities.type import Entities, Entity, Response, Responses, Value, URL\n-from .source_collector import SourceCollector, SourceUpToDatenessCollector\n+from collector_utilities.type import Entities, Entity, Responses, Value, URL\n+from base_collectors import JenkinsPluginSourceUpToDatenessCollector, SourceCollector\n \n \n class OWASPDependencyCheckJenkinsPluginSecurityWarnings(SourceCollector):\n \"\"\"OWASP Dependency Check Jenkins plugin security warnings collector.\"\"\"\n \n- def _api_url(self) -> URL:\n- return URL(f\"{super()._api_url()}/lastSuccessfulBuild/dependency-check-jenkins-pluginResult/api/json?depth=1\")\n+ async def _api_url(self) -> URL:\n+ api_url = await super()._api_url()\n+ return URL(f\"{api_url}/lastSuccessfulBuild/dependency-check-jenkins-pluginResult/api/json?depth=1\")\n \n- def _landing_url(self, responses: Responses) -> URL:\n- return URL(f\"{super()._api_url()}/lastSuccessfulBuild/dependency-check-jenkins-pluginResult\")\n+ async def _landing_url(self, responses: Responses) -> URL:\n+ return URL(f\"{await super()._api_url()}/lastSuccessfulBuild/dependency-check-jenkins-pluginResult\")\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- json = responses[0].json()\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ json = await responses[0].json()\n severities = self._parameter(\"severities\")\n warnings = [warning for warning in json.get(\"warnings\", []) if warning[\"priority\"].lower() in severities]\n entities: Dict[str, Entity] = dict()\n@@ -39,11 +39,5 @@ def __highest_severity(self, severity1: str, severity2: str) -> str:\n return severity1 if severities.index(severity1) >= severities.index(severity2) else severity2\n \n \n-class OWASPDependencyCheckJenkinsPluginSourceUpToDateness(SourceUpToDatenessCollector):\n+class OWASPDependencyCheckJenkinsPluginSourceUpToDateness(JenkinsPluginSourceUpToDatenessCollector):\n \"\"\"Collector to get the age of the OWASP Dependency Check Jenkins plugin report.\"\"\"\n-\n- def _api_url(self) -> URL:\n- return URL(f\"{super()._api_url()}/lastSuccessfulBuild/api/json\")\n-\n- def _parse_source_response_date_time(self, response: Response) -> datetime:\n- return datetime.fromtimestamp(float(response.json()[\"timestamp\"]) / 1000.)\ndiff --git a/components/collector/src/source_collectors/quality_time.py b/components/collector/src/source_collectors/api_source_collectors/quality_time.py\nsimilarity index 71%\nrename from components/collector/src/source_collectors/quality_time.py\nrename to components/collector/src/source_collectors/api_source_collectors/quality_time.py\n--- a/components/collector/src/source_collectors/quality_time.py\n+++ b/components/collector/src/source_collectors/api_source_collectors/quality_time.py\n@@ -1,42 +1,43 @@\n \"\"\"Collector for Quality-time.\"\"\"\n \n-from functools import lru_cache\n from typing import Any, Dict, List, Tuple\n from urllib import parse\n \n from collector_utilities.type import Entity, Entities, Measurement, Response, Responses, URL, Value\n-from .source_collector import SourceCollector\n+from base_collectors import SourceCollector\n \n \n class QualityTimeMetrics(SourceCollector):\n \"\"\"Collector to get the \"metrics\" metric from Quality-time.\"\"\"\n \n- def _api_url(self) -> URL:\n- parts = parse.urlsplit(super()._api_url())\n+ def __init__(self, *args, **kwargs):\n+ self.__metrics_and_entities: List[Tuple[Dict[str, Dict], Entity]] = []\n+ super().__init__(*args, **kwargs)\n+\n+ async def _api_url(self) -> URL:\n+ parts = parse.urlsplit(await super()._api_url())\n netloc = f\"{parts.netloc.split(':')[0]}\"\n return URL(parse.urlunsplit((parts.scheme, netloc, \"/api/v2\", \"\", \"\")))\n \n- def _get_source_responses(self, api_url: URL) -> Responses:\n+ async def _get_source_responses(self, *urls: URL) -> Responses:\n # First, get the report(s):\n- responses = super()._get_source_responses(URL(f\"{api_url}/reports\"))\n+ responses = await super()._get_source_responses(URL(f\"{urls[0]}/reports\"))\n # Then, add the measurements for each of the applicable metrics:\n- for _, entity in self.__get_metrics_and_entities(responses[0]):\n- responses.extend(super()._get_source_responses(URL(f\"{api_url}/measurements/{entity['key']}\")))\n- return responses\n+ self.__metrics_and_entities = await self.__get_metrics_and_entities(responses[0])\n+ measurement_urls = [URL(f\"{urls[0]}/measurements/{entity['key']}\") for _, entity in self.__metrics_and_entities]\n+ return responses + await super()._get_source_responses(*measurement_urls)\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- metrics_and_entities = self.__get_metrics_and_entities(responses[0])\n- entities = self.__get_entities(responses[1:], metrics_and_entities)\n- return str(len(entities)), str(len(metrics_and_entities)), entities\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ entities = await self.__get_entities(responses[1:])\n+ return str(len(entities)), str(len(self.__metrics_and_entities)), entities\n \n- def __get_entities(\n- self, responses: Responses, metrics_and_entities: List[Tuple[Dict[str, Dict], Entity]]) -> Entities:\n+ async def __get_entities(self, responses: Responses) -> Entities:\n \"\"\"Get the metric entities from the responses.\"\"\"\n- last_measurements = self.__get_last_measurements(responses)\n+ last_measurements = await self.__get_last_measurements(responses)\n status_to_count = self._parameter(\"status\")\n- landing_url = self._landing_url(responses)\n+ landing_url = await self._landing_url(responses)\n entities: Entities = []\n- for metric, entity in metrics_and_entities:\n+ for metric, entity in self.__metrics_and_entities:\n status, value = self.__get_status_and_value(metric, last_measurements.get(str(entity[\"key\"]), {}))\n if status in status_to_count:\n entity[\"report_url\"] = report_url = f\"{landing_url}/{metric['report_uuid']}\"\n@@ -54,11 +55,11 @@ def __get_entities(\n return entities\n \n @staticmethod\n- def __get_last_measurements(responses: Responses) -> Dict[str, Measurement]:\n+ async def __get_last_measurements(responses: Responses) -> Dict[str, Measurement]:\n \"\"\"Return the last measurements by metric UUID for easy lookup.\"\"\"\n last_measurements = dict()\n for response in responses:\n- if measurements := response.json()[\"measurements\"]:\n+ if measurements := (await response.json())[\"measurements\"]:\n last_measurement = measurements[-1]\n last_measurements[last_measurement[\"metric_uuid\"]] = last_measurement\n return last_measurements\n@@ -70,14 +71,13 @@ def __get_status_and_value(metric, measurement: Measurement) -> Tuple[str, Value\n scale_data = measurement.get(scale, {})\n return scale_data.get(\"status\") or \"unknown\", scale_data.get(\"value\")\n \n- @lru_cache(maxsize=2)\n- def __get_metrics_and_entities(self, response: Response) -> List[Tuple[Dict[str, Dict], Entity]]:\n+ async def __get_metrics_and_entities(self, response: Response) -> List[Tuple[Dict[str, Dict], Entity]]:\n \"\"\"Get the relevant metrics from the reports response.\"\"\"\n tags = set(self._parameter(\"tags\"))\n metric_types = self._parameter(\"metric_type\")\n source_types = set(self._parameter(\"source_type\"))\n metrics_and_entities = []\n- for report in self.__get_reports(response):\n+ for report in await self.__get_reports(response):\n for subject_uuid, subject in report.get(\"subjects\", {}).items():\n for metric_uuid, metric in subject.get(\"metrics\", {}).items():\n if self.__metric_is_to_be_measured(metric, metric_types, source_types, tags):\n@@ -87,10 +87,10 @@ def __get_metrics_and_entities(self, response: Response) -> List[Tuple[Dict[str,\n metrics_and_entities.append((metric, entity))\n return metrics_and_entities\n \n- def __get_reports(self, response) -> List[Dict[str, Any]]:\n+ async def __get_reports(self, response: Response) -> List[Dict[str, Any]]:\n \"\"\"Get the relevant reports from the reports response.\"\"\"\n report_titles_or_ids = set(self._parameter(\"reports\"))\n- reports = list(response.json()[\"reports\"])\n+ reports = list((await response.json())[\"reports\"])\n return [report for report in reports if (report_titles_or_ids & {report[\"title\"], report[\"report_uuid\"]})] \\\n if report_titles_or_ids else reports\n \ndiff --git a/components/collector/src/source_collectors/sonarqube.py b/components/collector/src/source_collectors/api_source_collectors/sonarqube.py\nsimilarity index 69%\nrename from components/collector/src/source_collectors/sonarqube.py\nrename to components/collector/src/source_collectors/api_source_collectors/sonarqube.py\n--- a/components/collector/src/source_collectors/sonarqube.py\n+++ b/components/collector/src/source_collectors/api_source_collectors/sonarqube.py\n@@ -4,26 +4,29 @@\n from typing import Dict, List, Tuple\n \n from dateutil.parser import isoparse\n-import requests\n \n from collector_utilities.type import URL, Entities, Entity, Response, Responses, Value\n-from .source_collector import SourceCollector, SourceUpToDatenessCollector\n+from base_collectors import SourceCollector, SourceUpToDatenessCollector\n+\n+\n+class SonarQubeException(Exception):\n+ \"\"\"Something went wrong collecting information from SonarQube.\"\"\"\n \n \n class SonarQubeCollector(SourceCollector):\n \"\"\"Base class for SonarQube collectors.\"\"\"\n \n- def _get_source_responses(self, api_url: URL) -> Responses:\n+ async def _get_source_responses(self, *urls: URL) -> Responses:\n # SonarQube sometimes gives results (e.g. zero violations) even if the component does not exist, so we\n # check whether the component specified by the user actually exists before getting the data.\n- url = SourceCollector._api_url(self)\n+ url = await SourceCollector._api_url(self)\n component = self._parameter(\"component\")\n show_component_url = URL(f\"{url}/api/components/show?component={component}\")\n- response = super()._get_source_responses(show_component_url)[0]\n- json = response.json()\n+ response = (await super()._get_source_responses(show_component_url))[0]\n+ json = await response.json()\n if \"errors\" in json:\n- raise Exception(json[\"errors\"][0][\"msg\"])\n- return super()._get_source_responses(api_url)\n+ raise SonarQubeException(json[\"errors\"][0][\"msg\"])\n+ return await super()._get_source_responses(*urls)\n \n \n class SonarQubeViolations(SonarQubeCollector):\n@@ -31,15 +34,15 @@ class SonarQubeViolations(SonarQubeCollector):\n \n rules_parameter = \"\" # Subclass responsibility\n \n- def _landing_url(self, responses: Responses) -> URL:\n- url = super()._landing_url(responses)\n+ async def _landing_url(self, responses: Responses) -> URL:\n+ url = await super()._landing_url(responses)\n component = self._parameter(\"component\")\n branch = self._parameter(\"branch\")\n landing_url = f\"{url}/project/issues?id={component}&resolved=false&branch={branch}\"\n return URL(landing_url + self.__rules_url_parameter())\n \n- def _api_url(self) -> URL:\n- url = super()._api_url()\n+ async def _api_url(self) -> URL:\n+ url = await super()._api_url()\n component = self._parameter(\"component\")\n branch = self._parameter(\"branch\")\n severities = \",\".join([severity.upper() for severity in self._parameter(\"severities\")])\n@@ -55,27 +58,27 @@ def __rules_url_parameter(self) -> str:\n rules = self._parameter(self.rules_parameter) if self.rules_parameter else []\n return f\"&rules={','.join(rules)}\" if rules else \"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n value = 0\n entities: Entities = []\n for response in responses:\n- json = response.json()\n+ json = await response.json()\n value += int(json.get(\"total\", 0))\n- entities.extend([self._entity(issue) for issue in json.get(\"issues\", [])])\n+ entities.extend([await self._entity(issue) for issue in json.get(\"issues\", [])])\n return str(value), \"100\", entities\n \n- def __issue_landing_url(self, issue_key: str) -> URL:\n+ async def __issue_landing_url(self, issue_key: str) -> URL:\n \"\"\"Generate a landing url for the issue.\"\"\"\n- url = super()._landing_url([])\n+ url = await super()._landing_url([])\n component = self._parameter(\"component\")\n branch = self._parameter(\"branch\")\n return URL(f\"{url}/project/issues?id={component}&issues={issue_key}&open={issue_key}&branch={branch}\")\n \n- def _entity(self, issue) -> Entity:\n+ async def _entity(self, issue) -> Entity:\n \"\"\"Create an entity from an issue.\"\"\"\n return dict(\n key=issue[\"key\"],\n- url=self.__issue_landing_url(issue[\"key\"]),\n+ url=await self.__issue_landing_url(issue[\"key\"]),\n message=issue[\"message\"],\n severity=issue[\"severity\"].lower(),\n type=issue[\"type\"].lower(),\n@@ -97,23 +100,21 @@ class SonarQubeViolationsWithPercentageScale(SonarQubeViolations):\n \n total_metric = \"\" # Subclass responsibility\n \n- def _get_source_responses(self, api_url: URL) -> Responses:\n+ async def _get_source_responses(self, *urls: URL) -> Responses:\n \"\"\"Next to the violations, also get the total number of units as basis for the percentage scale.\"\"\"\n- responses = super()._get_source_responses(api_url)\n component = self._parameter(\"component\")\n branch = self._parameter(\"branch\")\n- base_api_url = SonarQubeCollector._api_url(self) # pylint: disable=protected-access\n+ base_api_url = await SonarQubeCollector._api_url(self) # pylint: disable=protected-access\n total_metric_api_url = URL(\n f\"{base_api_url}/api/measures/component?component={component}&metricKeys={self.total_metric}&\"\n f\"branch={branch}\")\n- return responses + [\n- requests.get(total_metric_api_url, timeout=self.TIMEOUT, auth=self._basic_auth_credentials())]\n+ return await super()._get_source_responses(*(urls + (total_metric_api_url,)))\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- value, _, entities = super()._parse_source_responses(responses)\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ value, _, entities = await super()._parse_source_responses(responses)\n measures: List[Dict[str, str]] = []\n for response in responses:\n- measures.extend(response.json().get(\"component\", {}).get(\"measures\", []))\n+ measures.extend((await response.json()).get(\"component\", {}).get(\"measures\", []))\n return value, str(sum(int(measure[\"value\"]) for measure in measures)), entities\n \n \n@@ -143,26 +144,23 @@ class SonarQubeSuppressedViolations(SonarQubeViolations):\n \n rules_parameter = \"suppression_rules\"\n \n- def _get_source_responses(self, api_url: URL) -> Responses:\n+ async def _get_source_responses(self, *urls: URL) -> Responses:\n \"\"\"In addition to the suppressed rules, also get issues closed as false positive and won't fix from SonarQube\n as well as the total number of violations.\"\"\"\n- responses = super()._get_source_responses(api_url)\n- url = SourceCollector._api_url(self) # pylint: disable=protected-access\n+ url = await SourceCollector._api_url(self) # pylint: disable=protected-access\n component = self._parameter(\"component\")\n branch = self._parameter(\"branch\")\n all_issues_api_url = URL(f\"{url}/api/issues/search?componentKeys={component}&branch={branch}\")\n resolved_issues_api_url = URL(f\"{all_issues_api_url}&status=RESOLVED&resolutions=WONTFIX,FALSE-POSITIVE&ps=500\")\n- for issues_api_url in (resolved_issues_api_url, all_issues_api_url):\n- responses.append(requests.get(issues_api_url, timeout=self.TIMEOUT, auth=self._basic_auth_credentials()))\n- return responses\n+ return await super()._get_source_responses(*(urls + (resolved_issues_api_url, all_issues_api_url)))\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- value, _, entities = super()._parse_source_responses(responses[:-1])\n- return value, str(responses[-1].json()[\"total\"]), entities\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ value, _, entities = await super()._parse_source_responses(responses[:-1])\n+ return value, str((await responses[-1].json())[\"total\"]), entities\n \n- def _entity(self, issue) -> Entity:\n+ async def _entity(self, issue) -> Entity:\n \"\"\"Also add the resolution to the entity.\"\"\"\n- entity = super()._entity(issue)\n+ entity = await super()._entity(issue)\n resolution = issue.get(\"resolution\", \"\").lower()\n entity[\"resolution\"] = dict(wontfix=\"won't fix\").get(resolution, resolution)\n return entity\n@@ -175,23 +173,23 @@ class SonarQubeMetricsBaseClass(SonarQubeCollector):\n # the metric value, the second for the total value (used for calculating a percentage).\n metricKeys = \"\" # Subclass responsibility\n \n- def _landing_url(self, responses: Responses) -> URL:\n- url = super()._landing_url(responses)\n+ async def _landing_url(self, responses: Responses) -> URL:\n+ url = await super()._landing_url(responses)\n component = self._parameter(\"component\")\n branch = self._parameter(\"branch\")\n metric = self._metric_keys().split(\",\")[0]\n return URL(f\"{url}/component_measures?id={component}&metric={metric}&branch={branch}\")\n \n- def _api_url(self) -> URL:\n- url = super()._api_url()\n+ async def _api_url(self) -> URL:\n+ url = await super()._api_url()\n component = self._parameter(\"component\")\n branch = self._parameter(\"branch\")\n return URL(\n f\"{url}/api/measures/component?component={component}&metricKeys={self._metric_keys()}&branch={branch}\")\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n metric_keys = self._metric_keys().split(\",\")\n- metrics = self.__get_metrics(responses)\n+ metrics = await self.__get_metrics(responses)\n value = str(metrics[metric_keys[0]])\n total = str(metrics[metric_keys[1]]) if len(metric_keys) > 1 else \"100\"\n return value, total, []\n@@ -201,10 +199,13 @@ def _metric_keys(self) -> str:\n return self.metricKeys\n \n @staticmethod\n- def __get_metrics(responses: Responses) -> Dict[str, int]:\n+ async def __get_metrics(responses: Responses) -> Dict[str, int]:\n \"\"\"Get the metric(s) from the responses.\"\"\"\n- measures = responses[0].json()[\"component\"][\"measures\"]\n- return dict((measure[\"metric\"], int(measure[\"value\"])) for measure in measures)\n+ measures = (await responses[0].json())[\"component\"][\"measures\"]\n+ # Without the local variable, coverage.py thinks: \"line xyz didn't return from function '__get_metrics',\n+ # because the return on line xyz wasn't executed\"\n+ metrics = dict((measure[\"metric\"], int(measure[\"value\"])) for measure in measures)\n+ return metrics\n \n \n class SonarQubeDuplicatedLines(SonarQubeMetricsBaseClass):\n@@ -235,31 +236,32 @@ class SonarQubeUncoveredBranches(SonarQubeMetricsBaseClass):\n class SonarQubeTests(SonarQubeCollector):\n \"\"\"SonarQube collector for the tests metric.\"\"\"\n \n- def _api_url(self) -> URL:\n- url = super()._api_url()\n+ async def _api_url(self) -> URL:\n+ url = await super()._api_url()\n component = self._parameter(\"component\")\n branch = self._parameter(\"branch\")\n metric_keys = \"tests,test_errors,test_failures,skipped_tests\"\n return URL(f\"{url}/api/measures/component?component={component}&metricKeys={metric_keys}&branch={branch}\")\n \n- def _landing_url(self, responses: Responses) -> URL:\n- url = super()._landing_url(responses)\n+ async def _landing_url(self, responses: Responses) -> URL:\n+ url = await super()._landing_url(responses)\n component = self._parameter(\"component\")\n branch = self._parameter(\"branch\")\n return URL(f\"{url}/component_measures?id={component}&metric=tests&branch={branch}\")\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- tests = self.__nr_of_tests(responses)\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ tests = await self.__nr_of_tests(responses)\n value = str(sum(tests[test_result] for test_result in self._parameter(\"test_result\")))\n test_results = self._datamodel[\"sources\"][self.source_type][\"parameters\"][\"test_result\"][\"values\"]\n total = str(sum(tests[test_result] for test_result in test_results))\n return value, total, []\n \n @staticmethod\n- def __nr_of_tests(responses: Responses) -> Dict[str, int]:\n+ async def __nr_of_tests(responses: Responses) -> Dict[str, int]:\n \"\"\"Return the number of tests by test result.\"\"\"\n measures = dict(\n- (measure[\"metric\"], int(measure[\"value\"])) for measure in responses[0].json()[\"component\"][\"measures\"])\n+ (measure[\"metric\"], int(measure[\"value\"]))\n+ for measure in (await responses[0].json())[\"component\"][\"measures\"])\n errored = measures.get(\"test_errors\", 0)\n failed = measures.get(\"test_failures\", 0)\n skipped = measures.get(\"skipped_tests\", 0)\n@@ -270,17 +272,17 @@ def __nr_of_tests(responses: Responses) -> Dict[str, int]:\n class SonarQubeSourceUpToDateness(SonarQubeCollector, SourceUpToDatenessCollector):\n \"\"\"SonarQube source up-to-dateness.\"\"\"\n \n- def _api_url(self) -> URL:\n- url = super()._api_url()\n+ async def _api_url(self) -> URL:\n+ url = await super()._api_url()\n component = self._parameter(\"component\")\n branch = self._parameter(\"branch\")\n return URL(f\"{url}/api/project_analyses/search?project={component}&branch={branch}\")\n \n- def _landing_url(self, responses: Responses) -> URL:\n- url = super()._landing_url(responses)\n+ async def _landing_url(self, responses: Responses) -> URL:\n+ url = await super()._landing_url(responses)\n component = self._parameter(\"component\")\n branch = self._parameter(\"branch\")\n return URL(f\"{url}/project/activity?id={component}&branch={branch}\")\n \n- def _parse_source_response_date_time(self, response: Response) -> datetime:\n- return isoparse(response.json()[\"analyses\"][0][\"date\"])\n+ async def _parse_source_response_date_time(self, response: Response) -> datetime:\n+ return isoparse((await response.json())[\"analyses\"][0][\"date\"])\ndiff --git a/components/collector/src/source_collectors/trello.py b/components/collector/src/source_collectors/api_source_collectors/trello.py\nsimilarity index 75%\nrename from components/collector/src/source_collectors/trello.py\nrename to components/collector/src/source_collectors/api_source_collectors/trello.py\n--- a/components/collector/src/source_collectors/trello.py\n+++ b/components/collector/src/source_collectors/api_source_collectors/trello.py\n@@ -5,44 +5,43 @@\n from typing import cast, Tuple\n \n from dateutil.parser import parse\n-import requests\n \n from collector_utilities.type import Entity, Entities, Response, Responses, URL, Value\n from collector_utilities.functions import days_ago\n-from .source_collector import SourceCollector, SourceUpToDatenessCollector\n+from base_collectors import SourceCollector, SourceUpToDatenessCollector\n \n \n class TrelloBase(SourceCollector, ABC): # pylint: disable=abstract-method\n \"\"\"Base class for Trello collectors.\"\"\"\n \n- def _landing_url(self, responses: Responses) -> URL:\n- return URL(responses[0].json()[\"url\"] if responses else \"https://trello.com\")\n+ async def _landing_url(self, responses: Responses) -> URL:\n+ return URL((await responses[0].json())[\"url\"] if responses else \"https://trello.com\")\n \n- def _get_source_responses(self, api_url: URL) -> Responses:\n+ async def _get_source_responses(self, *urls: URL) -> Responses:\n \"\"\"Override because we need to do multiple requests to get all the data we need.\"\"\"\n- api = f\"1/boards/{self.__board_id()}?fields=id,url,dateLastActivity&lists=open&\" \\\n+ api = f\"1/boards/{await self.__board_id()}?fields=id,url,dateLastActivity&lists=open&\" \\\n \"list_fields=name&cards=visible&card_fields=name,dateLastActivity,due,idList,url\"\n- return [requests.get(self.__url_with_auth(api), timeout=self.TIMEOUT)]\n+ return await super()._get_source_responses(await self.__url_with_auth(api))\n \n- def __board_id(self) -> str:\n+ async def __board_id(self) -> str:\n \"\"\"Return the id of the board specified by the user.\"\"\"\n- url = self.__url_with_auth(\"1/members/me/boards?fields=name\")\n- boards = requests.get(url, timeout=self.TIMEOUT).json()\n+ url = await self.__url_with_auth(\"1/members/me/boards?fields=name\")\n+ boards = await (await super()._get_source_responses(url))[0].json()\n return str([board for board in boards if self._parameter(\"board\") in board.values()][0][\"id\"])\n \n- def __url_with_auth(self, api_part: str) -> str:\n+ async def __url_with_auth(self, api_part: str) -> URL:\n \"\"\"Return the authentication URL parameters.\"\"\"\n sep = \"&\" if \"?\" in api_part else \"?\"\n api_key = self._parameter(\"api_key\")\n token = self._parameter(\"token\")\n- return f\"{self._api_url()}/{api_part}{sep}key={api_key}&token={token}\"\n+ return URL(f\"{await self._api_url()}/{api_part}{sep}key={api_key}&token={token}\")\n \n \n class TrelloIssues(TrelloBase):\n \"\"\"Collector to get issues (cards) from Trello.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- json = responses[0].json()\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ json = await responses[0].json()\n cards = json[\"cards\"]\n lists = {lst[\"id\"]: lst[\"name\"] for lst in json[\"lists\"]}\n entities = [self.__card_to_entity(card, lists) for card in cards if not self.__ignore_card(card, lists)]\n@@ -82,8 +81,8 @@ def __card_to_entity(card, lists) -> Entity:\n class TrelloSourceUpToDateness(TrelloBase, SourceUpToDatenessCollector):\n \"\"\"Collector to measure how up-to-date a Trello board is.\"\"\"\n \n- def _parse_source_response_date_time(self, response: Response) -> datetime:\n- json = response.json()\n+ async def _parse_source_response_date_time(self, response: Response) -> datetime:\n+ json = await response.json()\n cards = json[\"cards\"]\n lists = {lst[\"id\"]: lst[\"name\"] for lst in json[\"lists\"]}\n dates = [json[\"dateLastActivity\"]] + \\\ndiff --git a/components/collector/src/source_collectors/wekan.py b/components/collector/src/source_collectors/api_source_collectors/wekan.py\nsimilarity index 52%\nrename from components/collector/src/source_collectors/wekan.py\nrename to components/collector/src/source_collectors/api_source_collectors/wekan.py\n--- a/components/collector/src/source_collectors/wekan.py\n+++ b/components/collector/src/source_collectors/api_source_collectors/wekan.py\n@@ -4,48 +4,71 @@\n from datetime import datetime\n from typing import cast, Dict, List, Tuple\n \n-import cachetools.func\n from dateutil.parser import parse\n-import requests\n \n from collector_utilities.type import Entity, Entities, Responses, URL, Value\n from collector_utilities.functions import days_ago\n-from .source_collector import SourceCollector\n+from base_collectors import SourceCollector\n+\n+\n+WekanCard = Dict[str, str]\n+WekanBoard = Dict[str, str]\n+WekanList = Dict[str, str]\n \n \n class WekanBase(SourceCollector, ABC): # pylint: disable=abstract-method\n \"\"\"Base class for Wekan collectors.\"\"\"\n \n- def _landing_url(self, responses: Responses) -> URL:\n- api_url = self._api_url()\n- return URL(f\"{api_url}/b/{self._board_id(responses[0].json()['token'])}\") if responses else api_url\n+ def __init__(self, *args, **kwargs) -> None:\n+ self.__token = \"\"\n+ self._board: WekanBoard = {}\n+ self._board_url = \"\"\n+ self._lists: List[WekanList] = []\n+ self._cards: Dict[str, List[WekanCard]] = {}\n+ super().__init__(*args, **kwargs)\n \n- def _get_source_responses(self, api_url: URL) -> Responses:\n- \"\"\"Override because we want to do a post request to login.\"\"\"\n- credentials = dict(username=self._parameter(\"username\"), password=self._parameter(\"password\"))\n- return [requests.post(f\"{api_url}/users/login\", data=credentials, timeout=self.TIMEOUT)]\n+ async def _landing_url(self, responses: Responses) -> URL:\n+ api_url = await self._api_url()\n+ return URL(f\"{api_url}/b/{self._board['_id']}\") if responses else api_url\n \n- def _board_id(self, token) -> str:\n- \"\"\"Return the id of the board specified by the user.\"\"\"\n- api_url = self._api_url()\n- user_id = self._get_json(URL(f\"{api_url}/api/user\"), token)[\"_id\"]\n- boards = self._get_json(URL(f\"{api_url}/api/users/{user_id}/boards\"), token)\n- return str([board for board in boards if self._parameter(\"board\") in board.values()][0][\"_id\"])\n+ def _headers(self) -> Dict[str, str]:\n+ return dict(Authorization=f\"Bearer {self.__token}\")\n \n- def _lists(self, board_url: str, token: str) -> List:\n+ async def _get_source_responses(self, *urls: URL) -> Responses:\n+ \"\"\"Override because we want to do a post request to login.\"\"\"\n+ credentials = dict(username=self._parameter(\"username\"), password=self._parameter(\"password\"))\n+ response = await self._session.post(f\"{urls[0]}/users/login\", data=credentials)\n+ self.__token = (await response.json())[\"token\"]\n+ await self.__get_board()\n+ await self.__get_lists()\n+ await self.__get_cards()\n+ return [response]\n+\n+ async def __get_board(self) -> None:\n+ \"\"\"Return the board specified by the user.\"\"\"\n+ api_url = await self._api_url()\n+ user_id = (await self._get_json(URL(f\"{api_url}/api/user\")))[\"_id\"]\n+ boards = await self._get_json(URL(f\"{api_url}/api/users/{user_id}/boards\"))\n+ self._board = [board for board in boards if self._parameter(\"board\") in board.values()][0]\n+ self._board_url = f\"{api_url}/api/boards/{self._board['_id']}\"\n+\n+ async def __get_lists(self) -> None:\n \"\"\"Return the lists on the board.\"\"\"\n- return [lst for lst in self._get_json(URL(f\"{board_url}/lists\"), token) if not self.__ignore_list(lst)]\n-\n- def _cards(self, list_url: str, token: str) -> List:\n- \"\"\"Return the cards on the board.\"\"\"\n- cards = self._get_json(URL(f\"{list_url}/cards\"), token)\n- full_cards = [self._get_json(URL(f\"{list_url}/cards/{card['_id']}\"), token) for card in cards]\n- return [card for card in full_cards if not self._ignore_card(card)]\n-\n- @cachetools.func.ttl_cache(ttl=60)\n- def _get_json(self, api_url: URL, token: str):\n+ self._lists = [\n+ lst for lst in await self._get_json(URL(f\"{self._board_url}/lists\"))\n+ if not self.__ignore_list(lst)]\n+\n+ async def __get_cards(self) -> None:\n+ \"\"\"Get the cards for the list.\"\"\"\n+ for lst in self._lists:\n+ list_url = f\"{self._board_url}/lists/{lst['_id']}\"\n+ cards = await self._get_json(URL(f\"{list_url}/cards\"))\n+ full_cards = [await self._get_json(URL(f\"{list_url}/cards/{card['_id']}\")) for card in cards]\n+ self._cards[lst[\"_id\"]] = [card for card in full_cards if not self._ignore_card(card)]\n+\n+ async def _get_json(self, api_url: URL):\n \"\"\"Get the JSON from the API url.\"\"\"\n- return requests.get(api_url, timeout=self.TIMEOUT, headers=dict(Authorization=f\"Bearer {token}\")).json()\n+ return await (await super()._get_source_responses(api_url))[0].json()\n \n def __ignore_list(self, card_list) -> bool:\n \"\"\"Return whether the list should be ignored.\"\"\"\n@@ -62,14 +85,12 @@ def _ignore_card(self, card: Dict) -> bool: # pylint: disable=unused-argument,n\n class WekanIssues(WekanBase):\n \"\"\"Collector to get issues (cards) from Wekan.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- token = responses[0].json()['token']\n- api_url = self._api_url()\n- board_url = f\"{api_url}/api/boards/{self._board_id(token)}\"\n- board_slug = self._get_json(URL(board_url), token)[\"slug\"]\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ api_url = await self._api_url()\n+ board_slug = self._board[\"slug\"]\n entities: Entities = []\n- for lst in self._lists(board_url, token):\n- for card in self._cards(f\"{board_url}/lists/{lst['_id']}\", token):\n+ for lst in self._lists:\n+ for card in self._cards.get(lst[\"_id\"], []):\n entities.append(self.__card_to_entity(card, api_url, board_slug, lst[\"title\"]))\n return str(len(entities)), \"100\", entities\n \n@@ -105,13 +126,9 @@ def __card_to_entity(card, api_url: URL, board_slug: str, list_title: str) -> En\n class WekanSourceUpToDateness(WekanBase):\n \"\"\"Collector to measure how up-to-date a Wekan board is.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- token = responses[0].json()['token']\n- board_url = f\"{self._api_url()}/api/boards/{self._board_id(token)}\"\n- board = self._get_json(URL(board_url), token)\n- dates = [board.get(\"createdAt\"), board.get(\"modifiedAt\")]\n- for lst in self._lists(board_url, token):\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ dates = [self._board.get(\"createdAt\"), self._board.get(\"modifiedAt\")]\n+ for lst in self._lists:\n dates.extend([lst.get(\"createdAt\"), lst.get(\"updatedAt\")])\n- list_url = f\"{board_url}/lists/{lst['_id']}\"\n- dates.extend([card[\"dateLastActivity\"] for card in self._cards(list_url, token)])\n+ dates.extend([card[\"dateLastActivity\"] for card in self._cards.get(lst[\"_id\"], [])])\n return str(days_ago(parse(max([date for date in dates if date])))), \"100\", []\ndiff --git a/components/collector/src/source_collectors/cxsast.py b/components/collector/src/source_collectors/cxsast.py\ndeleted file mode 100644\n--- a/components/collector/src/source_collectors/cxsast.py\n+++ /dev/null\n@@ -1,93 +0,0 @@\n-\"\"\"Collectors for the Checkmarx CxSAST product.\"\"\"\n-\n-from abc import ABC\n-from typing import cast, Final, Tuple\n-\n-from dateutil.parser import parse\n-import requests\n-\n-from collector_utilities.type import Entities, Response, Responses, URL, Value\n-from collector_utilities.functions import days_ago\n-from .source_collector import SourceCollector\n-\n-\n-class CxSASTBase(SourceCollector, ABC): # pylint: disable=abstract-method\n- \"\"\"Base class for CxSAST collectors.\"\"\"\n-\n- TOKEN_RESPONSE: Final[int] = 0\n- PROJECT_RESPONSE: Final[int] = 1\n- SCAN_RESPONSE: Final[int] = 2\n-\n- def _landing_url(self, responses: Responses) -> URL:\n- api_url = self._api_url()\n- if len(responses) > self.SCAN_RESPONSE:\n- project_id = self.__project_id(responses[self.PROJECT_RESPONSE])\n- scan_id = self._scan_id(responses)\n- return URL(f\"{api_url}/CxWebClient/ViewerMain.aspx?scanId={scan_id}&ProjectID={project_id}\")\n- return api_url\n-\n- def _get_source_responses(self, api_url: URL) -> Responses:\n- \"\"\"Override because we need to do multiple requests to get all the data we need.\"\"\"\n- # See https://checkmarx.atlassian.net/wiki/spaces/KC/pages/1187774721/Using+the+CxSAST+REST+API+v8.6.0+and+up\n- credentials = dict( # nosec, The client secret is not really secret, see previous url\n- username=cast(str, self._parameter(\"username\")),\n- password=cast(str, self._parameter(\"password\")),\n- grant_type=\"password\", scope=\"sast_rest_api\", client_id=\"resource_owner_client\",\n- client_secret=\"014DF517-39D1-4453-B7B3-9930C563627C\")\n- token_response = self._api_post(\"auth/identity/connect/token\", credentials)\n- token = token_response.json()['access_token']\n- project_response = self._api_get(f\"projects\", token)\n- project_id = self.__project_id(project_response)\n- scan_response = self._api_get(f\"sast/scans?projectId={project_id}&scanStatus=Finished&last=1\", token)\n- return [token_response, project_response, scan_response]\n-\n- def __project_id(self, project_response: Response) -> str:\n- \"\"\"Return the project id that belongs to the project parameter.\"\"\"\n- project_name_or_id = self._parameter(\"project\")\n- projects = project_response.json()\n- return str([project for project in projects if project_name_or_id in (project[\"name\"], project[\"id\"])][0][\"id\"])\n-\n- def _scan_id(self, responses: Responses) -> str:\n- \"\"\"Return the scan id.\"\"\"\n- return str(responses[self.SCAN_RESPONSE].json()[0][\"id\"])\n-\n- def _api_get(self, api: str, token: str) -> Response:\n- \"\"\"Open the API and return the response.\"\"\"\n- response = requests.get(\n- f\"{self._api_url()}/cxrestapi/{api}\", headers=dict(Authorization=f\"Bearer {token}\"), timeout=self.TIMEOUT)\n- response.raise_for_status()\n- return response\n-\n- def _api_post(self, api: str, data, token: str = None) -> Response:\n- \"\"\"Post to the API and return the response.\"\"\"\n- headers = dict(Authorization=f\"Bearer {token}\") if token else dict()\n- response = requests.post(f\"{self._api_url()}/cxrestapi/{api}\", data=data, headers=headers, timeout=self.TIMEOUT)\n- response.raise_for_status()\n- return response\n-\n-\n-class CxSASTSourceUpToDateness(CxSASTBase):\n- \"\"\"Collector class to measure the up-to-dateness of a Checkmarx CxSAST scan.\"\"\"\n-\n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- scan = responses[self.SCAN_RESPONSE].json()[0]\n- return str(days_ago(parse(scan[\"dateAndTime\"][\"finishedOn\"]))), \"100\", []\n-\n-\n-class CxSASTSecurityWarnings(CxSASTBase):\n- \"\"\"Collector class to measure the number of security warnings in a Checkmarx CxSAST scan.\"\"\"\n-\n- STATS_RESPONSE = 3\n-\n- def _get_source_responses(self, api_url: URL) -> Responses:\n- responses = super()._get_source_responses(api_url)\n- token = responses[self.TOKEN_RESPONSE].json()[\"access_token\"]\n- scan_id = self._scan_id(responses)\n- # Get the statistics of the last scan; this is a single API call:\n- responses.append(self._api_get(f\"sast/scans/{scan_id}/resultsStatistics\", token))\n- return responses\n-\n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- stats = responses[self.STATS_RESPONSE].json()\n- severities = self._parameter(\"severities\")\n- return str(sum(stats.get(f\"{severity.lower()}Severity\", 0) for severity in severities)), \"100\", []\ndiff --git a/components/collector/src/source_collectors/file_source_collectors/__init__.py b/components/collector/src/source_collectors/file_source_collectors/__init__.py\nnew file mode 100644\ndiff --git a/components/collector/src/source_collectors/anchore.py b/components/collector/src/source_collectors/file_source_collectors/anchore.py\nsimilarity index 80%\nrename from components/collector/src/source_collectors/anchore.py\nrename to components/collector/src/source_collectors/file_source_collectors/anchore.py\n--- a/components/collector/src/source_collectors/anchore.py\n+++ b/components/collector/src/source_collectors/file_source_collectors/anchore.py\n@@ -7,17 +7,17 @@\n \n from collector_utilities.functions import md5_hash\n from collector_utilities.type import Entities, Response, Responses, Value\n-from .source_collector import JSONFileSourceCollector, SourceUpToDatenessCollector\n+from base_collectors import JSONFileSourceCollector, SourceUpToDatenessCollector\n \n \n class AnchoreSecurityWarnings(JSONFileSourceCollector):\n \"\"\"Anchore collector for security warnings.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n severities = self._parameter(\"severities\")\n entities = []\n for response in responses:\n- json = response.json()\n+ json = await response.json()\n vulnerabilities = json.get(\"vulnerabilities\", []) if isinstance(json, dict) else []\n entities.extend([\n dict(\n@@ -36,7 +36,7 @@ class AnchoreSourceUpToDateness(JSONFileSourceCollector, SourceUpToDatenessColle\n \n API_URL_PARAMETER_KEY = \"details_url\"\n \n- def _parse_source_response_date_time(self, response: Response) -> datetime:\n- details = response.json()\n+ async def _parse_source_response_date_time(self, response: Response) -> datetime:\n+ details = await response.json()\n return parse(details[0][\"analyzed_at\"]) \\\n if isinstance(details, list) and details and \"analyzed_at\" in details[0] else datetime.now(timezone.utc)\ndiff --git a/components/collector/src/source_collectors/axe_csv.py b/components/collector/src/source_collectors/file_source_collectors/axe_csv.py\nsimilarity index 71%\nrename from components/collector/src/source_collectors/axe_csv.py\nrename to components/collector/src/source_collectors/file_source_collectors/axe_csv.py\n--- a/components/collector/src/source_collectors/axe_csv.py\n+++ b/components/collector/src/source_collectors/file_source_collectors/axe_csv.py\n@@ -6,32 +6,30 @@\n from typing import Dict, List, Tuple\n \n from collector_utilities.functions import md5_hash\n-from collector_utilities.type import Responses, Value, Entities\n-from .source_collector import FileSourceCollector\n+from collector_utilities.type import Entities, Responses, Value\n+from base_collectors import CSVFileSourceCollector\n \n \n-class AxeCSVAccessibility(FileSourceCollector):\n+class AxeCSVAccessibility(CSVFileSourceCollector):\n \"\"\"Collector class to get accessibility violations.\"\"\"\n \n- file_extensions = [\"csv\"]\n-\n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n entities: Entities = [\n dict(\n url=str(row[\"URL\"]), violation_type=row[\"Violation Type\"], impact=row[\"Impact\"],\n element=row[\"DOM Element\"], page=re.sub(r'http[s]?://[^/]+', '', row['URL']),\n description=row[\"Messages\"], help=row[\"Help\"])\n- for row in self.__parse_csv(responses)]\n+ for row in await self.__parse_csv(responses)]\n for entity in entities:\n entity[\"key\"] = md5_hash(\",\".join(str(value) for value in entity.values()))\n return str(len(entities)), \"100\", entities\n \n- def __parse_csv(self, responses: Responses) -> List[Dict[str, str]]:\n+ async def __parse_csv(self, responses: Responses) -> List[Dict[str, str]]:\n \"\"\"Parse the CSV and return the rows and parsed items .\"\"\"\n impact_levels = self._parameter(\"impact\")\n violation_types = self._parameter(\"violation_type\")\n rows = []\n for response in responses:\n- csv_text = response.text.strip()\n+ csv_text = (await response.text()).strip()\n rows.extend(list(csv.DictReader(StringIO(csv_text, newline=\"\"))))\n return [row for row in rows if row[\"Impact\"] in impact_levels and row[\"Violation Type\"] in violation_types]\ndiff --git a/components/collector/src/source_collectors/bandit.py b/components/collector/src/source_collectors/file_source_collectors/bandit.py\nsimilarity index 72%\nrename from components/collector/src/source_collectors/bandit.py\nrename to components/collector/src/source_collectors/file_source_collectors/bandit.py\n--- a/components/collector/src/source_collectors/bandit.py\n+++ b/components/collector/src/source_collectors/file_source_collectors/bandit.py\n@@ -6,13 +6,13 @@\n from dateutil.parser import parse\n \n from collector_utilities.type import Entities, Response, Responses, Value\n-from .source_collector import JSONFileSourceCollector, SourceUpToDatenessCollector\n+from base_collectors import JSONFileSourceCollector, SourceUpToDatenessCollector\n \n \n class BanditSecurityWarnings(JSONFileSourceCollector):\n \"\"\"Bandit collector for security warnings.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n severities = self._parameter(\"severities\")\n confidence_levels = self._parameter(\"confidence_levels\")\n entities = []\n@@ -25,7 +25,8 @@ def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, E\n issue_severity=warning[\"issue_severity\"].capitalize(),\n issue_confidence=warning[\"issue_confidence\"].capitalize(),\n more_info=warning[\"more_info\"])\n- for warning in response.json().get(\"results\", []) if warning[\"issue_severity\"].lower() in severities\n+ for warning in (await response.json()).get(\"results\", [])\n+ if warning[\"issue_severity\"].lower() in severities\n and warning[\"issue_confidence\"].lower() in confidence_levels])\n return str(len(entities)), \"100\", entities\n \n@@ -33,5 +34,5 @@ def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, E\n class BanditSourceUpToDateness(JSONFileSourceCollector, SourceUpToDatenessCollector):\n \"\"\"Bandit collector for source up-to-dateness.\"\"\"\n \n- def _parse_source_response_date_time(self, response: Response) -> datetime:\n- return parse(response.json()[\"generated_at\"])\n+ async def _parse_source_response_date_time(self, response: Response) -> datetime:\n+ return parse((await response.json())[\"generated_at\"])\ndiff --git a/components/collector/src/source_collectors/composer.py b/components/collector/src/source_collectors/file_source_collectors/composer.py\nsimilarity index 81%\nrename from components/collector/src/source_collectors/composer.py\nrename to components/collector/src/source_collectors/file_source_collectors/composer.py\n--- a/components/collector/src/source_collectors/composer.py\n+++ b/components/collector/src/source_collectors/file_source_collectors/composer.py\n@@ -3,17 +3,17 @@\n from typing import Dict, List, Tuple\n \n from collector_utilities.type import Entities, Responses, Value\n-from .source_collector import JSONFileSourceCollector\n+from base_collectors import JSONFileSourceCollector\n \n \n class ComposerDependencies(JSONFileSourceCollector):\n \"\"\"Composer collector for dependencies.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n statuses = self._parameter(\"latest_version_status\")\n installed_dependencies: List[Dict[str, str]] = []\n for response in responses:\n- installed_dependencies.extend(response.json().get(\"installed\", []))\n+ installed_dependencies.extend((await response.json()).get(\"installed\", []))\n entities: Entities = [\n dict(\n key=f'{dependency[\"name\"]}@{dependency.get(\"version\", \"?\")}',\ndiff --git a/components/collector/src/source_collectors/jacoco.py b/components/collector/src/source_collectors/file_source_collectors/jacoco.py\nsimilarity index 78%\nrename from components/collector/src/source_collectors/jacoco.py\nrename to components/collector/src/source_collectors/file_source_collectors/jacoco.py\n--- a/components/collector/src/source_collectors/jacoco.py\n+++ b/components/collector/src/source_collectors/file_source_collectors/jacoco.py\n@@ -6,7 +6,7 @@\n from defusedxml import ElementTree\n \n from collector_utilities.type import Entities, Response, Responses, Value\n-from .source_collector import XMLFileSourceCollector, SourceUpToDatenessCollector\n+from base_collectors import XMLFileSourceCollector, SourceUpToDatenessCollector\n \n \n class JacocoCoverageBaseClass(XMLFileSourceCollector):\n@@ -14,10 +14,10 @@ class JacocoCoverageBaseClass(XMLFileSourceCollector):\n \n coverage_type = \"Subclass responsibility (Jacoco has: line, branch, instruction, complexity, method, class)\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n missed, covered = 0, 0\n for response in responses:\n- tree = ElementTree.fromstring(response.text)\n+ tree = ElementTree.fromstring(await response.text())\n counter = [c for c in tree.findall(\"counter\") if c.get(\"type\").lower() == self.coverage_type][0]\n missed += int(counter.get(\"missed\"))\n covered += int(counter.get(\"covered\"))\n@@ -39,8 +39,8 @@ class JacocoUncoveredBranches(JacocoCoverageBaseClass):\n class JacocoSourceUpToDateness(XMLFileSourceCollector, SourceUpToDatenessCollector):\n \"\"\"Collector to collect the Jacoco report age.\"\"\"\n \n- def _parse_source_response_date_time(self, response: Response) -> datetime:\n- tree = ElementTree.fromstring(response.text)\n+ async def _parse_source_response_date_time(self, response: Response) -> datetime:\n+ tree = ElementTree.fromstring(await response.text())\n session_info = tree.find(\".//sessioninfo\")\n timestamp = session_info.get(\"dump\") if session_info is not None else \"0\"\n return datetime.utcfromtimestamp(int(timestamp) / 1000.)\ndiff --git a/components/collector/src/source_collectors/junit.py b/components/collector/src/source_collectors/file_source_collectors/junit.py\nsimilarity index 81%\nrename from components/collector/src/source_collectors/junit.py\nrename to components/collector/src/source_collectors/file_source_collectors/junit.py\n--- a/components/collector/src/source_collectors/junit.py\n+++ b/components/collector/src/source_collectors/file_source_collectors/junit.py\n@@ -7,18 +7,18 @@\n \n from collector_utilities.type import Entity, Entities, Response, Responses, Value\n from collector_utilities.functions import parse_source_response_xml\n-from .source_collector import XMLFileSourceCollector, SourceUpToDatenessCollector\n+from base_collectors import XMLFileSourceCollector, SourceUpToDatenessCollector\n \n \n class JUnitTests(XMLFileSourceCollector):\n \"\"\"Collector for JUnit tests.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n entities = []\n test_statuses_to_count = cast(List[str], self._parameter(\"test_result\"))\n junit_status_nodes = dict(errored=\"error\", failed=\"failure\", skipped=\"skipped\")\n for response in responses:\n- tree = parse_source_response_xml(response)\n+ tree = await parse_source_response_xml(response)\n for test_case in tree.findall(\".//testcase\"):\n for test_result, junit_status_node in junit_status_nodes.items():\n if test_case.find(junit_status_node) is not None:\n@@ -39,7 +39,7 @@ def __entity(case_node, case_result: str) -> Entity:\n class JUnitSourceUpToDateness(XMLFileSourceCollector, SourceUpToDatenessCollector):\n \"\"\"Collector to collect the Junit report age.\"\"\"\n \n- def _parse_source_response_date_time(self, response: Response) -> datetime:\n- tree = parse_source_response_xml(response)\n+ async def _parse_source_response_date_time(self, response: Response) -> datetime:\n+ tree = await parse_source_response_xml(response)\n test_suite = tree if tree.tag == \"testsuite\" else tree.findall(\"testsuite\")[0]\n return parse(test_suite.get(\"timestamp\", \"\"))\ndiff --git a/components/collector/src/source_collectors/ncover.py b/components/collector/src/source_collectors/file_source_collectors/ncover.py\nsimilarity index 75%\nrename from components/collector/src/source_collectors/ncover.py\nrename to components/collector/src/source_collectors/file_source_collectors/ncover.py\n--- a/components/collector/src/source_collectors/ncover.py\n+++ b/components/collector/src/source_collectors/file_source_collectors/ncover.py\n@@ -9,16 +9,16 @@\n from bs4 import BeautifulSoup\n \n from collector_utilities.type import Entities, Response, Responses, Value\n-from .source_collector import HTMLFileSourceCollector, SourceUpToDatenessCollector\n+from base_collectors import HTMLFileSourceCollector, SourceUpToDatenessCollector\n \n \n class NCoverBase(HTMLFileSourceCollector, ABC): # pylint: disable=abstract-method\n \"\"\"Base class for NCover collectors.\"\"\"\n \n @staticmethod\n- def _find_script(response: Response, text: str) -> str:\n+ async def _find_script(response: Response, text: str) -> str:\n \"\"\"Return the script containing the text.\"\"\"\n- for script in BeautifulSoup(response.text, \"html.parser\").find_all(\"script\", type=\"text/javascript\"):\n+ for script in BeautifulSoup(await response.text(), \"html.parser\").find_all(\"script\", type=\"text/javascript\"):\n if text in script.string:\n return str(script.string)\n return \"\" # pragma: nocover\n@@ -29,10 +29,10 @@ class NCoverCoverageBase(NCoverBase, ABC): # pylint: disable=abstract-method\n \n coverage_type = \"Subclass responsibility\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n covered, total = 0, 0\n for response in responses:\n- script = self._find_script(response, \"ncover.execution.stats = \")\n+ script = await self._find_script(response, \"ncover.execution.stats = \")\n json_string = script.strip()[len('ncover.execution.stats = '):].strip(\";\")\n coverage = json.loads(json_string)[f\"{self.coverage_type}Coverage\"]\n covered += int(coverage[\"coveredPoints\"])\n@@ -56,8 +56,8 @@ class NCoverUncoveredBranches(NCoverCoverageBase):\n class NCoverSourceUpToDateness(NCoverBase, SourceUpToDatenessCollector):\n \"\"\"Collector to collect the NCover report age.\"\"\"\n \n- def _parse_source_response_date_time(self, response: Response) -> datetime:\n- script = self._find_script(response, \"ncover.createDateTime\")\n+ async def _parse_source_response_date_time(self, response: Response) -> datetime:\n+ script = await self._find_script(response, \"ncover.createDateTime\")\n match = re.search(r\"ncover\\.createDateTime = '(\\d+)'\", script)\n timestamp = match.group(1) if match else \"\"\n return datetime.fromtimestamp(float(timestamp) / 1000)\ndiff --git a/components/collector/src/source_collectors/ojaudit.py b/components/collector/src/source_collectors/file_source_collectors/ojaudit.py\nsimilarity index 93%\nrename from components/collector/src/source_collectors/ojaudit.py\nrename to components/collector/src/source_collectors/file_source_collectors/ojaudit.py\n--- a/components/collector/src/source_collectors/ojaudit.py\n+++ b/components/collector/src/source_collectors/file_source_collectors/ojaudit.py\n@@ -5,7 +5,7 @@\n \n from collector_utilities.type import Namespaces, Entities, Entity, Responses, Value\n from collector_utilities.functions import sha1_hash, parse_source_response_xml_with_namespace\n-from .source_collector import XMLFileSourceCollector\n+from base_collectors import XMLFileSourceCollector\n \n \n ModelFilePaths = Dict[str, str] # Model id to model file path mapping\n@@ -18,12 +18,12 @@ def __init__(self, *args, **kwargs) -> None:\n super().__init__(*args, **kwargs)\n self.violation_counts: Dict[str, int] = dict() # Keep track of the number of duplicated violations per key\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n severities = cast(List[str], self._parameter(\"severities\"))\n count = 0\n entities = []\n for response in responses:\n- tree, namespaces = parse_source_response_xml_with_namespace(response)\n+ tree, namespaces = await parse_source_response_xml_with_namespace(response)\n entities.extend(self.__violations(tree, namespaces, severities))\n for severity in severities:\n count += int(tree.findtext(f\"./ns:{severity}-count\", default=\"0\", namespaces=namespaces))\ndiff --git a/components/collector/src/source_collectors/openvas.py b/components/collector/src/source_collectors/file_source_collectors/openvas.py\nsimilarity index 81%\nrename from components/collector/src/source_collectors/openvas.py\nrename to components/collector/src/source_collectors/file_source_collectors/openvas.py\n--- a/components/collector/src/source_collectors/openvas.py\n+++ b/components/collector/src/source_collectors/file_source_collectors/openvas.py\n@@ -8,17 +8,17 @@\n \n from collector_utilities.type import Entities, Response, Responses, Value\n from collector_utilities.functions import parse_source_response_xml\n-from .source_collector import XMLFileSourceCollector, SourceUpToDatenessCollector\n+from base_collectors import XMLFileSourceCollector, SourceUpToDatenessCollector\n \n \n class OpenVASSecurityWarnings(XMLFileSourceCollector):\n \"\"\"Collector to get security warnings from OpenVAS.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n entities: Entities = []\n severities = cast(List[str], self._parameter(\"severities\"))\n for response in responses:\n- tree = parse_source_response_xml(response)\n+ tree = await parse_source_response_xml(response)\n entities.extend(\n [dict(key=result.attrib[\"id\"], name=result.findtext(\"name\", default=\"\"),\n description=result.findtext(\"description\", default=\"\"),\n@@ -37,6 +37,6 @@ def __results(element: Element, severities: List[str]) -> List[Element]:\n class OpenVASSourceUpToDateness(XMLFileSourceCollector, SourceUpToDatenessCollector):\n \"\"\"Collector to collect the OpenVAS report age.\"\"\"\n \n- def _parse_source_response_date_time(self, response: Response) -> datetime:\n- tree = parse_source_response_xml(response)\n+ async def _parse_source_response_date_time(self, response: Response) -> datetime:\n+ tree = await parse_source_response_xml(response)\n return isoparse(tree.findtext(\"creation_time\", default=\"\"))\ndiff --git a/components/collector/src/source_collectors/owasp_dependency_check.py b/components/collector/src/source_collectors/file_source_collectors/owasp_dependency_check.py\nsimilarity index 80%\nrename from components/collector/src/source_collectors/owasp_dependency_check.py\nrename to components/collector/src/source_collectors/file_source_collectors/owasp_dependency_check.py\n--- a/components/collector/src/source_collectors/owasp_dependency_check.py\n+++ b/components/collector/src/source_collectors/file_source_collectors/owasp_dependency_check.py\n@@ -7,9 +7,9 @@\n \n from dateutil.parser import isoparse\n \n-from collector_utilities.type import Namespaces, Entity, Entities, Response, Responses, URL, Value\n+from collector_utilities.type import Namespaces, Entity, Entities, Response, Responses, Value\n from collector_utilities.functions import sha1_hash, parse_source_response_xml_with_namespace\n-from .source_collector import XMLFileSourceCollector, SourceUpToDatenessCollector\n+from base_collectors import XMLFileSourceCollector, SourceUpToDatenessCollector\n \n \n class OWASPDependencyCheckBase(XMLFileSourceCollector, ABC): # pylint: disable=abstract-method\n@@ -18,22 +18,15 @@ class OWASPDependencyCheckBase(XMLFileSourceCollector, ABC): # pylint: disable=\n allowed_root_tags = [f\"{{https://jeremylong.github.io/DependencyCheck/dependency-check.{version}.xsd}}analysis\"\n for version in (\"2.0\", \"2.1\", \"2.2\")]\n \n- def _get_source_responses(self, api_url: URL) -> Responses:\n- responses = super()._get_source_responses(api_url)\n- for response in responses:\n- if not response.encoding:\n- response.encoding = \"utf-8\" # Assume UTF-8, detecting encoding on large XML files is very slow.\n- return responses\n-\n \n class OWASPDependencyCheckSecurityWarnings(OWASPDependencyCheckBase):\n \"\"\"Collector to get security warnings from OWASP Dependency Check.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- landing_url = self._landing_url(responses)\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ landing_url = await self._landing_url(responses)\n entities = []\n for response in responses:\n- tree, namespaces = parse_source_response_xml_with_namespace(response, self.allowed_root_tags)\n+ tree, namespaces = await parse_source_response_xml_with_namespace(response, self.allowed_root_tags)\n entities.extend(\n [self.__parse_entity(dependency, index, namespaces, landing_url) for (index, dependency)\n in self.__vulnerable_dependencies(tree, namespaces)])\n@@ -75,6 +68,6 @@ def __vulnerabilities(self, element: Element, namespaces: Namespaces) -> List[El\n class OWASPDependencyCheckSourceUpToDateness(OWASPDependencyCheckBase, SourceUpToDatenessCollector):\n \"\"\"Collector to collect the OWASP Dependency Check report age.\"\"\"\n \n- def _parse_source_response_date_time(self, response: Response) -> datetime:\n- tree, namespaces = parse_source_response_xml_with_namespace(response, self.allowed_root_tags)\n+ async def _parse_source_response_date_time(self, response: Response) -> datetime:\n+ tree, namespaces = await parse_source_response_xml_with_namespace(response, self.allowed_root_tags)\n return isoparse(tree.findtext(\".//ns:reportDate\", default=\"\", namespaces=namespaces))\ndiff --git a/components/collector/src/source_collectors/owasp_zap.py b/components/collector/src/source_collectors/file_source_collectors/owasp_zap.py\nsimilarity index 80%\nrename from components/collector/src/source_collectors/owasp_zap.py\nrename to components/collector/src/source_collectors/file_source_collectors/owasp_zap.py\n--- a/components/collector/src/source_collectors/owasp_zap.py\n+++ b/components/collector/src/source_collectors/file_source_collectors/owasp_zap.py\n@@ -9,17 +9,17 @@\n \n from collector_utilities.functions import hashless, md5_hash, parse_source_response_xml\n from collector_utilities.type import Entities, Entity, Response, Responses, URL, Value\n-from .source_collector import XMLFileSourceCollector, SourceUpToDatenessCollector\n+from base_collectors import XMLFileSourceCollector, SourceUpToDatenessCollector\n \n \n class OWASPZAPSecurityWarnings(XMLFileSourceCollector):\n \"\"\"Collector to get security warnings from OWASP ZAP.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n entities: Dict[str, Entity] = {}\n tag_re = re.compile(r\"<[^>]*>\")\n risks = cast(List[str], self._parameter(\"risks\"))\n- for alert in self.__alerts(responses, risks):\n+ for alert in await self.__alerts(responses, risks):\n alert_key = \":\".join(\n [alert.findtext(id_tag, default=\"\") for id_tag in (\"pluginid\", \"cweid\", \"wascid\", \"sourceid\")])\n name = alert.findtext(\"name\", default=\"\")\n@@ -42,11 +42,11 @@ def __stable(self, url: URL) -> URL:\n return URL(stable_url)\n \n @staticmethod\n- def __alerts(responses: Responses, risks: List[str]) -> List[Element]:\n+ async def __alerts(responses: Responses, risks: List[str]) -> List[Element]:\n \"\"\"Return a list of the alerts with one of the specified risk levels.\"\"\"\n alerts = []\n for response in responses:\n- tree = parse_source_response_xml(response)\n+ tree = await parse_source_response_xml(response)\n for risk in risks:\n alerts.extend(tree.findall(f\".//alertitem[riskcode='{risk}']\"))\n return alerts\n@@ -55,5 +55,5 @@ def __alerts(responses: Responses, risks: List[str]) -> List[Element]:\n class OWASPZAPSourceUpToDateness(XMLFileSourceCollector, SourceUpToDatenessCollector):\n \"\"\"Collector to collect the OWASP ZAP report age.\"\"\"\n \n- def _parse_source_response_date_time(self, response: Response) -> datetime:\n- return parse(parse_source_response_xml(response).get(\"generated\", \"\"))\n+ async def _parse_source_response_date_time(self, response: Response) -> datetime:\n+ return parse((await parse_source_response_xml(response)).get(\"generated\", \"\"))\ndiff --git a/components/collector/src/source_collectors/performancetest_runner.py b/components/collector/src/source_collectors/file_source_collectors/performancetest_runner.py\nsimilarity index 67%\nrename from components/collector/src/source_collectors/performancetest_runner.py\nrename to components/collector/src/source_collectors/file_source_collectors/performancetest_runner.py\n--- a/components/collector/src/source_collectors/performancetest_runner.py\n+++ b/components/collector/src/source_collectors/file_source_collectors/performancetest_runner.py\n@@ -7,23 +7,23 @@\n from bs4 import BeautifulSoup, Tag\n \n from collector_utilities.type import Entities, Entity, Response, Responses, Value\n-from .source_collector import HTMLFileSourceCollector, SourceUpToDatenessCollector\n+from base_collectors import HTMLFileSourceCollector, SourceUpToDatenessCollector\n \n \n class PerformanceTestRunnerBaseClass(HTMLFileSourceCollector, ABC): # pylint: disable=abstract-method\n \"\"\"Base class for performance test runner collectors.\"\"\"\n \n @staticmethod\n- def _soup(response: Response):\n+ async def _soup(response: Response):\n \"\"\"Return the HTML soup.\"\"\"\n- return BeautifulSoup(response.text, \"html.parser\")\n+ return BeautifulSoup(await response.text(), \"html.parser\")\n \n \n class PerformanceTestRunnerSlowTransactions(PerformanceTestRunnerBaseClass):\n \"\"\"Collector for the number of slow transactions in a Performancetest-runner performance test report.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- entities = [self.__entity(transaction) for transaction in self.__slow_transactions(responses)]\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ entities = [self.__entity(transaction) for transaction in await self.__slow_transactions(responses)]\n return str(len(entities)), \"100\", entities\n \n @staticmethod\n@@ -33,12 +33,12 @@ def __entity(transaction) -> Entity:\n threshold = \"high\" if transaction.select(\"td.red.evaluated\") else \"warning\"\n return dict(key=name, name=name, threshold=threshold)\n \n- def __slow_transactions(self, responses: Responses) -> List[Tag]:\n+ async def __slow_transactions(self, responses: Responses) -> List[Tag]:\n \"\"\"Return the slow transactions in the performance test report.\"\"\"\n thresholds = self._parameter(\"thresholds\")\n slow_transactions: List[Tag] = []\n for response in responses:\n- soup = self._soup(response)\n+ soup = await self._soup(response)\n for color in thresholds:\n slow_transactions.extend(soup.select(f\"tr.transaction:has(> td.{color}.evaluated)\"))\n return slow_transactions\n@@ -47,19 +47,20 @@ def __slow_transactions(self, responses: Responses) -> List[Tag]:\n class PerformanceTestRunnerSourceUpToDateness(PerformanceTestRunnerBaseClass, SourceUpToDatenessCollector):\n \"\"\"Collector for the performance test report age.\"\"\"\n \n- def _parse_source_response_date_time(self, response: Response) -> datetime:\n- datetime_parts = [int(part) for part in self._soup(response).find(id=\"start_of_the_test\").string.split(\".\")]\n+ async def _parse_source_response_date_time(self, response: Response) -> datetime:\n+ datetime_parts = [\n+ int(part) for part in (await self._soup(response)).find(id=\"start_of_the_test\").string.split(\".\")]\n return datetime(*datetime_parts) # type: ignore\n \n \n class PerformanceTestRunnerPerformanceTestDuration(PerformanceTestRunnerBaseClass):\n \"\"\"Collector for the performance test duration.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n durations = []\n for response in responses:\n hours, minutes, seconds = [\n- int(part) for part in self._soup(response).find(id=\"duration\").string.split(\":\", 2)]\n+ int(part) for part in (await self._soup(response)).find(id=\"duration\").string.split(\":\", 2)]\n durations.append(60 * hours + minutes + round(seconds / 60.))\n return str(sum(durations)), \"100\", []\n \n@@ -67,31 +68,31 @@ def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, E\n class PerformanceTestRunnerPerformanceTestStability(PerformanceTestRunnerBaseClass):\n \"\"\"Collector for the performance test stability.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n trend_breaks = []\n for response in responses:\n- trend_breaks.append(int(self._soup(response).find(id=\"trendbreak_stability\").string))\n+ trend_breaks.append(int((await self._soup(response)).find(id=\"trendbreak_stability\").string))\n return str(min(trend_breaks)), \"100\", []\n \n \n class PerformanceTestRunnerTests(PerformanceTestRunnerBaseClass):\n \"\"\"Collector for the number of performance test transactions.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n count = 0\n statuses = self._parameter(\"test_result\")\n for response in responses:\n- count += sum(int(self._soup(response).find(id=status).string) for status in statuses)\n+ count += sum([int((await self._soup(response)).find(id=status).string) for status in statuses])\n return str(count), \"100\", []\n \n \n class PerformanceTestRunnerScalability(PerformanceTestRunnerBaseClass):\n \"\"\"Collector for the scalability metric.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n trend_breaks = []\n for response in responses:\n- breaking_point = int(self._soup(response).find(id=\"trendbreak_scalability\").string)\n+ breaking_point = int((await self._soup(response)).find(id=\"trendbreak_scalability\").string)\n if breaking_point == 100:\n raise AssertionError(\n \"No performance scalability breaking point occurred (breaking point is at 100%, expected < 100%)\")\ndiff --git a/components/collector/src/source_collectors/pyupio_safety.py b/components/collector/src/source_collectors/file_source_collectors/pyupio_safety.py\nsimilarity index 79%\nrename from components/collector/src/source_collectors/pyupio_safety.py\nrename to components/collector/src/source_collectors/file_source_collectors/pyupio_safety.py\n--- a/components/collector/src/source_collectors/pyupio_safety.py\n+++ b/components/collector/src/source_collectors/file_source_collectors/pyupio_safety.py\n@@ -3,7 +3,7 @@\n from typing import Final, Tuple\n \n from collector_utilities.type import Entities, Responses, Value\n-from .source_collector import JSONFileSourceCollector\n+from base_collectors import JSONFileSourceCollector\n \n \n class PyupioSafetySecurityWarnings(JSONFileSourceCollector):\n@@ -15,7 +15,7 @@ class PyupioSafetySecurityWarnings(JSONFileSourceCollector):\n VULNERABILITY: Final[int] = 3\n KEY: Final[int] = 4\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n \"\"\"Return a list of warnings.\"\"\"\n entities = []\n for response in responses:\n@@ -23,5 +23,5 @@ def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, E\n [dict(\n key=warning[self.KEY], package=warning[self.PACKAGE], installed=warning[self.INSTALLED],\n affected=warning[self.AFFECTED], vulnerability=warning[self.VULNERABILITY])\n- for warning in response.json()])\n+ for warning in await response.json()])\n return str(len(entities)), \"100\", entities\ndiff --git a/components/collector/src/source_collectors/robot_framework.py b/components/collector/src/source_collectors/file_source_collectors/robot_framework.py\nsimilarity index 71%\nrename from components/collector/src/source_collectors/robot_framework.py\nrename to components/collector/src/source_collectors/file_source_collectors/robot_framework.py\n--- a/components/collector/src/source_collectors/robot_framework.py\n+++ b/components/collector/src/source_collectors/file_source_collectors/robot_framework.py\n@@ -8,26 +8,26 @@\n \n from collector_utilities.type import Entities, Response, Responses, URL, Value\n from collector_utilities.functions import parse_source_response_xml\n-from .source_collector import XMLFileSourceCollector, SourceUpToDatenessCollector\n+from base_collectors import XMLFileSourceCollector, SourceUpToDatenessCollector\n \n \n class RobotFrameworkBaseClass(XMLFileSourceCollector, ABC): # pylint: disable=abstract-method\n \"\"\"Base class for Robot Framework collectors.\"\"\"\n \n- def _landing_url(self, responses: Responses) -> URL:\n- url = str(super()._landing_url(responses))\n+ async def _landing_url(self, responses: Responses) -> URL:\n+ url = str(await super()._landing_url(responses))\n return URL(url.replace(\"output.html\", \"report.html\"))\n \n \n class RobotFrameworkTests(RobotFrameworkBaseClass):\n \"\"\"Collector for Robot Framework tests.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n count = 0\n entities: Entities = []\n test_results = cast(List[str], self._parameter(\"test_result\"))\n for response in responses:\n- tree = parse_source_response_xml(response)\n+ tree = await parse_source_response_xml(response)\n stats = tree.findall(\"statistics/total/stat\")[1]\n for test_result in test_results:\n count += int(stats.get(test_result, 0))\n@@ -39,5 +39,5 @@ def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, E\n class RobotFrameworkSourceUpToDateness(RobotFrameworkBaseClass, SourceUpToDatenessCollector):\n \"\"\"Collector to collect the Robot Framework report age.\"\"\"\n \n- def _parse_source_response_date_time(self, response: Response) -> datetime:\n- return parse(parse_source_response_xml(response).get(\"generated\", \"\"))\n+ async def _parse_source_response_date_time(self, response: Response) -> datetime:\n+ return parse((await parse_source_response_xml(response)).get(\"generated\", \"\"))\ndiff --git a/components/collector/src/source_collectors/local_source_collectors/__init__.py b/components/collector/src/source_collectors/local_source_collectors/__init__.py\nnew file mode 100644\ndiff --git a/components/collector/src/source_collectors/calendar.py b/components/collector/src/source_collectors/local_source_collectors/calendar.py\nsimilarity index 69%\nrename from components/collector/src/source_collectors/calendar.py\nrename to components/collector/src/source_collectors/local_source_collectors/calendar.py\n--- a/components/collector/src/source_collectors/calendar.py\n+++ b/components/collector/src/source_collectors/local_source_collectors/calendar.py\n@@ -4,11 +4,11 @@\n from typing import cast\n \n from collector_utilities.type import Response\n-from .source_collector import LocalSourceCollector, SourceUpToDatenessCollector\n+from base_collectors import LocalSourceCollector, SourceUpToDatenessCollector\n \n \n class CalendarSourceUpToDateness(SourceUpToDatenessCollector, LocalSourceCollector):\n \"\"\"Collector class to get the number of days since a user-specified date.\"\"\"\n \n- def _parse_source_response_date_time(self, response: Response) -> datetime:\n+ async def _parse_source_response_date_time(self, response: Response) -> datetime:\n return datetime.fromisoformat(cast(str, self._parameter(\"date\")))\ndiff --git a/components/collector/src/source_collectors/manual_number.py b/components/collector/src/source_collectors/local_source_collectors/manual_number.py\nsimilarity index 66%\nrename from components/collector/src/source_collectors/manual_number.py\nrename to components/collector/src/source_collectors/local_source_collectors/manual_number.py\n--- a/components/collector/src/source_collectors/manual_number.py\n+++ b/components/collector/src/source_collectors/local_source_collectors/manual_number.py\n@@ -3,11 +3,11 @@\n from typing import Tuple\n \n from collector_utilities.type import Entities, Responses, Value\n-from .source_collector import LocalSourceCollector\n+from base_collectors import LocalSourceCollector\n \n \n class ManualNumber(LocalSourceCollector):\n \"\"\"Manual number metric collector.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n return str(self._parameter(\"number\")), \"100\", []\ndiff --git a/components/collector/src/source_collectors/random_number.py b/components/collector/src/source_collectors/local_source_collectors/random_number.py\nsimilarity index 74%\nrename from components/collector/src/source_collectors/random_number.py\nrename to components/collector/src/source_collectors/local_source_collectors/random_number.py\n--- a/components/collector/src/source_collectors/random_number.py\n+++ b/components/collector/src/source_collectors/local_source_collectors/random_number.py\n@@ -4,7 +4,7 @@\n from typing import Final, Tuple\n \n from collector_utilities.type import Entities, Responses, Value\n-from .source_collector import LocalSourceCollector\n+from base_collectors import LocalSourceCollector\n \n \n class Random(LocalSourceCollector):\n@@ -12,6 +12,6 @@ class Random(LocalSourceCollector):\n MIN: Final[int] = 1\n MAX: Final[int] = 99\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n value = random.randint(self.MIN, self.MAX) # nosec, random generator is not used for security purpose\n return str(value), \"100\", []\n", "test_patch": "diff --git a/components/collector/tests/metric_collectors/__init__.py b/components/collector/src/source_collectors/api_source_collectors/__init__.py\nsimilarity index 100%\nrename from components/collector/tests/metric_collectors/__init__.py\nrename to components/collector/src/source_collectors/api_source_collectors/__init__.py\ndiff --git a/components/collector/src/source_collectors/jenkins_test_report.py b/components/collector/src/source_collectors/api_source_collectors/jenkins_test_report.py\nsimilarity index 73%\nrename from components/collector/src/source_collectors/jenkins_test_report.py\nrename to components/collector/src/source_collectors/api_source_collectors/jenkins_test_report.py\n--- a/components/collector/src/source_collectors/jenkins_test_report.py\n+++ b/components/collector/src/source_collectors/api_source_collectors/jenkins_test_report.py\n@@ -4,11 +4,10 @@\n from typing import cast, Dict, Final, List, Tuple\n \n from dateutil.parser import parse\n-import requests\n \n from collector_utilities.type import Entity, Entities, Responses, URL, Value\n from collector_utilities.functions import days_ago\n-from .source_collector import SourceCollector\n+from base_collectors import SourceCollector\n \n \n TestCase = Dict[str, str]\n@@ -21,11 +20,11 @@ class JenkinsTestReportTests(SourceCollector):\n JENKINS_TEST_REPORT_COUNTS: Final[Dict[str, str]] = dict(\n failed=\"failCount\", passed=\"passCount\", skipped=\"skipCount\")\n \n- def _api_url(self) -> URL:\n- return URL(f\"{super()._api_url()}/lastSuccessfulBuild/testReport/api/json\")\n+ async def _api_url(self) -> URL:\n+ return URL(f\"{await super()._api_url()}/lastSuccessfulBuild/testReport/api/json\")\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- json = responses[0].json()\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ json = await responses[0].json()\n statuses = cast(List[str], self._parameter(\"test_result\"))\n status_counts = [self.JENKINS_TEST_REPORT_COUNTS[status] for status in statuses]\n results = [report[\"result\"] for report in json[\"childReports\"]] if \"childReports\" in json else [json]\n@@ -56,15 +55,14 @@ def __status(case: TestCase) -> str:\n class JenkinsTestReportSourceUpToDateness(SourceCollector):\n \"\"\"Collector to get the age of the Jenkins test report.\"\"\"\n \n- def _get_source_responses(self, api_url: URL) -> Responses:\n- test_report_url = URL(f\"{api_url}/lastSuccessfulBuild/testReport/api/json\")\n- job_url = URL(f\"{api_url}/lastSuccessfulBuild/api/json\")\n- return [requests.get(url, timeout=self.TIMEOUT, auth=self._basic_auth_credentials())\n- for url in (test_report_url, job_url)]\n+ async def _get_source_responses(self, *urls: URL) -> Responses:\n+ test_report_url = URL(f\"{urls[0]}/lastSuccessfulBuild/testReport/api/json\")\n+ job_url = URL(f\"{urls[0]}/lastSuccessfulBuild/api/json\")\n+ return await super()._get_source_responses(test_report_url, job_url)\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n- timestamps = [suite.get(\"timestamp\") for suite in responses[0].json().get(\"suites\", [])\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ timestamps = [suite.get(\"timestamp\") for suite in (await responses[0].json()).get(\"suites\", [])\n if suite.get(\"timestamp\")]\n report_datetime = parse(max(timestamps)) if timestamps else \\\n- datetime.fromtimestamp(float(responses[1].json()[\"timestamp\"]) / 1000.)\n+ datetime.fromtimestamp(float((await responses[1].json())[\"timestamp\"]) / 1000.)\n return str(days_ago(report_datetime)), \"100\", []\ndiff --git a/components/collector/tests/base_collectors/__init__.py b/components/collector/tests/base_collectors/__init__.py\nnew file mode 100644\ndiff --git a/components/collector/tests/base_collectors/test_cached_client_session.py b/components/collector/tests/base_collectors/test_cached_client_session.py\nnew file mode 100644\n--- /dev/null\n+++ b/components/collector/tests/base_collectors/test_cached_client_session.py\n@@ -0,0 +1,34 @@\n+\"\"\"Unit tests for the client session with cached GET requests.\"\"\"\n+\n+import asyncio\n+from unittest.mock import patch\n+\n+import aiounittest\n+\n+from base_collectors.cached_client_session import CachedClientSession\n+\n+\n+class CachedClientSessionTest(aiounittest.AsyncTestCase):\n+ \"\"\"Unit tests for the cached client session class.\"\"\"\n+\n+ async def get(self, *args, **kwargs): # pylint: disable=unused-argument\n+ \"\"\"Fake the session.get method.\"\"\"\n+ self.get_calls += 1 # pylint: disable=no-member\n+ await asyncio.sleep(0)\n+\n+ @patch(\"aiohttp.ClientSession.get\", new=get)\n+ async def test_get_same_url_once(self):\n+ \"\"\"Test that the url is retrieved once.\"\"\"\n+ async with CachedClientSession() as session:\n+ session.get_calls = 0\n+ await session.get(\"https://url\")\n+ self.assertEqual(1, session.get_calls)\n+\n+ @patch(\"aiohttp.ClientSession.get\", new=get)\n+ async def test_get_same_url_twice(self):\n+ \"\"\"Test that the url is retrieved only once.\"\"\"\n+ async with CachedClientSession() as session:\n+ session.get_calls = 0\n+ await asyncio.gather(session.get(\"https://url\"), session.get(\"https://url\"))\n+ await asyncio.gather(session.get(\"https://url\"), session.get(\"https://url\"))\n+ self.assertEqual(1, session.get_calls)\ndiff --git a/components/collector/tests/metric_collectors/test_metrics_collector.py b/components/collector/tests/base_collectors/test_metrics_collector.py\nsimilarity index 56%\nrename from components/collector/tests/metric_collectors/test_metrics_collector.py\nrename to components/collector/tests/base_collectors/test_metrics_collector.py\n--- a/components/collector/tests/metric_collectors/test_metrics_collector.py\n+++ b/components/collector/tests/base_collectors/test_metrics_collector.py\n@@ -1,31 +1,29 @@\n \"\"\"Unit tests for the collector main script.\"\"\"\n \n import logging\n-import unittest\n from datetime import datetime\n from typing import Tuple\n-from unittest.mock import patch, mock_open, Mock\n+from unittest.mock import patch, mock_open, AsyncMock, Mock\n+\n+import aiohttp\n+import aiounittest\n \n import quality_time_collector\n-from metric_collectors import MetricsCollector\n-from source_collectors import source_collector\n+from base_collectors import MetricsCollector, SourceCollector\n from collector_utilities.type import Entities, Responses, Value\n \n \n-class CollectorTest(unittest.TestCase):\n+class CollectorTest(aiounittest.AsyncTestCase):\n \"\"\"Unit tests for the collection methods.\"\"\"\n \n def setUp(self):\n- class SourceMetric(source_collector.SourceCollector): # pylint: disable=unused-variable\n+ class SourceMetric(SourceCollector): # pylint: disable=unused-variable\n \"\"\"Register a fake collector automatically.\"\"\"\n \n- def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n+ async def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, Entities]:\n return \"42\", \"84\", []\n \n- self.data_model_response = Mock()\n self.data_model = dict(sources=dict(source=dict(parameters=dict(url=dict(mandatory=True, metrics=[\"metric\"])))))\n- self.data_model_response.json.return_value = self.data_model\n- self.metrics_response = Mock()\n self.metrics_collector = MetricsCollector()\n self.url = \"https://url\"\n self.measurement_api_url = \"http://localhost:5001/api/v2/measurements\"\n@@ -34,34 +32,39 @@ def _parse_source_responses(self, responses: Responses) -> Tuple[Value, Value, E\n def tearDown(self):\n logging.disable(logging.NOTSET)\n \n- @patch(\"requests.post\")\n- @patch(\"requests.get\")\n- def test_fetch_without_sources(self, mocked_get, mocked_post):\n+ async def fetch_measurements(self, mock_async_get_request, number=1):\n+ \"\"\"Fetch the measurements with patched get method.\"\"\"\n+ with patch(\"aiohttp.ClientSession.get\", AsyncMock(return_value=mock_async_get_request)):\n+ async with aiohttp.ClientSession() as session:\n+ for _ in range(number):\n+ await self.metrics_collector.collect_metrics(session, 60)\n+\n+ @patch(\"aiohttp.ClientSession.post\")\n+ async def test_fetch_without_sources(self, mocked_post):\n \"\"\"Test fetching measurement for a metric without sources.\"\"\"\n- self.metrics_response.json.return_value = dict(\n- metric_uuid=dict(type=\"metric\", addition=\"sum\", sources=dict()))\n- mocked_get.return_value = self.metrics_response\n- self.metrics_collector.fetch_measurements(60)\n+ metrics = dict(metric_uuid=dict(type=\"metric\", addition=\"sum\", sources=dict()))\n+ mock_async_get_request = AsyncMock()\n+ mock_async_get_request.json.return_value = metrics\n+ await self.fetch_measurements(mock_async_get_request)\n mocked_post.assert_not_called()\n \n- @patch(\"requests.post\")\n- @patch(\"requests.get\", Mock(side_effect=RuntimeError))\n- def test_fetch_with_get_error(self, mocked_post):\n+ @patch(\"aiohttp.ClientSession.post\")\n+ async def test_fetch_with_get_error(self, mocked_post):\n \"\"\"Test fetching measurement when getting fails.\"\"\"\n- self.metrics_collector.fetch_measurements(60)\n+ await self.fetch_measurements(Mock(side_effect=RuntimeError))\n mocked_post.assert_not_called()\n \n- @patch(\"requests.post\", side_effect=RuntimeError)\n- @patch(\"requests.get\")\n- def test_fetch_with_post_error(self, mocked_get, mocked_post):\n+ @patch(\"aiohttp.ClientSession.post\", side_effect=RuntimeError)\n+ async def test_fetch_with_post_error(self, mocked_post):\n \"\"\"Test fetching measurement when posting fails.\"\"\"\n- self.metrics_response.json.return_value = dict(\n+ metrics = dict(\n metric_uuid=dict(\n addition=\"sum\", type=\"metric\",\n sources=dict(source_id=dict(type=\"source\", parameters=dict(url=self.url)))))\n- mocked_get.side_effect = [self.metrics_response, Mock()]\n self.metrics_collector.data_model = self.data_model\n- self.metrics_collector.fetch_measurements(60)\n+ mock_async_get_request = AsyncMock()\n+ mock_async_get_request.json.return_value = metrics\n+ await self.fetch_measurements(mock_async_get_request)\n mocked_post.assert_called_once_with(\n self.measurement_api_url,\n json=dict(\n@@ -70,18 +73,20 @@ def test_fetch_with_post_error(self, mocked_get, mocked_post):\n connection_error=None, parse_error=None, source_uuid=\"source_id\")],\n metric_uuid=\"metric_uuid\"))\n \n+ @patch(\"asyncio.sleep\", Mock(side_effect=RuntimeError))\n @patch(\"builtins.open\", mock_open())\n- @patch(\"time.sleep\", Mock(side_effect=RuntimeError))\n- @patch(\"requests.post\")\n- @patch(\"requests.get\")\n- def test_collect(self, mocked_get, mocked_post):\n+ @patch(\"aiohttp.ClientSession.post\")\n+ async def test_collect(self, mocked_post):\n \"\"\"Test the collect method.\"\"\"\n- self.metrics_response.json.return_value = dict(\n+ metrics = dict(\n metric_uuid=dict(\n addition=\"sum\", type=\"metric\",\n sources=dict(source_id=dict(type=\"source\", parameters=dict(url=self.url)))))\n- mocked_get.side_effect = [self.data_model_response, self.metrics_response, Mock()]\n- self.assertRaises(RuntimeError, quality_time_collector.collect)\n+ mock_async_get_request = AsyncMock()\n+ mock_async_get_request.json.side_effect = [self.data_model, metrics]\n+ with patch(\"aiohttp.ClientSession.get\", AsyncMock(return_value=mock_async_get_request)):\n+ with self.assertRaises(RuntimeError):\n+ await quality_time_collector.collect()\n mocked_post.assert_called_once_with(\n self.measurement_api_url,\n json=dict(\n@@ -90,28 +95,29 @@ def test_collect(self, mocked_get, mocked_post):\n connection_error=None, parse_error=None, source_uuid=\"source_id\")],\n metric_uuid=\"metric_uuid\"))\n \n- @patch(\"requests.get\")\n- def test_missing_collector(self, mocked_get):\n+ async def test_missing_collector(self):\n \"\"\"Test that an exception is thrown if there's no collector for the source and metric type.\"\"\"\n- self.metrics_response.json.return_value = dict(\n+ metrics = dict(\n metric_uuid=dict(\n type=\"metric\", addition=\"sum\",\n sources=dict(missing=dict(type=\"unknown_source\", parameters=dict(url=self.url)))))\n- mocked_get.return_value = self.metrics_response\n- self.assertRaises(LookupError, self.metrics_collector.fetch_measurements, 60)\n+ self.metrics_collector.data_model = self.data_model\n+ mock_async_get_request = AsyncMock()\n+ mock_async_get_request.json.return_value = metrics\n+ with self.assertRaises(LookupError):\n+ await self.fetch_measurements(mock_async_get_request)\n \n- @patch(\"requests.post\")\n- @patch(\"requests.get\")\n- def test_fetch_twice(self, mocked_get, mocked_post):\n+ @patch(\"aiohttp.ClientSession.post\")\n+ async def test_fetch_twice(self, mocked_post):\n \"\"\"Test that the metric is skipped on the second fetch.\"\"\"\n- self.metrics_response.json.return_value = dict(\n+ metrics = dict(\n metric_uuid=dict(\n addition=\"sum\", type=\"metric\",\n sources=dict(source_id=dict(type=\"source\", parameters=dict(url=self.url)))))\n- mocked_get.side_effect = [self.metrics_response, Mock(), self.metrics_response]\n self.metrics_collector.data_model = self.data_model\n- self.metrics_collector.fetch_measurements(60)\n- self.metrics_collector.fetch_measurements(60)\n+ mock_async_get_request = AsyncMock()\n+ mock_async_get_request.json.side_effect = [metrics, metrics]\n+ await self.fetch_measurements(mock_async_get_request, number=2)\n mocked_post.assert_called_once_with(\n \"http://localhost:5001/api/v2/measurements\",\n json=dict(\n@@ -120,28 +126,30 @@ def test_fetch_twice(self, mocked_get, mocked_post):\n connection_error=None, parse_error=None, source_uuid=\"source_id\")],\n metric_uuid=\"metric_uuid\"))\n \n- @patch(\"requests.post\")\n- @patch(\"requests.get\")\n- def test_missing_mandatory_parameter(self, mocked_get, mocked_post):\n+ @patch(\"aiohttp.ClientSession.post\")\n+ async def test_missing_mandatory_parameter(self, mocked_post):\n \"\"\"Test that a metric with sources but without a mandatory parameter is skipped.\"\"\"\n- self.metrics_response.json.return_value = dict(\n+ metrics = dict(\n metric_uuid=dict(\n type=\"metric\", addition=\"sum\", sources=dict(missing=dict(type=\"source\", parameters=dict(url=\"\")))))\n- mocked_get.return_value = self.metrics_response\n self.metrics_collector.data_model = self.data_model\n- self.metrics_collector.fetch_measurements(60)\n+ mock_async_get_request = AsyncMock()\n+ mock_async_get_request.json.return_value = metrics\n+ await self.fetch_measurements(mock_async_get_request)\n mocked_post.assert_not_called()\n \n @patch(\"builtins.open\", mock_open())\n- @patch(\"requests.get\")\n- def test_fetch_data_model_after_failure(self, mocked_get):\n+ async def test_fetch_data_model_after_failure(self):\n \"\"\"Test that the data model is fetched on the second try.\"\"\"\n- mocked_get.side_effect = [None, self.data_model_response]\n- data_model = self.metrics_collector.fetch_data_model(0)\n+ mock_async_get_request = AsyncMock()\n+ mock_async_get_request.json.side_effect = [RuntimeError, self.data_model]\n+ with patch(\"aiohttp.ClientSession.get\", AsyncMock(return_value=mock_async_get_request)):\n+ async with aiohttp.ClientSession() as session:\n+ data_model = await self.metrics_collector.fetch_data_model(session, 0)\n self.assertEqual(self.data_model, data_model)\n \n @patch(\"builtins.open\", new_callable=mock_open)\n- @patch(\"metric_collectors.metrics_collector.datetime\")\n+ @patch(\"base_collectors.metrics_collector.datetime\")\n def test_writing_health_check(self, mocked_datetime, mocked_open):\n \"\"\"Test that the current time is written to the health check file.\"\"\"\n mocked_datetime.now.return_value = now = datetime.now()\ndiff --git a/components/collector/tests/source_collectors/api_source_collectors/__init__.py b/components/collector/tests/source_collectors/api_source_collectors/__init__.py\nnew file mode 100644\ndiff --git a/components/collector/tests/source_collectors/test_azure_devops.py b/components/collector/tests/source_collectors/api_source_collectors/test_azure_devops.py\nsimilarity index 87%\nrename from components/collector/tests/source_collectors/test_azure_devops.py\nrename to components/collector/tests/source_collectors/api_source_collectors/test_azure_devops.py\n--- a/components/collector/tests/source_collectors/test_azure_devops.py\n+++ b/components/collector/tests/source_collectors/api_source_collectors/test_azure_devops.py\n@@ -3,7 +3,7 @@\n from dateutil.parser import parse\n \n from collector_utilities.functions import days_ago\n-from .source_collector_test_case import SourceCollectorTestCase\n+from ..source_collector_test_case import SourceCollectorTestCase\n \n \n class AzureDevopsTestCase(SourceCollectorTestCase):\n@@ -25,21 +25,21 @@ def setUp(self):\n super().setUp()\n self.metric = dict(type=\"issues\", sources=self.sources, addition=\"sum\")\n \n- def test_nr_of_issues(self):\n+ async def test_nr_of_issues(self):\n \"\"\"Test that the number of issues is returned.\"\"\"\n- response = self.collect(\n+ response = await self.collect(\n self.metric, post_request_json_return_value=dict(workItems=[dict(id=\"id1\"), dict(id=\"id2\")]),\n get_request_json_return_value=dict(value=[self.work_item, self.work_item]))\n self.assert_measurement(response, value=\"2\")\n \n- def test_no_issues(self):\n+ async def test_no_issues(self):\n \"\"\"Test zero issues.\"\"\"\n- response = self.collect(self.metric, post_request_json_return_value=dict(workItems=[]))\n+ response = await self.collect(self.metric, post_request_json_return_value=dict(workItems=[]))\n self.assert_measurement(response, value=\"0\", entities=[])\n \n- def test_issues(self):\n+ async def test_issues(self):\n \"\"\"Test that the issues are returned.\"\"\"\n- response = self.collect(\n+ response = await self.collect(\n self.metric, post_request_json_return_value=dict(workItems=[dict(id=\"id\")]),\n get_request_json_return_value=dict(value=[self.work_item]))\n self.assert_measurement(\n@@ -55,16 +55,16 @@ def setUp(self):\n super().setUp()\n self.metric = dict(type=\"ready_user_story_points\", sources=self.sources, addition=\"sum\")\n \n- def test_story_points(self):\n+ async def test_story_points(self):\n \"\"\"Test that the number of story points are returned.\"\"\"\n- response = self.collect(\n+ response = await self.collect(\n self.metric, post_request_json_return_value=dict(workItems=[dict(id=\"id1\"), dict(id=\"id2\")]),\n get_request_json_return_value=dict(value=[self.work_item, self.work_item]))\n self.assert_measurement(response, value=\"4\")\n \n- def test_story_points_without_stories(self):\n+ async def test_story_points_without_stories(self):\n \"\"\"Test that the number of story points is zero when there are no work items.\"\"\"\n- response = self.collect(\n+ response = await self.collect(\n self.metric, post_request_json_return_value=dict(workItems=[]),\n get_request_json_return_value=dict(value=[]))\n self.assert_measurement(response, value=\"0\", entities=[])\n@@ -82,14 +82,14 @@ def setUp(self):\n self.metric = dict(type=\"unmerged_branches\", sources=self.sources, addition=\"sum\")\n self.repositories = dict(value=[dict(id=\"id\", name=\"project\")])\n \n- def test_no_branches_except_master(self):\n+ async def test_no_branches_except_master(self):\n \"\"\"Test that the number of unmerged branches is returned.\"\"\"\n branches = dict(value=[dict(name=\"master\", isBaseVersion=True)])\n- response = self.collect(self.metric, get_request_json_side_effect=[self.repositories, branches])\n+ response = await self.collect(self.metric, get_request_json_side_effect=[self.repositories, branches])\n self.assert_measurement(\n response, value=\"0\", entities=[], landing_url=\"https://azure_devops/org/project/_git/project/branches\")\n \n- def test_unmerged_branches(self):\n+ async def test_unmerged_branches(self):\n \"\"\"Test that the number of unmerged branches is returned.\"\"\"\n timestamp = \"2019-09-03T20:43:00Z\"\n branches = dict(\n@@ -99,11 +99,10 @@ def test_unmerged_branches(self):\n commit=dict(committer=dict(date=timestamp))),\n dict(name=\"ignored_branch\", isBaseVersion=False, aheadCount=1,\n commit=dict(committer=dict(date=timestamp)))])\n- response = self.collect(self.metric, get_request_json_side_effect=[self.repositories, branches])\n+ response = await self.collect(self.metric, get_request_json_side_effect=[self.repositories, branches])\n expected_age = str(days_ago(parse(timestamp)))\n self.assert_measurement(\n- response,\n- value=\"1\",\n+ response, value=\"1\",\n entities=[dict(name=\"branch\", key=\"branch\", commit_age=expected_age, commit_date=\"2019-09-03\")],\n landing_url=\"https://azure_devops/org/project/_git/project/branches\")\n \n@@ -111,7 +110,7 @@ def test_unmerged_branches(self):\n class AzureDevopsSourceUpToDatenessTest(SourceCollectorTestCase):\n \"\"\"Unit tests for the Azure DevOps Server source up-to-dateness collector.\"\"\"\n \n- def test_age(self):\n+ async def test_age(self):\n \"\"\"Test that the age of the file is returned.\"\"\"\n sources = dict(\n source_id=dict(\n@@ -123,27 +122,24 @@ def test_age(self):\n repositories = dict(value=[dict(id=\"id\", name=\"repo\")])\n timestamp = \"2019-09-03T20:43:00Z\"\n commits = dict(value=[dict(committer=dict(date=timestamp))])\n- response = self.collect(\n- metric, get_request_json_side_effect=[repositories, commits])\n+ response = await self.collect(metric, get_request_json_side_effect=[repositories, commits])\n expected_age = str(days_ago(parse(timestamp)))\n self.assert_measurement(\n- response,\n- value=expected_age,\n+ response, value=expected_age,\n landing_url=\"https://azure_devops/org/project/_git/repo?path=README.md&version=GBmaster\")\n \n \n class AzureDevopsTestsTest(SourceCollectorTestCase):\n \"\"\"Unit tests for the Azure DevOps Server tests collector.\"\"\"\n \n- def test_nr_of_tests(self):\n+ async def test_nr_of_tests(self):\n \"\"\"Test that the number of tests is returned.\"\"\"\n sources = dict(\n source_id=dict(\n type=\"azure_devops\", parameters=dict(url=\"https://azure_devops\", private_token=\"xxx\", test_result=[])))\n metric = dict(type=\"tests\", sources=sources, addition=\"sum\")\n- response = self.collect(\n- metric,\n- get_request_json_return_value=dict(\n+ response = await self.collect(\n+ metric, get_request_json_return_value=dict(\n value=[\n dict(build=dict(id=\"1\"), passedTests=2),\n dict(build=dict(id=\"2\"), passedTests=2, notApplicableTests=1),\n@@ -151,14 +147,14 @@ def test_nr_of_tests(self):\n dict(build=dict(id=\"2\"), passedTests=1)]))\n self.assert_measurement(response, value=\"4\")\n \n- def test_nr_of_failed_tests(self):\n+ async def test_nr_of_failed_tests(self):\n \"\"\"Test that the number of failed tests is returned.\"\"\"\n sources = dict(\n source_id=dict(\n type=\"azure_devops\",\n parameters=dict(url=\"https://azure_devops\", private_token=\"xxx\", test_result=[\"failed\"])))\n metric = dict(type=\"tests\", sources=sources, addition=\"sum\")\n- response = self.collect(\n+ response = await self.collect(\n metric, get_request_json_return_value=dict(value=[dict(build=dict(id=\"1\"), unanalyzedTests=4)]))\n self.assert_measurement(response, value=\"4\")\n \n@@ -166,7 +162,7 @@ def test_nr_of_failed_tests(self):\n class AzureDevopsFailedJobsTest(SourceCollectorTestCase):\n \"\"\"Unit tests for the Azure Devops Server failed jobs collector.\"\"\"\n \n- def test_nr_of_failed_jobs(self):\n+ async def test_nr_of_failed_jobs(self):\n \"\"\"Test that the number of failed jobs is returned, that pipelines can be ignored by status, by name, and by\n regular expression.\"\"\"\n sources = dict(\n@@ -176,7 +172,7 @@ def test_nr_of_failed_jobs(self):\n url=\"https://azure_devops\", private_token=\"xxx\", failure_type=[\"failed\"],\n jobs_to_ignore=[\"ignore_by_name\", \"folder/ignore.*\"])))\n metric = dict(type=\"failed_jobs\", sources=sources, addition=\"sum\")\n- response = self.collect(\n+ response = await self.collect(\n metric,\n get_request_json_return_value=dict(\n value=[\n@@ -196,7 +192,7 @@ def test_nr_of_failed_jobs(self):\n dict(name=r\"folder/pipeline\", key=r\"folder/pipeline\", url=\"https://azure_devops/build\",\n build_date=\"2019-11-15\", build_age=str(expected_age), build_status=\"failed\")])\n \n- def test_nr_of_unused_jobs(self):\n+ async def test_nr_of_unused_jobs(self):\n \"\"\"Test that the number of unused jobs is returned, that pipelines can be ignored by name and by\n regular expression.\"\"\"\n sources = dict(\n@@ -206,7 +202,7 @@ def test_nr_of_unused_jobs(self):\n url=\"https://azure_devops\", private_token=\"xxx\",\n jobs_to_ignore=[\"ignore_by_name\", \"folder/ignore.*\"])))\n metric = dict(type=\"unused_jobs\", sources=sources, addition=\"sum\")\n- response = self.collect(\n+ response = await self.collect(\n metric,\n get_request_json_return_value=dict(\n value=[\ndiff --git a/components/collector/tests/source_collectors/test_cxsast.py b/components/collector/tests/source_collectors/api_source_collectors/test_cxsast.py\nsimilarity index 73%\nrename from components/collector/tests/source_collectors/test_cxsast.py\nrename to components/collector/tests/source_collectors/api_source_collectors/test_cxsast.py\n--- a/components/collector/tests/source_collectors/test_cxsast.py\n+++ b/components/collector/tests/source_collectors/api_source_collectors/test_cxsast.py\n@@ -2,7 +2,7 @@\n \n from datetime import datetime, timezone\n \n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class CxSASTTestCase(SourceCollectorTestCase):\n@@ -22,35 +22,37 @@ def setUp(self):\n super().setUp()\n self.metric = dict(type=\"source_up_to_dateness\", sources=self.sources, addition=\"sum\")\n \n- def test_age(self):\n+ async def test_age(self):\n \"\"\"Test that the age of the last finished scan is returned.\"\"\"\n get_json = [\n- [dict(name=\"project\", id=\"id\")], [dict(dateAndTime=dict(finishedOn=\"2019-01-01T09:06:12+00:00\"))],\n- [dict(name=\"project\", id=\"id\")], [dict(id=\"scan_id\")]]\n- post_json = [dict(access_token=\"token\")] * 2\n- response = self.collect(\n- self.metric, get_request_json_side_effect=get_json, post_request_json_side_effect=post_json)\n+ [dict(name=\"project\", id=\"id\")], [dict(id=\"scan_id\")],\n+ [dict(dateAndTime=dict(finishedOn=\"2019-01-01T09:06:12+00:00\"))]]\n+ post_json = dict(access_token=\"token\")\n+ response = await self.collect(\n+ self.metric, get_request_json_side_effect=get_json, post_request_json_return_value=post_json)\n expected_age = (datetime.now(timezone.utc) - datetime(2019, 1, 1, 9, 6, 9, tzinfo=timezone.utc)).days\n self.assert_measurement(\n response, value=str(expected_age),\n landing_url=\"https://checkmarx/CxWebClient/ViewerMain.aspx?scanId=scan_id&ProjectID=id\")\n \n- def test_landing_url_without_response(self):\n+ async def test_landing_url_without_response(self):\n \"\"\"Test that a default landing url is returned when connecting to the source fails.\"\"\"\n- response = self.collect(self.metric, post_request_side_effect=RuntimeError)\n+ response = await self.collect(self.metric, post_request_side_effect=RuntimeError)\n self.assert_measurement(response, landing_url=\"https://checkmarx\", connection_error=\"Traceback\")\n \n \n class CxSASTSecurityWarningsTest(CxSASTTestCase):\n \"\"\"Unit tests for the security warnings collector.\"\"\"\n \n- def test_nr_of_warnings(self):\n+ async def test_nr_of_warnings(self):\n \"\"\"Test that the number of security warnings is returned.\"\"\"\n metric = dict(type=\"security_warnings\", sources=self.sources, addition=\"sum\")\n get_json = [\n [dict(name=\"project\", id=\"id\")], [dict(id=1000)],\n dict(highSeverity=1, mediumSeverity=2, lowSeverity=3, infoSeverity=4),\n [dict(name=\"project\", id=\"id\")], [dict(id=\"scan_id\")]]\n- post_json = [dict(access_token=\"token\")] * 2 + [dict(reportId=\"1\")]\n- response = self.collect(metric, get_request_json_side_effect=get_json, post_request_json_side_effect=post_json)\n+ post_json = dict(access_token=\"token\")\n+ response = await self.collect(\n+ metric, get_request_json_side_effect=get_json,\n+ post_request_json_return_value=post_json)\n self.assert_measurement(response, value=\"10\", entities=[])\ndiff --git a/components/collector/tests/source_collectors/test_gitlab.py b/components/collector/tests/source_collectors/api_source_collectors/test_gitlab.py\nsimilarity index 75%\nrename from components/collector/tests/source_collectors/test_gitlab.py\nrename to components/collector/tests/source_collectors/api_source_collectors/test_gitlab.py\n--- a/components/collector/tests/source_collectors/test_gitlab.py\n+++ b/components/collector/tests/source_collectors/api_source_collectors/test_gitlab.py\n@@ -1,9 +1,9 @@\n \"\"\"Unit tests for the GitLab source.\"\"\"\n \n from datetime import datetime, timezone\n-from unittest.mock import Mock, patch\n+from unittest.mock import AsyncMock, Mock, patch\n \n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class GitLabTestCase(SourceCollectorTestCase):\n@@ -33,43 +33,43 @@ def setUp(self):\n super().setUp()\n self.metric = dict(type=\"failed_jobs\", sources=self.sources, addition=\"sum\")\n \n- def test_nr_of_failed_jobs(self):\n+ async def test_nr_of_failed_jobs(self):\n \"\"\"Test that the number of failed jobs is returned.\"\"\"\n- response = self.collect(self.metric, get_request_json_return_value=self.gitlab_jobs_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=self.gitlab_jobs_json)\n self.assert_measurement(response, value=\"1\", entities=self.expected_entities)\n \n- def test_nr_of_failed_jobs_without_failed_jobs(self):\n+ async def test_nr_of_failed_jobs_without_failed_jobs(self):\n \"\"\"Test that the number of failed jobs is returned.\"\"\"\n self.gitlab_jobs_json[0][\"status\"] = \"success\"\n- response = self.collect(self.metric, get_request_json_return_value=self.gitlab_jobs_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=self.gitlab_jobs_json)\n self.assert_measurement(response, value=\"0\", entities=[])\n \n- def test_private_token(self):\n+ async def test_private_token(self):\n \"\"\"Test that the private token is used.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"private_token\"] = \"token\"\n- response = self.collect(self.metric)\n+ response = await self.collect(self.metric)\n self.assert_measurement(\n response,\n api_url=\"https://gitlab/api/v4/projects/namespace%2Fproject/jobs?per_page=100&private_token=token\",\n parse_error=\"Traceback\")\n \n- def test_ignore_previous_runs_of_jobs(self):\n+ async def test_ignore_previous_runs_of_jobs(self):\n \"\"\"Test that previous runs of the same job are ignored.\"\"\"\n self.gitlab_jobs_json.insert(\n 0,\n dict(id=\"2\", status=\"success\", name=\"name\", stage=\"stage\", created_at=\"2019-03-31T19:51:39.927Z\",\n web_url=\"https://gitlab/jobs/2\", ref=\"master\"))\n- response = self.collect(self.metric, get_request_json_return_value=self.gitlab_jobs_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=self.gitlab_jobs_json)\n self.assert_measurement(response, value=\"0\", entities=[])\n \n \n class GitLabUnusedJobsTest(GitLabTestCase):\n \"\"\"Unit tests for the GitLab unused jobs metric.\"\"\"\n \n- def test_nr_of_unused_jobs(self):\n+ async def test_nr_of_unused_jobs(self):\n \"\"\"Test that the number of unused jobs is returned.\"\"\"\n metric = dict(type=\"unused_jobs\", sources=self.sources, addition=\"sum\")\n- response = self.collect(metric, get_request_json_return_value=self.gitlab_jobs_json)\n+ response = await self.collect(metric, get_request_json_return_value=self.gitlab_jobs_json)\n self.assert_measurement(response, value=\"1\", entities=self.expected_entities)\n \n \n@@ -84,19 +84,19 @@ def setUp(self):\n self.head_response = Mock()\n self.head_response.headers = {\"X-Gitlab-Last-Commit-Id\": \"commit-sha\"}\n \n- def test_source_up_to_dateness_file(self):\n+ async def test_source_up_to_dateness_file(self):\n \"\"\"Test that the age of a file in a repo can be measured.\"\"\"\n- with patch(\"requests.head\", return_value=self.head_response):\n- response = self.collect(\n+ with patch(\"aiohttp.ClientSession.head\", AsyncMock(return_value=self.head_response)):\n+ response = await self.collect(\n self.metric,\n get_request_json_side_effect=[[], self.commit_json, dict(web_url=\"https://gitlab.com/project\")])\n self.assert_measurement(\n response, value=str(self.expected_age), landing_url=\"https://gitlab.com/project/blob/branch/file\")\n \n- def test_source_up_to_dateness_folder(self):\n+ async def test_source_up_to_dateness_folder(self):\n \"\"\"Test that the age of a folder in a repo can be measured.\"\"\"\n- with patch(\"requests.head\", side_effect=[self.head_response, self.head_response]):\n- response = self.collect(\n+ with patch(\"aiohttp.ClientSession.head\", AsyncMock(side_effect=[self.head_response, self.head_response])):\n+ response = await self.collect(\n self.metric,\n get_request_json_side_effect=[\n [dict(type=\"blob\", path=\"file.txt\"), dict(type=\"tree\", path=\"folder\")],\n@@ -105,11 +105,16 @@ def test_source_up_to_dateness_folder(self):\n self.assert_measurement(\n response, value=str(self.expected_age), landing_url=\"https://gitlab.com/project/blob/branch/file\")\n \n+ async def test_landing_url_on_failure(self):\n+ \"\"\"Test that the landing url is the API url when GitLab cannot be reached.\"\"\"\n+ response = await self.collect(self.metric, get_request_json_side_effect=[ConnectionError])\n+ self.assert_measurement(response, landing_url=\"https://gitlab\", connection_error=\"Traceback\")\n+\n \n class GitlabUnmergedBranchesTest(GitLabTestCase):\n \"\"\"Unit tests for the unmerged branches metric.\"\"\"\n \n- def test_unmerged_branches(self):\n+ async def test_unmerged_branches(self):\n \"\"\"Test that the number of unmerged branches can be measured.\"\"\"\n metric = dict(type=\"unmerged_branches\", sources=self.sources, addition=\"sum\")\n gitlab_json = [\n@@ -121,7 +126,7 @@ def test_unmerged_branches(self):\n dict(name=\"active_unmerged_branch\", default=False, merged=False,\n commit=dict(committed_date=datetime.now(timezone.utc).isoformat())),\n dict(name=\"merged_branch\", default=False, merged=True)]\n- response = self.collect(metric, get_request_json_return_value=gitlab_json)\n+ response = await self.collect(metric, get_request_json_return_value=gitlab_json)\n expected_age = str((datetime.now(timezone.utc) - datetime(2019, 4, 2, 9, 33, 4, tzinfo=timezone.utc)).days)\n expected_entities = [\n dict(key=\"unmerged_branch\", name=\"unmerged_branch\", commit_age=expected_age, commit_date=\"2019-04-02\")]\ndiff --git a/components/collector/tests/source_collectors/test_jacoco_jenkins_plugin.py b/components/collector/tests/source_collectors/api_source_collectors/test_jacoco_jenkins_plugin.py\nsimilarity index 67%\nrename from components/collector/tests/source_collectors/test_jacoco_jenkins_plugin.py\nrename to components/collector/tests/source_collectors/api_source_collectors/test_jacoco_jenkins_plugin.py\n--- a/components/collector/tests/source_collectors/test_jacoco_jenkins_plugin.py\n+++ b/components/collector/tests/source_collectors/api_source_collectors/test_jacoco_jenkins_plugin.py\n@@ -3,7 +3,7 @@\n from datetime import datetime\n \n from collector_utilities.functions import days_ago\n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class JaCoCoJenkinsPluginTest(SourceCollectorTestCase):\n@@ -13,21 +13,22 @@ def setUp(self):\n super().setUp()\n self.sources = dict(source_id=dict(type=\"jacoco_jenkins_plugin\", parameters=dict(url=\"https://jenkins/job\")))\n \n- def test_uncovered_lines(self):\n+ async def test_uncovered_lines(self):\n \"\"\"Test that the number of uncovered lines and the total number of lines are returned.\"\"\"\n metric = dict(type=\"uncovered_lines\", sources=self.sources, addition=\"sum\")\n- response = self.collect(metric, get_request_json_return_value=dict(lineCoverage=dict(total=6, missed=2)))\n+ response = await self.collect(metric, get_request_json_return_value=dict(lineCoverage=dict(total=6, missed=2)))\n self.assert_measurement(response, value=\"2\", total=\"6\")\n \n- def test_uncovered_branches(self):\n+ async def test_uncovered_branches(self):\n \"\"\"Test that the number of uncovered branches and the total number of branches are returned.\"\"\"\n metric = dict(type=\"uncovered_branches\", sources=self.sources, addition=\"sum\")\n- response = self.collect(metric, get_request_json_return_value=dict(branchCoverage=dict(total=6, missed=2)))\n+ response = await self.collect(\n+ metric, get_request_json_return_value=dict(branchCoverage=dict(total=6, missed=2)))\n self.assert_measurement(response, value=\"2\", total=\"6\")\n \n- def test_source_up_to_dateness(self):\n+ async def test_source_up_to_dateness(self):\n \"\"\"Test that the source up to dateness is returned.\"\"\"\n metric = dict(type=\"source_up_to_dateness\", addition=\"max\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=dict(timestamp=\"1565284457173\"))\n+ response = await self.collect(metric, get_request_json_return_value=dict(timestamp=\"1565284457173\"))\n expected_age = days_ago(datetime.fromtimestamp(1565284457173 / 1000.))\n self.assert_measurement(response, value=str(expected_age))\ndiff --git a/components/collector/tests/source_collectors/test_jenkins.py b/components/collector/tests/source_collectors/api_source_collectors/test_jenkins.py\nsimilarity index 79%\nrename from components/collector/tests/source_collectors/test_jenkins.py\nrename to components/collector/tests/source_collectors/api_source_collectors/test_jenkins.py\n--- a/components/collector/tests/source_collectors/test_jenkins.py\n+++ b/components/collector/tests/source_collectors/api_source_collectors/test_jenkins.py\n@@ -2,7 +2,7 @@\n \n from datetime import datetime\n \n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class JenkinsTestCase(SourceCollectorTestCase):\n@@ -25,7 +25,7 @@ def setUp(self):\n super().setUp()\n self.metric = dict(type=\"failed_jobs\", sources=self.sources, addition=\"sum\")\n \n- def test_nr_of_failed_jobs(self):\n+ async def test_nr_of_failed_jobs(self):\n \"\"\"Test that the number of failed jobs is returned.\"\"\"\n jenkins_json = dict(\n jobs=[\n@@ -35,47 +35,47 @@ def test_nr_of_failed_jobs(self):\n dict(\n name=\"child_job\", url=\"https://child_job\", buildable=True, color=\"red\",\n builds=self.builds)])])\n- response = self.collect(self.metric, get_request_json_return_value=jenkins_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=jenkins_json)\n self.assert_measurement(response, value=\"2\")\n \n- def test_failed_jobs(self):\n+ async def test_failed_jobs(self):\n \"\"\"Test that the failed jobs are returned.\"\"\"\n jenkins_json = dict(\n jobs=[dict(name=\"job\", url=self.job_url, buildable=True, color=\"red\", builds=self.builds)])\n- response = self.collect(self.metric, get_request_json_return_value=jenkins_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=jenkins_json)\n expected_entities = [\n dict(build_date=\"2019-03-15\", build_age=self.build_age, build_status=\"Red\", key=\"job\", name=\"job\",\n url=self.job_url)]\n self.assert_measurement(response, entities=expected_entities)\n \n- def test_ignore_jobs(self):\n+ async def test_ignore_jobs(self):\n \"\"\"Test that a failed job can be ignored.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"jobs_to_ignore\"] = [\"job2\"]\n jenkins_json = dict(\n jobs=[dict(name=\"job\", url=self.job_url, buildable=True, color=\"red\", builds=self.builds),\n dict(name=\"job2\", url=self.job2_url, buildable=True, color=\"red\", builds=self.builds)])\n- response = self.collect(self.metric, get_request_json_return_value=jenkins_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=jenkins_json)\n expected_entities = [\n dict(build_date=\"2019-03-15\", build_age=self.build_age, build_status=\"Red\", key=\"job\", name=\"job\",\n url=self.job_url)]\n self.assert_measurement(response, entities=expected_entities)\n \n- def test_ignore_jobs_by_regular_expression(self):\n+ async def test_ignore_jobs_by_regular_expression(self):\n \"\"\"Test that failed jobs can be ignored by regular expression.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"jobs_to_ignore\"] = [\"job.\"]\n jenkins_json = dict(\n jobs=[dict(name=\"job\", url=self.job_url, buildable=True, color=\"red\", builds=self.builds),\n dict(name=\"job2\", url=self.job2_url, buildable=True, color=\"red\", builds=self.builds)])\n- response = self.collect(self.metric, get_request_json_return_value=jenkins_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=jenkins_json)\n expected_entities = [\n dict(build_date=\"2019-03-15\", build_age=self.build_age, build_status=\"Red\", key=\"job\", name=\"job\",\n url=self.job_url)]\n self.assert_measurement(response, entities=expected_entities)\n \n- def test_no_builds(self):\n+ async def test_no_builds(self):\n \"\"\"Test no builds.\"\"\"\n jenkins_json = dict(jobs=[dict(name=\"job\", url=self.job_url, buildable=True, color=\"notbuilt\", builds=[])])\n- response = self.collect(self.metric, get_request_json_return_value=jenkins_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=jenkins_json)\n self.assert_measurement(response, entities=[])\n \n \n@@ -86,16 +86,16 @@ def setUp(self):\n super().setUp()\n self.metric = dict(type=\"unused_jobs\", sources=self.sources, addition=\"sum\")\n \n- def test_unused_jobs(self):\n+ async def test_unused_jobs(self):\n \"\"\"Test that the number of unused jobs is returned.\"\"\"\n jenkins_json = dict(\n jobs=[dict(\n name=\"job\", url=self.job_url, buildable=True, color=\"red\", builds=[dict(timestamp=\"1548311610349\")])])\n- response = self.collect(self.metric, get_request_json_return_value=jenkins_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=jenkins_json)\n self.assert_measurement(response, value=\"1\")\n \n- def test_unbuild_job(self):\n+ async def test_unbuild_job(self):\n \"\"\"Test that jobs without builds are ignored.\"\"\"\n jenkins_json = dict(jobs=[dict(name=\"job\", url=self.job_url, buildable=True, color=\"red\")])\n- response = self.collect(self.metric, get_request_json_return_value=jenkins_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=jenkins_json)\n self.assert_measurement(response, value=\"0\")\ndiff --git a/components/collector/tests/source_collectors/test_jenkins_test_report.py b/components/collector/tests/source_collectors/api_source_collectors/test_jenkins_test_report.py\nsimilarity index 83%\nrename from components/collector/tests/source_collectors/test_jenkins_test_report.py\nrename to components/collector/tests/source_collectors/api_source_collectors/test_jenkins_test_report.py\n--- a/components/collector/tests/source_collectors/test_jenkins_test_report.py\n+++ b/components/collector/tests/source_collectors/api_source_collectors/test_jenkins_test_report.py\n@@ -3,7 +3,7 @@\n from datetime import datetime\n \n from collector_utilities.functions import days_ago\n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class JenkinsTestReportTest(SourceCollectorTestCase):\n@@ -13,21 +13,21 @@ def setUp(self):\n super().setUp()\n self.sources = dict(source_id=dict(type=\"jenkins_test_report\", parameters=dict(url=\"https://jenkins/job\")))\n \n- def test_nr_of_tests(self):\n+ async def test_nr_of_tests(self):\n \"\"\"Test that the number of tests is returned.\"\"\"\n jenkins_json = dict(\n failCount=1, passCount=1, suites=[dict(\n cases=[dict(status=\"FAILED\", name=\"tc1\", className=\"c1\"),\n dict(status=\"PASSED\", name=\"tc2\", className=\"c2\")])])\n metric = dict(type=\"tests\", addition=\"sum\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=jenkins_json)\n+ response = await self.collect(metric, get_request_json_return_value=jenkins_json)\n self.assert_measurement(\n response, value=\"2\",\n entities=[\n dict(class_name=\"c1\", key=\"tc1\", name=\"tc1\", test_result=\"failed\"),\n dict(class_name=\"c2\", key=\"tc2\", name=\"tc2\", test_result=\"passed\")])\n \n- def test_nr_of_tests_with_aggregated_report(self):\n+ async def test_nr_of_tests_with_aggregated_report(self):\n \"\"\"Test that the number of tests is returned when the test report is an aggregated report.\"\"\"\n jenkins_json = dict(\n childReports=[\n@@ -39,14 +39,14 @@ def test_nr_of_tests_with_aggregated_report(self):\n dict(status=\"FAILED\", name=\"tc1\", className=\"c1\"),\n dict(status=\"PASSED\", name=\"tc2\", className=\"c2\")])]))])\n metric = dict(type=\"tests\", addition=\"sum\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=jenkins_json)\n+ response = await self.collect(metric, get_request_json_return_value=jenkins_json)\n self.assert_measurement(\n response, value=\"2\",\n entities=[\n dict(class_name=\"c1\", key=\"tc1\", name=\"tc1\", test_result=\"failed\"),\n dict(class_name=\"c2\", key=\"tc2\", name=\"tc2\", test_result=\"passed\")])\n \n- def test_nr_of_passed_tests(self):\n+ async def test_nr_of_passed_tests(self):\n \"\"\"Test that the number of passed tests is returned.\"\"\"\n jenkins_json = dict(\n failCount=1, passCount=1, suites=[dict(\n@@ -54,11 +54,11 @@ def test_nr_of_passed_tests(self):\n dict(status=\"PASSED\", name=\"tc2\", className=\"c2\")])])\n self.sources[\"source_id\"][\"parameters\"][\"test_result\"] = [\"passed\"]\n metric = dict(type=\"tests\", addition=\"sum\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=jenkins_json)\n+ response = await self.collect(metric, get_request_json_return_value=jenkins_json)\n expected_entities = [dict(class_name=\"c2\", key=\"tc2\", name=\"tc2\", test_result=\"passed\")]\n self.assert_measurement(response, value=\"1\", entities=expected_entities)\n \n- def test_nr_of_failed_tests(self):\n+ async def test_nr_of_failed_tests(self):\n \"\"\"Test that the number of failed tests is returned.\"\"\"\n jenkins_json = dict(\n failCount=2, suites=[dict(\n@@ -67,24 +67,24 @@ def test_nr_of_failed_tests(self):\n dict(status=\"PASSED\", name=\"tc3\", className=\"c3\")])])\n self.sources[\"source_id\"][\"parameters\"][\"test_result\"] = [\"failed\"]\n metric = dict(type=\"tests\", addition=\"sum\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=jenkins_json)\n+ response = await self.collect(metric, get_request_json_return_value=jenkins_json)\n expected_entities = [\n dict(class_name=\"c1\", key=\"tc1\", name=\"tc1\", test_result=\"failed\"),\n dict(class_name=\"c2\", key=\"tc2\", name=\"tc2\", test_result=\"failed\")]\n self.assert_measurement(response, value=\"2\", entities=expected_entities)\n \n- def test_source_up_to_dateness(self):\n+ async def test_source_up_to_dateness(self):\n \"\"\"Test that the source age in days is returned.\"\"\"\n metric = dict(type=\"source_up_to_dateness\", addition=\"max\", sources=self.sources)\n- response = self.collect(\n+ response = await self.collect(\n metric, get_request_json_return_value=dict(suites=[dict(timestamp=\"2019-04-02T08:52:50\")]))\n expected_age = (datetime.now() - datetime(2019, 4, 2, 8, 52, 50)).days\n self.assert_measurement(response, value=str(expected_age))\n \n- def test_source_up_to_dateness_without_timestamps(self):\n+ async def test_source_up_to_dateness_without_timestamps(self):\n \"\"\"Test that the job age in days is returned if the test report doesn't contain timestamps.\"\"\"\n metric = dict(type=\"source_up_to_dateness\", addition=\"max\", sources=self.sources)\n- response = self.collect(\n+ response = await self.collect(\n metric,\n get_request_json_side_effect=[dict(suites=[dict(timestamp=None)]), dict(timestamp=\"1565284457173\")])\n expected_age = days_ago(datetime.fromtimestamp(1565284457173 / 1000.))\ndiff --git a/components/collector/tests/source_collectors/test_jira.py b/components/collector/tests/source_collectors/api_source_collectors/test_jira.py\nsimilarity index 89%\nrename from components/collector/tests/source_collectors/test_jira.py\nrename to components/collector/tests/source_collectors/api_source_collectors/test_jira.py\n--- a/components/collector/tests/source_collectors/test_jira.py\n+++ b/components/collector/tests/source_collectors/api_source_collectors/test_jira.py\n@@ -5,7 +5,7 @@\n from dateutil.parser import parse\n \n from collector_utilities.functions import days_ago\n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class JiraTestCase(SourceCollectorTestCase):\n@@ -30,16 +30,16 @@ def setUp(self):\n super().setUp()\n self.metric = dict(type=\"issues\", addition=\"sum\", sources=self.sources)\n \n- def test_nr_of_issues(self):\n+ async def test_nr_of_issues(self):\n \"\"\"Test that the number of issues is returned.\"\"\"\n issues_json = dict(total=42)\n- response = self.collect(self.metric, get_request_json_side_effect=[self.fields_json, issues_json])\n+ response = await self.collect(self.metric, get_request_json_side_effect=[self.fields_json, issues_json])\n self.assert_measurement(response, value=\"42\")\n \n- def test_issues(self):\n+ async def test_issues(self):\n \"\"\"Test that the issues are returned.\"\"\"\n issues_json = dict(total=1, issues=[dict(key=\"key\", id=\"id\", fields=dict(summary=\"Summary\"))])\n- response = self.collect(self.metric, get_request_json_side_effect=[self.fields_json, issues_json])\n+ response = await self.collect(self.metric, get_request_json_side_effect=[self.fields_json, issues_json])\n self.assert_measurement(response, entities=[dict(key=\"id\", summary=\"Summary\", url=\"https://jira/browse/key\")])\n \n \n@@ -51,7 +51,7 @@ def setUp(self):\n self.too_long_ago_summary = \"Tested too long ago according to its own desired frequency\"\n self.metric = dict(type=\"manual_test_execution\", addition=\"sum\", sources=self.sources)\n \n- def test_nr_of_test_cases(self):\n+ async def test_nr_of_test_cases(self):\n \"\"\"Test that the number of test cases is returned.\"\"\"\n comment_updated = \"2019-10-02T11:07:02.444+0200\"\n test_cases_json = dict(\n@@ -69,7 +69,7 @@ def test_nr_of_test_cases(self):\n comment=dict(comments=[dict(updated=str(datetime.now()-timedelta(days=10)))]),\n desired_test_frequency=\"5\",\n summary=self.too_long_ago_summary))])\n- response = self.collect(\n+ response = await self.collect(\n self.metric, get_request_json_side_effect=[self.fields_json, test_cases_json])\n expected_days = str(days_ago(parse(comment_updated)))\n self.assert_measurement(\n@@ -80,7 +80,7 @@ def test_nr_of_test_cases(self):\n dict(key=\"id4\", summary=self.too_long_ago_summary,\n url=\"https://jira/browse/key4\", days_untested=\"10\", desired_test_frequency=\"5\")])\n \n- def test_nr_of_test_cases_with_field_name(self):\n+ async def test_nr_of_test_cases_with_field_name(self):\n \"\"\"Test that the number of test cases is returned when the field name for the test frequency is specified\n by name.\"\"\"\n fields_json = [dict(name=\"Required test frequency\", id=\"custom_field_001\")]\n@@ -91,7 +91,7 @@ def test_nr_of_test_cases_with_field_name(self):\n fields=dict(\n comment=dict(comments=[dict(updated=str(datetime.now()-timedelta(days=10)))]),\n custom_field_001=\"5\", summary=self.too_long_ago_summary))])\n- response = self.collect(\n+ response = await self.collect(\n self.metric, get_request_json_side_effect=[fields_json, test_cases_json])\n self.assert_measurement(\n response, value=\"1\",\n@@ -103,14 +103,14 @@ def test_nr_of_test_cases_with_field_name(self):\n class JiraReadyUserStoryPointsTest(JiraTestCase):\n \"\"\"Unit tests for the Jira ready story points collector.\"\"\"\n \n- def test_nr_story_points(self):\n+ async def test_nr_story_points(self):\n \"\"\"Test that the number of story points is returned.\"\"\"\n metric = dict(type=\"ready_user_story_points\", addition=\"sum\", sources=self.sources)\n user_stories_json = dict(\n issues=[\n dict(key=\"1\", id=\"1\", fields=dict(summary=\"user story 1\", field=10)),\n dict(key=\"2\", id=\"2\", fields=dict(summary=\"user story 2\", field=32))])\n- response = self.collect(\n+ response = await self.collect(\n metric, get_request_json_side_effect=[self.fields_json, user_stories_json])\n self.assert_measurement(\n response, value=\"42\",\n@@ -122,7 +122,7 @@ def test_nr_story_points(self):\n class JiraManualTestDurationTest(JiraTestCase):\n \"\"\"Unit tests for the Jira manual test duration collector.\"\"\"\n \n- def test_duration(self):\n+ async def test_duration(self):\n \"\"\"Test that the duration is returned.\"\"\"\n metric = dict(type=\"manual_test_duration\", addition=\"sum\", sources=self.sources)\n test_cases_json = dict(\n@@ -130,7 +130,7 @@ def test_duration(self):\n dict(key=\"1\", id=\"1\", fields=dict(summary=\"test 1\", field=10)),\n dict(key=\"2\", id=\"2\", fields=dict(summary=\"test 2\", field=15)),\n dict(key=\"3\", id=\"3\", fields=dict(summary=\"test 3\", field=None))])\n- response = self.collect(\n+ response = await self.collect(\n metric, get_request_json_side_effect=[self.fields_json, test_cases_json])\n self.assert_measurement(\n response, value=\"25\",\ndiff --git a/components/collector/tests/source_collectors/test_owasp_dependency_check_jenkins_plugin.py b/components/collector/tests/source_collectors/api_source_collectors/test_owasp_dependency_check_jenkins_plugin.py\nsimilarity index 88%\nrename from components/collector/tests/source_collectors/test_owasp_dependency_check_jenkins_plugin.py\nrename to components/collector/tests/source_collectors/api_source_collectors/test_owasp_dependency_check_jenkins_plugin.py\n--- a/components/collector/tests/source_collectors/test_owasp_dependency_check_jenkins_plugin.py\n+++ b/components/collector/tests/source_collectors/api_source_collectors/test_owasp_dependency_check_jenkins_plugin.py\n@@ -3,7 +3,7 @@\n from datetime import datetime\n \n from collector_utilities.functions import days_ago\n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class OWASPDependencyCheckJenkinsPluginTest(SourceCollectorTestCase):\n@@ -15,10 +15,10 @@ def setUp(self):\n type=\"owasp_dependency_check_jenkins_plugin\",\n parameters=dict(url=\"https://jenkins/job\", severities=[\"critical\", \"high\", \"normal\"])))\n \n- def test_warnings(self):\n+ async def test_warnings(self):\n \"\"\"Test that the number of security warnings is returned.\"\"\"\n metric = dict(type=\"security_warnings\", addition=\"sum\", sources=self.sources)\n- response = self.collect(\n+ response = await self.collect(\n metric,\n get_request_json_return_value=dict(\n warnings=[\n@@ -33,10 +33,10 @@ def test_warnings(self):\n dict(key=\"/f4\", file_path=\"/f4\", highest_severity=\"Critical\", nr_vulnerabilities=1)]\n self.assert_measurement(response, value=\"3\", entities=expected_entities)\n \n- def test_up_to_dateness(self):\n+ async def test_up_to_dateness(self):\n \"\"\"Test that the source age in days is returned.\"\"\"\n metric = dict(type=\"source_up_to_dateness\", addition=\"max\", sources=self.sources)\n- response = self.collect(\n+ response = await self.collect(\n metric, get_request_json_return_value=dict(timestamp=\"1565284457173\"))\n expected_age = days_ago(datetime.fromtimestamp(1565284457173 / 1000.))\n self.assert_measurement(response, value=str(expected_age))\ndiff --git a/components/collector/tests/source_collectors/test_quality_time.py b/components/collector/tests/source_collectors/api_source_collectors/test_quality_time.py\nsimilarity index 95%\nrename from components/collector/tests/source_collectors/test_quality_time.py\nrename to components/collector/tests/source_collectors/api_source_collectors/test_quality_time.py\n--- a/components/collector/tests/source_collectors/test_quality_time.py\n+++ b/components/collector/tests/source_collectors/api_source_collectors/test_quality_time.py\n@@ -1,12 +1,12 @@\n \"\"\"Unit tests for the Quality-time source collector(s).\"\"\"\n \n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class QualityTimeMetricsTest(SourceCollectorTestCase):\n \"\"\"Fixture for Quality-time metrics unit tests.\"\"\"\n \n- def test_nr_of_metrics(self):\n+ async def test_nr_of_metrics(self):\n \"\"\"Test that the number of metrics is returned.\"\"\"\n sources = dict(\n source_id=dict(\n@@ -46,7 +46,7 @@ def test_nr_of_metrics(self):\n measurements1 = dict(measurements=[dict(metric_uuid=\"m1\", count=dict(status=\"target_met\", value=\"0\"))])\n measurements2 = dict(measurements=[dict(metric_uuid=\"m2\", count=dict(status=\"target_not_met\", value=\"20\"))])\n measurements3 = dict(measurements=[])\n- response = self.collect(\n+ response = await self.collect(\n metric, get_request_json_side_effect=[reports, measurements1, measurements2, measurements3])\n # The count should be one because the user selected metrics from report \"r1\", with status \"target_not_met\",\n # metric type \"tests\" or \"violations\", source type \"sonarqube\" or \"junit\", and tag \"security\".\ndiff --git a/components/collector/tests/source_collectors/test_sonarqube.py b/components/collector/tests/source_collectors/api_source_collectors/test_sonarqube.py\nsimilarity index 82%\nrename from components/collector/tests/source_collectors/test_sonarqube.py\nrename to components/collector/tests/source_collectors/api_source_collectors/test_sonarqube.py\n--- a/components/collector/tests/source_collectors/test_sonarqube.py\n+++ b/components/collector/tests/source_collectors/api_source_collectors/test_sonarqube.py\n@@ -2,7 +2,7 @@\n \n from datetime import datetime, timedelta, timezone\n \n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class SonarQubeTest(SourceCollectorTestCase):\n@@ -13,7 +13,7 @@ def setUp(self):\n self.sources = dict(source_id=dict(type=\"sonarqube\", parameters=dict(url=\"https://sonar\", component=\"id\")))\n self.tests_landing_url = \"https://sonar/component_measures?id=id&metric=tests&branch=master\"\n \n- def test_violations(self):\n+ async def test_violations(self):\n \"\"\"Test that the number of violations is returned.\"\"\"\n json = dict(\n total=\"2\",\n@@ -21,7 +21,7 @@ def test_violations(self):\n dict(key=\"a\", message=\"a\", component=\"a\", severity=\"INFO\", type=\"BUG\"),\n dict(key=\"b\", message=\"b\", component=\"b\", severity=\"MAJOR\", type=\"CODE_SMELL\")])\n metric = dict(type=\"violations\", addition=\"sum\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=json)\n+ response = await self.collect(metric, get_request_json_return_value=json)\n expected_entities = [\n dict(component=\"a\", key=\"a\", message=\"a\", severity=\"info\", type=\"bug\",\n url=\"https://sonar/project/issues?id=id&issues=a&open=a&branch=master\"),\n@@ -31,11 +31,11 @@ def test_violations(self):\n response, value=\"2\", entities=expected_entities,\n landing_url=\"https://sonar/project/issues?id=id&resolved=false&branch=master\")\n \n- def test_commented_out_code(self):\n+ async def test_commented_out_code(self):\n \"\"\"Test that the number of lines with commented out code is returned.\"\"\"\n json = dict(total=\"2\")\n metric = dict(type=\"commented_out_code\", addition=\"sum\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=json)\n+ response = await self.collect(metric, get_request_json_return_value=json)\n self.assert_measurement(\n response, value=\"2\", total=\"100\",\n landing_url=\"https://sonar/project/issues?id=id&resolved=false&branch=master&rules=abap:S125,apex:S125,\"\n@@ -44,14 +44,15 @@ def test_commented_out_code(self):\n \"scala:S125,squid:CommentedOutCodeLine,swift:S125,typescript:S125,\"\n \"Web:AvoidCommentedOutCodeCheck,xml:S125\")\n \n- def test_complex_units(self):\n+ async def test_complex_units(self):\n \"\"\"Test that the number of lines with commented out code is returned.\"\"\"\n complex_units_json = dict(total=\"2\")\n functions_json = dict(component=dict(measures=[dict(metric=\"functions\", value=\"4\")]))\n metric = dict(type=\"complex_units\", addition=\"sum\", sources=self.sources)\n- response = self.collect(\n+ response = await self.collect(\n metric,\n- get_request_json_side_effect=[{}, complex_units_json, functions_json, complex_units_json, functions_json])\n+ get_request_json_side_effect=[\n+ {}, complex_units_json, functions_json, complex_units_json, functions_json, complex_units_json])\n self.assert_measurement(\n response, value=\"2\", total=\"4\",\n landing_url=\"https://sonar/project/issues?id=id&resolved=false&branch=master&rules=csharpsquid:S1541,\"\n@@ -60,58 +61,58 @@ def test_complex_units(self):\n \"scala:S3776,squid:MethodCyclomaticComplexity,squid:S3776,typescript:S1541,typescript:S3776,\"\n \"vbnet:S1541,vbnet:S3776\")\n \n- def test_tests(self):\n+ async def test_tests(self):\n \"\"\"Test that the number of tests is returned.\"\"\"\n json = dict(component=dict(measures=[dict(metric=\"tests\", value=\"88\")]))\n metric = dict(type=\"tests\", addition=\"sum\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=json)\n+ response = await self.collect(metric, get_request_json_return_value=json)\n self.assert_measurement(response, value=\"88\", landing_url=self.tests_landing_url)\n \n- def test_uncovered_lines(self):\n+ async def test_uncovered_lines(self):\n \"\"\"Test that the number of uncovered lines and the number of lines to cover are returned.\"\"\"\n json = dict(\n component=dict(\n measures=[dict(metric=\"uncovered_lines\", value=\"100\"), dict(metric=\"lines_to_cover\", value=\"1000\")]))\n metric = dict(type=\"uncovered_lines\", addition=\"sum\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=json)\n+ response = await self.collect(metric, get_request_json_return_value=json)\n self.assert_measurement(\n response, value=\"100\", total=\"1000\",\n landing_url=\"https://sonar/component_measures?id=id&metric=uncovered_lines&branch=master\")\n \n- def test_uncovered_branches(self):\n+ async def test_uncovered_branches(self):\n \"\"\"Test that the number of uncovered branches and the number of branches to cover are returned.\"\"\"\n json = dict(\n component=dict(\n measures=[\n dict(metric=\"uncovered_conditions\", value=\"10\"), dict(metric=\"conditions_to_cover\", value=\"200\")]))\n metric = dict(type=\"uncovered_branches\", addition=\"sum\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=json)\n+ response = await self.collect(metric, get_request_json_return_value=json)\n self.assert_measurement(\n response, value=\"10\", total=\"200\",\n landing_url=\"https://sonar/component_measures?id=id&metric=uncovered_conditions&branch=master\")\n \n- def test_duplicated_lines(self):\n+ async def test_duplicated_lines(self):\n \"\"\"Test that the number of duplicated lines and the total number of lines are returned.\"\"\"\n json = dict(\n component=dict(\n measures=[\n dict(metric=\"duplicated_lines\", value=\"10\"), dict(metric=\"lines\", value=\"100\")]))\n metric = dict(type=\"duplicated_lines\", addition=\"sum\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=json)\n+ response = await self.collect(metric, get_request_json_return_value=json)\n self.assert_measurement(\n response, value=\"10\", total=\"100\",\n landing_url=\"https://sonar/component_measures?id=id&metric=duplicated_lines&branch=master\")\n \n- def test_many_parameters(self):\n+ async def test_many_parameters(self):\n \"\"\"Test that the number of functions with too many parameters is returned.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"rules\"] = [\"rule1\"]\n many_parameters_json = dict(total=\"2\", issues=[])\n functions_json = dict(component=dict(measures=[dict(metric=\"functions\", value=\"4\")]))\n metric = dict(type=\"many_parameters\", addition=\"sum\", sources=self.sources)\n- response = self.collect(\n+ response = await self.collect(\n metric,\n get_request_json_side_effect=[\n- {}, many_parameters_json, functions_json, many_parameters_json, functions_json])\n+ {}, many_parameters_json, functions_json, many_parameters_json, functions_json, many_parameters_json])\n self.assert_measurement(\n response, value=\"2\", total=\"4\",\n landing_url=\"https://sonar/project/issues?id=id&resolved=false&branch=master&rules=c:S107,csharpsquid:S107,\"\n@@ -119,14 +120,15 @@ def test_many_parameters(self):\n \"plsql:PlSql.FunctionAndProcedureExcessiveParameters,python:S107,squid:S00107,tsql:S107,\"\n \"typescript:S107\")\n \n- def test_long_units(self):\n+ async def test_long_units(self):\n \"\"\"Test that the number of long units is returned.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"rules\"] = [\"rule1\"]\n long_units_json = dict(total=\"2\", issues=[])\n functions_json = dict(component=dict(measures=[dict(metric=\"functions\", value=\"4\")]))\n metric = dict(type=\"long_units\", addition=\"sum\", sources=self.sources)\n- response = self.collect(\n- metric, get_request_json_side_effect=[{}, long_units_json, functions_json, long_units_json, functions_json])\n+ response = await self.collect(\n+ metric, get_request_json_side_effect=[\n+ {}, long_units_json, functions_json, long_units_json, functions_json, long_units_json])\n self.assert_measurement(\n response, value=\"2\", total=\"4\",\n landing_url=\"https://sonar/project/issues?id=id&resolved=false&branch=master&rules=abap:S104,c:FileLoc,\"\n@@ -136,17 +138,17 @@ def test_long_units(self):\n \"squid:S2972,swift:S104,typescript:S104,typescript:S138,vbnet:S104,vbnet:S138,\"\n \"Web:FileLengthCheck,Web:LongJavaScriptCheck\")\n \n- def test_source_up_to_dateness(self):\n+ async def test_source_up_to_dateness(self):\n \"\"\"Test that the number of days since the last analysis is returned.\"\"\"\n json = dict(analyses=[dict(date=\"2019-03-29T14:20:15+0100\")])\n metric = dict(type=\"source_up_to_dateness\", addition=\"max\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=json)\n+ response = await self.collect(metric, get_request_json_return_value=json)\n timezone_info = timezone(timedelta(hours=1))\n expected_age = (datetime.now(timezone_info) - datetime(2019, 3, 29, 14, 20, 15, tzinfo=timezone_info)).days\n self.assert_measurement(\n response, value=str(expected_age), landing_url=\"https://sonar/project/activity?id=id&branch=master\")\n \n- def test_suppressed_violations(self):\n+ async def test_suppressed_violations(self):\n \"\"\"Test that the number of suppressed violations includes both suppressed issues as well as suppressed rules.\"\"\"\n violations_json = dict(\n total=\"1\", issues=[dict(key=\"a\", message=\"a\", component=\"a\", severity=\"INFO\", type=\"BUG\")])\n@@ -156,7 +158,7 @@ def test_suppressed_violations(self):\n dict(key=\"b\", message=\"b\", component=\"b\", severity=\"MAJOR\", type=\"CODE_SMELL\", resolution=\"WONTFIX\")])\n total_violations_json = dict(total=\"4\")\n metric = dict(type=\"suppressed_violations\", addition=\"sum\", sources=self.sources)\n- response = self.collect(\n+ response = await self.collect(\n metric, get_request_json_side_effect=[{}, violations_json, wont_fix_json, total_violations_json])\n expected_entities = [\n dict(component=\"a\", key=\"a\", message=\"a\", severity=\"info\", type=\"bug\",\n@@ -168,52 +170,53 @@ def test_suppressed_violations(self):\n landing_url=\"https://sonar/project/issues?id=id&resolved=false&branch=master&rules=csharpsquid:S1309,\"\n \"php:NoSonar,Pylint:I0011,Pylint:I0020,squid:NoSonar,squid:S1309,squid:S1310,squid:S1315\")\n \n- def test_loc_returns_ncloc_by_default(self):\n+ async def test_loc_returns_ncloc_by_default(self):\n \"\"\"Test that the number of lines of non-comment code is returned.\"\"\"\n json = dict(component=dict(measures=[dict(metric=\"ncloc\", value=\"1234\")]))\n metric = dict(type=\"loc\", addition=\"sum\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=json)\n+ response = await self.collect(metric, get_request_json_return_value=json)\n self.assert_measurement(\n response, value=\"1234\", total=\"100\",\n landing_url=\"https://sonar/component_measures?id=id&metric=ncloc&branch=master\")\n \n- def test_loc_all_lines(self):\n+ async def test_loc_all_lines(self):\n \"\"\"Test that the number of lines of code is returned.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"lines_to_count\"] = \"all lines\"\n json = dict(component=dict(measures=[dict(metric=\"lines\", value=\"1234\")]))\n metric = dict(type=\"loc\", addition=\"sum\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=json)\n+ response = await self.collect(metric, get_request_json_return_value=json)\n self.assert_measurement(\n response, value=\"1234\", total=\"100\",\n landing_url=\"https://sonar/component_measures?id=id&metric=lines&branch=master\")\n \n- def test_nr_of_tests(self):\n+ async def test_nr_of_tests(self):\n \"\"\"Test that the number of tests is returned.\"\"\"\n json = dict(component=dict(measures=[dict(metric=\"tests\", value=\"123\")]))\n metric = dict(type=\"tests\", addition=\"sum\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=json)\n+ response = await self.collect(metric, get_request_json_return_value=json)\n self.assert_measurement(response, value=\"123\", total=\"123\", landing_url=self.tests_landing_url)\n \n- def test_nr_of_skipped_tests(self):\n+ async def test_nr_of_skipped_tests(self):\n \"\"\"Test that the number of skipped tests is returned.\"\"\"\n json = dict(\n component=dict(measures=[dict(metric=\"tests\", value=\"123\"), dict(metric=\"skipped_tests\", value=\"4\")]))\n self.sources[\"source_id\"][\"parameters\"][\"test_result\"] = [\"skipped\"]\n metric = dict(type=\"tests\", addition=\"sum\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=json)\n+ response = await self.collect(metric, get_request_json_return_value=json)\n self.assert_measurement(response, value=\"4\", total=\"123\", landing_url=self.tests_landing_url)\n \n- def test_nr_of_tests_without_tests(self):\n+ async def test_nr_of_tests_without_tests(self):\n \"\"\"Test that the collector throws an exception if there are no tests.\"\"\"\n json = dict(component=dict(measures=[]))\n metric = dict(type=\"tests\", addition=\"sum\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=json)\n+ response = await self.collect(metric, get_request_json_return_value=json)\n self.assert_measurement(\n response, value=None, total=None, parse_error=\"KeyError\", landing_url=self.tests_landing_url)\n \n- def test_nr_of_tests_with_faulty_component(self):\n+ async def test_nr_of_tests_with_faulty_component(self):\n \"\"\"Test that the measurement fails if the component does not exist.\"\"\"\n metric = dict(type=\"tests\", addition=\"sum\", sources=self.sources)\n- response = self.collect(metric, get_request_json_return_value=dict(errors=[dict(msg=\"No such component\")]))\n+ response = await self.collect(\n+ metric, get_request_json_return_value=dict(errors=[dict(msg=\"No such component\")]))\n self.assert_measurement(\n response, value=None, total=None, connection_error=\"No such component\", landing_url=self.tests_landing_url)\ndiff --git a/components/collector/tests/source_collectors/test_trello.py b/components/collector/tests/source_collectors/api_source_collectors/test_trello.py\nsimilarity index 79%\nrename from components/collector/tests/source_collectors/test_trello.py\nrename to components/collector/tests/source_collectors/api_source_collectors/test_trello.py\n--- a/components/collector/tests/source_collectors/test_trello.py\n+++ b/components/collector/tests/source_collectors/api_source_collectors/test_trello.py\n@@ -2,7 +2,7 @@\n \n from datetime import datetime\n \n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class TrelloTestCase(SourceCollectorTestCase):\n@@ -45,28 +45,28 @@ def setUp(self):\n self.metric = dict(type=\"issues\", addition=\"sum\", sources=self.sources)\n self.json = [[dict(id=\"board1\", name=\"Board1\")], self.cards, self.cards]\n \n- def test_issues(self):\n+ async def test_issues(self):\n \"\"\"Test that the number of issues and the individual issues are returned.\"\"\"\n- response = self.collect(self.metric, get_request_json_side_effect=self.json)\n+ response = await self.collect(self.metric, get_request_json_side_effect=self.json)\n self.assert_measurement(response, value=\"2\", entities=self.entities)\n \n- def test_issues_with_ignored_list(self):\n+ async def test_issues_with_ignored_list(self):\n \"\"\"Test that lists can be ignored when counting issues.\"\"\"\n self.metric[\"sources\"][\"source_id\"][\"parameters\"][\"lists_to_ignore\"] = [\"list1\"]\n- response = self.collect(self.metric, get_request_json_side_effect=self.json)\n+ response = await self.collect(self.metric, get_request_json_side_effect=self.json)\n self.assert_measurement(response, value=\"1\", entities=[self.entities[1]])\n \n- def test_overdue_issues(self):\n+ async def test_overdue_issues(self):\n \"\"\"Test overdue issues.\"\"\"\n self.metric[\"sources\"][\"source_id\"][\"parameters\"][\"cards_to_count\"] = [\"overdue\"]\n- response = self.collect(self.metric, get_request_json_side_effect=self.json)\n+ response = await self.collect(self.metric, get_request_json_side_effect=self.json)\n self.assert_measurement(response, value=\"1\", entities=[self.entities[1]])\n \n- def test_inactive_issues(self):\n+ async def test_inactive_issues(self):\n \"\"\"Test inactive issues.\"\"\"\n self.metric[\"sources\"][\"source_id\"][\"parameters\"][\"cards_to_count\"] = [\"inactive\"]\n self.cards[\"cards\"][0][\"dateLastActivity\"] = datetime.now().isoformat()\n- response = self.collect(self.metric, get_request_json_side_effect=self.json)\n+ response = await self.collect(self.metric, get_request_json_side_effect=self.json)\n self.assert_measurement(response, value=\"1\", entities=[self.entities[1]])\n \n \n@@ -78,13 +78,13 @@ def setUp(self):\n self.metric = dict(type=\"source_up_to_dateness\", addition=\"max\", sources=self.sources)\n self.side_effect = [[dict(id=\"board1\", name=\"Board1\")], self.cards, self.cards]\n \n- def test_age(self):\n+ async def test_age(self):\n \"\"\"Test that the source up to dateness is the number of days since the most recent change.\"\"\"\n- response = self.collect(self.metric, get_request_json_side_effect=self.side_effect)\n+ response = await self.collect(self.metric, get_request_json_side_effect=self.side_effect)\n self.assert_measurement(response, value=str((datetime.now() - datetime(2019, 3, 3)).days))\n \n- def test_age_with_ignored_lists(self):\n+ async def test_age_with_ignored_lists(self):\n \"\"\"Test that lists can be ignored when measuring the source up to dateness.\"\"\"\n self.metric[\"sources\"][\"source_id\"][\"parameters\"][\"lists_to_ignore\"] = [\"list1\"]\n- response = self.collect(self.metric, get_request_json_side_effect=self.side_effect)\n+ response = await self.collect(self.metric, get_request_json_side_effect=self.side_effect)\n self.assert_measurement(response, value=str((datetime.now() - datetime(2019, 2, 10)).days))\ndiff --git a/components/collector/tests/source_collectors/test_wekan.py b/components/collector/tests/source_collectors/api_source_collectors/test_wekan.py\nsimilarity index 82%\nrename from components/collector/tests/source_collectors/test_wekan.py\nrename to components/collector/tests/source_collectors/api_source_collectors/test_wekan.py\n--- a/components/collector/tests/source_collectors/test_wekan.py\n+++ b/components/collector/tests/source_collectors/api_source_collectors/test_wekan.py\n@@ -3,7 +3,7 @@\n from datetime import datetime\n from typing import Dict\n \n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class WekanTestCase(SourceCollectorTestCase):\n@@ -19,8 +19,7 @@ def setUp(self):\n inactive_days=\"90\", lists_to_ignore=[])))\n self.json = [\n dict(_id=\"user_id\"),\n- [dict(_id=\"board1\", title=\"Board 1\")],\n- dict(slug=\"board-slug\"),\n+ [dict(_id=\"board1\", title=\"Board 1\", slug=\"board-slug\")],\n [self.list(1), self.list(2), self.list(3, archived=True)],\n [self.card(1), self.card(2)],\n self.full_card(1),\n@@ -59,36 +58,36 @@ def setUp(self):\n super().setUp()\n self.metric = dict(type=\"issues\", addition=\"sum\", sources=self.sources)\n \n- def test_issues(self):\n+ async def test_issues(self):\n \"\"\"Test that the number of issues and the individual issues are returned and that archived cards are ignored.\"\"\"\n- self.json[6][\"archived\"] = True\n- response = self.collect(\n+ self.json[5][\"archived\"] = True\n+ response = await self.collect(\n self.metric, get_request_json_side_effect=self.json, post_request_json_return_value=dict(token=\"token\"))\n self.assert_measurement(response, value=\"2\", entities=self.entities)\n \n- def test_issues_with_ignored_list(self):\n+ async def test_issues_with_ignored_list(self):\n \"\"\"Test that lists can be ignored when counting issues.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"lists_to_ignore\"] = [\"list2\"]\n- self.json[6][\"archived\"] = True\n+ self.json[5][\"archived\"] = True\n del self.entities[1]\n- response = self.collect(\n+ response = await self.collect(\n self.metric, get_request_json_side_effect=self.json, post_request_json_return_value=dict(token=\"token\"))\n self.assert_measurement(response, value=\"1\", entities=self.entities)\n \n- def test_overdue_issues(self):\n+ async def test_overdue_issues(self):\n \"\"\"Test overdue issues.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"cards_to_count\"] = [\"overdue\"]\n- self.entities[0][\"due_date\"] = self.json[5][\"dueAt\"] = \"2019-01-01\"\n- self.entities[1][\"due_date\"] = self.json[8][\"dueAt\"] = \"2019-02-02\"\n- response = self.collect(\n+ self.entities[0][\"due_date\"] = self.json[4][\"dueAt\"] = \"2019-01-01\"\n+ self.entities[1][\"due_date\"] = self.json[7][\"dueAt\"] = \"2019-02-02\"\n+ response = await self.collect(\n self.metric, get_request_json_side_effect=self.json, post_request_json_return_value=dict(token=\"token\"))\n self.assert_measurement(response, value=\"2\", entities=self.entities)\n \n- def test_inactive_issues(self):\n+ async def test_inactive_issues(self):\n \"\"\"Test inactive issues.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"cards_to_count\"] = [\"inactive\"]\n- self.json[6][\"dateLastActivity\"] = datetime.now().isoformat()\n- response = self.collect(\n+ self.json[5][\"dateLastActivity\"] = datetime.now().isoformat()\n+ response = await self.collect(\n self.metric, get_request_json_side_effect=self.json, post_request_json_return_value=dict(token=\"token\"))\n self.assert_measurement(response, value=\"2\", entities=self.entities)\n \n@@ -96,10 +95,10 @@ def test_inactive_issues(self):\n class WekanSourceUpToDatenessTest(WekanTestCase):\n \"\"\"Unit tests for the Wekan source up-to-dateness collector.\"\"\"\n \n- def test_age_with_ignored_lists(self):\n+ async def test_age_with_ignored_lists(self):\n \"\"\"Test that lists can be ignored when measuring the number of days since the last activity.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"lists_to_ignore\"] = [\"list1\"]\n metric = dict(type=\"source_up_to_dateness\", addition=\"max\", sources=self.sources)\n- response = self.collect(\n+ response = await self.collect(\n metric, get_request_json_side_effect=self.json, post_request_json_return_value=dict(token=\"token\"))\n self.assert_measurement(response, value=str((datetime.now() - datetime(2019, 1, 1)).days))\ndiff --git a/components/collector/tests/source_collectors/file_source_collectors/__init__.py b/components/collector/tests/source_collectors/file_source_collectors/__init__.py\nnew file mode 100644\ndiff --git a/components/collector/tests/source_collectors/test_anchore.py b/components/collector/tests/source_collectors/file_source_collectors/test_anchore.py\nsimilarity index 81%\nrename from components/collector/tests/source_collectors/test_anchore.py\nrename to components/collector/tests/source_collectors/file_source_collectors/test_anchore.py\n--- a/components/collector/tests/source_collectors/test_anchore.py\n+++ b/components/collector/tests/source_collectors/file_source_collectors/test_anchore.py\n@@ -5,7 +5,7 @@\n import zipfile\n from datetime import datetime, timezone\n \n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class AnchoreTestCase(SourceCollectorTestCase):\n@@ -34,18 +34,18 @@ def setUp(self):\n key=\"1fe53aa1061841cbd9fcdab1179191dc\", cve=\"CVE-000\", url=\"https://cve\", fix=\"None\", severity=\"Low\",\n package=\"package\")]\n \n- def test_warnings(self):\n+ async def test_warnings(self):\n \"\"\"Test the number of security warnings.\"\"\"\n- response = self.collect(self.metric, get_request_json_return_value=self.vulnerabilities_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=self.vulnerabilities_json)\n self.assert_measurement(response, value=\"1\", entities=self.expected_entities)\n \n- def test_zipped_report(self):\n+ async def test_zipped_report(self):\n \"\"\"Test that a zip with reports can be read.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"url\"] = \"anchore.zip\"\n with zipfile.ZipFile(bytes_io := io.BytesIO(), mode=\"w\") as zipped_anchore_report:\n zipped_anchore_report.writestr(\"vuln.json\", json.dumps(self.vulnerabilities_json))\n zipped_anchore_report.writestr(\"details.json\", json.dumps(self.details_json))\n- response = self.collect(self.metric, get_request_content=bytes_io.getvalue())\n+ response = await self.collect(self.metric, get_request_content=bytes_io.getvalue())\n self.assert_measurement(response, value=\"1\", entities=self.expected_entities)\n \n \n@@ -57,16 +57,16 @@ def setUp(self):\n self.metric = dict(type=\"source_up_to_dateness\", sources=self.sources, addition=\"max\")\n self.expected_age = (datetime.now(tz=timezone.utc) - datetime(2020, 2, 7, 22, 53, 43, tzinfo=timezone.utc)).days\n \n- def test_source_up_to_dateness(self):\n+ async def test_source_up_to_dateness(self):\n \"\"\"Test that the source age in days is returned.\"\"\"\n- response = self.collect(self.metric, get_request_json_return_value=self.details_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=self.details_json)\n self.assert_measurement(response, value=str(self.expected_age))\n \n- def test_zipped_report(self):\n+ async def test_zipped_report(self):\n \"\"\"Test that a zip with reports can be read.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"details_url\"] = \"anchore.zip\"\n with zipfile.ZipFile(bytes_io := io.BytesIO(), mode=\"w\") as zipped_anchore_report:\n zipped_anchore_report.writestr(\"vuln.json\", json.dumps(self.vulnerabilities_json))\n zipped_anchore_report.writestr(\"details.json\", json.dumps(self.details_json))\n- response = self.collect(self.metric, get_request_content=bytes_io.getvalue())\n+ response = await self.collect(self.metric, get_request_content=bytes_io.getvalue())\n self.assert_measurement(response, value=str(self.expected_age))\ndiff --git a/components/collector/tests/source_collectors/test_axe_csv.py b/components/collector/tests/source_collectors/file_source_collectors/test_axe_csv.py\nsimilarity index 78%\nrename from components/collector/tests/source_collectors/test_axe_csv.py\nrename to components/collector/tests/source_collectors/file_source_collectors/test_axe_csv.py\n--- a/components/collector/tests/source_collectors/test_axe_csv.py\n+++ b/components/collector/tests/source_collectors/file_source_collectors/test_axe_csv.py\n@@ -4,7 +4,7 @@\n import zipfile\n \n from collector_utilities.functions import md5_hash\n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class AxeCSVAccessibilityTest(SourceCollectorTestCase):\n@@ -41,44 +41,44 @@ def setUp(self):\n for entity in self.expected_entities:\n entity[\"key\"] = md5_hash(\",\".join(str(value) for value in entity.values()))\n \n- def test_nr_of_issues(self):\n+ async def test_nr_of_issues(self):\n \"\"\"Test that the number of issues is returned.\"\"\"\n- response = self.collect(self.metric, get_request_text=self.csv)\n+ response = await self.collect(self.metric, get_request_text=self.csv)\n self.assert_measurement(response, value=\"2\", entities=self.expected_entities)\n \n- def test_no_issues(self):\n+ async def test_no_issues(self):\n \"\"\"Test zero issues.\"\"\"\n- response = self.collect(self.metric, get_request_text=\"\")\n+ response = await self.collect(self.metric, get_request_text=\"\")\n self.assert_measurement(response, value=\"0\", entities=[])\n \n- def test_filter_by_impact(self):\n+ async def test_filter_by_impact(self):\n \"\"\"Test that violations can be filtered by impact level.\"\"\"\n self.metric[\"sources\"][\"source_id\"][\"parameters\"][\"impact\"] = [\"serious\", \"critical\"]\n- response = self.collect(self.metric, get_request_text=self.csv)\n+ response = await self.collect(self.metric, get_request_text=self.csv)\n self.assert_measurement(response, value=\"1\")\n \n- def test_filter_by_violation_type(self):\n+ async def test_filter_by_violation_type(self):\n \"\"\"Test that violations can be filtered by violation type.\"\"\"\n self.metric[\"sources\"][\"source_id\"][\"parameters\"][\"violation_type\"] = \\\n [\"aria-input-field-name\", \"area-hidden-focus\"]\n- response = self.collect(self.metric, get_request_text=self.csv)\n+ response = await self.collect(self.metric, get_request_text=self.csv)\n self.assert_measurement(response, value=\"1\")\n \n- def test_zipped_csv(self):\n+ async def test_zipped_csv(self):\n \"\"\"Test that a zip archive with CSV files is processed correctly.\"\"\"\n self.metric[\"sources\"][\"source_id\"][\"parameters\"][\"url\"] = \"https://axecsv.zip\"\n with zipfile.ZipFile(bytes_io := io.BytesIO(), mode=\"w\") as zipped_axe_csv:\n for index in range(2):\n zipped_axe_csv.writestr(f\"axe{index}.csv\", self.csv)\n- response = self.collect(self.metric, get_request_content=bytes_io.getvalue())\n+ response = await self.collect(self.metric, get_request_content=bytes_io.getvalue())\n self.assert_measurement(response, value=\"4\", entities=self.expected_entities + self.expected_entities)\n \n- def test_empty_line(self):\n+ async def test_empty_line(self):\n \"\"\"Test that empty lines are ignored.\"\"\"\n- response = self.collect(self.metric, get_request_text=self.csv + \"\\n\\n\")\n+ response = await self.collect(self.metric, get_request_text=self.csv + \"\\n\\n\")\n self.assert_measurement(response, value=\"2\", entities=self.expected_entities)\n \n- def test_embedded_newlines(self):\n+ async def test_embedded_newlines(self):\n \"\"\"Test that embedded newlines are ignored.\"\"\"\n violation_with_newline = 'url3,aria-hidden-focus,moderate,help3,html3,\"messages3\\nsecond line\",dom3\\n'\n expected_entity = {\n@@ -91,5 +91,5 @@ def test_embedded_newlines(self):\n 'help': 'help3'\n }\n expected_entity[\"key\"] = md5_hash(\",\".join(str(value) for value in expected_entity.values()))\n- response = self.collect(self.metric, get_request_text=self.csv + violation_with_newline)\n+ response = await self.collect(self.metric, get_request_text=self.csv + violation_with_newline)\n self.assert_measurement(response, value=\"3\", entities=self.expected_entities + [expected_entity])\ndiff --git a/components/collector/tests/source_collectors/test_bandit.py b/components/collector/tests/source_collectors/file_source_collectors/test_bandit.py\nsimilarity index 77%\nrename from components/collector/tests/source_collectors/test_bandit.py\nrename to components/collector/tests/source_collectors/file_source_collectors/test_bandit.py\n--- a/components/collector/tests/source_collectors/test_bandit.py\n+++ b/components/collector/tests/source_collectors/file_source_collectors/test_bandit.py\n@@ -5,7 +5,7 @@\n import zipfile\n from datetime import datetime, timezone\n \n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class BanditTestCase(SourceCollectorTestCase):\n@@ -40,46 +40,46 @@ def setUp(self):\n issue_severity=\"Low\", issue_confidence=\"Medium\",\n more_info=\"https://bandit/b106_hardcoded_password_funcarg.html\")]\n \n- def test_warnings(self):\n+ async def test_warnings(self):\n \"\"\"Test the number of security warnings.\"\"\"\n- response = self.collect(self.metric, get_request_json_return_value=self.bandit_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=self.bandit_json)\n self.assert_measurement(response, value=\"1\", entities=self.expected_entities)\n \n- def test_warnings_with_high_severity(self):\n+ async def test_warnings_with_high_severity(self):\n \"\"\"Test the number of high severity security warnings.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"severities\"] = [\"high\"]\n- response = self.collect(self.metric, get_request_json_return_value=self.bandit_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=self.bandit_json)\n self.assert_measurement(response, value=\"0\", entities=[])\n \n- def test_warnings_with_high_confidence(self):\n+ async def test_warnings_with_high_confidence(self):\n \"\"\"Test the number of high confidence security warnings.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"confidence_levels\"] = [\"high\"]\n- response = self.collect(self.metric, get_request_json_return_value=self.bandit_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=self.bandit_json)\n self.assert_measurement(response, value=\"0\", entities=[])\n \n- def test_zipped_report(self):\n+ async def test_zipped_report(self):\n \"\"\"Test that a zip with reports can be read.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"url\"] = \"bandit.zip\"\n with zipfile.ZipFile(bytes_io := io.BytesIO(), mode=\"w\") as zipped_bandit_report:\n zipped_bandit_report.writestr(\n \"bandit.json\", json.dumps(self.bandit_json))\n- response = self.collect(self.metric, get_request_content=bytes_io.getvalue())\n+ response = await self.collect(self.metric, get_request_content=bytes_io.getvalue())\n self.assert_measurement(response, value=\"1\", entities=self.expected_entities)\n \n- def test_report_in_gitlab(self):\n+ async def test_report_in_gitlab(self):\n \"\"\"Test that a private token can be added to the request header for accessing a report in GitLab.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"private_token\"] = \"token\"\n- response = self.collect(self.metric, get_request_json_return_value=self.bandit_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=self.bandit_json)\n self.assert_measurement(response, value=\"1\", entities=self.expected_entities)\n \n \n class BanditSourceUpToDatenessTest(BanditTestCase):\n \"\"\"Unit tests for the source up to dateness metric.\"\"\"\n \n- def test_source_up_to_dateness(self):\n+ async def test_source_up_to_dateness(self):\n \"\"\"Test that the source age in days is returned.\"\"\"\n metric = dict(type=\"source_up_to_dateness\", sources=self.sources, addition=\"max\")\n bandit_json = dict(generated_at=\"2019-07-12T07:38:47Z\")\n- response = self.collect(metric, get_request_json_return_value=bandit_json)\n+ response = await self.collect(metric, get_request_json_return_value=bandit_json)\n expected_age = (datetime.now(tz=timezone.utc) - datetime(2019, 7, 12, 7, 38, 47, tzinfo=timezone.utc)).days\n self.assert_measurement(response, value=str(expected_age))\ndiff --git a/components/collector/tests/source_collectors/test_composer.py b/components/collector/tests/source_collectors/file_source_collectors/test_composer.py\nsimilarity index 81%\nrename from components/collector/tests/source_collectors/test_composer.py\nrename to components/collector/tests/source_collectors/file_source_collectors/test_composer.py\n--- a/components/collector/tests/source_collectors/test_composer.py\n+++ b/components/collector/tests/source_collectors/file_source_collectors/test_composer.py\n@@ -1,6 +1,6 @@\n \"\"\"Unit tests for the Composer source.\"\"\"\n \n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class ComposerDependenciesTest(SourceCollectorTestCase):\n@@ -22,13 +22,13 @@ def setUp(self):\n self.sources = dict(source_id=dict(type=\"composer\", parameters=dict(url=\"composer.json\")))\n self.metric = dict(type=\"dependencies\", sources=self.sources, addition=\"sum\")\n \n- def test_dependencies(self):\n+ async def test_dependencies(self):\n \"\"\"Test that the number of dependencies is returned.\"\"\"\n- response = self.collect(self.metric, get_request_json_return_value=self.composer_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=self.composer_json)\n self.assert_measurement(response, value=\"2\", total=\"2\", entities=self.expected_entities)\n \n- def test_dependencies_by_status(self):\n+ async def test_dependencies_by_status(self):\n \"\"\"Test that the number of dependencies can be filtered by status.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"latest_version_status\"] = [\"safe update possible\"]\n- response = self.collect(self.metric, get_request_json_return_value=self.composer_json)\n+ response = await self.collect(self.metric, get_request_json_return_value=self.composer_json)\n self.assert_measurement(response, value=\"1\", total=\"2\", entities=self.expected_entities[:1])\ndiff --git a/components/collector/tests/source_collectors/test_jacoco.py b/components/collector/tests/source_collectors/file_source_collectors/test_jacoco.py\nsimilarity index 77%\nrename from components/collector/tests/source_collectors/test_jacoco.py\nrename to components/collector/tests/source_collectors/file_source_collectors/test_jacoco.py\n--- a/components/collector/tests/source_collectors/test_jacoco.py\n+++ b/components/collector/tests/source_collectors/file_source_collectors/test_jacoco.py\n@@ -4,7 +4,7 @@\n import zipfile\n from datetime import datetime\n \n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class JaCoCoTest(SourceCollectorTestCase):\n@@ -14,33 +14,33 @@ def setUp(self):\n super().setUp()\n self.sources = dict(source_id=dict(type=\"jacoco\", parameters=dict(url=\"https://jacoco/\")))\n \n- def test_uncovered_lines(self):\n+ async def test_uncovered_lines(self):\n \"\"\"Test that the number of uncovered lines and the total number of lines are returned.\"\"\"\n metric = dict(type=\"uncovered_lines\", sources=self.sources, addition=\"sum\")\n- response = self.collect(\n+ response = await self.collect(\n metric, get_request_text=\"\")\n self.assert_measurement(response, value=\"2\", total=\"6\")\n \n- def test_uncovered_branches(self):\n+ async def test_uncovered_branches(self):\n \"\"\"Test that the number of uncovered branches is returned.\"\"\"\n metric = dict(type=\"uncovered_branches\", sources=self.sources, addition=\"sum\")\n- response = self.collect(\n+ response = await self.collect(\n metric, get_request_text=\"\")\n self.assert_measurement(response, value=\"4\", total=\"10\")\n \n- def test_source_up_to_dateness(self):\n+ async def test_source_up_to_dateness(self):\n \"\"\"Test that the source age in days is returned.\"\"\"\n metric = dict(type=\"source_up_to_dateness\", sources=self.sources, addition=\"sum\")\n- response = self.collect(metric, get_request_text='')\n+ response = await self.collect(metric, get_request_text='')\n expected_age = (datetime.utcnow() - datetime.utcfromtimestamp(1553821197.442)).days\n self.assert_measurement(response, value=str(expected_age))\n \n- def test_zipped_report(self):\n+ async def test_zipped_report(self):\n \"\"\"Test that a zipped report can be read.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"url\"] = \"https://jacoco.zip\"\n metric = dict(type=\"uncovered_lines\", sources=self.sources, addition=\"sum\")\n with zipfile.ZipFile(bytes_io := io.BytesIO(), mode=\"w\") as zipped_jacoco_report:\n zipped_jacoco_report.writestr(\n \"jacoco.xml\", \"\")\n- response = self.collect(metric, get_request_content=bytes_io.getvalue())\n+ response = await self.collect(metric, get_request_content=bytes_io.getvalue())\n self.assert_measurement(response, value=\"2\", total=\"6\")\ndiff --git a/components/collector/tests/source_collectors/test_junit.py b/components/collector/tests/source_collectors/file_source_collectors/test_junit.py\nsimilarity index 83%\nrename from components/collector/tests/source_collectors/test_junit.py\nrename to components/collector/tests/source_collectors/file_source_collectors/test_junit.py\n--- a/components/collector/tests/source_collectors/test_junit.py\n+++ b/components/collector/tests/source_collectors/file_source_collectors/test_junit.py\n@@ -4,7 +4,7 @@\n import zipfile\n from datetime import datetime\n \n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class JUnitTestReportTest(SourceCollectorTestCase):\n@@ -29,35 +29,35 @@ def setUp(self):\n dict(key=\"tc4\", name=\"tc4\", class_name=\"cn\", test_result=\"errored\"),\n dict(key=\"tc5\", name=\"tc5\", class_name=\"cn\", test_result=\"skipped\")]\n \n- def test_tests(self):\n+ async def test_tests(self):\n \"\"\"Test that the number of tests is returned.\"\"\"\n- response = self.collect(self.metric, get_request_text=self.junit_xml)\n+ response = await self.collect(self.metric, get_request_text=self.junit_xml)\n self.assert_measurement(response, value=\"5\", entities=self.expected_entities)\n \n- def test_failed_tests(self):\n+ async def test_failed_tests(self):\n \"\"\"Test that the failed tests are returned.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"test_result\"] = [\"failed\"]\n- response = self.collect(self.metric, get_request_text=self.junit_xml)\n+ response = await self.collect(self.metric, get_request_text=self.junit_xml)\n self.assert_measurement(\n response, value=\"1\", entities=[dict(key=\"tc3\", name=\"tc3\", class_name=\"cn\", test_result=\"failed\")])\n \n- def test_zipped_junit_report(self):\n+ async def test_zipped_junit_report(self):\n \"\"\"Test that the number of tests is returned from a zip with JUnit reports.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"url\"] = \"junit.zip\"\n with zipfile.ZipFile(bytes_io := io.BytesIO(), mode=\"w\") as zipped_bandit_report:\n zipped_bandit_report.writestr(\"junit.xml\", self.junit_xml)\n- response = self.collect(self.metric, get_request_content=bytes_io.getvalue())\n+ response = await self.collect(self.metric, get_request_content=bytes_io.getvalue())\n self.assert_measurement(response, value=\"5\", entities=self.expected_entities)\n \n \n class JUnitSourceUpToDatenessTest(SourceCollectorTestCase):\n \"\"\"Unit tests for the source up-to-dateness metric.\"\"\"\n \n- def test_source_up_to_dateness(self):\n+ async def test_source_up_to_dateness(self):\n \"\"\"Test that the source age in days is returned.\"\"\"\n sources = dict(source_id=dict(type=\"junit\", parameters=dict(url=\"junit.xml\")))\n metric = dict(type=\"source_up_to_dateness\", sources=sources, addition=\"max\")\n- response = self.collect(\n+ response = await self.collect(\n metric, get_request_text='')\n expected_age = (datetime.now() - datetime(2009, 12, 19, 17, 58, 59)).days\n self.assert_measurement(response, value=str(expected_age))\ndiff --git a/components/collector/tests/source_collectors/test_ncover.py b/components/collector/tests/source_collectors/file_source_collectors/test_ncover.py\nsimilarity index 82%\nrename from components/collector/tests/source_collectors/test_ncover.py\nrename to components/collector/tests/source_collectors/file_source_collectors/test_ncover.py\n--- a/components/collector/tests/source_collectors/test_ncover.py\n+++ b/components/collector/tests/source_collectors/file_source_collectors/test_ncover.py\n@@ -4,7 +4,7 @@\n import zipfile\n from datetime import datetime\n \n-from .source_collector_test_case import SourceCollectorTestCase\n+from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase\n \n \n class NCoverTest(SourceCollectorTestCase):\n@@ -25,16 +25,16 @@ def setUp(self):\n };\n \"\"\"\n \n- def test_uncovered_lines(self):\n+ async def test_uncovered_lines(self):\n \"\"\"Test that the number of uncovered sequence points is returned.\"\"\"\n metric = dict(type=\"uncovered_lines\", sources=self.sources, addition=\"sum\")\n- response = self.collect(metric, get_request_text=self.ncover_html)\n+ response = await self.collect(metric, get_request_text=self.ncover_html)\n self.assert_measurement(response, value=f\"{17153-14070}\", total=\"17153\")\n \n- def test_uncovered_branches(self):\n+ async def test_uncovered_branches(self):\n \"\"\"Test that the number of uncovered branches is returned.\"\"\"\n metric = dict(type=\"uncovered_branches\", sources=self.sources, addition=\"sum\")\n- response = self.collect(metric, get_request_text=\"\"\"\n+ response = await self.collect(metric, get_request_text=\"\"\"\n \n@@ -48,19 +48,19 @@ def test_uncovered_branches(self):\n \"\"\")\n self.assert_measurement(response, value=f\"{12034-9767}\", total=\"12034\")\n \n- def test_zipped_report(self):\n+ async def test_zipped_report(self):\n \"\"\"Test that the coverage can be read from a zip with NCover reports.\"\"\"\n self.sources[\"source_id\"][\"parameters\"][\"url\"] = \"https://report.zip\"\n metric = dict(type=\"uncovered_lines\", sources=self.sources, addition=\"sum\")\n with zipfile.ZipFile(bytes_io := io.BytesIO(), mode=\"w\") as zipped_ncover_report:\n zipped_ncover_report.writestr(\"ncover.html\", self.ncover_html)\n- response = self.collect(metric, get_request_content=bytes_io.getvalue())\n+ response = await self.collect(metric, get_request_content=bytes_io.getvalue())\n self.assert_measurement(response, value=f\"{17153-14070}\", total=\"17153\")\n \n- def test_source_up_to_dateness(self):\n+ async def test_source_up_to_dateness(self):\n \"\"\"Test that the source age in days is returned.\"\"\"\n metric = dict(type=\"source_up_to_dateness\", sources=self.sources, addition=\"sum\")\n- response = self.collect(metric, get_request_text=\"\"\"\n+ response = await self.collect(metric, get_request_text=\"\"\"\n