Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Address PR #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.
  • Loading branch information
AtharvaTilewale committed Nov 21, 2026
commit f456c974af7521f84c08aa58a67989276018f050
28 changes: 22 additions & 6 deletions packages/pymol-plugin/atomworks_studio_pymol/bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,19 +286,35 @@ def _load_array_into_pymol(
def _replace_pymol_object(array: AtomArrayPlus, obj_name: str) -> None:
"""Load *array* into PyMOL as *obj_name*, replacing any existing object of that name.
PyMOL cannot load an mmCIF into an existing object, so the old object is deleted
first. Callers update ``STATE`` only after this succeeds; if loading fails, the
structure still tracked under *obj_name* (if any) is restored in PyMOL, so the
plugin and the viewer never disagree about what *obj_name* holds.
PyMOL cannot load an mmCIF into an existing object, so a replacement must remove
the old object before loading the new one. Doing the delete up front, however,
destroys the existing object before we know the new load will succeed -- on
failure there would be nothing left to restore for an object the user loaded
directly with ``cmd.load`` (one not tracked in ``STATE.arrays``).
So the replacement is transactional: any pre-existing PyMOL object is first
renamed to a temporary name, the new array is loaded under *obj_name*, and only
on success is the old object deleted. If the load fails, the partially loaded
object is removed and the original is renamed back, so the viewer is left exactly
as it was -- whether or not *obj_name* is a tracked object. (A tracked object
with no live PyMOL counterpart is still reloaded from ``STATE`` as a fallback.)
"""
cmd.delete(obj_name)
had_object = obj_name in cmd.get_names("objects")
backup_name = cmd.get_unused_name(f"{obj_name}_aw_backup") if had_object else None
if backup_name is not None:
cmd.set_name(obj_name, backup_name)
try:
_load_array_into_pymol(array, obj_name, hide_nans=STATE.hide_nans, show_seq_gaps=STATE.show_seq_gaps)
except Exception:
cmd.delete(obj_name)
if obj_name in STATE.arrays:
if backup_name is not None:
cmd.set_name(backup_name, obj_name)
elif obj_name in STATE.arrays:
reload_structure_in_pymol(obj_name)
raise
else:
if backup_name is not None:
cmd.delete(backup_name)


def load_structure(
Expand Down
5 changes: 4 additions & 1 deletion packages/pymol-plugin/atomworks_studio_pymol/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,10 @@ def _aw_load(path: str, obj_name: str = "") -> None:
if preset is None:
print(f"AtomWorks: '{path}' needs an explicit preset; loading annotated. Use the panel to choose.")
preset = "minimal"
config = build_load_config(preset, assembly="first")
# Use build_load_config's default assembly ("1"), matching the GUI Load dialog. Passing
# assembly="first" would import a different structure than the panel for a multi-assembly
# CIF whose first parsed entry is not assembly 1.
config = build_load_config(preset)
obj_name = load_structure(path, config=config, obj_name=obj_name or None)
print(f"AtomWorks: loaded '{path}' as '{obj_name}' ({preset})")

Expand Down
17 changes: 15 additions & 2 deletions packages/pymol-plugin/atomworks_studio_pymol/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,9 +201,22 @@ def push_snapshot(self, obj_name: str, *, interactive: bool = True) -> None:
self.documents[obj_name].snapshot()

def pop_snapshot(self, obj_name: str) -> AtomArrayPlus | None:
"""Undo the document edit and rebuild the renderer's identity map."""
"""Undo the document edit and rebuild the renderer's identity map.
An object the user deleted directly in PyMOL (``delete obj``, the object
menu) is not resurrected: its state is cleared and ``None`` is returned,
mirroring :py:meth:`get_synced_array`. Without this check, undo would
restore the document and the subsequent reload would recreate an object
the user had deleted.
"""
document = self.documents.get(obj_name)
if document is None or not document.undo():
if document is None:
return None
if obj_name in self.arrays and obj_name not in cmd.get_names("objects"):
logger.info("'%s' was deleted in PyMOL; refusing to undo (not resurrecting it)", obj_name)
self.clear_object(obj_name)
return None
if not document.undo():
return None
self.set_array(obj_name, document.array)
return document.array
Expand Down
12 changes: 8 additions & 4 deletions packages/pymol-plugin/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,16 @@
from a conftest it ends the entire session during collection instead of one package.
"""

import importlib.util
from pathlib import Path

import pytest

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

# Anchor: <repo>/packages/pymol-plugin/tests/conftest.py → <repo>
REPO_ROOT = Path(__file__).resolve().parents[3]
Expand Down
80 changes: 80 additions & 0 deletions packages/pymol-plugin/tests/test_review_fixes.py
Original file line number Diff line number Diff line change
Expand Up @@ -319,3 +319,83 @@ def test_missing_sele_warns_instead_of_raising(panel, messages):
assert ChargeWizard(STATE)._active_indices() is None
assert messages == ["No selection", "No selection"]
assert selection_to_indices("sele", STATE.index_maps["objA"]) == []


# PR #22 review: a failed replacement load must restore an object the user loaded
# directly (one not tracked in STATE.arrays), not just a plugin-tracked object.


def test_replace_pymol_object_restores_untracked_object_on_failure(monkeypatch):
from atomworks_studio_pymol import bridge

# A directly loaded object is a real PyMOL object with no entry in STATE.arrays.
cmd.pseudoatom("rawobj")
assert "rawobj" in cmd.get_names("objects")
assert "rawobj" not in STATE.arrays

def boom(*args, **kwargs):
raise RuntimeError("simulated load failure")

monkeypatch.setattr(bridge, "_load_array_into_pymol", boom)
with pytest.raises(RuntimeError):
bridge._replace_pymol_object(object(), "rawobj")

# The pre-existing untracked object must survive a failed replacement.
assert "rawobj" in cmd.get_names("objects")


# PR #22 review: aw_load must use the same default assembly as the GUI Load dialog
# (build_load_config's default "1"), not assembly="first".


def test_aw_load_uses_gui_assembly_default(monkeypatch):
captured: dict = {}

def capture_load(path, config, obj_name=None):
captured["build_assembly"] = config.build_assembly
return "objX"

monkeypatch.setattr(commands, "inspect_import", lambda path: {"preset": "minimal"})
monkeypatch.setattr(commands, "load_structure", capture_load)
commands._aw_load(str(BINDER))

assert captured["build_assembly"] == build_load_config("minimal").build_assembly
assert captured["build_assembly"] == ["1"]


# PR #22 review: undo must not resurrect an object the user deleted directly in PyMOL.


def test_undo_does_not_resurrect_object_deleted_in_pymol():
_load(BINDER, "objA")
cmd.select("sele", "objA and chain B_1 and resi 1 and name CA")
commands._aw_delete_selection("sele", "objA")
assert STATE.documents["objA"]._undo # there is undo history to pop

cmd.delete("objA") # the user deletes the object directly in PyMOL
assert STATE.pop_snapshot("objA") is None
assert "objA" not in cmd.get_names("objects")
assert "objA" not in STATE.arrays


# PR #22 review: a present pymol spec whose import fails must ignore the plugin-test
# package, not abort the whole collection session.


def test_conftest_import_guard_ignores_package_when_pymol_import_fails(monkeypatch):
import builtins

conftest_path = Path(__file__).resolve().parent / "conftest.py"
source = conftest_path.read_text()
real_import = builtins.__import__

def fake_import(name, *args, **kwargs):
if name == "pymol" or name.startswith("pymol."):
raise ImportError("simulated: PyMOL shared library unavailable")
return real_import(name, *args, **kwargs)

monkeypatch.setattr(builtins, "__import__", fake_import)
ns: dict = {"__file__": str(conftest_path), "__name__": "conftest_guard_probe"}
exec(compile(source, str(conftest_path), "exec"), ns)

assert ns.get("collect_ignore_glob") == ["*.py"]