Skip to content

Commit

Permalink
Handle importstring pre/post save hooks
Browse files Browse the repository at this point in the history
Try access the __name__ attribute on the function form of the hook, and
if it doesn't exist then use the string as the name.

Closes #753
  • Loading branch information
dleen committed Mar 24, 2022
1 parent cd1b1b8 commit 92499f4
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
12 changes: 10 additions & 2 deletions jupyter_server/services/contents/manager.py
Expand Up @@ -128,8 +128,12 @@ def _validate_pre_save_hook(self, proposal):
if not callable(value):
raise TraitError("pre_save_hook must be callable")
if self.pre_save_hook is not None:
try:
existing_name = self.pre_save_hook.__name__
except AttributeError:
existing_name = self.pre_save_hook
warnings.warn(
f"Overriding existing pre_save_hook ({self.pre_save_hook.__name__}) with a new one ({value.__name__}).",
f"Overriding existing pre_save_hook ({existing_name}) with a new one ({value.__name__}).",
stacklevel=2,
)
return value
Expand Down Expand Up @@ -163,8 +167,12 @@ def _validate_post_save_hook(self, proposal):
if not callable(value):
raise TraitError("post_save_hook must be callable")
if self.post_save_hook is not None:
try:
existing_name = self.post_save_hook.__name__
except AttributeError:
existing_name = self.post_save_hook
warnings.warn(
f"Overriding existing post_save_hook ({self.post_save_hook.__name__}) with a new one ({value.__name__}).",
f"Overriding existing post_save_hook ({existing_name}) with a new one ({value.__name__}).",
stacklevel=2,
)
return value
Expand Down
24 changes: 24 additions & 0 deletions tests/services/contents/test_config.py
Expand Up @@ -18,6 +18,30 @@ def test_config_did_something(jp_server_config, jp_serverapp):
)


def example_pre_save_hook():
pass


def example_post_save_hook():
pass


@pytest.mark.parametrize(
"jp_server_config",
[
{
"ContentsManager": {
"pre_save_hook": "tests.services.contents.test_config.example_pre_save_hook",
"post_save_hook": "tests.services.contents.test_config.example_post_save_hook",
},
}
],
)
def test_pre_post_save_hook_config(jp_serverapp, jp_server_config):
assert jp_serverapp.contents_manager.pre_save_hook.__name__ == "example_pre_save_hook"
assert jp_serverapp.contents_manager.post_save_hook.__name__ == "example_post_save_hook"


async def test_async_contents_manager(jp_configurable_serverapp):
config = {"ContentsManager": {"checkpoints_class": AsyncCheckpoints}}
argv = [
Expand Down

0 comments on commit 92499f4

Please sign in to comment.