From c8bac8fd45dbf8af47ac08870a86d68b9dc16d32 Mon Sep 17 00:00:00 2001 From: hdwhdw Date: Mon, 6 Jan 2025 20:59:00 +0000 Subject: [PATCH] switch to extracting json substring using re. --- tests/gnmi/test_gnoi_system.py | 32 ++++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/tests/gnmi/test_gnoi_system.py b/tests/gnmi/test_gnoi_system.py index 65c18b1747a..cf65d5ac9ca 100644 --- a/tests/gnmi/test_gnoi_system.py +++ b/tests/gnmi/test_gnoi_system.py @@ -4,6 +4,7 @@ from .helper import gnoi_request from tests.common.helpers.assertions import pytest_assert +import re pytestmark = [ pytest.mark.topology('any') @@ -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