diff --git a/connaisseur/flask_application.py b/connaisseur/flask_application.py index b901519fd..d6528d0e8 100644 --- a/connaisseur/flask_application.py +++ b/connaisseur/flask_application.py @@ -55,8 +55,8 @@ def handle_alert_config_error(err): "mutate_requests_total", "Total number of mutate requests", labels={ - "allowed": lambda r: r.get_json(silent=True)["response"]["allowed"], - "status_code": lambda r: r.get_json(silent=True)["response"]["status"]["code"], + "allowed": lambda r: metrics_label(r, "allowed"), + "status_code": lambda r: metrics_label(r, "status_code"), }, ) def mutate(): @@ -92,6 +92,16 @@ def mutate(): return jsonify(response) +def metrics_label(response, label): + l = response.get_json(silent=True) + if l: + if label == "allowed": + return l["response"]["allowed"] + elif label == "status_code": + return l["response"]["status"]["code"] + return l + + # health probe @APP.route("/health", methods=["GET", "POST"]) @metrics.do_not_track() diff --git a/tests/test_flask_application.py b/tests/test_flask_application.py index 21eba40c7..833be2338 100644 --- a/tests/test_flask_application.py +++ b/tests/test_flask_application.py @@ -116,11 +116,13 @@ def test_mutate_calls_send_alert_for_invalid_admission_request( def test_healthz(): - assert pytest.fa.healthz() == ("", 200) + with pytest.fa.APP.test_request_context(): + assert pytest.fa.healthz() == ("", 200) def test_readyz(): - assert pytest.fa.readyz() == ("", 200) + with pytest.fa.APP.test_request_context(): + assert pytest.fa.readyz() == ("", 200) @pytest.mark.parametrize( @@ -231,8 +233,9 @@ def test_error_handler( mocker.patch("connaisseur.flask_application.__admit", return_value=True) mock_function = mocker.patch(**function) - client = pytest.fa.APP.test_client() - mock_request_data = fix.get_admreq("deployments") - response = client.post("/mutate", json=mock_request_data) - assert response.status_code == 500 - assert response.get_data().decode() == err + with pytest.fa.APP.test_request_context(): + client = pytest.fa.APP.test_client() + mock_request_data = fix.get_admreq("deployments") + response = client.post("/mutate", json=mock_request_data) + assert response.status_code == 500 + assert response.get_data().decode() == err