Skip to content

Commit

Permalink
switch to extracting json substring using re.
Browse files Browse the repository at this point in the history
  • Loading branch information
hdwhdw committed Jan 6, 2025
1 parent b8c9bd1 commit c8bac8f
Showing 1 changed file with 24 additions and 8 deletions.
32 changes: 24 additions & 8 deletions tests/gnmi/test_gnoi_system.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

from .helper import gnoi_request
from tests.common.helpers.assertions import pytest_assert
import re

pytestmark = [
pytest.mark.topology('any')
Expand All @@ -25,11 +26,26 @@ def test_gnoi_system_time(duthosts, rand_one_dut_hostname, localhost):
ret, msg = gnoi_request(duthost, localhost, "Time", "")
logging.info("System.Time API returned: {}".format(msg))
pytest_assert(ret == 0, "System.Time API unexpectedly reported failure")
try:
# Message should looks like this: System Time\n{"time":1735921221909617549}
# Extract JSON part from the message
json_part = msg.split('\n', 1)[1]
msg_json = json.loads(json_part)
pytest_assert("time" in msg_json, "System.Time API did not return time")
except (json.JSONDecodeError, IndexError):
pytest.fail("System.Time API did not return valid JSON")
# Message should contain a json substring like this {"time":1735921221909617549}
# Extract JSON part from the message
msg_json = extract_first_json_substring(msg)
logging.info("Extracted JSON: {}".format(msg_json))
pytest_assert("time" in msg_json, "System.Time API did not return time")


def extract_first_json_substring(s):
"""
Extract the first JSON substring from a given string.
:param s: The input string containing JSON substring.
:return: The first JSON substring if found, otherwise None.
"""

json_pattern = re.compile(r'\{.*?\}')
match = json_pattern.search(s)
if match:
try:
return json.loads(match.group())
except json.JSONDecodeError:
return None
return None

0 comments on commit c8bac8f

Please sign in to comment.