Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions tests/test_port_alignment.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import sys
import tempfile
import unittest
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools"))

from port_alignment import build


class PortAlignmentTest(unittest.TestCase):
def test_reports_alignment(self):
with tempfile.TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
(root / "mx_exporter").mkdir()
(root / "deployment" / "mx-exporter").mkdir(parents=True)
(root / "mx_exporter" / "__init__.py").write_text('parser.add_argument("-p", "--port", default=8000)\n', encoding="utf-8")
(root / "start_mxexporter.sh").write_text("HOST_PORT=8000\n", encoding="utf-8")
(root / "deployment" / "mx-exporter" / "mx-exporter-daemonset.yaml").write_text(
"port: 8000\ncontainerPort: 8000\n", encoding="utf-8"
)

report = build(root)

self.assertTrue(report["aligned"])

def test_errors_when_yaml_ports_are_missing(self):
with tempfile.TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
(root / "mx_exporter").mkdir()
(root / "deployment" / "mx-exporter").mkdir(parents=True)
(root / "mx_exporter" / "__init__.py").write_text(
'parser.add_argument("-p", "--port", default=8000)\n',
encoding="utf-8",
)
(root / "start_mxexporter.sh").write_text("HOST_PORT=8000\n", encoding="utf-8")
(root / "deployment" / "mx-exporter" / "mx-exporter-daemonset.yaml").write_text(
"kind: DaemonSet\n",
encoding="utf-8",
)

with self.assertRaises(ValueError):
build(root)


if __name__ == "__main__":
unittest.main()
58 changes: 58 additions & 0 deletions tools/port_alignment.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
#!/usr/bin/env python3
"""Audit mx-exporter port defaults across code and deployment files."""

from __future__ import annotations

import argparse
import json
import re
from pathlib import Path


CLI_RE = re.compile(r'parser\.add_argument\("-p".*default=(\d+)')
SCRIPT_RE = re.compile(r"HOST_PORT=(\d+)")
YAML_PORT_RE = re.compile(r"(?:port|containerPort):\s*(\d+)")


def build(repo_root: Path) -> dict[str, object]:
cli_text = (repo_root / "mx_exporter" / "__init__.py").read_text(encoding="utf-8")
script_text = (repo_root / "start_mxexporter.sh").read_text(encoding="utf-8")
static_text = (repo_root / "deployment" / "mx-exporter" / "mx-exporter-daemonset.yaml").read_text(encoding="utf-8")

cli_match = CLI_RE.search(cli_text)
script_match = SCRIPT_RE.search(script_text)
if not cli_match:
raise ValueError("Failed to find CLI default port in mx_exporter/__init__.py")
if not script_match:
raise ValueError("Failed to find default HOST_PORT in start_mxexporter.sh")

cli_default = int(cli_match.group(1))
script_default = int(script_match.group(1))
static_ports = sorted({int(value) for value in YAML_PORT_RE.findall(static_text)})
if not static_ports:
raise ValueError("Failed to find any ports in mx-exporter-daemonset.yaml")
aligned = script_default == cli_default and all(port == cli_default for port in static_ports)
Comment on lines +31 to +34

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

如果 YAML_PORT_RE.findall(static_text) 没有匹配到任何端口(例如 YAML 格式发生变化导致正则失效),static_ports 将为空列表,此时 aligned 仍会返回 True

建议增加对 static_ports 是否为空的校验,以避免因匹配失败导致的一致性误判。

    static_ports = sorted({int(value) for value in YAML_PORT_RE.findall(static_text)})
    if not static_ports:
        raise ValueError("Failed to find any ports in mx-exporter-daemonset.yaml")
    aligned = script_default == cli_default and all(port == cli_default for port in static_ports)

return {
"cli_default_port": cli_default,
"script_default_port": script_default,
"static_ports": static_ports,
"aligned": aligned,
}


def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--repo-root", type=Path, default=Path("."))
parser.add_argument("--output", type=Path)
args = parser.parse_args()

text = json.dumps(build(args.repo_root), indent=2, ensure_ascii=False)
if args.output:
args.output.write_text(text + "\n", encoding="utf-8")
else:
print(text)
return 0


if __name__ == "__main__":
raise SystemExit(main())