Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(models-project): remove all project update code #802

Merged
merged 17 commits into from
Feb 6, 2024
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
63 changes: 5 additions & 58 deletions src/dsp_tools/commands/project/create/project_create.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@
def _create_project_on_server(
project_definition: ProjectDefinition,
con: Connection,
verbose: bool,
) -> tuple[Project, bool]:
"""
Create the project on the DSP server.
Expand All @@ -41,7 +40,6 @@ def _create_project_on_server(
Args:
project_definition: object with information about the project
con: connection to the DSP server
verbose: verbose switch

Raises:
UserError: if the project cannot be created on the DSP server
Expand All @@ -51,23 +49,13 @@ def _create_project_on_server(
"""
all_projects = Project.getAllProjects(con=con)
if project_definition.shortcode in [proj.shortcode for proj in all_projects]:
project_local = Project(con=con, shortcode=project_definition.shortcode)
project_remote: Project = project_local.read()
msg = (
f"A project with shortcode {project_definition.shortcode} already exists on the DSP server. Updating it..."
Nora-Olivia-Ammann marked this conversation as resolved.
Show resolved Hide resolved
f"The project with the shortcode'{project_definition.shortcode}' already exists on the server.\n"
Nora-Olivia-Ammann marked this conversation as resolved.
Show resolved Hide resolved
f"No changes were made to the project meta-data.\n"
Nora-Olivia-Ammann marked this conversation as resolved.
Show resolved Hide resolved
f"Continue with the upload of lists and ontologies ..."
)
print(f" WARNING: {msg}")
logger.warning(msg)
# try to update the basic info
project_remote, _ = _update_basic_info_of_project(
project=project_remote,
project_definition=project_definition,
verbose=verbose,
)
# It doesn't matter if the update is successful or not: continue anyway, because success is anyways false.
# There are other things from this file that can be created on the server,
# e.g. the groups and users, so the process must continue.
return project_remote, False
print(f"WARNING: {msg}")
logger.warning(msg, exc_info=True)
Nora-Olivia-Ammann marked this conversation as resolved.
Show resolved Hide resolved

success = True
project_local = Project(
Expand All @@ -94,46 +82,6 @@ def _create_project_on_server(
return project_remote, success


def _update_basic_info_of_project(
project: Project,
project_definition: ProjectDefinition,
verbose: bool,
) -> tuple[Project, bool]:
"""
Updates the longname, description and keywords of a project on a DSP server.
Returns the updated project (or the unchanged project if not successful)
and a boolean saying if the update was successful or not.
If the update was not successful, an error message is printed to stdout.

Args:
project: the project to be updated (must exist on the DSP server)
project_definition: object with project info
verbose: verbose switch

Returns:
tuple of (updated project, success status)
"""

# update the local "project" object
project.longname = project_definition.longname
project.description = LangString(project_definition.descriptions) # type: ignore[arg-type]
project.keywords = set(project_definition.keywords) if project_definition.keywords else set()

# make the call to DSP-API
try:
project_remote: Project = project.update()
info_str = f" Updated project '{project_definition.shortname}' ({project_definition.shortcode})."
if verbose:
print(info_str)
logger.info(info_str)
return project_remote, True
except BaseError:
msg = f"WARNING: Could not update project '{project_definition.shortname}' ({project_definition.shortcode})."
print(msg)
logger.warning(msg, exc_info=True)
return project, False


def _create_groups(
con: Connection,
groups: list[dict[str, str]],
Expand Down Expand Up @@ -1032,7 +980,6 @@ def create_project(
project_remote, success = _create_project_on_server(
project_definition=project_definition,
con=con,
verbose=verbose,
)
if not success:
overall_success = False
Expand Down
37 changes: 0 additions & 37 deletions src/dsp_tools/commands/project/models/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,6 @@
* Call the ``read``-method on the instance
* Access the information that has been provided to the instance

UPDATE:
* You need an instance of an existing Project by reading an instance
* Change the attributes by assigning the new values
* Call the ``update`` method on the instance

In addition there is a static methods ``getAllProjects`` which returns a list of all projects
"""

from __future__ import annotations
Expand Down Expand Up @@ -73,9 +67,6 @@ class Project(Model):
read : DSP project information object
Read project data from an existing project

update : DSP project information object
Updates the changed attributes and returns the updated information from the project as it is in DSP

getAllprojects [static]: List of all projects
Returns a list of all projects available

Expand Down Expand Up @@ -351,34 +342,6 @@ def read(self) -> Project:
f"from DSP server."
)

def update(self) -> Project:
"""
Update the project information on the DSP with the modified data in this project instance

Returns: JSON object returned as response from DSP reflecting the update
"""
jsonobj = self._toJsonObj_update()
result = self._con.put(Project.IRI + quote_plus(self.iri), jsonobj)
return Project.fromJsonObj(self._con, result["project"])

def _toJsonObj_update(self) -> dict[str, str]:
tmp = {}
if self._shortcode is not None and "shortcode" in self._changed:
tmp["shortcode"] = self._shortcode
if self._shortname is not None and "shortname" in self._changed:
tmp["shortname"] = self._shortname
if self._longname is not None and "longname" in self._changed:
tmp["longname"] = self._longname
if not self._description.isEmpty() and "description" in self._changed:
tmp["description"] = self._description.toJsonObj()
if len(self._keywords) > 0 and "keywords" in self._changed:
tmp["keywords"] = self._keywords
if self._selfjoin is not None and "selfjoin" in self._changed:
tmp["selfjoin"] = self._selfjoin
if self._status is not None and "status" in self._changed:
tmp["status"] = self._status
return tmp

@staticmethod
def getAllProjects(con: Connection) -> list[Project]:
"""
Expand Down
3 changes: 2 additions & 1 deletion src/dsp_tools/utils/shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,8 +237,9 @@ def parse_json_input(project_file_as_path_or_parsed: Union[str, Path, dict[str,
Returns:
the parsed JSON object
"""
project_definition: dict[str, Any] = {}
if isinstance(project_file_as_path_or_parsed, dict):
project_definition: dict[str, Any] = project_file_as_path_or_parsed
project_definition = project_file_as_path_or_parsed
elif isinstance(project_file_as_path_or_parsed, (str, Path)) and Path(project_file_as_path_or_parsed).exists():
with open(project_file_as_path_or_parsed, encoding="utf-8") as f:
try:
Expand Down
121 changes: 0 additions & 121 deletions test/e2e/commands/project/test_project.py

This file was deleted.

2 changes: 0 additions & 2 deletions test/unittests/commands/project/test_create_project.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
"""unit tests for ontology creation"""

import json
from typing import Any

Expand Down
54 changes: 54 additions & 0 deletions test/unittests/commands/project/test_models_project.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
from test.unittests.commands.xmlupload.connection_mock import ConnectionMockBase

import pytest

from dsp_tools.commands.project.models.project import Project
from dsp_tools.models.langstring import LangString, Languages


@pytest.fixture()
def project() -> Project:
return Project(
con=ConnectionMockBase(),
iri="http://rdfh.ch/test",
shortcode="0FF0",
shortname="test_project",
longname="Test Project",
description=LangString({Languages.EN: "This is a test project", Languages.DE: "Das ist ein Testprojekt"}),
keywords=set(),
selfjoin=False,
status=True,
logo="logo.gif",
)


def test_return_values(project: Project) -> None:
assert project.iri == "http://rdfh.ch/test"
assert project.shortcode == "0FF0"
assert project.shortname == "test_project"
assert project.longname == "Test Project"
assert project.description["en"] == "This is a test project"
assert project.description["de"] == "Das ist ein Testprojekt"
assert project.selfjoin is False
assert project.status is True
assert project.keywords == set()
Nora-Olivia-Ammann marked this conversation as resolved.
Show resolved Hide resolved


def test_to_json_obj_create(project: Project) -> None:
Nora-Olivia-Ammann marked this conversation as resolved.
Show resolved Hide resolved
res_json = project._toJsonObj_create()
expected = {
"shortcode": "0FF0",
"shortname": "test_project",
"longname": "Test Project",
"description": [
{"language": "en", "value": "This is a test project"},
{"language": "de", "value": "Das ist ein Testprojekt"},
],
"selfjoin": False,
"status": True,
}
assert res_json == expected

Nora-Olivia-Ammann marked this conversation as resolved.
Show resolved Hide resolved

if __name__ == "__main__":
pytest.main([__file__])