Skip to content

Commit 37d2459

Browse files
Address PR RosettaCommons#22 review comments on PyMOL plugin
- bridge.py: make _replace_pymol_object transactional for untracked objects (rename-load-delete) so a failed replacement restores an object the user loaded directly with cmd.load, not just plugin-tracked objects. - commands.py: aw_load now uses build_load_config's default assembly ('1'), matching the GUI Load dialog, instead of assembly='first'. - state.py: pop_snapshot refuses to resurrect an object deleted directly in PyMOL, mirroring get_synced_array's forget-on-delete behaviour. - tests/conftest.py: guard the real 'import pymol' (not just find_spec) in try/except, setting collect_ignore_glob on any import failure. - tests/test_review_fixes.py: add regression tests for each fix.
1 parent 43bc5c2 commit 37d2459

5 files changed

Lines changed: 129 additions & 13 deletions

File tree

‎packages/pymol-plugin/atomworks_studio_pymol/bridge.py‎

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -286,19 +286,35 @@ def _load_array_into_pymol(
286286
def _replace_pymol_object(array: AtomArrayPlus, obj_name: str) -> None:
287287
"""Load *array* into PyMOL as *obj_name*, replacing any existing object of that name.
288288
289-
PyMOL cannot load an mmCIF into an existing object, so the old object is deleted
290-
first. Callers update ``STATE`` only after this succeeds; if loading fails, the
291-
structure still tracked under *obj_name* (if any) is restored in PyMOL, so the
292-
plugin and the viewer never disagree about what *obj_name* holds.
289+
PyMOL cannot load an mmCIF into an existing object, so a replacement must remove
290+
the old object before loading the new one. Doing the delete up front, however,
291+
destroys the existing object before we know the new load will succeed -- on
292+
failure there would be nothing left to restore for an object the user loaded
293+
directly with ``cmd.load`` (one not tracked in ``STATE.arrays``).
294+
295+
So the replacement is transactional: any pre-existing PyMOL object is first
296+
renamed to a temporary name, the new array is loaded under *obj_name*, and only
297+
on success is the old object deleted. If the load fails, the partially loaded
298+
object is removed and the original is renamed back, so the viewer is left exactly
299+
as it was -- whether or not *obj_name* is a tracked object. (A tracked object
300+
with no live PyMOL counterpart is still reloaded from ``STATE`` as a fallback.)
293301
"""
294-
cmd.delete(obj_name)
302+
had_object = obj_name in cmd.get_names("objects")
303+
backup_name = cmd.get_unused_name(f"{obj_name}_aw_backup") if had_object else None
304+
if backup_name is not None:
305+
cmd.set_name(obj_name, backup_name)
295306
try:
296307
_load_array_into_pymol(array, obj_name, hide_nans=STATE.hide_nans, show_seq_gaps=STATE.show_seq_gaps)
297308
except Exception:
298309
cmd.delete(obj_name)
299-
if obj_name in STATE.arrays:
310+
if backup_name is not None:
311+
cmd.set_name(backup_name, obj_name)
312+
elif obj_name in STATE.arrays:
300313
reload_structure_in_pymol(obj_name)
301314
raise
315+
else:
316+
if backup_name is not None:
317+
cmd.delete(backup_name)
302318

303319

304320
def load_structure(

‎packages/pymol-plugin/atomworks_studio_pymol/commands.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,10 @@ def _aw_load(path: str, obj_name: str = "") -> None:
4242
if preset is None:
4343
print(f"AtomWorks: '{path}' needs an explicit preset; loading annotated. Use the panel to choose.")
4444
preset = "minimal"
45-
config = build_load_config(preset, assembly="first")
45+
# Use build_load_config's default assembly ("1"), matching the GUI Load dialog. Passing
46+
# assembly="first" would import a different structure than the panel for a multi-assembly
47+
# CIF whose first parsed entry is not assembly 1.
48+
config = build_load_config(preset)
4649
obj_name = load_structure(path, config=config, obj_name=obj_name or None)
4750
print(f"AtomWorks: loaded '{path}' as '{obj_name}' ({preset})")
4851

‎packages/pymol-plugin/atomworks_studio_pymol/state.py‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -201,9 +201,22 @@ def push_snapshot(self, obj_name: str, *, interactive: bool = True) -> None:
201201
self.documents[obj_name].snapshot()
202202

203203
def pop_snapshot(self, obj_name: str) -> AtomArrayPlus | None:
204-
"""Undo the document edit and rebuild the renderer's identity map."""
204+
"""Undo the document edit and rebuild the renderer's identity map.
205+
206+
An object the user deleted directly in PyMOL (``delete obj``, the object
207+
menu) is not resurrected: its state is cleared and ``None`` is returned,
208+
mirroring :py:meth:`get_synced_array`. Without this check, undo would
209+
restore the document and the subsequent reload would recreate an object
210+
the user had deleted.
211+
"""
205212
document = self.documents.get(obj_name)
206-
if document is None or not document.undo():
213+
if document is None:
214+
return None
215+
if obj_name in self.arrays and obj_name not in cmd.get_names("objects"):
216+
logger.info("'%s' was deleted in PyMOL; refusing to undo (not resurrecting it)", obj_name)
217+
self.clear_object(obj_name)
218+
return None
219+
if not document.undo():
207220
return None
208221
self.set_array(obj_name, document.array)
209222
return document.array

‎packages/pymol-plugin/tests/conftest.py‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,16 @@
55
from a conftest it ends the entire session during collection instead of one package.
66
"""
77

8-
import importlib.util
98
from pathlib import Path
109

1110
import pytest
1211

13-
if importlib.util.find_spec("pymol") is None:
14-
collect_ignore_glob = ["*.py"]
15-
else:
12+
# A present ``pymol`` spec does not guarantee ``import pymol`` succeeds: the import can
13+
# still fail on a missing shared library or an unavailable Qt backend. Guard the real
14+
# import (and the launch + plugin imports it enables) so any such failure ignores this
15+
# package instead of aborting the whole collection session. ``find_spec`` alone cannot
16+
# catch that — it only proves a spec exists.
17+
try:
1618
# Launch PyMOL headless and skip ``~/.pymolrc`` before any ``cmd`` access.
1719
# Without ``-k`` PyMOL sources the user's pymolrc, which for developers who
1820
# ran the plugin's register step re-runs ``pymol_plugin/__init__.py`` as a
@@ -26,6 +28,8 @@
2628
from atomworks_studio_pymol.bridge import load_structure
2729
from atomworks_studio_pymol.state import STATE
2830
from pymol import cmd
31+
except Exception:
32+
collect_ignore_glob = ["*.py"]
2933

3034
# Anchor: <repo>/packages/pymol-plugin/tests/conftest.py → <repo>
3135
REPO_ROOT = Path(__file__).resolve().parents[3]

‎packages/pymol-plugin/tests/test_review_fixes.py‎

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -319,3 +319,83 @@ def test_missing_sele_warns_instead_of_raising(panel, messages):
319319
assert ChargeWizard(STATE)._active_indices() is None
320320
assert messages == ["No selection", "No selection"]
321321
assert selection_to_indices("sele", STATE.index_maps["objA"]) == []
322+
323+
324+
# PR #22 review: a failed replacement load must restore an object the user loaded
325+
# directly (one not tracked in STATE.arrays), not just a plugin-tracked object.
326+
327+
328+
def test_replace_pymol_object_restores_untracked_object_on_failure(monkeypatch):
329+
from atomworks_studio_pymol import bridge
330+
331+
# A directly loaded object is a real PyMOL object with no entry in STATE.arrays.
332+
cmd.pseudoatom("rawobj")
333+
assert "rawobj" in cmd.get_names("objects")
334+
assert "rawobj" not in STATE.arrays
335+
336+
def boom(*args, **kwargs):
337+
raise RuntimeError("simulated load failure")
338+
339+
monkeypatch.setattr(bridge, "_load_array_into_pymol", boom)
340+
with pytest.raises(RuntimeError):
341+
bridge._replace_pymol_object(object(), "rawobj")
342+
343+
# The pre-existing untracked object must survive a failed replacement.
344+
assert "rawobj" in cmd.get_names("objects")
345+
346+
347+
# PR #22 review: aw_load must use the same default assembly as the GUI Load dialog
348+
# (build_load_config's default "1"), not assembly="first".
349+
350+
351+
def test_aw_load_uses_gui_assembly_default(monkeypatch):
352+
captured: dict = {}
353+
354+
def capture_load(path, config, obj_name=None):
355+
captured["build_assembly"] = config.build_assembly
356+
return "objX"
357+
358+
monkeypatch.setattr(commands, "inspect_import", lambda path: {"preset": "minimal"})
359+
monkeypatch.setattr(commands, "load_structure", capture_load)
360+
commands._aw_load(str(BINDER))
361+
362+
assert captured["build_assembly"] == build_load_config("minimal").build_assembly
363+
assert captured["build_assembly"] == ["1"]
364+
365+
366+
# PR #22 review: undo must not resurrect an object the user deleted directly in PyMOL.
367+
368+
369+
def test_undo_does_not_resurrect_object_deleted_in_pymol():
370+
_load(BINDER, "objA")
371+
cmd.select("sele", "objA and chain B_1 and resi 1 and name CA")
372+
commands._aw_delete_selection("sele", "objA")
373+
assert STATE.documents["objA"]._undo # there is undo history to pop
374+
375+
cmd.delete("objA") # the user deletes the object directly in PyMOL
376+
assert STATE.pop_snapshot("objA") is None
377+
assert "objA" not in cmd.get_names("objects")
378+
assert "objA" not in STATE.arrays
379+
380+
381+
# PR #22 review: a present pymol spec whose import fails must ignore the plugin-test
382+
# package, not abort the whole collection session.
383+
384+
385+
def test_conftest_import_guard_ignores_package_when_pymol_import_fails(monkeypatch):
386+
import builtins
387+
388+
conftest_path = Path(__file__).resolve().parent / "conftest.py"
389+
source = conftest_path.read_text()
390+
real_import = builtins.__import__
391+
392+
def fake_import(name, *args, **kwargs):
393+
if name == "pymol" or name.startswith("pymol."):
394+
raise ImportError("simulated: PyMOL shared library unavailable")
395+
return real_import(name, *args, **kwargs)
396+
397+
monkeypatch.setattr(builtins, "__import__", fake_import)
398+
ns: dict = {"__file__": str(conftest_path), "__name__": "conftest_guard_probe"}
399+
exec(compile(source, str(conftest_path), "exec"), ns)
400+
401+
assert ns.get("collect_ignore_glob") == ["*.py"]

0 commit comments

Comments
 (0)