Files
mxaccessgw/clients/python/tests/test_cli.py
T
Joseph Doherty a0203503a7 Code-review 2026-05-20 sweep: re-review at 1cd51bb, resolve 72 findings across all 11 modules
Re-reviewed every module/client against the 10-category checklist
(REVIEW-PROCESS.md) at commit 1cd51bb, filed 72 new findings, and
fixed them in three priority waves (3 High, 17 Medium, 52 Low).

Highs
- Server-017: enumerate AcknowledgeAlarm / QueryActiveAlarms in
  GatewayGrpcScopeResolver so non-admin keys can use them; document
  the mapping in docs/Authorization.md; add interceptor tests.
- Client.Java-013: add the five missing bulk-method stubs to the
  CLI FakeSession so the test module compiles on a clean tree.
- Client.Rust-013: fix the clippy::doc_lazy_continuation regression
  in generated tonic code by reformatting the ReadBulkCommand proto
  comment and scoping a #![allow(...)] to the generated submodules.

Mediums (highlights)
- Server: unify GatewaySession state-lock discipline (-015) and
  make DisposeAsync race-safe against in-flight CloseAsync (-016);
  add constraint-enforcement test coverage for the bulk-plan path
  (-021).
- Worker: introduce StaRuntimeShutdownException so RunAlarmPollLoop
  can distinguish graceful shutdown from a real STA-affinity
  violation (-016); have the watchdog skip StaHung while
  CurrentCommandCorrelationId is non-empty so a legitimate slow
  ReadBulk no longer self-faults (-017).
- Tests: add per-method round-trip + cancellation coverage for the
  11 GatewaySession bulk methods (-013); replace the real TCP probe
  in GalaxyHierarchyCacheTests with an IGalaxyRepository fake
  (-016).
- IntegrationTests: drive the StreamEvents writer in the live Write
  test and assert OnWriteComplete (-012); add live tests for
  Unadvise/RemoveItem/Unregister ordering, WriteSecured, and
  abnormal worker exit (-014).
- Worker.Tests: replace MxAccessSession reflection with an internal
  CreateForTesting factory (-016); cover WorkerCancel and
  unexpected-body envelope branches (-017).
- Client.Java: cancel MxEventStream when close() races
  beforeStart() (-014); return a CancellingCompletableFuture that
  actually forwards cancellation through .thenApply chains (-015).
- Client.Python: drop the silent localhost-plaintext downgrade in
  the CLI; require explicit --plaintext (-013).
- Client.Rust: stop bench-read-bulk from polluting success-latency
  histograms with failed-call durations (-015); add coverage for
  the five MalformedReply paths, the bulk-write helpers, the
  Error::Unavailable mapping, and the unary-fault path (-016).
- Contracts: extend docs/Contracts.md with the bulk read/write
  command family (-009).

Lows (highlights)
- Server: cap GalaxyGlobMatcher.RegexCache; align
  WorkerAlarmRpcDispatcher missing-session handling; drop the
  duplicate dashboard @page routes; refresh IAlarmRpcDispatcher
  XML doc.
- Worker: surface SetXmlAlarmQuery COM failures; remove dead
  subscriptionExpression / ExecutingCommand arms; preserve
  factory-supplied runtime sessions; split MxAlarmSnapshot.cs into
  three files.
- Tests: dispose the WebApplication in seven test classes; rebuild
  FakeWorkerProcess.WaitForExitAsync against a real TaskCompletion
  source; switch the heartbeat-expires test to ManualTimeProvider;
  add InvariantCulture to the remaining DateTimeOffset.Parse sites;
  document GalaxyFilterInputSafetyTests in GatewayTesting.md.
- IntegrationTests: comment fixes, RecordingServerStreamWriter
  IDisposable, class-level [Trait], single-source ZB default
  connection string.
- Worker.Tests: replace silent-return gating with LiveMxAccessFact
  so absent env vars SKIP not pass; PascalCase rename of probe
  [Fact]s; deterministic deadline test; new frame-protocol error
  tests; ComputeTransitions diff-coverage; relocate dev-rig probes
  to Probes/.
- Contracts: add round-trip coverage and per-field redaction /
  Galaxy-identifier comments to the protos.
- Client.Dotnet: introduce clients/dotnet/Directory.Build.props so
  TreatWarningsAsErrors / analysers apply; document
  DiscoverHierarchyOptions and IMxGatewayCliClient; require typed
  bulk-read handles in CLI; surface AcknowledgeAlarm transport
  faults through Translate().
- Client.Go: kill dead code in alarms_test / fakeGalaxyServer /
  runWriteBulkVariant; document the six new subcommands in
  writeUsage; drain galaxy-watch events on limit; switch io.EOF
  comparisons to errors.Is.
- Client.Java: shared shutdown helpers + new shutdownTimeout
  option; regex-based credential redaction; Long.toUnsignedString
  for uint64 sequence; doc fixes.
- Client.Python: combine duplicate imports; add coverage for
  _percentile / bench-read-bulk / MAX_AGGREGATE_EVENTS /
  _api_key_from_env; populate pyproject metadata and ship py.typed.
- Client.Rust: expose next_correlation_id() so CLI ping/close
  stop hard-coding correlation IDs; resync RustClientDesign.md
  with the current Session / Error surface and CLI subcommand set.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 09:46:47 -04:00

219 lines
5.6 KiB
Python

"""Tests for the Python CLI."""
import json
import click
import pytest
from click.testing import CliRunner
from mxgateway import __version__
from mxgateway_cli.commands import _use_plaintext, main
def test_version_json_is_deterministic() -> None:
runner = CliRunner()
result = runner.invoke(main, ["version", "--json"])
assert result.exit_code == 0
assert json.loads(result.output) == {
"client": "mxgw-py",
"package": "mxaccess-gateway-client",
"version": __version__,
}
def test_write_parser_rejects_unknown_value_type() -> None:
runner = CliRunner()
result = runner.invoke(
main,
[
"write",
"--session-id",
"session-1",
"--server-handle",
"12",
"--item-handle",
"34",
"--type",
"unsupported",
"--value",
"123",
"--api-key",
"mxgw_test_secret",
"--json",
],
)
assert result.exit_code != 0
assert "unsupported value type" in result.output
def test_cli_error_output_redacts_api_key() -> None:
runner = CliRunner()
result = runner.invoke(
main,
[
"open-session",
"--endpoint",
"127.0.0.1:1",
"--api-key",
"mxgw_test_secret",
"--plaintext",
"--json",
],
)
assert result.exit_code != 0
assert "mxgw_test_secret" not in result.output
# Regression tests for Client.Python-013: ``_use_plaintext`` must not silently
# downgrade ``localhost:`` / ``127.0.0.1:`` endpoints to plaintext. TLS is the
# default; users must pass ``--plaintext`` to opt in.
def test_use_plaintext_requires_explicit_flag_for_localhost_endpoint() -> None:
"""A ``localhost:`` endpoint with no flags must resolve to TLS."""
assert (
_use_plaintext(
{"endpoint": "localhost:5000", "plaintext": False, "use_tls": False}
)
is False
)
def test_use_plaintext_requires_explicit_flag_for_loopback_ip_endpoint() -> None:
"""A ``127.0.0.1:`` endpoint with no flags must resolve to TLS."""
assert (
_use_plaintext(
{"endpoint": "127.0.0.1:5000", "plaintext": False, "use_tls": False}
)
is False
)
def test_use_plaintext_explicit_plaintext_flag_opts_in() -> None:
"""``--plaintext`` must select plaintext regardless of endpoint host."""
assert (
_use_plaintext(
{"endpoint": "localhost:5000", "plaintext": True, "use_tls": False}
)
is True
)
assert (
_use_plaintext(
{
"endpoint": "mxgateway.example.local:5001",
"plaintext": True,
"use_tls": False,
}
)
is True
)
def test_use_plaintext_explicit_tls_flag_is_accepted_and_idempotent() -> None:
"""``--tls`` is accepted as a redundant affirmation of the default."""
assert (
_use_plaintext(
{
"endpoint": "mxgateway.example.local:5001",
"plaintext": False,
"use_tls": True,
}
)
is False
)
# Even for a localhost endpoint, ``--tls`` (the default) must yield TLS.
assert (
_use_plaintext(
{"endpoint": "localhost:5000", "plaintext": False, "use_tls": True}
)
is False
)
def test_use_plaintext_rejects_conflicting_flags() -> None:
"""``--plaintext`` combined with ``--tls`` is a usage error."""
with pytest.raises(click.UsageError):
_use_plaintext(
{"endpoint": "localhost:5000", "plaintext": True, "use_tls": True}
)
def test_cli_localhost_endpoint_defaults_to_tls_via_open_session(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""End-to-end: ``open-session`` against ``localhost:`` with no flags
must build a TLS ``ClientOptions`` (plaintext=False)."""
captured: dict[str, object] = {}
async def _fake_connect(options): # type: ignore[no-untyped-def]
captured["plaintext"] = options.plaintext
raise RuntimeError("stop-before-network")
monkeypatch.setattr(
"mxgateway_cli.commands.GatewayClient.connect", _fake_connect
)
runner = CliRunner()
result = runner.invoke(
main,
[
"open-session",
"--endpoint",
"localhost:5000",
"--api-key",
"mxgw_test_secret",
"--json",
],
)
assert result.exit_code != 0 # connect was stubbed to raise
assert captured.get("plaintext") is False, (
"localhost endpoint must default to TLS without an explicit --plaintext "
"flag (Client.Python-013 regression)."
)
def test_cli_localhost_endpoint_with_plaintext_flag_uses_plaintext(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""End-to-end: ``--plaintext`` opts in to plaintext as expected."""
captured: dict[str, object] = {}
async def _fake_connect(options): # type: ignore[no-untyped-def]
captured["plaintext"] = options.plaintext
raise RuntimeError("stop-before-network")
monkeypatch.setattr(
"mxgateway_cli.commands.GatewayClient.connect", _fake_connect
)
runner = CliRunner()
result = runner.invoke(
main,
[
"open-session",
"--endpoint",
"localhost:5000",
"--api-key",
"mxgw_test_secret",
"--plaintext",
"--json",
],
)
assert result.exit_code != 0
assert captured.get("plaintext") is True