Repository navigation
Expand file tree
/
Copy pathtest_workbook_lifecycle.py
More file actions
812 lines (656 loc) · 33.2 KB
/
Copy pathtest_workbook_lifecycle.py
File metadata and controls
812 lines (656 loc) · 33.2 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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
# WriterAgent - AI Writing Assistant for LibreOffice
# Copyright (c) 2026 KeithCu (modifications and relicensing)
#
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import annotations
from typing import Any, Callable
from unittest.mock import MagicMock, patch
import pytest
from plugin.calc.python.spill import SpillRecord
from tests.harness.strip_bundle import skip_if_release_build
import plugin.calc.python.workbook_lifecycle as lifecycle
from plugin.calc.python.workbook_state import WorkbookState
from plugin.calc.python.geometric_recalc import (
EvalIndexKey,
GeometricRecord,
_RUNTIME,
replace_geometric_strip_safe,
reset_geometric_runtime_for_tests,
)
from plugin.calc.python.workbook_lifecycle import (
_CalcPythonUnloadListener,
_doc_from_event,
ensure_calc_workbook_unload_resets_python,
ensure_python_session_cleared_on_unload,
install_global_document_event_listener,
)
from plugin.tests.testing_utils import CalcDocStub
def _ensure_calc_unload(doc: Any) -> WorkbookState:
st = WorkbookState.for_doc(doc)
assert st is not None
ensure_calc_workbook_unload_resets_python(doc, state=st)
return st
@pytest.fixture(autouse=True)
def _reset_lifecycle_registry():
WorkbookState.reset_for_tests()
lifecycle.reset_for_tests()
yield
WorkbookState.reset_for_tests()
lifecycle.reset_for_tests()
def test_for_doc_reuses_state_by_runtime_key_when_known_misses() -> None:
"""Weakref/id lookup can miss a new doc handle; for_doc must not mint an empty duplicate state."""
doc_a = CalcDocStub(props={"RuntimeUID": "uid-reuse-state"})
st = WorkbookState(key="uid-reuse-state")
st.spills[("Sheet1", 0, 0)] = SpillRecord(code="", rows=1, cols=1)
WorkbookState._remember(doc_a, st)
doc_b = CalcDocStub(props={"RuntimeUID": "uid-reuse-state"})
assert WorkbookState.known(doc_b) is None
reused = WorkbookState.for_doc(doc_b)
assert reused is st
assert ("Sheet1", 0, 0) in reused.spills
def test_unload_forgets_cached_workbook_key():
"""Off-main spill lookup must not keep a closed workbook's id."""
doc = CalcDocStub(props={"RuntimeUID": "uid-forget"})
st = WorkbookState(key="uid-forget")
WorkbookState._remember(doc, st)
assert WorkbookState.known(doc) is not None
listener = _CalcPythonUnloadListener(st.key, "calc:wb-forget", st)
with patch("plugin.calc.python.workbook_lifecycle.reset_python_session") as mock_reset:
mock_reset.return_value = {"status": "ok"}
listener.on_document_event(MagicMock(EventName="OnUnload"))
assert WorkbookState.known(doc) is None
assert WorkbookState.known(None) is None
@pytest.mark.parametrize(
"trigger",
[
pytest.param(lambda listener: listener.on_document_event(MagicMock(EventName="OnUnload")), id="on_unload"),
pytest.param(lambda listener: listener.on_disposing(MagicMock()), id="on_disposing"),
],
)
def test_unload_listener_resets_worker_session(trigger: Callable[[_CalcPythonUnloadListener], None]):
listener = _CalcPythonUnloadListener("key-1", "calc:wb-1", WorkbookState(key="key-1"))
with patch("plugin.calc.python.workbook_lifecycle.reset_python_session") as mock_reset:
mock_reset.return_value = {"status": "ok"}
for _idx in range(2):
trigger(listener)
mock_reset.assert_called_once_with("calc:wb-1", timeout_sec=3, lease_wait_sec=3)
def test_non_calc_unload_resets_rps_and_notebook_sessions(monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr("plugin.calc.python.workbook_lifecycle.HAVE_UNO", True)
doc = MagicMock()
doc.getPropertyValue.return_value = "writer-uid"
ensure_python_session_cleared_on_unload(doc, "rps:file:///a.odt")
ensure_python_session_cleared_on_unload(doc, "notebook:file:///a.odt")
doc.addDocumentEventListener.assert_called_once()
listener = doc.addDocumentEventListener.call_args[0][0]
with patch("plugin.calc.python.workbook_lifecycle.reset_python_session") as mock_reset:
mock_reset.return_value = {"status": "ok"}
listener.on_document_event(MagicMock(EventName="OnUnload"))
assert mock_reset.call_count == 2
assert {call.args[0] for call in mock_reset.call_args_list} == {
"rps:file:///a.odt",
"notebook:file:///a.odt",
}
def test_unload_clears_in_memory_spill_state():
state = WorkbookState(key="key-spill")
state.spills[("Sheet1", 0, 0)] = SpillRecord(code="", rows=1, cols=1)
state.used_ends["Sheet1"] = (2, 2)
state.loaded = True
listener = _CalcPythonUnloadListener("key-spill", "calc:file:///gone.ods", state)
with patch("plugin.calc.python.workbook_lifecycle.reset_python_session") as mock_reset:
mock_reset.return_value = {"status": "ok"}
listener.on_document_event(MagicMock(EventName="OnUnload"))
assert ("Sheet1", 0, 0) not in state.spills
assert not state.used_ends
assert not state.loaded
@pytest.mark.parametrize("event_name", ["OnPrepareSave", "OnSave", "OnSaveAs", "OnSaveTo", "OnCopyTo"])
def test_save_events_flush_dirty_spill_registry_once(event_name: str):
"""Save-prepare events flush a dirty spill registry once and clear the pending timer."""
doc = MagicMock()
state = WorkbookState(key="key-save-flush")
listener = _CalcPythonUnloadListener("key-save-flush", "calc:file:///save.ods", state)
try:
state.mark_spill_registry_dirty(doc)
assert "spill-registry" in state.debounce.pending_for_tests()
with patch("plugin.calc.python.spill.save_spill_registry_for_doc") as mock_save:
listener.on_document_event(MagicMock(EventName=event_name))
mock_save.assert_called_once_with(doc, state)
assert "spill-registry" not in state.debounce.pending_for_tests()
# A later flush (e.g. a timer callback that already fired) writes nothing.
state.flush_spill_registry()
mock_save.assert_called_once()
finally:
state.clear()
def test_unload_clears_in_memory_geometric_state():
reset_geometric_runtime_for_tests()
key = "key-geo"
_RUNTIME.records[(key, "Sheet1", "A2")] = GeometricRecord(predecessor="A1")
replace_geometric_strip_safe(key, frozenset({EvalIndexKey(key, "x", 2)}))
state = WorkbookState(key=key)
listener = _CalcPythonUnloadListener(key, "calc:file:///gone-geo.ods", state)
with patch("plugin.calc.python.workbook_lifecycle.reset_python_session") as mock_reset:
mock_reset.return_value = {"status": "ok"}
listener.on_document_event(MagicMock(EventName="OnUnload"))
assert (key, "Sheet1", "A2") not in _RUNTIME.records
assert _RUNTIME.strip_safe == frozenset()
def test_ensure_registers_listener_once():
doc = CalcDocStub(props={"RuntimeUID": "uid-reg"})
with patch("plugin.calc.python.workbook_lifecycle.HAVE_UNO", True):
_ensure_calc_unload(doc)
_ensure_calc_unload(doc)
assert len(doc._document_event_listeners) == 1
def test_unload_clears_registration_so_reopen_can_reregister():
"""After OnUnload the same RuntimeUID can register again (close then reopen)."""
doc = CalcDocStub(props={"RuntimeUID": "uid-reopen"})
with patch("plugin.calc.python.workbook_lifecycle.HAVE_UNO", True):
with patch("plugin.calc.python.workbook_lifecycle.reset_python_session") as mock_reset:
mock_reset.return_value = {"status": "ok"}
_ensure_calc_unload(doc)
assert "uid-reopen" in lifecycle._LISTENERS
doc._document_event_listeners[0].on_document_event(MagicMock(EventName="OnUnload"))
assert "uid-reopen" not in lifecycle._LISTENERS
mock_reset.assert_called_once()
_ensure_calc_unload(doc)
assert len(doc._document_event_listeners) == 2
assert "uid-reopen" in lifecycle._LISTENERS
@pytest.mark.parametrize(
("register", "ui_thread_patch", "id_sequence"),
[
pytest.param(
_ensure_calc_unload,
False,
["calc:uuid-1", "calc:uuid-1", "calc:file:///saved.ods", "calc:file:///saved.ods", "calc:file:///saved.ods"],
id="ensure-calc-unload",
),
pytest.param(
# Each UI-thread for_doc refreshes the unload listener (note_calc_identity on Save).
WorkbookState.for_doc,
True,
["calc:uuid-1", "calc:file:///saved.ods", "calc:file:///saved.ods"],
id="for-doc-ui-thread",
),
],
)
def test_save_notes_new_session_id_reset_on_unload(
register: Callable[[Any], WorkbookState | None], ui_thread_patch: bool, id_sequence: list[str]
) -> None:
"""After Save the listener must reset both the uuid kernel and the file-URL kernel."""
from contextlib import nullcontext
doc = CalcDocStub(props={"RuntimeUID": "uid-save"}, url="")
main_ctx = patch("plugin.framework.queue_executor.main.is_current", return_value=True) if ui_thread_patch else nullcontext()
with (
main_ctx,
patch("plugin.calc.python.workbook_lifecycle.HAVE_UNO", True),
patch("plugin.calc.python.workbook_lifecycle.calc_workbook_base_session_id", side_effect=id_sequence),
patch("plugin.calc.python.workbook_lifecycle.reset_python_session") as mock_reset,
):
mock_reset.return_value = {"status": "ok"}
register(doc)
doc.url = "file:///saved.ods"
register(doc)
assert len(doc._document_event_listeners) == 1
doc._document_event_listeners[0].on_document_event(MagicMock(EventName="OnUnload"))
reset_ids = {call.args[0] for call in mock_reset.call_args_list}
assert reset_ids == {"calc:uuid-1", "calc:file:///saved.ods"}
assert "uid-save" not in lifecycle._LISTENERS
def test_unload_resets_worker_when_busy():
listener = _CalcPythonUnloadListener("key-busy", "calc:wb-1", WorkbookState(key="key-busy"))
seen = []
def mock_reset_side_effect(sid: str, **kwargs: Any) -> dict[str, Any]:
seen.append(sid)
if len(seen) == 1:
return {"status": "error", "code": "WORKER_REENTRY"}
return {"status": "ok"}
with patch("plugin.calc.python.workbook_lifecycle.reset_python_session", side_effect=mock_reset_side_effect):
with patch("plugin.calc.python.workbook_lifecycle.run_in_background") as mock_run:
listener.on_document_event(MagicMock(EventName="OnUnload"))
# Initial call
assert len(seen) == 1
# Ensure background fallback was scheduled with dedicated=True
retry_calls = [c for c in mock_run.call_args_list if c[1].get("name") == "reset_python_session_retry"]
assert len(retry_calls) == 1
assert retry_calls[0][1].get("dedicated") is True
callback = retry_calls[0][0][0]
with patch("time.sleep"):
callback()
assert len(seen) == 2
assert listener._teardown_done is True
@pytest.mark.parametrize("error_code", ["WORKER_REENTRY", "VENV_TIMEOUT"])
def test_teardown_passes_lease_wait_sec_and_triggers_retry(error_code: str):
listener = _CalcPythonUnloadListener("key-blocked", "calc:wb-blocked", WorkbookState(key="key-blocked"))
with (
patch("plugin.calc.python.workbook_lifecycle.reset_python_session", return_value={"status": "error", "code": error_code}) as mock_reset,
patch("plugin.calc.python.workbook_lifecycle.run_in_background") as mock_run,
):
listener._teardown()
mock_reset.assert_called_once()
assert mock_reset.call_args[0] == ("calc:wb-blocked",)
assert mock_reset.call_args[1]["timeout_sec"] > 0
assert mock_reset.call_args[1]["lease_wait_sec"] > 0
retry_calls = [c for c in mock_run.call_args_list if c[1].get("name") == "reset_python_session_retry"]
assert len(retry_calls) == 1
assert retry_calls[0][1].get("dedicated") is True
def test_teardown_drops_retry_when_reopened():
"""When a workbook is closed and immediately reopened, any pending retry must abort."""
old_listener = _CalcPythonUnloadListener("key-old2", "calc:wb-reopen2", WorkbookState(key="key-old2"))
new_listener = _CalcPythonUnloadListener("key-new2", "calc:wb-reopen2", WorkbookState(key="key-new2"))
lifecycle._LISTENERS["key-new2"] = new_listener
try:
with patch("time.sleep"), patch("plugin.calc.python.workbook_lifecycle.reset_python_session") as mock_reset:
old_listener._retry_reset("calc:wb-reopen2")
mock_reset.assert_not_called()
finally:
lifecycle._LISTENERS.pop("key-new2", None)
def test_retry_reset_exhausts_retries_and_warns_on_timeout(caplog: pytest.LogCaptureFixture):
listener = _CalcPythonUnloadListener("key-timeout", "calc:wb-timeout", WorkbookState(key="key-timeout"))
with patch("plugin.calc.python.workbook_lifecycle.reset_python_session", return_value={"status": "error", "code": "WORKER_REENTRY"}) as mock_reset:
with patch("time.sleep"):
with caplog.at_level("WARNING", logger="plugin.calc.python.workbook_lifecycle"):
listener._retry_reset("calc:wb-timeout")
assert mock_reset.call_count > 1
assert len([r for r in caplog.records if r.levelname == "WARNING"]) == 1
def test_remember_keeps_strong_ref_until_forget_key():
"""Objects rejecting weakref must be held strongly in id map until unload."""
import plugin.calc.python.workbook_state as wb_state
class NoWeakRefDoc:
__slots__ = ()
doc = NoWeakRefDoc()
doc_id = id(doc)
st = WorkbookState(key="key-strong-ref")
WorkbookState._remember(doc, st)
assert WorkbookState.known(doc).key == "key-strong-ref"
assert doc_id in wb_state._STATE_BY_DOC_ID
entry = wb_state._STATE_BY_DOC_ID[doc_id]
assert entry[0].key == "key-strong-ref"
assert entry[1] is doc
WorkbookState.forget_key("key-strong-ref")
assert doc_id not in wb_state._STATE_BY_DOC_ID
assert WorkbookState.known(doc) is None
def test_release_calc_state_clears_state_once():
"""_release_calc_state calls state.clear once."""
state = MagicMock(spec=WorkbookState)
state.key = "key-dedupe"
listener = _CalcPythonUnloadListener("key-dedupe", "calc:wb-dedupe", state)
with patch(
"plugin.calc.python.workbook_lifecycle.reset_python_session",
return_value={"status": "ok"},
):
listener._release_calc_state(("calc:wb-dedupe",))
state.clear.assert_called_once()
def test_for_doc_reuses_session_fallback_without_runtime_uid(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr("plugin.framework.queue_executor.main.is_current", lambda: True)
doc1 = CalcDocStub(url="", props={})
doc2 = CalcDocStub(url="", props={})
counter = 0
def sid(_doc: Any) -> str:
nonlocal counter
counter += 1
return f"calc:unsaved:{counter}"
monkeypatch.setattr("plugin.calc.python.workbook_state.calc_workbook_base_session_id", sid)
assert WorkbookState.for_doc(doc1).key == "calc:unsaved:1"
assert WorkbookState.for_doc(doc1).key == "calc:unsaved:1"
assert counter == 1
assert WorkbookState.for_doc(doc2).key == "calc:unsaved:2"
assert counter == 2
def test_spill_save_as_lifecycle_consistency() -> None:
"""Save As changes the document URL, so spills stay keyed by RuntimeUID."""
mock_doc = MagicMock()
mock_doc.getRuntimeUID.return_value = "uid-123"
mock_doc.getPropertyValue.return_value = "uid-123"
mock_doc.getURL.return_value = "file:///tmp/old.ods"
state = WorkbookState.for_doc(mock_doc)
assert state is not None and state.key == "uid-123"
state.spills[("Sheet1", 0, 0)] = SpillRecord(
code="result = 1",
rows=3,
cols=1,
)
mock_doc.getURL.return_value = "file:///tmp/new.ods"
new_state = WorkbookState.for_doc(mock_doc)
assert new_state is state
assert ("Sheet1", 0, 0) in new_state.spills
rec = new_state.spills[("Sheet1", 0, 0)]
assert (rec.rows, rec.cols) == (3, 1)
def test_open_event_arms_spill_registry(monkeypatch: pytest.MonkeyPatch) -> None:
import json
doc = CalcDocStub(url="file:///open-arm.ods", props={"RuntimeUID": "uid-open-arm"})
payload = json.dumps({"Sheet1:0,0": {"code": "x", "rows": 2, "cols": 1}})
monkeypatch.setattr(
"plugin.doc.udprops.read_document_property",
lambda _model, name, default=None: payload if name == "WriterAgentSpillRegistry" else default,
)
lifecycle._geometric_open_job(MagicMock(), doc)
state = WorkbookState.known(doc)
assert state is not None
assert state.loaded is True
assert ("Sheet1", 0, 0) in state.spills
rec = state.spills[("Sheet1", 0, 0)]
assert (rec.rows, rec.cols) == (2, 1)
assert "Sheet1" in state.used_ends
assert "Sheet1" in state.listeners
def test_runtime_uid_upgrade_keeps_one_listener(monkeypatch: pytest.MonkeyPatch) -> None:
doc = CalcDocStub(url="", props={})
monkeypatch.setattr(
"plugin.calc.python.workbook_state.calc_workbook_base_session_id",
lambda _doc: "calc:unsaved:1",
)
monkeypatch.setattr(
"plugin.calc.python.workbook_lifecycle.calc_workbook_base_session_id",
lambda _doc: "calc:unsaved:1",
)
with patch("plugin.calc.python.workbook_lifecycle.HAVE_UNO", True):
_ensure_calc_unload(doc)
doc.setPropertyValue("RuntimeUID", "uid-upgrade")
_ensure_calc_unload(doc)
assert len(doc._document_event_listeners) == 1
assert set(lifecycle._LISTENERS) == {"uid-upgrade"}
known = WorkbookState.known(doc)
assert known is not None and known.key == "uid-upgrade"
assert all(s.key != "calc:unsaved:1" for s in WorkbookState.all_states())
with patch("plugin.calc.python.workbook_lifecycle.reset_python_session") as mock_reset:
mock_reset.return_value = {"status": "ok"}
doc._document_event_listeners[0].on_document_event(MagicMock(EventName="OnUnload"))
assert lifecycle._LISTENERS == {}
assert WorkbookState.known(doc) is None
assert WorkbookState.all_states() == []
mock_reset.assert_called_once_with("calc:unsaved:1", timeout_sec=3, lease_wait_sec=3)
_ensure_calc_unload(doc)
assert len(doc._document_event_listeners) == 2
def test_non_calc_unload_listener_has_no_workbook_state(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr("plugin.calc.python.workbook_lifecycle.HAVE_UNO", True)
doc = MagicMock()
doc.getPropertyValue.return_value = "writer-uid"
ensure_python_session_cleared_on_unload(doc, "rps:file:///a.odt")
listener = doc.addDocumentEventListener.call_args[0][0]
with (
patch.object(WorkbookState, "forget_key") as mock_forget,
patch("plugin.calc.python.workbook_lifecycle.reset_python_session", return_value={"status": "ok"}) as mock_reset,
):
listener.on_document_event(MagicMock(EventName="OnUnload"))
assert lifecycle._LISTENERS == {}
mock_forget.assert_not_called()
mock_reset.assert_called_once()
def _mock_broadcaster(ctx: Any | None = None) -> tuple[Any, Any]:
ctx_obj = ctx if ctx is not None else MagicMock()
smgr = MagicMock()
broadcaster = MagicMock()
ctx_obj.getServiceManager.return_value = smgr
smgr.createInstanceWithContext.return_value = broadcaster
return ctx_obj, broadcaster
def _installed(ctx: Any) -> Any:
_ctx, broadcaster = _mock_broadcaster(ctx)
install_global_document_event_listener(ctx)
return broadcaster.addDocumentEventListener.call_args[0][0]
def test_install_global_document_event_listener_once():
ctx, broadcaster = _mock_broadcaster()
install_global_document_event_listener(ctx)
install_global_document_event_listener(ctx)
assert broadcaster.addDocumentEventListener.call_count == 1
def test_install_global_listener_reentrant_call_attaches_once():
ctx, broadcaster = _mock_broadcaster()
def _reenter(_listener: Any) -> None:
install_global_document_event_listener(ctx)
broadcaster.addDocumentEventListener.side_effect = _reenter
install_global_document_event_listener(ctx)
assert broadcaster.addDocumentEventListener.call_count == 1
def test_install_global_listener_failure_frees_slot():
ctx, broadcaster = _mock_broadcaster()
broadcaster.addDocumentEventListener.side_effect = [RuntimeError("disposed"), None]
with patch.object(lifecycle.log, "warning") as warn:
install_global_document_event_listener(ctx)
assert lifecycle._global_listener is None
warn.assert_called_once()
install_global_document_event_listener(ctx)
assert broadcaster.addDocumentEventListener.call_count == 2
assert lifecycle._global_listener is not None
class _DisposedViewControllerEvent:
"""Simulates UNO DocumentEvent where ViewController access raises (disposed)."""
def __init__(self, source=None):
self.Source = source
self.EventName = ""
def __getattr__(self, name: str):
if name == "ViewController":
raise RuntimeError("DrawController object has already been disposed")
raise AttributeError(name)
def test_doc_from_event_disposed_view_controller_returns_none():
assert _doc_from_event(_DisposedViewControllerEvent()) is None
def test_doc_from_event_disposed_view_controller_falls_back_to_calc_source():
source = CalcDocStub()
setattr(source, "CurrentController", None)
setattr(source, "_controller", None)
assert _doc_from_event(_DisposedViewControllerEvent(source=source)) is source
def test_doc_from_event_onnew_controller_throw_still_returns_calc_source():
"""Hidden factory OnNew: Source is the scalc, getCurrentController raises."""
source = CalcDocStub()
def _boom():
raise RuntimeError("no controller yet")
setattr(source, "getCurrentController", _boom)
class _OnNew:
EventName = "OnNew"
Source = source
assert _doc_from_event(_OnNew()) is source
def test_onload_rewrites_collabora_py_via_call():
"""OnLoadFinished marshals geometric open (ctx, doc) then Collabora rewrite (doc only)."""
from plugin.calc.python.collabora_formula import maybe_rewrite_collabora_py_formulas
ctx = MagicMock()
listener = _installed(ctx)
doc = CalcDocStub()
class _LoadEvent:
EventName = "OnLoadFinished"
Source = doc
event = _LoadEvent()
with (
patch("plugin.calc.excel_py_convert.auto_open.maybe_convert_excel_py_document") as convert,
patch("plugin.framework.queue_executor.main.call") as marshal,
patch("plugin.framework.queue_executor.main.is_current", return_value=False),
):
listener.on_document_event(event)
convert.assert_called_once()
assert [c.args for c in marshal.call_args_list] == [
(lifecycle._geometric_open_job, ctx, doc),
(maybe_rewrite_collabora_py_formulas, doc),
]
def test_onload_collabora_rewrite_inlines_on_untagged_dummy():
"""OnLoadFinished inlines Collabora rewrite on an untagged Dummy thread (dev UNTAGGED_DUMMY_IS_CURRENT)."""
from tests.testing_utils import run_in_dummy_thread
skip_if_release_build("UNTAGGED_DUMMY_IS_CURRENT is False in release bundles")
ctx = MagicMock()
listener = _installed(ctx)
doc = CalcDocStub()
class _LoadEvent:
EventName = "OnLoadFinished"
Source = doc
event = _LoadEvent()
with (
patch("plugin.calc.excel_py_convert.auto_open.maybe_convert_excel_py_document") as convert,
patch.object(lifecycle, "_geometric_open_job"),
patch(
"plugin.calc.python.workbook_lifecycle.maybe_rewrite_collabora_py_formulas"
) as rewrite,
patch("plugin.framework.queue_executor.main.call", side_effect=TimeoutError("main.call should not be reached")) as marshal,
patch.object(lifecycle.log, "warning") as warn,
):
def _fire() -> None:
listener.on_document_event(event)
run_in_dummy_thread(_fire)
convert.assert_called_once()
rewrite.assert_called_once_with(doc)
marshal.assert_not_called()
warn.assert_not_called()
def test_onnew_records_geometric_session_inline_on_uno_thread():
"""OnNew is already on the VCL thread — do not enqueue (30s leftover hang)."""
ctx = MagicMock()
listener = _installed(ctx)
doc = CalcDocStub()
class _NewEvent:
EventName = "OnNew"
Source = doc
with (
patch("plugin.calc.excel_py_convert.auto_open.maybe_convert_excel_py_document") as convert,
patch("plugin.framework.queue_executor.main.call") as marshal,
patch("plugin.framework.queue_executor.main.is_current", return_value=True),
patch(
"plugin.calc.python.workbook_lifecycle.maybe_geometric_on_document_open"
) as open_geo,
):
listener.on_document_event(_NewEvent())
convert.assert_not_called()
marshal.assert_not_called()
open_geo.assert_called_once_with(ctx, doc)
def test_oncreate_without_resolvable_doc_skips_geometric_open():
"""OnCreate with no resolvable document returns before posting the open job."""
ctx = MagicMock()
listener = _installed(ctx)
class _CreateEvent:
EventName = "OnCreate"
Source = None
with (
patch("plugin.calc.excel_py_convert.auto_open.maybe_convert_excel_py_document") as convert,
patch("plugin.framework.queue_executor.main.call") as marshal,
patch("plugin.framework.queue_executor.main.is_current", return_value=True),
patch(
"plugin.calc.python.workbook_lifecycle.maybe_geometric_on_document_open"
) as open_geo,
):
listener.on_document_event(_CreateEvent())
convert.assert_not_called()
marshal.assert_not_called()
open_geo.assert_not_called()
def test_geometric_open_job_wires_unload_listener():
"""Closing the workbook is the soffice-side clear for its kernel and geometric state."""
doc = CalcDocStub()
ctx = MagicMock()
with (
patch("plugin.calc.python.workbook_lifecycle.maybe_geometric_on_document_open") as open_geo,
patch(
"plugin.calc.python.workbook_state.WorkbookState.for_doc",
) as for_doc_mock,
):
lifecycle._geometric_open_job(ctx, doc)
open_geo.assert_called_once_with(ctx, doc)
for_doc_mock.assert_called_once_with(doc)
def test_onnew_records_geometric_session_via_call():
"""Factory Calc fires OnNew off-main; leftover still needs a marshaled record."""
ctx = MagicMock()
listener = _installed(ctx)
doc = CalcDocStub()
class _NewEvent:
EventName = "OnNew"
Source = doc
with (
patch("plugin.calc.excel_py_convert.auto_open.maybe_convert_excel_py_document") as convert,
patch("plugin.framework.queue_executor.main.call") as marshal,
patch("plugin.framework.queue_executor.main.is_current", return_value=False),
):
listener.on_document_event(_NewEvent())
convert.assert_not_called()
assert marshal.call_count == 1
assert marshal.call_args_list[0][0][0] is lifecycle._geometric_open_job
assert marshal.call_args_list[0][0][1:] == (ctx, doc)
class _ProbeRecordingEvent:
"""DocumentEvent whose ViewController / Source reads are recorded (``_doc_from_event`` swallows raises)."""
def __init__(self, name: str) -> None:
self.EventName = name
self.reads: list[str] = []
@property
def ViewController(self) -> Any: # noqa: N802 -- UNO struct field
self.reads.append("ViewController")
raise RuntimeError("ViewController must not be read")
@property
def Source(self) -> Any: # noqa: N802 -- UNO struct field
self.reads.append("Source")
raise RuntimeError("Source must not be read")
@pytest.mark.parametrize("event_name", ["OnFocus", "OnModifyChanged", "OnTitleChanged", "OnUnload"])
def test_global_listener_ignores_unhandled_events_without_probing_the_event(event_name: str):
listener = _installed(MagicMock())
event = _ProbeRecordingEvent(event_name)
with patch("plugin.framework.queue_executor.main.run") as run:
listener.on_document_event(event)
assert event.reads == []
run.assert_not_called()
def test_global_listener_disposed_view_controller_does_not_warn():
"""Listener must not hit the outer warning path when ViewController is disposed."""
ctx = MagicMock()
listener = _installed(ctx)
event = _DisposedViewControllerEvent()
event.EventName = "OnLoadFinished"
with patch.object(lifecycle.log, "warning") as warn:
listener.on_document_event(event)
warn.assert_not_called()
def test_unload_keeps_session_shared_with_another_listener(monkeypatch: pytest.MonkeyPatch):
import plugin.framework.scratch_writer as scratch_writer
monkeypatch.setattr("plugin.calc.python.workbook_lifecycle.HAVE_UNO", True)
monkeypatch.setattr(scratch_writer, "_scratch_uids", {"uid-scratch"})
sid = "calc:file:///tmp/shared.ods"
doc_scratch = CalcDocStub(url="file:///tmp/shared.ods", props={"RuntimeUID": "uid-scratch"})
doc_user = CalcDocStub(url="file:///tmp/shared.ods", props={"RuntimeUID": "uid-user"})
state_scratch = WorkbookState("uid-scratch")
state_user = WorkbookState("uid-user")
lifecycle.ensure_calc_workbook_unload_resets_python(doc_scratch, state=state_scratch)
lifecycle.ensure_calc_workbook_unload_resets_python(doc_user, state=state_user)
listener_scratch = lifecycle._LISTENERS["uid-scratch"]
listener_user = lifecycle._LISTENERS["uid-user"]
with (
patch("plugin.calc.python.workbook_lifecycle.reset_python_session", return_value={"status": "ok"}) as reset_mock,
patch("plugin.calc.python.workbook_lifecycle.clear_in_memory_geometric_state") as geo_mock,
):
listener_scratch.on_document_event(MagicMock(EventName="OnUnload"))
reset_mock.assert_not_called()
geo_mock.assert_called_once_with(workbook_key="uid-scratch")
geo_mock.reset_mock()
listener_user.on_document_event(MagicMock(EventName="OnUnload"))
reset_mock.assert_called_once_with(
sid,
timeout_sec=lifecycle._UNLOAD_RESET_TIMEOUT_SEC,
lease_wait_sec=lifecycle._UNLOAD_RESET_TIMEOUT_SEC,
)
geo_mock.assert_called_once_with(workbook_key="uid-user")
def test_unload_resets_on_reload_when_two_non_scratch_listeners_share_session(monkeypatch: pytest.MonkeyPatch):
import plugin.framework.scratch_writer as scratch_writer
monkeypatch.setattr("plugin.calc.python.workbook_lifecycle.HAVE_UNO", True)
monkeypatch.setattr(scratch_writer, "_scratch_uids", set())
sid = "calc:file:///tmp/reload.ods"
doc_old = CalcDocStub(url="file:///tmp/reload.ods", props={"RuntimeUID": "uid-old"})
doc_new = CalcDocStub(url="file:///tmp/reload.ods", props={"RuntimeUID": "uid-new"})
lifecycle.ensure_calc_workbook_unload_resets_python(doc_old, state=WorkbookState("uid-old"))
lifecycle.ensure_calc_workbook_unload_resets_python(doc_new, state=WorkbookState("uid-new"))
listener_old = lifecycle._LISTENERS["uid-old"]
with (
patch("plugin.calc.python.workbook_lifecycle.reset_python_session", return_value={"status": "ok"}) as reset_mock,
patch("plugin.calc.python.workbook_lifecycle.clear_in_memory_geometric_state") as geo_mock,
):
listener_old.on_document_event(MagicMock(EventName="OnUnload"))
reset_mock.assert_called_once_with(
sid,
timeout_sec=lifecycle._UNLOAD_RESET_TIMEOUT_SEC,
lease_wait_sec=lifecycle._UNLOAD_RESET_TIMEOUT_SEC,
)
geo_mock.assert_called_once_with(workbook_key="uid-old")
def test_unload_resets_user_close_even_while_scratch_copy_is_open(monkeypatch: pytest.MonkeyPatch):
import plugin.framework.scratch_writer as scratch_writer
monkeypatch.setattr("plugin.calc.python.workbook_lifecycle.HAVE_UNO", True)
monkeypatch.setattr(scratch_writer, "_scratch_uids", {"uid-scratch"})
sid = "calc:file:///tmp/user_first.ods"
doc_user = CalcDocStub(url="file:///tmp/user_first.ods", props={"RuntimeUID": "uid-user"})
doc_scratch = CalcDocStub(url="file:///tmp/user_first.ods", props={"RuntimeUID": "uid-scratch"})
lifecycle.ensure_calc_workbook_unload_resets_python(doc_user, state=WorkbookState("uid-user"))
lifecycle.ensure_calc_workbook_unload_resets_python(doc_scratch, state=WorkbookState("uid-scratch"))
listener_user = lifecycle._LISTENERS["uid-user"]
with (
patch("plugin.calc.python.workbook_lifecycle.reset_python_session", return_value={"status": "ok"}) as reset_mock,
patch("plugin.calc.python.workbook_lifecycle.clear_in_memory_geometric_state") as geo_mock,
):
listener_user.on_document_event(MagicMock(EventName="OnUnload"))
reset_mock.assert_called_once_with(
sid,
timeout_sec=lifecycle._UNLOAD_RESET_TIMEOUT_SEC,
lease_wait_sec=lifecycle._UNLOAD_RESET_TIMEOUT_SEC,
)
geo_mock.assert_called_once_with(workbook_key="uid-user")
def test_failed_listener_attach_leaves_no_registration(monkeypatch: pytest.MonkeyPatch) -> None:
"""A document that cannot take the listener keeps no entry, so a later call can register again."""
monkeypatch.setattr("plugin.calc.python.workbook_lifecycle.HAVE_UNO", True)
class _NoBroadcasterDoc:
def getPropertyValue(self, _name: str) -> str:
return "uid-no-broadcaster"
ensure_python_session_cleared_on_unload(_NoBroadcasterDoc(), "rps:file:///b.odt")
assert lifecycle._LISTENERS == {}