Copilot commented on code in PR #13850:
URL: https://github.com/apache/trafficserver/pull/13850#discussion_r4319554002
##########
plugins/traffic_dump/post_process.py:
##########
@@ -259,11 +259,11 @@ def readAndCombine(replay_dir, num_sessions_per_file,
indent, fabricate_proxy_re
try:
verify_session(session, fabricate_proxy_requests)
except VerifyError as e:
- connection_time = session['connection-time']
- if not connection_time:
- connection_time = session['start-time']
+ connection_time = None
+ if session:
+ connection_time = session.get('connection-time') or
session.get('start-time')
if connection_time:
- logging.debug("Omitting session in %s with
connection-time: %d: %s", replay_file, session['connection-time'], e)
+ logging.debug("Omitting session in %s with
connection-time: %d: %s", replay_file, connection_time, e)
Review Comment:
`session.get('connection-time') or ...` treats a legitimate
`connection-time` value of `0` as “missing” (because `0` is falsy), and `if
connection_time:` will also skip logging `0`. Additionally, `if session:` does
not guarantee `session` is a dict, so `session.get(...)` can still raise (e.g.,
for a non-empty list), defeating the goal of preventing secondary exceptions.
Prefer checking `isinstance(session, dict)` and selecting timestamps based on
key presence / `is not None` (and log when the key exists even if the value is
`0`).
##########
plugins/traffic_dump/unit_tests/test_post_process.py:
##########
@@ -0,0 +1,133 @@
+#!/usr/bin/env python3
+'''
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+'''
+"""Verify incomplete sessions do not prevent valid sessions from being
written."""
+import importlib.util
+import json
+import logging
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import unittest
+
+SCRIPT = Path(__file__).resolve().parents[1] / "post_process.py"
+spec = importlib.util.spec_from_file_location("post_process", SCRIPT)
+post_process = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(post_process)
+
+INVALID_SESSIONS = {
+ "null": None,
+ "empty": {},
+ "missing_timestamp": {
+ "transactions": []
+ },
+ "legacy_timestamp": {
+ "start-time": 123,
+ "transactions": []
+ },
+ "zero_timestamp": {
+ "connection-time": 0,
+ "transactions": []
+ },
+ "connection_timestamp": {
+ "connection-time": 123,
+ "transactions": []
+ },
+}
+
+
+def valid_session(url: str) -> dict:
+ """Create a complete transaction served locally by the proxy."""
+ return {
+ "connection-time": 123,
+ "transactions":
+ [
+ {
+ "client-request": {
+ "method": "GET",
+ "url": url,
+ "headers": {
+ "fields": [["Host", "example.test"]]
+ }
+ },
+ "proxy-response": {
+ "status": 200
+ },
+ }
+ ],
+ }
+
+
+def write_input(root: Path, sessions: list) -> tuple[Path, Path]:
+ """Write one dump file in the client directory expected by the CLI."""
+ input_dir = root / "input" / "127"
+ input_dir.mkdir(parents=True)
+ output_dir = root / "output"
+ output_dir.mkdir()
+ (input_dir / "sessions.json").write_text(json.dumps({"sessions":
sessions}), encoding="utf-8")
+ return input_dir, output_dir
+
+
+class PostProcessTest(unittest.TestCase):
+
+ def assert_valid_sessions(self, output_dir: Path) -> None:
+ files = list(output_dir.glob("*.json"))
+ self.assertEqual(len(files), 1)
+ sessions = json.loads(files[0].read_text(encoding="utf-8"))["sessions"]
+ self.assertEqual([session["transactions"][0]["client-request"]["url"]
for session in sessions], ["/before", "/after"])
+
+ def test_complete_sessions(self) -> None:
+ with tempfile.TemporaryDirectory() as temp:
+ input_dir, output_dir = write_input(Path(temp),
[valid_session("/before"), valid_session("/after")])
+ sessions, transactions, _ =
post_process.readAndCombine(str(input_dir), 10, 2, True, str(output_dir))
+ self.assertEqual((sessions, transactions), (2, 2))
+ self.assert_valid_sessions(output_dir)
+
+ def test_incomplete_sessions(self) -> None:
+ for name, invalid in INVALID_SESSIONS.items():
+ with self.subTest(name=name), tempfile.TemporaryDirectory() as
temp:
+ input_dir, output_dir = write_input(Path(temp),
[valid_session("/before"), invalid, valid_session("/after")])
+ with self.assertLogs(level=logging.DEBUG) as logs:
+ sessions, transactions, _ =
post_process.readAndCombine(str(input_dir), 10, 2, True, str(output_dir))
+ self.assertEqual((sessions, transactions), (2, 2))
+ self.assert_valid_sessions(output_dir)
+ if name == "legacy_timestamp":
+ self.assertIn("connection-time: 123", logs.output[0])
Review Comment:
Indexing `logs.output[0]` is brittle because additional debug messages can
appear before the expected one (ordering can change as logging evolves). To
make the test stable, search across all captured log lines (e.g., assert that
any entry contains the substring) rather than assuming it’s the first message.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]