From 99504a122796b467cb51230e622a17eaf3d525a8 Mon Sep 17 00:00:00 2001 From: Bastien Abadie <bastien@nextcairn.com> Date: Tue, 2 Mar 2021 11:47:44 +0100 Subject: [PATCH] Cache YAML payloads in tests --- tests/conftest.py | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/tests/conftest.py b/tests/conftest.py index 5d65a20e..29b92252 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,10 +1,12 @@ # -*- coding: utf-8 -*- +import hashlib import json import os import sys from pathlib import Path import pytest +import yaml from arkindex.mock import MockApiClient from arkindex_worker.git import GitHelper, GitlabHelper @@ -12,9 +14,37 @@ from arkindex_worker.worker import ElementsWorker FIXTURES_DIR = Path(__file__).resolve().parent / "data" +__yaml_cache = {} + + +@pytest.fixture +def cache_yaml(monkeypatch): + """ + Cache all calls to yaml.safe_load in order to speedup + every test cases that load the OpenAPI schema + """ + # Keep a reference towards the original function + _original_yaml_load = yaml.safe_load + + def _cached_yaml_load(yaml_payload): + # Create a unique cache key for direct YAML strings + # and file descriptors + if isinstance(yaml_payload, str): + key = hashlib.md5(yaml_payload.encode("utf-8")).hexdigest() + else: + key = yaml_payload.name + + # Cache result + if key not in __yaml_cache: + __yaml_cache[key] = _original_yaml_load(yaml_payload) + + return __yaml_cache[key] + + monkeypatch.setattr(yaml, "safe_load", _cached_yaml_load) + @pytest.fixture(autouse=True) -def setup_api(responses, monkeypatch): +def setup_api(responses, monkeypatch, cache_yaml): # Always use the environment variable first schema_url = os.environ.get("ARKINDEX_API_SCHEMA_URL") -- GitLab