From b0d54350d09eae2ce7e98043ef4f50e67c4bcbaa Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Wed, 27 Nov 2024 10:01:40 +0100 Subject: [PATCH 1/7] fix: let CredentialManager and OswExpress default locations match Refs: #83 --- src/osw/auth.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/osw/auth.py b/src/osw/auth.py index 85b8aff1..3a6e1372 100644 --- a/src/osw/auth.py +++ b/src/osw/auth.py @@ -257,7 +257,7 @@ def save_credentials_to_file( if filepath is None: filepath_ = self.cred_filepath if self.cred_filepath is None: - filepath_ = [Path.cwd() / CREDENTIALS_FN_DEFAULT] + filepath_ = [Path.cwd() / "osw_files" / CREDENTIALS_FN_DEFAULT] if set_cred_filepath: # Creates error if file does not exist -> Using custom FilePath self.cred_filepath = filepath_ From be2a78932657f0d73c480e78c5c2ad4e4e786664 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Wed, 27 Nov 2024 10:06:46 +0100 Subject: [PATCH 2/7] feat: add osw_files to generated .gitignore not sure if this is the right location Refs: 83 --- src/osw/auth.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/osw/auth.py b/src/osw/auth.py index 3a6e1372..aebc522b 100644 --- a/src/osw/auth.py +++ b/src/osw/auth.py @@ -282,7 +282,11 @@ def save_credentials_to_file( # Creating or updating .gitignore file in the working directory cwd = Path.cwd() - potential_fp = [cwd / ".gitignore", cwd.parent / ".gitignore"] + potential_fp = [ + cwd / "osw_files", + cwd / ".gitignore", + cwd.parent / ".gitignore", + ] write_to_fp = potential_fp[0] for fp in potential_fp: if fp.exists(): From 8b97e705af8539c6ac1aa050e29f8131962a33f6 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Wed, 27 Nov 2024 15:33:38 +0100 Subject: [PATCH 3/7] fix: tests --- src/osw/auth.py | 1 - tests/integration/test_express.py | 4 +++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/osw/auth.py b/src/osw/auth.py index aebc522b..110309cd 100644 --- a/src/osw/auth.py +++ b/src/osw/auth.py @@ -283,7 +283,6 @@ def save_credentials_to_file( # Creating or updating .gitignore file in the working directory cwd = Path.cwd() potential_fp = [ - cwd / "osw_files", cwd / ".gitignore", cwd.parent / ".gitignore", ] diff --git a/tests/integration/test_express.py b/tests/integration/test_express.py index 2ec9cac4..688ad38f 100644 --- a/tests/integration/test_express.py +++ b/tests/integration/test_express.py @@ -110,7 +110,9 @@ def test_init_with_cred_filepath_but_missing_credentials( mocked_getpass = mocker.patch("getpass.getpass") mocked_input.return_value = wiki_username mocked_getpass.return_value = wiki_password - cred_filepath = Path.cwd() / "accounts.pwd.yaml" + cred_filepath = Path.cwd() / "osw_files" / "accounts.pwd.yaml" + if not cred_filepath.parent.exists(): + cred_filepath.parent.mkdir(parents=True) with open(cred_filepath, "w") as f: yaml.dump({"dummy.domain": {"username": "dummy", "password": "password"}}, f) import osw.express From 302a337b81649646077ff69b553a259df40f28e1 Mon Sep 17 00:00:00 2001 From: Lukas Gold Date: Wed, 27 Nov 2024 16:08:07 +0100 Subject: [PATCH 4/7] Introducing osw.defaults and adding the osw.defaults.paths.osw_files_dir to .gitignore programmatically --- examples/use_express_functions.py | 20 ++-- src/osw/auth.py | 68 +++++++++---- src/osw/data/import_utility.py | 9 +- src/osw/defaults.py | 154 ++++++++++++++++++++++++++++++ src/osw/express.py | 102 +++----------------- src/osw/params.py | 8 +- tests/integration/test_express.py | 2 +- 7 files changed, 232 insertions(+), 131 deletions(-) create mode 100644 src/osw/defaults.py diff --git a/examples/use_express_functions.py b/examples/use_express_functions.py index 92298cdb..df0428ee 100644 --- a/examples/use_express_functions.py +++ b/examples/use_express_functions.py @@ -1,22 +1,24 @@ from pathlib import Path -from osw.express import ( - OswExpress, - cred_filepath_default, - osw_download_file, - osw_upload_file, -) +from osw.defaults import params as default_params +from osw.defaults import paths as default_paths + +# The domain, osw.express will be initialized with +default_params.wiki_domain = "wiki-dev.open-semantic-lab.org" + +from osw.express import OswExpress, osw_download_file, osw_upload_file # noqa: E402 # (Optional) Set the default credentials filepath to desired location. Otherwise, # it will use the default location (current working directory) # cred_filepath_default.set_default(r"C:\Users\gold\ownCloud\Personal\accounts.pwd.yaml") # Check setting -print(f"Credentials loaded from '{str(cred_filepath_default)}") +print(f"Credentials loaded from '{str(default_paths.cred_fp)}'") -# Create an OswExpress object +# The domain to connect to domain = "wiki-dev.open-semantic-lab.org" -# domain = "arkeve.test.digital.isc.fraunhofer.de" +# domain = "demo.open-semantic-lab.org" +# Create an OswExpress object osw_obj = OswExpress(domain=domain) # Create a file diff --git a/src/osw/auth.py b/src/osw/auth.py index 110309cd..9ebbeea5 100644 --- a/src/osw/auth.py +++ b/src/osw/auth.py @@ -10,10 +10,9 @@ from pydantic.v1 import PrivateAttr from osw.custom_types import PossibleFilePath +from osw.defaults import paths as default_paths from osw.model.static import OswBaseModel -CREDENTIALS_FN_DEFAULT = "credentials.pwd.yaml" - class CredentialManager(OswBaseModel): """Handles credentials""" @@ -253,15 +252,16 @@ def save_credentials_to_file( If True, the cred_filepath is set to the given filepath. If False, the cred_filepath of the CredentialManager is not changed. """ - filepath_ = [filepath] + cred_filepaths = [filepath] + """The filepath to save the credentials to.""" if filepath is None: - filepath_ = self.cred_filepath + cred_filepaths = self.cred_filepath if self.cred_filepath is None: - filepath_ = [Path.cwd() / "osw_files" / CREDENTIALS_FN_DEFAULT] + cred_filepaths = [default_paths.cred_fp] if set_cred_filepath: # Creates error if file does not exist -> Using custom FilePath - self.cred_filepath = filepath_ - for fp in filepath_: + self.cred_filepath = cred_filepaths + for fp in cred_filepaths: file = Path(fp) if not file.parent.exists(): file.parent.mkdir(parents=True) @@ -286,29 +286,57 @@ def save_credentials_to_file( cwd / ".gitignore", cwd.parent / ".gitignore", ] - write_to_fp = potential_fp[0] + gitignore_fp = potential_fp[0] + # Stops if a .gitignore file is found for fp in potential_fp: if fp.exists(): - write_to_fp = fp + gitignore_fp = fp break - if not write_to_fp.exists(): - if not write_to_fp.parent.exists(): - write_to_fp.parent.mkdir(parents=True) - write_to_fp.touch() - with open(write_to_fp, "r") as stream: + # Creates a .gitignore file if none is found + if not gitignore_fp.exists(): + if not gitignore_fp.parent.exists(): + gitignore_fp.parent.mkdir(parents=True) + gitignore_fp.touch() + # Reads the .gitignore file + with open(gitignore_fp, "r") as stream: content = stream.read() comment_set = False - for _ii, fp in enumerate(filepath_): - if fp.name not in content: - print(f"Adding '{fp.name}' to gitignore file '{write_to_fp}'.") - with open(write_to_fp, "a") as stream: - if comment_set: + osw_dir_added = False + # For every file path in the list of credentials file paths + for _ii, fp in enumerate(cred_filepaths): + to_add = "" + if default_paths.osw_files_dir in fp.parents and not osw_dir_added: + print( + f"Adding '{default_paths.osw_files_dir}' to gitignore file " + f"'{gitignore_fp}'." + ) + containing_gitignore = gitignore_fp.parent.absolute() + + if containing_gitignore in default_paths.osw_files_dir.parents: + # If the default_path.osw_files_dir is a subdirectory of the directory + # containing the .gitignore file, add the relative path to the + # .gitignore file + rel = default_paths.osw_files_dir.relative_to(containing_gitignore) + to_add = f"\n*{str(rel.as_posix())}/*" + else: + # Test if the default_path.osw_files_dir is a subdirectory of the + # directory containing the .gitignore file + to_add = f"\n*{default_paths.osw_files_dir.absolute().as_posix()}/*" + osw_dir_added = True + elif fp.name not in content: + print(f"Adding '{fp.name}' to gitignore file '{gitignore_fp}'.") + to_add = f"\n*{fp.name}" + # If to_add is not empty, write to .gitignore file + if to_add: + with open(gitignore_fp, "a") as stream: + # Only add comment if not already set + if not comment_set: stream.write( "\n# Automatically added by osw.auth.CredentialManager." "save_credentials_to_file:" ) comment_set = True - stream.write(f"\n*{fp.name}") + stream.write(to_add) CredentialManager.CredentialConfig.update_forward_refs() diff --git a/src/osw/data/import_utility.py b/src/osw/data/import_utility.py index 9a0bb122..ff02e3d6 100644 --- a/src/osw/data/import_utility.py +++ b/src/osw/data/import_utility.py @@ -15,17 +15,14 @@ from osw import wiki_tools as wt from osw.auth import CredentialManager from osw.core import OSW +from osw.defaults import paths as default_paths from osw.model import entity as model from osw.utils.regex import MatchResult, RegExPatternExtended -from osw.utils.regex_pattern import REGEX_PATTERN_LIB, REGEX_PATTERN_LIST +from osw.utils.regex_pattern import REGEX_PATTERN_LIB from osw.wtsite import WtSite # Constants -PACKAGE_ROOT_PATH = Path(__file__).parents[2] -CREDENTIALS_FILE_PATH_DEFAULT = PACKAGE_ROOT_PATH / "examples" / "accounts.pwd.yaml" ENABLE_SORTING = True -# For compatibility with the old version of the module -REGEX_PATTERN = {rep.description: rep.dict() for rep in REGEX_PATTERN_LIST} # Classes @@ -879,7 +876,7 @@ def translate_list_with_deepl( ) -> dict: """Translates a list of strings with DeepL.""" if credentials_file_path is None: - credentials_file_path = CREDENTIALS_FILE_PATH_DEFAULT + credentials_file_path = default_paths.cred_fp if translations is None: translations = {} domains, accounts = wt.read_domains_from_credentials_file(credentials_file_path) diff --git a/src/osw/defaults.py b/src/osw/defaults.py new file mode 100644 index 00000000..8b396f78 --- /dev/null +++ b/src/osw/defaults.py @@ -0,0 +1,154 @@ +from __future__ import annotations + +import re +from pathlib import Path +from typing import List, Union + +from pydantic.v1 import PrivateAttr, validator + +from osw.model.static import OswBaseModel + +PACKAGE_ROOT_PATH = Path(__file__).parents[1] +BASE_PATH = Path.cwd() +OSW_FILES_DIR_DEFAULT = BASE_PATH / "osw_files" +DOWNLOAD_DIR_DEFAULT = OSW_FILES_DIR_DEFAULT / "downloads" +CREDENTIALS_FN_DEFAULT = "credentials.pwd.yaml" +CREDENTIALS_FP_DEFAULT = OSW_FILES_DIR_DEFAULT / CREDENTIALS_FN_DEFAULT +WIKI_DOMAIN_DEFAULT = "wiki.open-semantic-lab.org" + + +class FilePathDefault(OswBaseModel): + """A class to store the default file path. This is a helper class to make the + default file path, defined within this module, accessible from a calling script.""" + + _default: Union[Path] = PrivateAttr(BASE_PATH) + + class Config: + arbitrary_types_allowed = True + + def __init__(self, path: Union[str, Path] = BASE_PATH): + data = {"_default": Path(path) if isinstance(path, str) else path} + super().__init__(**data) + + def __str__(self): + return str(self.path) + + def __repr__(self): + return f"FilePathDefault(path={self.path})" + + def __eq__(self, other): + other_path = getattr(other, "path", None) + if other_path is None: + return False + + @property + def path(self): + return self._default + + def set(self, new: Union[str, Path]): + self._default = Path(new) if isinstance(new, str) else new + + def get(self): + return self._default + + +class Paths(OswBaseModel): + """A class to store the default paths. This is a helper class to make the default + paths, defined within this module, accessible from a calling script.""" + + base: Path = BASE_PATH + """If you want to have the sub folders created in an directory that is not the + current working directory of the calling script, use Path.base = new_path.""" + osw_files_dir: Path = OSW_FILES_DIR_DEFAULT + """If you want to specify the default OSW files directory, use + Path.osw_files_dir = new_path.""" + cred_fp: Path = CREDENTIALS_FP_DEFAULT + """If you want to specify the saving location of the credentials file, use + Path.cred_fp = new_path.""" + download_dir: Path = DOWNLOAD_DIR_DEFAULT + """If you want to specify the default download directory, use + Path.download_dir = new_path.""" + _changed: List[str] = PrivateAttr(default_factory=list) + """A flag to indicate if any of the paths have been changed.""" + + def __setattr__(self, name, value): + old_value = getattr(self, name) + super().__setattr__(name, value) + self.on_attribute_set(name, value, old_value) + if name not in self._changed: + self._changed.append(name) + + def has_changed(self, name): + return name in self._changed + + def on_attribute_set(self, attr_name, new_value, old_value): + """ + This method is called every time an attribute is set. It is used to update the + paths that are dependent on the [base, osw_files_dir] path when the + [base, osw_files_dir] path is changed. + + Parameters + ---------- + attr_name: + The name of the attribute that was set + new_value + The new value the attribute was set to + old_value + The value the attribute had before it was set + """ + + def update_attr(set_attr, to_update, old_val, new_val): + for attr_name in to_update: + if old_val in getattr(self, attr_name).parents: + old_rel_path = getattr(self, attr_name).relative_to(old_val) + new_rel_path = new_val / old_rel_path + setattr(self, attr_name, new_rel_path) + print( + f"Following the setting of {self.__name__}.{set_attr}, " + f"{self.__name__}.{attr_name} was updated to {new_rel_path}." + ) + + if attr_name == "base": + update_attr( + "base", + ["osw_files_dir", "cred_fp", "download_dir"], + old_value, + new_value, + ) + elif attr_name == "osw_files_dir": + update_attr( + "osw_files_dir", ["cred_fp", "download_dir"], old_value, new_value + ) + + +# Create an instance of the Paths class to make the default paths accessible from a +# calling script. +paths = Paths() +"""To overwrite a default path, execute, e.g.,: paths.base = new_path""" + + +class Params(OswBaseModel): + """A class to store the default parameters. This is a helper class to make the + default parameters, defined within this module, accessible from a calling script.""" + + wiki_domain: str = WIKI_DOMAIN_DEFAULT + """The default domain of the OSW instance to interact with.""" + _changed: List[str] = PrivateAttr(default_factory=list) + """A flag to indicate if any of the parameters have been changed.""" + + @validator("wiki_domain") + def validate_wiki_domain(cls, v): + pattern = r"^(?!-)[A-Za-z0-9.-]{1,63}(? Dict[str, Any]: # set by the source file controller del data["label"] if data.get("cred_filepath") is None: - data["cred_filepath"] = cred_filepath_default.get_default() + data["cred_filepath"] = default_paths.cred_fp if not data.get("cred_filepath").parent.exists(): data["cred_filepath"].parent.mkdir(parents=True) if data.get("cred_mngr") is None: @@ -645,7 +571,7 @@ def __init__(self, url_or_title, **data): if data.get("target_fn") is None: data["target_fn"] = url_or_title.split("File:")[-1] if data.get("target_dir") is None: - data["target_dir"] = download_dir_default.get_default() + data["target_dir"] = default_paths.download_dir if isinstance(data.get("target_dir"), str): data["target_dir"] = Path(data.get("target_dir")) if data.get("target_fp") is None: diff --git a/src/osw/params.py b/src/osw/params.py index 4130734b..6be389f9 100644 --- a/src/osw/params.py +++ b/src/osw/params.py @@ -5,13 +5,7 @@ AddOverwriteClassOptions, OverwriteOptions, ) -from osw.express import ( # noqa: F401 - CredentialsFpDefault, - DataModel, - DownloadDirDefault, - FilePathDefault, - OswExpress, -) +from osw.express import DataModel, OswExpress # noqa: F401 from osw.wiki_tools import SearchParam # noqa: F401 from osw.wtsite import WtPage, WtSite # noqa: F401 diff --git a/tests/integration/test_express.py b/tests/integration/test_express.py index 688ad38f..b6e7a294 100644 --- a/tests/integration/test_express.py +++ b/tests/integration/test_express.py @@ -79,7 +79,7 @@ def test_init_with_domain(wiki_domain, wiki_username, wiki_password, mocker): mocked_getpass.return_value = wiki_password osw_express = osw.express.OswExpress(domain=wiki_domain) osw_express_and_credentials(osw_express, wiki_domain, wiki_username, wiki_password) - assert osw_express.cred_filepath == Path(osw.express.cred_filepath_default.default) + assert osw_express.cred_filepath == Path(osw.express.default_paths.cred_fp) osw_express.shut_down() osw_express.cred_filepath.unlink() From 9493f0103d3ed194747d4b647c012c61513312b6 Mon Sep 17 00:00:00 2001 From: Lukas Gold Date: Wed, 27 Nov 2024 16:09:21 +0100 Subject: [PATCH 5/7] Using ModelField.get_default() instead of accessing ._default or .default --- src/osw/core.py | 6 +++--- src/osw/data/import_utility.py | 6 +++--- src/osw/express.py | 7 ++++--- tests/integration/test_file_page_migration.py | 2 +- 4 files changed, 11 insertions(+), 10 deletions(-) diff --git a/src/osw/core.py b/src/osw/core.py index d8b51115..9ddc37ec 100644 --- a/src/osw/core.py +++ b/src/osw/core.py @@ -163,7 +163,7 @@ def sort_list_of_entities_by_class( model_type = None else: # Get class type if available - model_type = entity.__class__.__fields__["type"].default[0] + model_type = entity.__class__.__fields__["type"].get_default()[0] # Add entity to by_name if name not in by_name: by_name[name] = [] @@ -1016,12 +1016,12 @@ def __init__(self, **data): True # Set to True after implementation of asynchronous upload ) if self.overwrite is None: - self.overwrite = self.__fields__["overwrite"].default + self.overwrite = self.__fields__["overwrite"].get_default() self._overwrite_per_class = {"by name": {}, "by type": {}} if self.overwrite_per_class is not None: for param in self.overwrite_per_class: model_name = param.model.__name__ - model_type = param.model.__fields__["type"].default[0] + model_type = param.model.__fields__["type"].get_default()[0] if ( model_name in self._overwrite_per_class["by name"].keys() or model_type in self._overwrite_per_class["by type"].keys() diff --git a/src/osw/data/import_utility.py b/src/osw/data/import_utility.py index ff02e3d6..c12ec996 100644 --- a/src/osw/data/import_utility.py +++ b/src/osw/data/import_utility.py @@ -174,7 +174,7 @@ def transform_attributes_and_merge( sorted_ = ent_as_dict["sorted"] else: sorted_ = False - cls_type_str = str(sel_cls.__fields__["type"].default) + cls_type_str = str(sel_cls.__fields__["type"].get_default()) # Merge entries with the same name / uuid entities_copy = copy.deepcopy(ent) # Copy to loop over @@ -295,7 +295,7 @@ def isclass(obj, cls): obj_type = obj.get("type") else: obj_type = getattr(obj, "type", None) - cls_type = cls.__fields__["type"].default + cls_type = cls.__fields__["type"].get_default() if isinstance(obj_type, list): obj_type.sort() if isinstance(cls_type, list): @@ -405,7 +405,7 @@ def jsonpath_search_and_return_list( if sorted_ and class_to_match: # See definition in loop_and_call_method with argument 'sorted' try: - cls_type = class_to_match.__fields__["type"].default + cls_type = class_to_match.__fields__["type"].get_default() # Search in a dramatically reduced number of entries result = jp_parse.find(search_tar[str(cls_type)]) except Exception as e: diff --git a/src/osw/express.py b/src/osw/express.py index b5de91be..b06e39f3 100644 --- a/src/osw/express.py +++ b/src/osw/express.py @@ -514,9 +514,10 @@ def process_init_data(self, data: Dict[str, Any]) -> Dict[str, Any]: data[key] = value # Do replacements if ( - data.get("label") == InMemoryController.__fields__["label"].default - or data.get("label") == LocalFileController.__fields__["label"].default - or data.get("label") == WikiFileController.__fields__["label"].default + data.get("label") == InMemoryController.__fields__["label"].get_default() + or data.get("label") + == LocalFileController.__fields__["label"].get_default() + or data.get("label") == WikiFileController.__fields__["label"].get_default() ): # Make sure that the label is not set to the default value, it will be # set by the source file controller diff --git a/tests/integration/test_file_page_migration.py b/tests/integration/test_file_page_migration.py index bd381d6a..c9e1e2a3 100644 --- a/tests/integration/test_file_page_migration.py +++ b/tests/integration/test_file_page_migration.py @@ -115,7 +115,7 @@ def test_file_page_migration(wiki_domain: str, wiki_username: str, wiki_password raise ValueError( "jsondata is None - meta data was not written to the file " "page!" ) - assert jsondata["type"] == WikiFile.__fields__["type"].default + assert jsondata["type"] == WikiFile.__fields__["type"].get_default() modified_using_page = wtsite.get_page( WtSite.GetPageParam(titles=[using_page_fpt]) ).pages[0] From 83b7ce3656b9cb0dfaebb922f5173194a77370b4 Mon Sep 17 00:00:00 2001 From: Lukas Gold Date: Wed, 27 Nov 2024 16:15:27 +0100 Subject: [PATCH 6/7] Properly deactivating test_statement_creation --- tests/integration/store_and_load_test.py | 66 ++++++++++++------------ 1 file changed, 34 insertions(+), 32 deletions(-) diff --git a/tests/integration/store_and_load_test.py b/tests/integration/store_and_load_test.py index 9b9543a6..d172b1da 100644 --- a/tests/integration/store_and_load_test.py +++ b/tests/integration/store_and_load_test.py @@ -1,12 +1,13 @@ import sys from pathlib import Path +import pytest + import osw.model.entity as model from osw.auth import CredentialManager from osw.core import OSW, AddOverwriteClassOptions, OverwriteOptions from osw.utils.wiki import get_full_title - -# from osw.wiki_tools import SearchParam +from osw.wiki_tools import SearchParam from osw.wtsite import WtSite # run with: tox -e test -- --wiki_domain domain --wiki_username user --wiki_password pass @@ -142,36 +143,37 @@ def test_query_instances(wiki_domain, wiki_username, wiki_password): osw.delete_entity(my_item) -# def test_statement_creation(wiki_domain, wiki_username, wiki_password): -# cm = CredentialManager() -# cm.add_credential( -# CredentialManager.UserPwdCredential( -# iri=wiki_domain, username=wiki_username, password=wiki_password -# ) -# ) -# wtsite = WtSite(WtSite.WtSiteConfig(iri=wiki_domain, cred_mngr=cm)) -# osw = OSW(site=wtsite) -# -# my_entity = model.Item( -# label=[model.Label(text="MyItem")], -# statements=[ -# model.DataStatement(property="Property:TestProperty", value="TestValue") -# ], -# ) -# -# osw.store_entity(my_entity) -# -# search_param = SearchParam(query="[[TestProperty::TestValue]]") -# full_page_titles = osw.site.semantic_search(search_param) -# assert f"Item:{OSW.get_osw_id(my_entity.uuid)}" in full_page_titles -# -# search_param = SearchParam( -# query="[[HasStatement.HasProperty::Property:TestProperty]]" -# ) -# full_page_titles = osw.site.semantic_search(search_param) -# assert f"Item:{OSW.get_osw_id(my_entity.uuid)}" in full_page_titles -# -# osw.delete_entity(my_entity) +@pytest.mark.skip(reason="Temporarily disabled - Failing due to unresolved error") +def test_statement_creation(wiki_domain, wiki_username, wiki_password): + cm = CredentialManager() + cm.add_credential( + CredentialManager.UserPwdCredential( + iri=wiki_domain, username=wiki_username, password=wiki_password + ) + ) + wtsite = WtSite(WtSite.WtSiteConfig(iri=wiki_domain, cred_mngr=cm)) + osw = OSW(site=wtsite) + + my_entity = model.Item( + label=[model.Label(text="MyItem")], + statements=[ + model.DataStatement(property="Property:TestProperty", value="TestValue") + ], + ) + + osw.store_entity(my_entity) + + search_param = SearchParam(query="[[TestProperty::TestValue]]") + full_page_titles = osw.site.semantic_search(search_param) + assert f"Item:{OSW.get_osw_id(my_entity.uuid)}" in full_page_titles + + search_param = SearchParam( + query="[[HasStatement.HasProperty::Property:TestProperty]]" + ) + full_page_titles = osw.site.semantic_search(search_param) + assert f"Item:{OSW.get_osw_id(my_entity.uuid)}" in full_page_titles + + osw.delete_entity(my_entity) def test_characteristic_creation(wiki_domain, wiki_username, wiki_password): From 1af371174dc14271a0837470221d0ec35c6da89a Mon Sep 17 00:00:00 2001 From: Lukas Gold Date: Wed, 27 Nov 2024 16:23:23 +0100 Subject: [PATCH 7/7] Adapting the basic tutorial for the use of osw.defaults --- docs/tutorials/basics.ipynb | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/docs/tutorials/basics.ipynb b/docs/tutorials/basics.ipynb index 3fc32974..0a253c85 100644 --- a/docs/tutorials/basics.ipynb +++ b/docs/tutorials/basics.ipynb @@ -313,10 +313,25 @@ ], "id": "137e9b3144a4db96" }, + { + "metadata": {}, + "cell_type": "code", + "outputs": [], + "execution_count": null, + "source": [ + "# Define the wiki_domain for later reuse:\n", + "wiki_domain = \"demo.open-semantic-lab.org\" # Replace with the domain of your OSL instance" + ], + "id": "ad9ed6244dc16547" + }, { "metadata": {}, "cell_type": "code", "source": [ + "# Set the default wiki domain for the osw package\n", + "from osw.defaults import params as default_params\n", + "default_params.wiki_domain = wiki_domain\n", + "# Now this domain will be used to initialize osw.express\n", "from osw.express import OswExpress\n", "# Some modules that will be required several times\n", "import osw.params as prm\n", @@ -328,17 +343,6 @@ "outputs": [], "execution_count": null }, - { - "metadata": {}, - "cell_type": "code", - "outputs": [], - "execution_count": null, - "source": [ - "# Define the wiki_domain for later reuse:\n", - "wiki_domain = \"demo.open-semantic-lab.org\" # Replace with the domain of your OSL instance" - ], - "id": "7d0db4de67f448b9" - }, { "metadata": {}, "cell_type": "markdown",