Skip to content

Commit

Permalink
Fix getting label by name (#5414)
Browse files Browse the repository at this point in the history
# 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.
  • Loading branch information
Ferril authored Jan 14, 2025
1 parent 7287367 commit dcb3741
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
3 changes: 2 additions & 1 deletion engine/apps/labels/models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import logging
import typing
from json import JSONDecodeError

from django.db import models
from django.utils import timezone
Expand Down Expand Up @@ -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

Expand Down
7 changes: 7 additions & 0 deletions engine/apps/labels/tests/test_labels_cache.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from json import JSONDecodeError
from unittest.mock import call, patch

import pytest
Expand Down Expand Up @@ -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"])
Expand Down

0 comments on commit dcb3741

Please sign in to comment.