|
| 1 | +import pytest |
| 2 | +import logging |
| 3 | +import json |
| 4 | + |
| 5 | +from .helper import gnoi_request |
| 6 | +from tests.common.helpers.assertions import pytest_assert |
| 7 | +import re |
| 8 | + |
| 9 | +pytestmark = [ |
| 10 | + pytest.mark.topology('any') |
| 11 | +] |
| 12 | + |
| 13 | + |
| 14 | +""" |
| 15 | +This module contains tests for the gNOI System API. |
| 16 | +""" |
| 17 | + |
| 18 | + |
| 19 | +def test_gnoi_system_time(duthosts, rand_one_dut_hostname, localhost): |
| 20 | + """ |
| 21 | + Verify the gNOI System Time API returns the current system time in valid JSON format. |
| 22 | + """ |
| 23 | + duthost = duthosts[rand_one_dut_hostname] |
| 24 | + |
| 25 | + # Get current time |
| 26 | + ret, msg = gnoi_request(duthost, localhost, "Time", "") |
| 27 | + pytest_assert(ret == 0, "System.Time API reported failure (rc = {}) with message: {}".format(ret, msg)) |
| 28 | + logging.info("System.Time API returned msg: {}".format(msg)) |
| 29 | + # Message should contain a json substring like this {"time":1735921221909617549} |
| 30 | + # Extract JSON part from the message |
| 31 | + msg_json = extract_first_json_substring(msg) |
| 32 | + if not msg_json: |
| 33 | + pytest.fail("Failed to extract JSON from System.Time API response") |
| 34 | + logging.info("Extracted JSON: {}".format(msg_json)) |
| 35 | + pytest_assert("time" in msg_json, "System.Time API did not return time") |
| 36 | + |
| 37 | + |
| 38 | +def extract_first_json_substring(s): |
| 39 | + """ |
| 40 | + Extract the first JSON substring from a given string. |
| 41 | +
|
| 42 | + :param s: The input string containing JSON substring. |
| 43 | + :return: The first JSON substring if found, otherwise None. |
| 44 | + """ |
| 45 | + |
| 46 | + json_pattern = re.compile(r'\{.*?\}') |
| 47 | + match = json_pattern.search(s) |
| 48 | + if match: |
| 49 | + try: |
| 50 | + return json.loads(match.group()) |
| 51 | + except json.JSONDecodeError: |
| 52 | + logging.error("Failed to parse JSON: {}".format(match.group())) |
| 53 | + return None |
| 54 | + return None |
0 commit comments