From dcb37417efc67240deebd76bce8d415505cb9668 Mon Sep 17 00:00:00 2001 From: Yulya Artyukhina Date: Tue, 14 Jan 2025 14:40:32 +0100 Subject: [PATCH] Fix getting label by name (#5414) # What this PR does Handle JSONDecodeError on getting label key by name ## Checklist - [x] Unit, integration, and e2e (if applicable) tests updated - [x] Documentation added (or `pr:no public docs` PR label added if not required) - [x] Added the relevant release notes label (see labels prefixed w/ `release:`). These labels dictate how your PR will show up in the autogenerated release notes. --- engine/apps/labels/models.py | 3 ++- engine/apps/labels/tests/test_labels_cache.py | 7 +++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/engine/apps/labels/models.py b/engine/apps/labels/models.py index 53a60ce38d..ae81d0db93 100644 --- a/engine/apps/labels/models.py +++ b/engine/apps/labels/models.py @@ -1,5 +1,6 @@ import logging import typing +from json import JSONDecodeError from django.db import models from django.utils import timezone @@ -44,7 +45,7 @@ def get_or_create_by_name(cls, organization: "Organization", key_name: str) -> t label, _ = LabelsAPIClient(organization.grafana_url, organization.api_token).get_label_by_key_name( label_key ) - except LabelsRepoAPIException as e: + except (LabelsRepoAPIException, JSONDecodeError) as e: logger.error(f"Failed to get or create label key {key_name} for organization {organization.id}: {e}") return None diff --git a/engine/apps/labels/tests/test_labels_cache.py b/engine/apps/labels/tests/test_labels_cache.py index f86533755d..531b2a8f28 100644 --- a/engine/apps/labels/tests/test_labels_cache.py +++ b/engine/apps/labels/tests/test_labels_cache.py @@ -1,3 +1,4 @@ +from json import JSONDecodeError from unittest.mock import call, patch import pytest @@ -165,6 +166,12 @@ def test_get_or_create_label_key_cache_by_name(make_organization): organization = make_organization() label_key_data = {"id": "testid", "name": "testname", "prescribed": False} + # test empty response from label repo (json decode error) + with patch.object(LabelsAPIClient, "get_label_by_key_name", side_effect=JSONDecodeError("test", "test", 0)): + label = LabelKeyCache.get_or_create_by_name(organization, label_key_data["name"]) + + assert label is None + # test label does not exist in labels repo with patch.object(LabelsAPIClient, "get_label_by_key_name", side_effect=LabelsRepoAPIException("test", "test")): label = LabelKeyCache.get_or_create_by_name(organization, label_key_data["name"])