8000 Implement the Profiles section on the Control page by yakutovicha · Pull Request #261 · aiidalab/aiidalab-home · GitHub
[go: up one dir, main page]

Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
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
141 changes: 140 additions & 1 deletion home/control.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import ipywidgets as ipw
from aiida import get_profile, manage, orm
from aiida.engine.daemon.client import DaemonException
from aiida.manage.configuration import load_config

from home.themes import ThemeDefault as Theme

Expand Down Expand Up @@ -511,11 +512,149 @@ def __init__(self):
super().__init__([ipw.HTML("To be implemented.")])


class ProfileRow(ipw.HBox):
"""A profile's name with its "Make default" and "Delete" buttons."""

def __init__(self, name, is_default, is_loaded, on_make_default, on_delete):
label = html.escape(name)
if is_default:
label += (
f" <span style='background:{Theme.COLORS.CHECK};color:white;"
"padding:1px 8px;border-radius:9px;font-size:11px;'>default</span>"
)
if is_loaded:
label += f" <span style='color:{Theme.COLORS.GRAY}'>(in use)</span>"

self.make_default_button = ipw.Button(
description="Make default",
button_style="info",
icon="star",
disabled=is_default,
tooltip="Already the default profile" if is_default else "",
)
self.make_default_button.on_click(lambda _: on_make_default(name))
self.delete_button = ipw.Button(
description="Delete",
button_style="danger",
icon="trash",
disabled=is_loaded,
tooltip="In use by this page, so it cannot be deleted" if is_loaded else "",
)
self.delete_button.on_click(lambda _: on_delete(name))

super().__init__(
[
ipw.HTML(label, layout=ipw.Layout(width="220px")),
self.make_default_button,
self.delete_button,
]
)


class ProfileControlWidget(ControlSectionWidget):
description = "Manage AiiDA profiles: default profile and deletion."

def __init__(self):
super().__init__([ipw.HTML("To be implemented.")])
self._delete_target = None
self._rows = ipw.VBox()

self._confirm_text = ipw.HTML()
self._delete_storage = ipw.Checkbox(
value=False,
description="Also delete all data of this profile "
"(database and file repository)",
indent=False,
layout=ipw.Layout(width="auto"),
)
confirm_button = ipw.Button(
description="Confirm delete", button_style="danger", icon="trash"
)
confirm_button.on_click(self._on_confirm_delete)
cancel_button = ipw.Button(description="Cancel", icon="times")
cancel_button.on_click(self._dismiss_confirmation)
self._confirm_box = ipw.VBox(
[
self._confirm_text,
self._delete_storage,
ipw.HBox([confirm_button, cancel_button]),
],
layout=ipw.Layout(display="none"),
)

super().__init__([self._rows, self._confirm_box])

def _do_refresh(self):
# Always read the config from disk: AiiDA's cached config misses
# changes made by other processes, and storing it would drop them.
self._render(load_config())

def _render(self, config):
loaded_profile = get_profile()
loaded_name = loaded_profile.name if loaded_profile is not None else None
self._rows.children = [
ProfileRow(
profile.name,
is_default=profile.name == config.default_profile_name,
is_loaded=profile.name == loaded_name,
on_make_default=self._on_make_default,
on_delete=self._on_delete,
)
for profile in config.profiles
]
# The profile a pending confirmation targets may be gone.
self._dismiss_confirmation()

def _on_make_default(self, name):
try:
config = load_config()
config.set_default_profile(name, overwrite=True)
config.store()
except Exception as exc:
self.show_error(f'Failed to make "{name}" the default profile: {exc}')
return
self.show_success(
f'Profile "{name}" is now the default. Reload the page to use it.'
)
self._render(config)

def _on_delete(self, name):
self._delete_target = name
self._delete_storage.value = False
self._confirm_text.value = (
f"You are about to delete profile <b>{html.escape(name)}</b>. "
"This cannot be undone."
)
self._confirm_box.layout.display = ""

def _dismiss_confirmation(self, _=None):
self._delete_target = None
self._confirm_box.layout.display = "none"

def _on_confirm_delete(self, _=None):
name = self._delete_target
if name is None:
return
delete_storage = self._delete_storage.value
self._dismiss_confirmation()
self.info.value = (
f'Deleting profile "{html.escape(name)}"... '
"<i class='fa fa-spinner fa-spin'></i>"
)
try:
config = load_config()
was_default = name == config.default_profile_name
# Pass delete_storage explicitly: AiiDA deletes the data by default.
config.delete_profile(name, delete_storage=delete_storage)
except Exception as exc:
self.show_error(f'Failed to delete profile "{name}": {exc}')
return

message = f'Profile "{name}" deleted.'
if was_default and config.profiles:
# AiiDA makes the first remaining profile the new default.
message += f' "{config.default_profile_name}" is now the default profile.'
self.show_success(message)
self._render(config)


class DangerZoneWidget(ControlSectionWidget):
Expand Down
198 changes: 198 additions & 0 deletions tests/test_control.py
8BD0
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
import html
import re
import threading
from pathlib import Path
from types import SimpleNamespace
from typing import cast

import pytest
from aiida.engine.daemon.client import DaemonException
from aiida.manage.configuration import Profile, load_config

import home.control as control_module
from home.control import (
AiidaStatusOverviewWidget,
ControlSectionWidget,
ProfileControlWidget,
State,
SystemResourcesWidget,
_cpu_status,
Expand Down Expand Up @@ -444,3 +448,197 @@ def _raise():
# ...but CPU and disk still updated independently.
assert widget._cpu_bar.bar_style == "success"
assert widget._disk_bar.bar_style == "success"


class _FakeConfig:
"""A stand-in for AiiDA's Config, recording the calls made to it."""

def __init__(self, names, default):
self.profiles = [SimpleNamespace(name=name) for name in names]
self.default_profile_name = default
self.calls = []

def set_default_profile(self, name, overwrite=False):
self.calls.append(("set_default_profile", name, overwrite))
self.default_profile_name = name

def store(self):
self.calls.append(("store",))

def delete_profile(self, name, delete_storage=True):
self.calls.append(("delete_profile", name, delete_storage))
self.profiles = [p for p in self.profiles if p.name != name]
# Like AiiDA, keep the stale default when no profiles remain.
if name == self.default_profile_name and self.profiles:
self.default_profile_name = self.profiles[0].name


@pytest.fixture
def profile_widget(monkeypatch):
"""A ProfileControlWidget over a fake config with the profiles "main"
(default), "other" and "in-use" (loaded by this page)."""
config = _FakeConfig(["main", "other", "in-use"], default="main")
monkeypatch.setattr(control_module, "load_config", lambda: config)
monkeypatch.setattr(
control_module, "get_profile", lambda: SimpleNamespace(name="in-use")
)
widget = ProfileControlWidget()
widget._do_refresh()
return widget, config


def _profile_rows(widget):
return {row.children[0].value.split(" ")[0]: row for row in widget._rows.children}


def test_profile_rows(profile_widget):
widget, _ = profile_widget
rows = _profile_rows(widget)
assert list(rows) == ["main", "other", "in-use"]

assert "default" in rows["main"].children[0].value
assert rows["main"].make_default_button.disabled is True
assert rows["main"].delete_button.disabled is False

assert "(in use)" in rows["in-use"].children[0].value
assert rows["in-use"].delete_button.disabled is True
assert rows["in-use"].make_default_button.disabled is False


def test_profile_names_are_escaped(monkeypatch):
config = _FakeConfig(["<b>bold</b>"], default=None)
monkeypatch.setattr(control_module, "load_config", lambda: config)
monkeypatch.setattr(control_module, "get_profile", lambda: None)
widget = ProfileControlWidget()
widget._do_refresh()
assert "&lt;b&gt;bold&lt;/b&gt;" in widget._rows.children[0].children[0].value


def test_profile_make_default(profile_widget):
widget, config = profile_widget
_profile_rows(widget)["other"].make_default_button.click()

assert config.calls == [("set_default_profile", "other", True), ("store",)]
assert (
'Profile "other" is now the default. Reload the page to use it.'
in html.unescape(widget.info.value)
)
rows = _profile_rows(widget)
assert "default" in rows["other"].children[0].value
assert "default" not in rows["main"].children[0].value


def test_profile_delete_needs_confirmation(profile_widget):
widget, config = profile_widget
_profile_rows(widget)["other"].delete_button.click()

assert widget._confirm_box.layout.display == ""
assert "<b>other</b>" in widget._confirm_text.value
assert widget._delete_storage.value is False
assert config.calls == []

widget._delete_storage.value = True
# Retargeting resets the checkbox and names the new target.
_profile_rows(widget)["main"].delete_button.click()
assert "<b>main</b>" in widget._confirm_text.value
assert widget._delete_storage.value is False

widget._on_confirm_delete()
assert config.calls == [("delete_profile", "main", False)]
assert widget._confirm_box.layout.display == "none"
# Deleting the default makes AiiDA pick a new one; the message says so.
assert 'Profile "main" deleted.' in html.unescape(widget.info.value)
assert '"other" is now the default profile.' in html.unescape(widget.info.value)
assert list(_profile_rows(widget)) == ["other", "in-use"]


def test_profile_delete_with_data(profile_widget):
widget, config = profile_widget
_profile_rows(widget)["other"].delete_button.click()
widget._delete_storage.value = True
widget._on_confirm_delete()
assert config.calls == [("delete_profile", "other", True)]
assert "now the default" not in widget.info.value


def test_profile_delete_last_default(monkeypatch):
# The loaded profile was removed by another process, so the last
# profile, the default, can be deleted: no new default is claimed.
config = _FakeConfig(["main"], default="main")
monkeypatch.setattr(control_module, "load_config", lambda: config)
monkeypatch.setattr(
control_module, "get_profile", lambda: SimpleNamespace(name="gone")
)
widget = ProfileControlWidget()
widget._do_refresh()
_profile_rows(widget)["main"].delete_button.click()
widget._on_confirm_delete()

message = html.unescape(widget.info.value)
assert 'Profile "main" deleted.' in message
assert "now the default" not in message
assert not widget._rows.children


def test_profile_delete_cancel(profile_widget):
widget, config = profile_widget
_profile_rows(widget)["other"].delete_button.click()
widget._dismiss_confirmation()
assert widget._confirm_box.layout.display == "none"
widget._on_confirm_delete()
assert config.calls == []


def test_profile_refresh_dismisses_confirmation(profile_widget):
widget, config = profile_widget
_profile_rows(widget)["other"].delete_button.click()
widget._do_refresh()
assert widget._confirm_box.layout.display == "none"
widget._on_confirm_delete()
assert config.calls == []


def test_profile_delete_failure_is_shown(profile_widget, monkeypatch):
widget, config = profile_widget

def _raise(name, delete_storage=True):
raise RuntimeError("database is busy")

monkeypatch.setattr(config, "delete_profile", _raise)
_profile_rows(widget)["other"].delete_button.click()
widget._on_confirm_delete()
assert State.ERROR.color in widget.info.value
assert 'Failed to delete profile "other": database is busy' in html.unescape(
widget.info.value
)


@pytest.fixture
def restore_config_file(aiida_profile):
"""Restore the test config file after a test that writes to it."""
path = Path(load_config().filepath)
content = path.read_text()
yield
path.write_text(content)


def test_profile_make_default_keeps_external_changes(
aiida_profile, restore_config_file
):
config = load_config()
config.add_profile(Profile("other", aiida_profile.dictionary))
config.store()
widget = ProfileControlWidget()
widget._do_refresh()

# Another process (e.g. `verdi presto` in a terminal) adds a profile
# after the page loaded the config.
external = load_config()
external.add_profile(Profile("external", aiida_profile.dictionary))
external.store()

_profile_rows(widget)["other"].make_default_button.click()

config = load_config()
assert config.default_profile_name == "other"
assert "external" in config.profile_names
0