Skip to content

Commit

Permalink
fix: catch json errors on empty responses from ralph (#461)
Browse files Browse the repository at this point in the history
* fix: catch json errors on empty responses from ralph

* fix: move JSONDecodeError catch statement to xapi lrs

* fix: move JSONDecodeError catch statement to xapi lrs

* chore: remove unnecessary condition

* refactor: define response outside try-except

* test: add tests for jsondecode error

* chore: update duplicated message

* chore: quality changes

* chore: quality changes
  • Loading branch information
Cristhian Garcia authored Oct 15, 2024
1 parent 9115267 commit b7e0c4b
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
17 changes: 17 additions & 0 deletions event_routing_backends/backends/tests/test_events_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import datetime
import json
from copy import copy
from json import JSONDecodeError
from unittest.mock import MagicMock, call, patch, sentinel

import ddt
Expand Down Expand Up @@ -273,6 +274,22 @@ def test_duplicate_xapi_event_id(self, mocked_logger):
mocked_logger.info.mock_calls
)

@patch('event_routing_backends.utils.xapi_lrs_client.logger')
def test_duplicate_xapi_event_id_json(self, mocked_logger):
"""
Test that when we receive a 204 response (and the LRSClient fails to parse to JSON
the response) when bulk inserting XAPI statements it may indicates all events are already stored.
"""
client = LrsClient({})
client.lrs_client = MagicMock()
client.lrs_client.save_statements.side_effect = JSONDecodeError(msg="msg", doc="...", pos=0)

client.bulk_send(statement_data=[])
self.assertIn(
call('JSON Decode Error, this may indicate that all sent events are already stored: []'),
mocked_logger.warning.mock_calls
)

@override_settings(
EVENT_ROUTING_BACKEND_BATCHING_ENABLED=True,
EVENT_ROUTING_BACKEND_BATCH_SIZE=2
Expand Down
12 changes: 11 additions & 1 deletion event_routing_backends/utils/xapi_lrs_client.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""
An LRS client for xAPI stores.
"""
from json.decoder import JSONDecodeError
from logging import getLogger

from tincan.remote_lrs import RemoteLRS
Expand Down Expand Up @@ -71,8 +72,17 @@ def bulk_send(self, statement_data):
requests.Response object
"""
logger.debug('Sending {} xAPI statements to {}'.format(len(statement_data), self.URL))
response = None

response = self.lrs_client.save_statements(statement_data)
try:
response = self.lrs_client.save_statements(statement_data)
except JSONDecodeError:
logger.warning(
f"JSON Decode Error, this may indicate that all sent events are already stored: {statement_data}"
)

if not response:
return

if not response.success:
if response.response.code == 409:
Expand Down

0 comments on commit b7e0c4b

Please sign in to comment.