File size: 12,404 Bytes
13d4e44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# Copyright (c) 2025-2026, RTE (https://www.rte-france.com)
# This Source Code Form is subject to the terms of the Mozilla Public License, version 2.0.
# If a copy of the MPL was not distributed with this file,
# you can obtain one at http://mozilla.org/MPL/2.0/.
# SPDX-License-Identifier: MPL-2.0

"""Coverage for ``services/diagram/action_patch.py``.

The action-variant patch pipeline (``/api/action-variant-diagram-patch``)
moved out of ``diagram_mixin.py`` into its own module to keep the
mixin under the function-LoC ceiling. The existing
``test_diagram_patch_helpers.py`` already covers the two pure helpers
(``compute_vl_topology_diff`` + ``get_disconnected_branches_from_snapshot``)
through the static-method wrappers on ``DiagramMixin``. This file
covers what the extraction added or moved:

* The direct import path (the helpers are now publicly importable
  from the new module — host code should prefer this over the mixin
  wrappers).
* The three new private orchestrator helpers:
  ``_extract_convergence_status``, ``_capture_action_snapshots``,
  ``_unpatchable_response``.
* ``extract_vl_subtrees_with_edges`` — exercised with a
  ``generate_diagram`` callable now that the NAD-generation seam is
  injected rather than read off ``self``.
* The early-return paths of ``build_action_patch_payload``
  (no-analysis-result / action-not-in-last-result). The happy path
  needs heavy pypowsybl machinery and is covered end-to-end by the
  integration tests; here we just check the soft-fail contract that
  the React frontend relies on.
"""
from __future__ import annotations

import pandas as pd
import pytest
from unittest.mock import MagicMock

from expert_backend.services.diagram.action_patch import (
    _capture_action_snapshots,
    _extract_convergence_status,
    _unpatchable_response,
    build_action_patch_payload,
    compute_vl_topology_diff,
    extract_vl_subtrees_with_edges,
    get_disconnected_branches_from_snapshot,
)


# ---------------------------------------------------------------------
# Public re-export — guards the contract that host code can import
# the helpers directly without going through the mixin wrappers.
# ---------------------------------------------------------------------

class TestPublicSurface:
    def test_pure_helpers_are_directly_importable(self):
        # The two pure helpers stay re-exported as static methods on
        # DiagramMixin for the existing test_diagram_patch_helpers
        # suite, but new callers should be able to use the module path.
        assert callable(compute_vl_topology_diff)
        assert callable(get_disconnected_branches_from_snapshot)

    def test_orchestrator_is_directly_importable(self):
        assert callable(build_action_patch_payload)
        assert callable(extract_vl_subtrees_with_edges)


# ---------------------------------------------------------------------
# _extract_convergence_status
# ---------------------------------------------------------------------

class TestExtractConvergenceStatus:
    def test_converged_when_no_exception(self):
        obs = MagicMock()
        obs._last_info = {"exception": None}
        lf_converged, lf_status, non_convergence = _extract_convergence_status(obs)
        assert lf_converged is True
        assert lf_status == "CONVERGED"
        assert non_convergence is None

    def test_missing_last_info_treated_as_converged(self):
        # Some upstream code paths don't stamp ``_last_info`` on the
        # observation at all. The helper must tolerate that — the
        # downstream payload would otherwise crash before the
        # frontend can fall back.
        obs = MagicMock(spec=[])  # no attributes at all
        lf_converged, lf_status, non_convergence = _extract_convergence_status(obs)
        assert lf_converged is True
        assert lf_status == "CONVERGED"
        assert non_convergence is None

    def test_single_exception_serialized_as_string(self):
        obs = MagicMock()
        obs._last_info = {"exception": ValueError("boom")}
        lf_converged, lf_status, non_convergence = _extract_convergence_status(obs)
        assert lf_converged is False
        assert "boom" in non_convergence
        assert lf_status == non_convergence

    def test_list_of_exceptions_joined_with_semicolon(self):
        # grid2op / pypowsybl wrappers sometimes return a list of
        # exceptions in ``info["exception"]``. The helper joins them
        # into a single human-readable string for the LF-status field
        # the React UI surfaces under each action card.
        obs = MagicMock()
        obs._last_info = {"exception": [ValueError("a"), RuntimeError("b")]}
        _, lf_status, non_convergence = _extract_convergence_status(obs)
        assert "a" in non_convergence and "b" in non_convergence
        assert "; " in non_convergence
        assert lf_status == non_convergence


# ---------------------------------------------------------------------
# _capture_action_snapshots
# ---------------------------------------------------------------------

class TestCaptureActionSnapshots:
    def test_happy_path_returns_five_snapshots(self):
        action_network = MagicMock()
        lines_df = pd.DataFrame(
            {"connected1": [True, False], "connected2": [True, True]},
            index=["L1", "L2"],
        )
        trafos_df = pd.DataFrame({"connected1": [True], "connected2": [True]}, index=["T1"])
        buses_df = pd.DataFrame({"voltage_level_id": ["VL1", "VL2"]}, index=["B1", "B2"])
        action_network.get_lines.return_value = lines_df
        action_network.get_2_windings_transformers.return_value = trafos_df
        action_network.get_buses.return_value = buses_df

        service = MagicMock()
        service._get_network_flows.return_value = {"p1": {"L1": 1.0}}
        service._get_asset_flows.return_value = {"GEN1": 50.0}

        snaps = _capture_action_snapshots(service, action_network)
        assert set(snaps.keys()) == {"lines_conn", "trafos_conn", "buses", "flows", "assets"}
        # ``.copy()`` discipline: the captured DataFrames must be a
        # fresh copy so a subsequent variant switch on the shared
        # network doesn't poison them.
        assert snaps["lines_conn"].equals(lines_df)
        assert snaps["lines_conn"] is not lines_df
        assert snaps["flows"] == {"p1": {"L1": 1.0}}
        assert snaps["assets"] == {"GEN1": 50.0}

    def test_each_snapshot_failure_independently_yields_none(self):
        # Pypowsybl can raise on any individual frame; the helper must
        # isolate failures so a single bad query doesn't prevent the
        # patch endpoint from soft-failing with a useful payload.
        action_network = MagicMock()
        action_network.get_lines.side_effect = RuntimeError("get_lines boom")
        action_network.get_2_windings_transformers.return_value = pd.DataFrame(
            {"connected1": [True], "connected2": [True]}, index=["T1"],
        )
        action_network.get_buses.side_effect = RuntimeError("get_buses boom")
        service = MagicMock()
        service._get_network_flows.return_value = {"p1": {}}
        service._get_asset_flows.side_effect = RuntimeError("assets boom")

        snaps = _capture_action_snapshots(service, action_network)
        assert snaps["lines_conn"] is None
        assert snaps["trafos_conn"] is not None
        assert snaps["buses"] is None
        assert snaps["flows"] == {"p1": {}}
        assert snaps["assets"] is None


# ---------------------------------------------------------------------
# _unpatchable_response
# ---------------------------------------------------------------------

class TestUnpatchableResponse:
    def test_carries_the_fixed_reason_and_supplied_metadata(self):
        out = _unpatchable_response(
            action_id="a1", lf_converged=True, lf_status="CONVERGED",
            non_convergence=None,
        )
        assert out == {
            "patchable": False,
            "reason": "vl_topology_changed",
            "action_id": "a1",
            "lf_converged": True,
            "lf_status": "CONVERGED",
            "non_convergence": None,
        }

    def test_propagates_non_convergence_string(self):
        out = _unpatchable_response(
            action_id="a2", lf_converged=False, lf_status="boom; bang",
            non_convergence="boom; bang",
        )
        assert out["lf_converged"] is False
        assert out["non_convergence"] == "boom; bang"
        assert out["lf_status"] == "boom; bang"


# ---------------------------------------------------------------------
# extract_vl_subtrees_with_edges — uses the injected callable seam
# ---------------------------------------------------------------------

class TestExtractVlSubtreesWithEdges:
    def test_returns_empty_when_no_vl_ids(self):
        # No VL needs a sub-NAD → no work, no calls.
        gen = MagicMock()
        out = extract_vl_subtrees_with_edges(
            action_network=MagicMock(), vl_ids=[], generate_diagram=gen,
        )
        assert out == {}
        gen.assert_not_called()

    def test_uses_injected_generate_diagram_for_each_vl(self):
        # The helper used to read ``self._generate_diagram``; the
        # extraction swapped that for a callable kwarg. Smoke-check
        # that the callable is invoked with the right shape (depth=1
        # focused sub-NAD per VL).
        gen = MagicMock(return_value={"svg": "", "metadata": "{}"})
        out = extract_vl_subtrees_with_edges(
            action_network=MagicMock(),
            vl_ids=["VL_A", "VL_B"],
            generate_diagram=gen,
        )
        assert gen.call_count == 2
        for call_args in gen.call_args_list:
            assert call_args.kwargs["depth"] == 1
            assert isinstance(call_args.kwargs["voltage_level_ids"], list)
            assert len(call_args.kwargs["voltage_level_ids"]) == 1
        # Empty svg / metadata → nothing extractable, but the helper
        # must NOT raise — the orchestrator handles the partial result.
        assert out == {}

    def test_per_vl_failure_is_swallowed(self):
        # If pypowsybl raises for VL_B, VL_A's subtree must still be
        # returned (the orchestrator's "len(subtrees) != len(vl_diff)"
        # gate decides whether to fall back to the full NAD).
        gen = MagicMock(side_effect=[
            {"svg": "", "metadata": "{}"},  # VL_A: empty (no actual SVG)
            RuntimeError("VL_B exploded"),  # VL_B: hard failure
        ])
        out = extract_vl_subtrees_with_edges(
            action_network=MagicMock(),
            vl_ids=["VL_A", "VL_B"],
            generate_diagram=gen,
        )
        # Both VLs attempted; result dict size determined by what we
        # could extract (here zero — empty svg → no <g id> match —
        # but no exception bubbled up).
        assert gen.call_count == 2
        assert isinstance(out, dict)


# ---------------------------------------------------------------------
# build_action_patch_payload — early-return contract
# ---------------------------------------------------------------------

class TestBuildActionPatchPayloadEarlyReturns:
    """The patch endpoint MUST soft-fail with
    ``patchable: false`` (not raise) on the two "no usable cached
    action" cases so the React frontend can fall back to the full
    NAD without surfacing a 400 to the operator."""

    def test_soft_fails_when_no_analysis_result(self):
        service = MagicMock()
        service._last_result = None
        out = build_action_patch_payload(service, "any_action")
        assert out["patchable"] is False
        assert out["reason"] == "no-analysis-result"
        assert out["action_id"] == "any_action"

    def test_soft_fails_when_last_result_has_no_prioritized_actions(self):
        service = MagicMock()
        service._last_result = {}  # missing the key
        out = build_action_patch_payload(service, "x")
        assert out["patchable"] is False
        assert out["reason"] == "no-analysis-result"

    def test_soft_fails_when_action_id_not_in_last_result(self):
        service = MagicMock()
        service._last_result = {"prioritized_actions": {"a1": {}}}
        out = build_action_patch_payload(service, "a2")
        assert out["patchable"] is False
        assert out["reason"] == "action-not-in-last-result"
        assert out["action_id"] == "a2"