Repository navigation
Expand file tree
/
Copy pathtest_forecast_auto_plot.py
More file actions
365 lines (317 loc) · 12.6 KB
/
Copy pathtest_forecast_auto_plot.py
File metadata and controls
365 lines (317 loc) · 12.6 KB
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
# WriterAgent - AI Writing Assistant for LibreOffice
# Copyright (c) 2026 KeithCu (modifications and relicensing)
#
# SPDX-License-Identifier: GPL-3.0-or-later
"""Tests for forecast_data auto_plot chaining."""
from __future__ import annotations
from unittest.mock import MagicMock, patch
import pytest
from plugin.calc.forecast import ForecastDataTool
from plugin.calc.forecast_auto_plot import merge_forecast_plot_data, run_auto_plot_after_forecast
from plugin.calc.viz_auto_plot import task_hint_implies_plot
from plugin.scripting.payload_codec import PAYLOAD_CALC_RANGE
def test_forecast_task_hint_implies_plot_reused():
assert task_hint_implies_plot("plot forecast with bands") is True
assert task_hint_implies_plot("monthly forecast") is False
def test_merge_forecast_plot_data():
history = [["Date", "Value"], ["2024-01-01", 100.0], ["2024-02-01", 110.0]]
forecast_result = {
"status": "ok",
"tables": [
{
"name": "forecast",
"columns": ["date", "forecast", "lower", "upper"],
"rows": [["2024-03-01", 120.0, 115.0, 125.0]],
}
],
}
merged = merge_forecast_plot_data(history, forecast_result, {"date_col": "Date", "value_col": "Value"})
assert merged is not None
assert merged[0] == ["date", "Value", "forecast", "lower", "upper"]
assert len(merged) == 4
def _forecast_band_result() -> dict:
return {
"status": "ok",
"tables": [
{
"name": "forecast",
"columns": ["date", "forecast", "lower", "upper"],
"rows": [["2024-03-01", 120.0, 115.0, 125.0]],
}
],
}
def test_merge_forecast_plot_data_unpacks_calc_range_envelope():
"""A packed calc_range must not become one cell. That dropped Date/Value."""
history = {
"__wa_payload__": PAYLOAD_CALC_RANGE,
"shape": [3, 2],
"address": "Sheet1.A1:B3",
"data": [
["Date", "Value"],
["2024-01-01", 100.0],
["2024-02-01", 110.0],
],
}
merged = merge_forecast_plot_data(history, _forecast_band_result(), {"date_col": "Date", "value_col": "Value"})
assert merged is not None
assert merged[0] == ["date", "Value", "forecast", "lower", "upper"]
assert str(merged[1][0]).startswith("2024-01-01")
assert merged[1][1] == 100.0
assert merged[1][2] is None
assert str(merged[2][0]).startswith("2024-02-01")
assert merged[3][2] == 120.0
assert all(not isinstance(cell, dict) for row in merged for cell in row)
@patch("plugin.calc.viz_auto_plot.insert_viz_result_into_doc")
@patch("plugin.calc.forecast.run_auto_plot_after_forecast")
@patch("plugin.framework.queue_executor.main.call")
@patch("plugin.calc.analysis.run_domain")
def test_forecast_data_auto_plot_inserts_chart(
mock_run_trusted,
mock_main_thread,
mock_auto_plot,
mock_insert,
calc_ctx,
):
mock_main_thread.side_effect = lambda fn, *args, **kwargs: fn(*args, **kwargs)
mock_run_trusted.return_value = {
"status": "ok",
"helper": "forecast_time_series",
"metrics": {"periods": 6},
"tables": [{"name": "forecast", "columns": ["date", "forecast"], "rows": [["2025-01-01", 120.0]]}],
}
mock_auto_plot.return_value = {
"status": "ok",
"helper": "time_series_plot",
"title": "Forecast plot",
"image": {"__wa_payload__": "image", "format": "png", "data": b"x"},
}
tool = ForecastDataTool()
result = tool.execute(
calc_ctx,
helper="forecast_time_series",
data_range="Sheet1.A1:B37",
auto_plot=True,
)
assert result["status"] == "ok"
assert result.get("image_inserted") is True
assert result.get("plot", {}).get("helper") == "time_series_plot"
mock_auto_plot.assert_called_once()
mock_insert.assert_called_once()
@patch("plugin.calc.viz_auto_plot.insert_viz_result_into_doc")
@patch("plugin.calc.forecast.run_auto_plot_after_forecast")
@patch("plugin.framework.queue_executor.main.call")
@patch("plugin.calc.analysis.run_domain")
def test_forecast_data_auto_plot_marshals_viz_read(
mock_run_trusted,
mock_main_thread,
mock_auto_plot,
mock_insert,
calc_ctx,
):
inside_marshal = {"flag": False}
def mock_execute_on_main(fn, *args, **kwargs):
inside_marshal["flag"] = True
try:
return fn(*args, **kwargs)
finally:
inside_marshal["flag"] = False
mock_main_thread.side_effect = mock_execute_on_main
mock_run_trusted.return_value = {
"status": "ok",
"helper": "forecast_time_series",
"metrics": {},
"tables": [{"name": "forecast", "columns": ["date", "forecast"], "rows": []}],
}
def _auto_plot_side_effect(*_args, **_kwargs):
assert not inside_marshal["flag"], "viz IPC must stay off main.call"
return {
"status": "ok",
"helper": "time_series_plot",
"title": "Forecast plot",
"image": {"__wa_payload__": "image", "format": "png", "data": b"x"},
}
def _insert_side_effect(*_args, **_kwargs):
assert inside_marshal["flag"], "chart insert must run on the main thread"
mock_auto_plot.side_effect = _auto_plot_side_effect
mock_insert.side_effect = _insert_side_effect
tool = ForecastDataTool()
result = tool.execute(
calc_ctx,
helper="forecast_time_series",
data_range="Sheet1.A1:B37",
auto_plot=True,
)
assert result["status"] == "ok"
assert result.get("image_inserted") is True
mock_auto_plot.assert_called_once()
mock_insert.assert_called_once()
assert mock_main_thread.call_count == 1
def test_auto_plot_reads_sheet_on_main_and_passes_doc():
"""Auto-plot history reads Calc data on the main thread and merges envelope."""
envelope = {
"__wa_payload__": PAYLOAD_CALC_RANGE,
"shape": [3, 2],
"address": "Sheet1.A1:B3",
"data": [
["Date", "Value"],
["2024-01-01", 100.0],
["2024-02-01", 110.0],
],
}
inside = {"flag": False}
def exec_main(fn, *args, timeout=30.0, bound_scope=None, **kwargs):
inside["flag"] = True
try:
return fn(*args, **kwargs)
finally:
inside["flag"] = False
def viz(*_args, **kwargs):
assert not inside["flag"], "run_trusted_viz must stay off the sheet-read hop"
assert kwargs["data"][0] == ["date", "Value", "forecast", "lower", "upper"]
assert kwargs["helper"] == "time_series_plot"
assert kwargs["params"] == {
"date_col": "date",
"value_col": "Value",
"forecast_col": "forecast",
"lower_col": "lower",
"upper_col": "upper",
}
assert str(kwargs["data"][1][0]).startswith("2024-01-01")
return {"status": "ok", "helper": "time_series_plot"}
with (
patch("plugin.framework.queue_executor.main.is_current", return_value=False),
patch("plugin.framework.queue_executor.main.call", side_effect=exec_main),
patch("plugin.calc.forecast_auto_plot.resolve_python_data", return_value=(envelope, None)) as mock_resolve,
patch("plugin.calc.forecast_auto_plot.run_domain", side_effect=viz) as mock_viz,
):
result = run_auto_plot_after_forecast(
MagicMock(),
MagicMock(),
forecast_helper="forecast_time_series",
forecast_result=_forecast_band_result(),
forecast_params={"date_col": "Date", "value_col": "Value"},
data_range="Sheet1.A1:B3",
task_hint=None,
)
assert result is not None
assert result["status"] == "ok"
mock_resolve.assert_called_once()
mock_viz.assert_called_once()
def test_auto_plot_viz_failure_is_non_fatal():
envelope = {
"__wa_payload__": PAYLOAD_CALC_RANGE,
"shape": [3, 2],
"address": "Sheet1.A1:B3",
"data": [
["Date", "Value"],
["2024-01-01", 100.0],
["2024-02-01", 110.0],
],
}
with (
patch("plugin.calc.forecast_auto_plot.resolve_python_data", return_value=(envelope, None)),
patch("plugin.calc.forecast_auto_plot.run_domain", side_effect=RuntimeError("viz ipc down")),
):
result = run_auto_plot_after_forecast(
MagicMock(),
MagicMock(),
forecast_helper="forecast_time_series",
forecast_result=_forecast_band_result(),
forecast_params={"date_col": "Date", "value_col": "Value"},
data_range="Sheet1.A1:B3",
task_hint=None,
)
assert result is not None
assert result["status"] == "error"
assert "viz ipc down" in result["message"]
def test_auto_plot_sheet_read_failure_returns_reason():
with patch("plugin.calc.forecast_auto_plot.resolve_python_data", return_value=(None, "bad range")):
result = run_auto_plot_after_forecast(
MagicMock(),
MagicMock(),
forecast_helper="forecast_time_series",
forecast_result=_forecast_band_result(),
forecast_params={"date_col": "Date", "value_col": "Value"},
data_range="Sheet1.A1:B3",
task_hint=None,
)
assert result is not None
assert result["status"] == "error"
assert result["code"] == "VIZ_ERROR"
assert result["message"] == "Could not read forecast history: bad range"
def test_auto_plot_merge_failure_returns_reason():
with patch("plugin.calc.forecast_auto_plot.resolve_python_data", return_value=([["Nope", "Other"], [1, 2]], None)):
result = run_auto_plot_after_forecast(
MagicMock(),
MagicMock(),
forecast_helper="forecast_time_series",
forecast_result=_forecast_band_result(),
forecast_params={"date_col": "Date", "value_col": "Value"},
data_range="Sheet1.A1:B3",
task_hint=None,
)
assert result is not None
assert result["status"] == "error"
assert result["message"] == "Could not merge forecast history with the forecast table"
@pytest.mark.parametrize(
("helper", "auto_plot", "task_hint"),
[
# Only forecast_time_series has a band-plot mapping; decompose must not plot
# even when asked to.
("decompose_time_series", True, "plot the decomposition"),
# forecast_time_series without auto_plot and without a plot hint stays table-only.
("forecast_time_series", False, "monthly forecast"),
("forecast_time_series", False, None),
],
)
@patch("plugin.calc.viz_auto_plot.insert_viz_result_into_doc")
@patch("plugin.calc.forecast.run_auto_plot_after_forecast")
@patch("plugin.framework.queue_executor.main.call")
@patch("plugin.calc.analysis.run_domain")
def test_forecast_data_auto_plot_gating_negatives(
mock_run_trusted,
mock_main_thread,
mock_auto_plot,
mock_insert,
calc_ctx,
helper,
auto_plot,
task_hint,
):
mock_main_thread.side_effect = lambda fn, *args, **kwargs: fn(*args, **kwargs)
mock_run_trusted.return_value = {
"status": "ok",
"helper": helper,
"tables": [{"name": "forecast", "columns": ["date", "forecast"], "rows": [["2025-01-01", 120.0]]}],
}
kwargs = {"helper": helper, "data_range": "Sheet1.A1:B37", "auto_plot": auto_plot}
if task_hint is not None:
kwargs["task_hint"] = task_hint
result = ForecastDataTool().execute(calc_ctx, **kwargs)
assert result["status"] == "ok"
mock_auto_plot.assert_not_called()
mock_insert.assert_not_called()
assert "plot" not in result
assert not result.get("image_inserted")
@patch("plugin.calc.viz_auto_plot.insert_viz_result_into_doc")
@patch("plugin.calc.forecast.run_auto_plot_after_forecast")
@patch("plugin.framework.queue_executor.main.call")
@patch("plugin.calc.analysis.run_domain")
def test_forecast_data_auto_plot_task_hint_alone_triggers(
mock_run_trusted, mock_main_thread, mock_auto_plot, mock_insert, calc_ctx
):
mock_main_thread.side_effect = lambda fn, *args, **kwargs: fn(*args, **kwargs)
mock_run_trusted.return_value = {
"status": "ok",
"helper": "forecast_time_series",
"tables": [{"name": "forecast", "columns": ["date", "forecast"], "rows": [["2025-01-01", 120.0]]}],
}
mock_auto_plot.return_value = None
ForecastDataTool().execute(
calc_ctx,
helper="forecast_time_series",
data_range="Sheet1.A1:B37",
task_hint="plot forecast with bands",
)
mock_auto_plot.assert_called_once()
assert mock_auto_plot.call_args.kwargs["forecast_helper"] == "forecast_time_series"