diff --git a/.gitignore b/.gitignore index 55fb3f0d1bc6c101704557da8f35d6e784b5ea89..d286b519f9713c5b89ed8f0e88b3bbcf81b3e52f 100644 --- a/.gitignore +++ b/.gitignore @@ -12,7 +12,7 @@ __pycache__/ *.egg-info/ dist/ build/ -src/caosdb/version.py +src/linkahead/version.py # documentation _apidoc diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 240175315b4acdc373129c7d112af71bb38565b2..17f40608d95467f7c040205c0447c7aae270cf37 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -22,6 +22,7 @@ variables: DEPLOY_REF: dev + # TODO rename to linkahead CI_REGISTRY_IMAGE: $CI_REGISTRY/caosdb/src/caosdb-pylib/testenv:latest # When using dind, it's wise to use the overlayfs driver for # improved performance. @@ -44,7 +45,7 @@ code_style: - make style allow_failure: true -# pylint tests for pycaosdb +# pylint tests for pylinkahead pylint: tags: [ docker ] stage: linting @@ -61,7 +62,7 @@ unittest_py3.7: image: python:3.7 script: &python_test_script # Python docker has problems with tox and pip so use plain pytest here - - touch ~/.pycaosdb.ini + - touch ~/.pylinkahead.ini - pip install nose pytest pytest-cov python-dateutil jsonschema>=4.4.0 - pip install . - python -m pytest unittests @@ -82,7 +83,7 @@ unittest_py3.9: script: # verify that this actually is Python 3.9 - python3 -c "import sys; assert sys.version.startswith('3.9')" - - touch ~/.pycaosdb.ini + - touch ~/.pylinkahead.ini - make unittest @@ -115,6 +116,7 @@ trigger_build: TRIGGERED_BY_HASH: $CI_COMMIT_SHORT_SHA trigger: + # TODO Rename to linkahead project: caosdb/src/caosdb-deploy branch: $DEPLOY_REF strategy: depend diff --git a/src/linkahead/__init__.py b/src/linkahead/__init__.py index 0bc70972495f63a1a9a9fde12c817a18b64fb492..25346aefba1dc704c33bb9e9f7251c56006fbb2a 100644 --- a/src/linkahead/__init__.py +++ b/src/linkahead/__init__.py @@ -22,11 +22,12 @@ # ** end header # -"""CaosDB Python bindings. +"""LinkAhead Python bindings. + +Tries to read from the inifile specified in the environment variable `PYLINKAHEADINI` or +alternatively in `~/.pylinkahead.ini` upon import. After that, the ini file `pylinkahead.ini` in +the current working directory will be read additionally, if it exists. -Tries to read from the inifile specified in the environment variable `PYCAOSDBINI` or alternatively -in `~/.pycaosdb.ini` upon import. After that, the ini file `pycaosdb.ini` in the current working -directory will be read additionally, if it exists. """ from os import environ, getcwd @@ -37,15 +38,15 @@ from os.path import expanduser, join import linkahead.apiutils from linkahead.common import administration from linkahead.common.datatype import (BOOLEAN, DATETIME, DOUBLE, FILE, INTEGER, - LIST, REFERENCE, TEXT) + LIST, REFERENCE, TEXT) from linkahead.common.state import State, Transition # Import of the basic API classes: from linkahead.common.models import (ACL, ALL, FIX, NONE, OBLIGATORY, RECOMMENDED, - SUGGESTED, Container, DropOffBox, Entity, - File, Info, Message, Permissions, Property, - Query, QueryTemplate, Record, RecordType, - delete, execute_query, get_global_acl, - get_known_permissions, raise_errors) + SUGGESTED, Container, DropOffBox, Entity, + File, Info, Message, Permissions, Property, + Query, QueryTemplate, Record, RecordType, + delete, execute_query, get_global_acl, + get_known_permissions, raise_errors) from linkahead.utils.get_entity import get_entity_by_name, get_entity_by_path, get_entity_by_id from linkahead.configuration import _read_config_files, configure, get_config from linkahead.connection.connection import configure_connection, get_connection diff --git a/src/linkahead/apiutils.py b/src/linkahead/apiutils.py index c522e34e173713905ef9f3c1324fc429f82f6bd2..d7d93dba3508a9b4fb1aaf7152cac3c1a85cbeb1 100644 --- a/src/linkahead/apiutils.py +++ b/src/linkahead/apiutils.py @@ -36,16 +36,16 @@ from subprocess import call from typing import Optional, Any, Dict, List from linkahead.common.datatype import (BOOLEAN, DATETIME, DOUBLE, FILE, INTEGER, - REFERENCE, TEXT, is_reference) + REFERENCE, TEXT, is_reference) from linkahead.common.models import (Container, Entity, File, Property, Query, - Record, RecordType, execute_query, - get_config, SPECIAL_ATTRIBUTES) -from linkahead.exceptions import CaosDBException + Record, RecordType, execute_query, + get_config, SPECIAL_ATTRIBUTES) +from linkahead.exceptions import LinkAheadException logger = logging.getLogger(__name__) -class EntityMergeConflictError(CaosDBException): +class EntityMergeConflictError(LinkAheadException): """An error that is raised in case of an unresolvable conflict when merging two entities. """ @@ -116,7 +116,7 @@ def get_type_of_entity_with(id_): if len(objs) > 1: raise RuntimeError( - "ID {} is not unique. This is probably a bug in the CaosDB server." .format(id_)) + "ID {} is not unique. This is probably a bug in the LinkAhead server." .format(id_)) obj = objs[0] if isinstance(obj, Record): @@ -456,7 +456,7 @@ def merge_entities(entity_a: Entity, entity_b: Entity, merge_references_with_emp f"{diff_r1['properties'][key][attribute]}") else: # TODO: This is a temporary FIX for - # https://gitlab.indiscale.com/caosdb/src/caosdb-pylib/-/issues/105 + # https://gitlab.indiscale.com/caosdb/src/linkahead-pylib/-/issues/105 entity_a.add_property(id=entity_b.get_property(key).id, name=entity_b.get_property(key).name, datatype=entity_b.get_property(key).datatype, diff --git a/src/linkahead/cached.py b/src/linkahead/cached.py index 33124d61ce5f86da362127aa3fde516088dd6b19..238af2ab1963e8ddbcfe88a17c3ebd33220799a4 100644 --- a/src/linkahead/cached.py +++ b/src/linkahead/cached.py @@ -85,7 +85,7 @@ If a query phrase is given, the result must be unique. If this is not what you def cached_query(query_string) -> Container: - """A cached version of :func:`caosdb.execute_query<caosdb.common.models.execute_query>`. + """A cached version of :func:`linkahead.execute_query<linkahead.common.models.execute_query>`. All additional arguments are at their default values. @@ -160,8 +160,8 @@ kind: AccessType, optional unique: bool, optional If True, fills the cache for :func:`cached_get_entity_by`, presumably with - :class:`caosdb.Entity<caosdb.common.models.Entity>` objects. If False, the cache should be filled - with :class:`caosdb.Container<caosdb.common.models.Container>` objects, for use with + :class:`linkahead.Entity<linkahead.common.models.Entity>` objects. If False, the cache should be + filled with :class:`linkahead.Container<linkahead.common.models.Container>` objects, for use with :func:`cached_query`. """ diff --git a/src/linkahead/common/__init__.py b/src/linkahead/common/__init__.py index 436281df8077b2cbf357537d36b21567b86ea5a2..f74e0da15952a3ed0bea2b3f3ebffe1cb5754cc4 100644 --- a/src/linkahead/common/__init__.py +++ b/src/linkahead/common/__init__.py @@ -1 +1 @@ -"""Commonly used classes for CaosDB.""" +"""Commonly used classes for LinkAhead.""" diff --git a/src/linkahead/common/administration.py b/src/linkahead/common/administration.py index 12c738f1532d2fc67b3da4315264b3429c5fea31..c23a61a559b5f6f5d7b782743baadbc34b3f62fb 100644 --- a/src/linkahead/common/administration.py +++ b/src/linkahead/common/administration.py @@ -134,7 +134,7 @@ def generate_password(length: int): """ minimum_password_length = 8 if length < minimum_password_length: - raise ValueError("CaosDB passwords have to be at least {} characters.".format( + raise ValueError("LinkAhead passwords have to be at least {} characters.".format( minimum_password_length)) sample_letters = string.ascii_letters + string.digits + "!#$%*+-/:;?_" password = ''.join((random.choice(sample_letters) for i in range(length))) diff --git a/src/linkahead/common/models.py b/src/linkahead/common/models.py index 7b6db6d8903788dfa34f4f6a19691df9d214c414..38a327a9077b0f65b28ab4d7195b62485f72d755 100644 --- a/src/linkahead/common/models.py +++ b/src/linkahead/common/models.py @@ -26,7 +26,7 @@ # """ -Collection of the central classes of the CaosDB client, namely the Entity class +Collection of the central classes of the LinkAhead client, namely the Entity class and all of its subclasses and the Container class which is used to carry out transactions. @@ -50,7 +50,7 @@ from tempfile import NamedTemporaryFile from warnings import warn from linkahead.common.datatype import (BOOLEAN, DATETIME, DOUBLE, INTEGER, TEXT, - is_list_datatype, is_reference) + is_list_datatype, is_reference) from linkahead.common.state import State from linkahead.common.utils import uuid, xml2str from linkahead.common.timezone import TimeZone @@ -59,14 +59,14 @@ from linkahead.configuration import get_config from linkahead.connection.connection import get_connection from linkahead.connection.encode import MultipartParam, multipart_encode from linkahead.exceptions import (AmbiguousEntityError, AuthorizationError, - CaosDBConnectionError, CaosDBException, - ConsistencyError, EmptyUniqueQueryError, - EntityDoesNotExistError, EntityError, - EntityHasNoDatatypeError, HTTPURITooLongError, - MismatchingEntitiesError, QueryNotUniqueError, - TransactionError, UniqueNamesError, - UnqualifiedParentsError, - UnqualifiedPropertiesError) + LinkAheadConnectionError, LinkAheadException, + ConsistencyError, EmptyUniqueQueryError, + EntityDoesNotExistError, EntityError, + EntityHasNoDatatypeError, HTTPURITooLongError, + MismatchingEntitiesError, QueryNotUniqueError, + TransactionError, UniqueNamesError, + UnqualifiedParentsError, + UnqualifiedPropertiesError) from lxml import etree _ENTITY_URI_SEGMENT = "Entity" @@ -86,7 +86,7 @@ SPECIAL_ATTRIBUTES = ["name", "role", "datatype", "description", class Entity: - """Entity is a generic CaosDB object. + """Entity is a generic LinkAhead object. The majority of all methods of the derived classes (e.g. Record, RecordType, Property ...) are defined here, e.g. add_property, @@ -560,7 +560,7 @@ class Entity: >>> rec.add_property(name="OtherRT", value=ref_rec) # or value=ref_rec.id if ref_rec has one set by the server See more on adding properties and inserting data in - https://docs.indiscale.com/caosdb-pylib/tutorials/Data-Insertion.html. + https://docs.linkahead.org/linkahead-pylib/tutorials/Data-Insertion.html. """ @@ -1305,7 +1305,7 @@ out: List[Entity] returns a Container containing the this entity. Note: If only a name is given this could lead to ambiguities. Usually - this would raise a CaosDBException. Set the flag 'unique' to False if + this would raise a LinkAheadException. Set the flag 'unique' to False if this Exception should be suppressed. If unique is False this method returns a Container object which carries the returned entities. They are distinct from this one. This entity will no be changed somehow. @@ -1334,12 +1334,12 @@ out: List[Entity] def insert(self, raise_exception_on_error=True, unique=True, sync=True, strict=False, flags=None): - """Insert this entity into a CaosDB server. A successful insertion will + """Insert this entity into a LinkAhead server. A successful insertion will generate a new persistent ID for this entity. This entity can be identified, retrieved, updated, and deleted via this ID until it has been deleted. - If the insertion fails, a CaosDBException will be raised. The server will have returned at + If the insertion fails, a LinkAheadException will be raised. The server will have returned at least one error-message describing the reason why it failed in that case (call <this_entity>.get_all_messages() in order to get these error-messages). @@ -1391,7 +1391,7 @@ Second: and attributes, which is not possible via the second one for internal reasons (which are reasons of definiteness). - If the update fails, a CaosDBException will be raised. The server will have returned at + If the update fails, a LinkAheadException will be raised. The server will have returned at least one error message describing the reason why it failed in that case (call <this_entity>.get_all_messages() in order to get these error-messages). @@ -1715,7 +1715,7 @@ class _ConcreteProperty(_EntityWrapper): class Property(Entity): - """CaosDB's Property object.""" + """LinkAhead's Property object.""" def add_property(self, property=None, value=None, id=None, name=None, description=None, datatype=None, unit=None, importance=FIX, inheritance=FIX): # @ReservedAssignment @@ -1849,7 +1849,7 @@ class Message(object): class RecordType(Entity): - """This class represents CaosDB's RecordType entities.""" + """This class represents LinkAhead's RecordType entities.""" def add_property(self, property=None, value=None, id=None, name=None, description=None, datatype=None, unit=None, importance=RECOMMENDED, inheritance=FIX): # @ReservedAssignment @@ -1905,7 +1905,7 @@ class RecordType(Entity): class Record(Entity): - """This class represents CaosDB's Record entities.""" + """This class represents LinkAhead's Record entities.""" def add_property(self, property=None, value=None, id=None, name=None, description=None, datatype=None, unit=None, importance=FIX, inheritance=FIX): # @ReservedAssignment @@ -1928,7 +1928,7 @@ class Record(Entity): class File(Record): - """This class represents CaosDB's file entities. + """This class represents LinkAhead's file entities. For inserting a new file to the server, `path` gives the new location, and (exactly?) one of `file` and `pickup` should (must?) be given to specify the @@ -1944,11 +1944,11 @@ class File(Record): @param id: An ID. @param description: A description for this file record. @param path: The complete path, including the file name, of the file in the - server's "caosroot" file system. + server's "linkaheadroot" file system. @param file: A local path or python file object. The file designated by this argument will be uploaded to the server via HTTP. @param pickup: A file/folder in the DropOffBox (the server will move that - file into its "caosroot" file system). + file into its "linkaheadroot" file system). @param thumbnail: (Local) filename to a thumbnail for this file. @param properties: A list of properties for this file record. @todo is this implemented? @@ -2095,7 +2095,7 @@ class _Properties(list): self._importance[property] = importance def get_by_name(self, name): - """Get a property of this list via it's name. Raises a CaosDBException + """Get a property of this list via it's name. Raises a LinkAheadException if not exactly one property has this name. @param name: the name of the property to be returned. @@ -2998,7 +2998,7 @@ class Container(list): return c else: - raise CaosDBException( + raise LinkAheadException( "The server's response didn't contain the expected elements. The configuration of this client might be invalid (especially the url).") def _sync(self, container, unique, raise_exception_on_error, @@ -3198,7 +3198,7 @@ class Container(list): """This function returns those elements of a given container that are a dependency of another element of the same container. Args: - container (Container): a caosdb container + container (Container): a linkahead container Returns: [set]: a set of unique elements that are a dependency of another element of `container` @@ -3366,7 +3366,7 @@ class Container(list): properties and parents will be synchronized as well. They will not be overridden. This method returns a Container containing the this entity. - If any entity has no id and no name a CaosDBException will be raised. + If any entity has no id and no name a LinkAheadException will be raised. Note: If only a name is given this could lead to ambiguities. All entities with the name in question will be returned. Therefore, the container could contain more elements after the retrieval than @@ -3613,12 +3613,12 @@ class Container(list): def insert(self, strict=False, raise_exception_on_error=True, unique=True, sync=True, flags=None): - """Insert this file entity into CaosDB. A successful insertion will + """Insert this file entity into LinkAhead. A successful insertion will generate a new persistent ID for this entity. This entity can be identified, retrieved, updated, and deleted via this ID until it has been deleted. - If the insertion fails, a CaosDBException will be raised. The server will have returned at + If the insertion fails, a LinkAheadException will be raised. The server will have returned at least one error-message describing the reason why it failed in that case (call <this_entity>.get_all_messages() in order to get these error-messages). @@ -3849,7 +3849,7 @@ def sync_global_acl(): if pelem.tag == "EntityACL": ACL.global_acl = ACL(xml=pelem) else: - raise CaosDBException( + raise LinkAheadException( "The server's response didn't contain the expected elements. The configuration of this client might be invalid (especially the url).") @@ -4447,7 +4447,7 @@ class Info(): c = get_connection() try: http_response = c.retrieve(["Info"]) - except CaosDBConnectionError as conn_e: + except LinkAheadConnectionError as conn_e: print(conn_e) return @@ -4466,14 +4466,14 @@ class Info(): def __str__(self): if "counts" not in self.messages: - return "caosdb.Info" + return "linkahead.Info" if int(self.messages["counts"]["records"]) > 0: - return "Connection to CaosDB with {} Records." .format( + return "Connection to LinkAhead with {} Records." .format( self.messages["counts"]["records"] ) else: - return "Connection to CaosDB without Records." + return "Connection to LinkAhead without Records." def __repr__(self): return self.__str__() @@ -4714,7 +4714,7 @@ def raise_errors(arg0): Parameters: ----------- arg0 : Entity, QueryTemplate, or Container - CaosDB object whose messages are evaluated according to their + LinkAhead object whose messages are evaluated according to their error codes """ diff --git a/src/linkahead/configuration.py b/src/linkahead/configuration.py index fcceba1a919974dcaefd68019738bcf017edb4cf..d5ec414141126f2bf85e6563ebf53742f31e3e82 100644 --- a/src/linkahead/configuration.py +++ b/src/linkahead/configuration.py @@ -38,8 +38,8 @@ from os.path import expanduser, join, isfile def _reset_config(): - global _pycaosdbconf - _pycaosdbconf = ConfigParser(allow_no_value=False) + global _pylinkaheadconf + _pylinkaheadconf = ConfigParser(allow_no_value=False) def configure(inifile): @@ -47,24 +47,24 @@ def configure(inifile): Return a list of files which have successfully been parsed. """ - global _pycaosdbconf - if "_pycaosdbconf" not in globals(): - _pycaosdbconf = None - if _pycaosdbconf is None: + global _pylinkaheadconf + if "_pylinkaheadconf" not in globals(): + _pylinkaheadconf = None + if _pylinkaheadconf is None: _reset_config() - read_config = _pycaosdbconf.read(inifile) - validate_yaml_schema(config_to_yaml(_pycaosdbconf)) + read_config = _pylinkaheadconf.read(inifile) + validate_yaml_schema(config_to_yaml(_pylinkaheadconf)) if "HTTPS_PROXY" in environ: - _pycaosdbconf["Connection"]["https_proxy"] = environ["HTTPS_PROXY"] + _pylinkaheadconf["Connection"]["https_proxy"] = environ["HTTPS_PROXY"] if "HTTP_PROXY" in environ: - _pycaosdbconf["Connection"]["http_proxy"] = environ["HTTP_PROXY"] + _pylinkaheadconf["Connection"]["http_proxy"] = environ["HTTP_PROXY"] return read_config def get_config(): - global _pycaosdbconf - return _pycaosdbconf + global _pylinkaheadconf + return _pylinkaheadconf def config_to_yaml(config): @@ -85,9 +85,9 @@ def config_to_yaml(config): def validate_yaml_schema(valobj): if optional_jsonschema_validate: - with open(os.path.join(os.path.dirname(__file__), "schema-pycaosdb-ini.yml")) as f: + with open(os.path.join(os.path.dirname(__file__), "schema-pylinkahead-ini.yml")) as f: schema = yaml.load(f, Loader=yaml.SafeLoader) - optional_jsonschema_validate(instance=valobj, schema=schema["schema-pycaosdb-ini"]) + optional_jsonschema_validate(instance=valobj, schema=schema["schema-pylinkahead-ini"]) else: warnings.warn(""" Warning: The validation could not be performed because `jsonschema` is not installed. @@ -97,8 +97,8 @@ def validate_yaml_schema(valobj): def _read_config_files(): """Function to read config files from different paths. - Checks for path either in ``$PYCAOSDBINI`` or home directory (``.pycaosdb.ini``), and - additionally in the current working directory (``pycaosdb.ini``). + Checks for path either in ``$PYLINKAHEADINI`` or home directory (``.pylinkahead.ini``), and + additionally in the current working directory (``pylinkahead.ini``). Returns ------- @@ -108,11 +108,11 @@ def _read_config_files(): """ return_var = [] - if "PYCAOSDBINI" in environ: - return_var.extend(configure(expanduser(environ["PYCAOSDBINI"]))) + if "PYLINKAHEADINI" in environ: + return_var.extend(configure(expanduser(environ["PYLINKAHEADINI"]))) else: - return_var.extend(configure(expanduser('~/.pycaosdb.ini'))) + return_var.extend(configure(expanduser('~/.pylinkahead.ini'))) - if isfile(join(getcwd(), "pycaosdb.ini")): - return_var.extend(configure(join(getcwd(), "pycaosdb.ini"))) + if isfile(join(getcwd(), "pylinkahead.ini")): + return_var.extend(configure(join(getcwd(), "pylinkahead.ini"))) return return_var diff --git a/src/linkahead/connection/authentication/auth_token.py b/src/linkahead/connection/authentication/auth_token.py index 761abcc7e0481cb5220af2712a26831d5e5540f3..87e2ec58345f8b1ebb67082c9b9ea6250d5f5788 100644 --- a/src/linkahead/connection/authentication/auth_token.py +++ b/src/linkahead/connection/authentication/auth_token.py @@ -28,7 +28,7 @@ An Authentictor which only uses only a pre-supplied authentication token. """ from __future__ import absolute_import, unicode_literals, print_function -from .interface import AbstractAuthenticator, CaosDBServerConnection +from .interface import AbstractAuthenticator, LinkAheadServerConnection from linkahead.connection.utils import auth_token_to_cookie from linkahead.exceptions import LoginFailedError @@ -90,7 +90,7 @@ class AuthTokenAuthenticator(AbstractAuthenticator): self.auth_token = config["auth_token"] if "connection" in config: self._connection = config["connection"] - if not isinstance(self._connection, CaosDBServerConnection): - raise Exception("""Bad configuration of the caosdb connection. + if not isinstance(self._connection, LinkAheadServerConnection): + raise Exception("""Bad configuration of the LinkAhead connection. The `connection` must be an instance of - `CaosDBConnection`.""") + `LinkAheadConnection`.""") diff --git a/src/linkahead/connection/authentication/external_credentials_provider.py b/src/linkahead/connection/authentication/external_credentials_provider.py index 91158c90add616ca42c0dca2e1b4eb8d1abf3c46..3d1b8afa17f58a87f09afba90c4bc7ae6dcba693 100644 --- a/src/linkahead/connection/authentication/external_credentials_provider.py +++ b/src/linkahead/connection/authentication/external_credentials_provider.py @@ -78,11 +78,11 @@ class ExternalCredentialsProvider(PlainTextCredentialsProvider, ABC): else: authm = "an external credentials provider" self.logger.log(logging.WARNING, - ("`password` defined. You configured caosdb to " + ("`password` defined. You configured LinkAhead to " "use %s as authentication method and yet " "provided a password yourself. This indicates " "a misconfiguration (e.g. in your " - "pycaosdb.ini) and should be avoided."), + "pylinkahead.ini) and should be avoided."), authm) self._config = dict(config) super(ExternalCredentialsProvider, self).configure(**config) diff --git a/src/linkahead/connection/authentication/interface.py b/src/linkahead/connection/authentication/interface.py index ad1147ebc22d1e6bcbda120eb4dfaffd297c9983..2bc0047b0d44095c6b27d7dae2ba6f599d6d3d24 100644 --- a/src/linkahead/connection/authentication/interface.py +++ b/src/linkahead/connection/authentication/interface.py @@ -22,14 +22,14 @@ # ** end header # """This module provides the interfaces for authenticating requests to the -caosdb server. +LinkAhead server. Implementing modules muts provide a `get_authentication_provider()` method. """ from abc import ABCMeta, abstractmethod, abstractproperty import logging from linkahead.connection.utils import urlencode -from linkahead.connection.interface import CaosDBServerConnection +from linkahead.connection.interface import LinkAheadServerConnection from linkahead.connection.utils import parse_auth_token, auth_token_to_cookie from linkahead.exceptions import LoginFailedError @@ -51,7 +51,7 @@ class AbstractAuthenticator(ABC): A logger which should be used for all logging which has to do with authentication. auth_token : str - A string representation of a CaosDB Auth Token. + A string representation of a LinkAhead Auth Token. Methods ------- @@ -116,7 +116,7 @@ class AbstractAuthenticator(ABC): Parameters ---------- - response : CaosDBHTTPResponse + response : LinkAheadHTTPResponse The response of the server Returns @@ -218,10 +218,10 @@ class CredentialsAuthenticator(AbstractAuthenticator): self._credentials_provider.configure(**config) if "connection" in config: self._connection = config["connection"] - if not isinstance(self._connection, CaosDBServerConnection): - raise Exception("""Bad configuration of the caosdb connection. + if not isinstance(self._connection, LinkAheadServerConnection): + raise Exception("""Bad configuration of the LinkAhead connection. The `connection` must be an instance of - `CaosDBConnection`.""") + `LinkAheadConnection`.""") class CredentialsProvider(ABC): diff --git a/src/linkahead/connection/authentication/keyring.py b/src/linkahead/connection/authentication/keyring.py index 5ed63634bcc68a0da2bc1b90f53d89477cefd3ba..9d73592b06e9f9b13e06de4091a8af30b7f492b0 100644 --- a/src/linkahead/connection/authentication/keyring.py +++ b/src/linkahead/connection/authentication/keyring.py @@ -69,7 +69,7 @@ def _call_keyring(**config): "password in question.") url = config.get("url") username = config.get("username") - app = "caosdb — {}".format(url) + app = "linkahead — {}".format(url) external_keyring = _get_external_keyring() password = external_keyring.get_password(app, username) if password is None: diff --git a/src/linkahead/connection/authentication/pass.py b/src/linkahead/connection/authentication/pass.py index 8067a890eee8999ce25d1a3d1cd19b36e50ac365..adbe8df970c5ac42d58a1c41c700772679f93a1c 100644 --- a/src/linkahead/connection/authentication/pass.py +++ b/src/linkahead/connection/authentication/pass.py @@ -62,7 +62,7 @@ def _call_pass(**config): except CalledProcessError as exc: raise RuntimeError( "Password manager returned error code {}. This usually " - "occurs if the password_identifier in .pycaosdb.ini is " + "occurs if the password_identifier in .pylinkahead.ini is " "incorrect or missing.".format(exc.returncode)) diff --git a/src/linkahead/connection/authentication/unauthenticated.py b/src/linkahead/connection/authentication/unauthenticated.py index 8c220acde2e10750a8bedf10067213ac869bb3bf..071fb96cad75c33bd684d7f1a1a95a83f675228a 100644 --- a/src/linkahead/connection/authentication/unauthenticated.py +++ b/src/linkahead/connection/authentication/unauthenticated.py @@ -29,7 +29,7 @@ An Authenticator which suppresses any authentication and also ignores auth_token cookies. """ from __future__ import absolute_import, unicode_literals, print_function -from .interface import AbstractAuthenticator, CaosDBServerConnection +from .interface import AbstractAuthenticator, LinkAheadServerConnection from linkahead.exceptions import LoginFailedError @@ -70,7 +70,7 @@ class Unauthenticated(AbstractAuthenticator): self._login() def _login(self): - raise LoginFailedError("This caosdb client is configured to stay " + raise LoginFailedError("This LinkAhead client is configured to stay " "unauthenticated. Change your " "`password_method` and provide an " "`auth_token` or credentials if you want " diff --git a/src/linkahead/connection/connection.py b/src/linkahead/connection/connection.py index 84e9add51552984845c709d566a31b4554cf88df..63f35a0113e2d7a807b889c31ddc70aa976013d8 100644 --- a/src/linkahead/connection/connection.py +++ b/src/linkahead/connection/connection.py @@ -22,7 +22,7 @@ # # ** end header # -"""Connection to a CaosDB server.""" +"""Connection to a LinkAhead server.""" from __future__ import absolute_import, print_function, unicode_literals import logging @@ -39,14 +39,14 @@ from urllib3.poolmanager import PoolManager from requests.adapters import HTTPAdapter from linkahead.configuration import get_config -from linkahead.exceptions import (CaosDBException, HTTPClientError, - ConfigurationError, - CaosDBConnectionError, - HTTPForbiddenError, - LoginFailedError, - HTTPResourceNotFoundError, - HTTPServerError, - HTTPURITooLongError) +from linkahead.exceptions import (LinkAheadException, HTTPClientError, + ConfigurationError, + LinkAheadConnectionError, + HTTPForbiddenError, + LoginFailedError, + HTTPResourceNotFoundError, + HTTPServerError, + HTTPURITooLongError) try: from linkahead.version import version except ModuleNotFoundError: @@ -54,14 +54,14 @@ except ModuleNotFoundError: from pkg_resources import resource_filename -from .interface import CaosDBHTTPResponse, CaosDBServerConnection +from .interface import LinkAheadHTTPResponse, LinkAheadServerConnection from .utils import make_uri_path, parse_url, urlencode from .encode import MultipartYielder, ReadableMultiparts _LOGGER = logging.getLogger(__name__) -class _WrappedHTTPResponse(CaosDBHTTPResponse): +class _WrappedHTTPResponse(LinkAheadHTTPResponse): def __init__(self, response): self.response = response @@ -140,8 +140,8 @@ class _SSLAdapter(HTTPAdapter): block=block, ssl_version=self.ssl_version) -class _DefaultCaosDBServerConnection(CaosDBServerConnection): - """_DefaultCaosDBServerConnection. +class _DefaultLinkAheadServerConnection(LinkAheadServerConnection): + """_DefaultLinkAheadServerConnection. Methods ------- @@ -150,7 +150,7 @@ class _DefaultCaosDBServerConnection(CaosDBServerConnection): """ def __init__(self): - self._useragent = ("caosdb-pylib/{version} - {implementation}".format( + self._useragent = ("linkahead-pylib/{version} - {implementation}".format( version=version, implementation=type(self).__name__)) self._base_path = None self._session = None @@ -176,7 +176,7 @@ class _DefaultCaosDBServerConnection(CaosDBServerConnection): Returns ------- - response : CaosDBHTTPResponse + response : LinkAheadHTTPResponse """ if headers is None: @@ -200,7 +200,7 @@ class _DefaultCaosDBServerConnection(CaosDBServerConnection): return _WrappedHTTPResponse(response) except HTTPConnectionError as conn_err: - raise CaosDBConnectionError( + raise LinkAheadConnectionError( "Connection failed. Network or server down? " + str(conn_err) ) @@ -215,29 +215,29 @@ class _DefaultCaosDBServerConnection(CaosDBServerConnection): Path to the CA certificate which will be used to identify the server. url : str - The url of the CaosDB Server, e.g. + The url of the LinkAhead Server, e.g. `https://example.com:443/rootpath`, including a possible root path. **config : Any further keyword arguments are being ignored. Raises ------ - CaosDBConnectionError + LinkAheadConnectionError If no url has been specified, or if the CA certificate cannot be loaded. """ if "url" not in config: - raise CaosDBConnectionError( + raise LinkAheadConnectionError( "No connection url specified. Please " - "do so via caosdb.configure_connection(...) or in a config " + "do so via linkahead.configure_connection(...) or in a config " "file.") if (not config["url"].lower().startswith("https://") and not config["url"].lower().startswith("http://")): - raise CaosDBConnectionError("The connection url is expected " - "to be a http or https url and " - "must include the url scheme " - "(i.e. start with https:// or " - "http://).") + raise LinkAheadConnectionError("The connection url is expected " + "to be a http or https url and " + "must include the url scheme " + "(i.e. start with https:// or " + "http://).") url = urlparse(config["url"]) path = url.path.strip("/") @@ -320,7 +320,7 @@ def _make_conf(*conf): _DEFAULT_CONF = { "password_method": "input", - "implementation": _DefaultCaosDBServerConnection, + "implementation": _DefaultLinkAheadServerConnection, "timeout": 210, } @@ -333,7 +333,7 @@ def _get_authenticator(**config): Parameters ---------- password_method : str - The simple name of a submodule of caosdb.connection.authentication. + The simple name of a submodule of linkahead.connection.authentication. Currently, there are four valid values for this parameter: 'plain', 'pass', 'keyring' and 'auth_token'. **config : @@ -349,10 +349,10 @@ def _get_authenticator(**config): Raises ------ ConfigurationError - If the password_method string cannot be resolved to a CaosAuthenticator + If the password_method string cannot be resolved to a LinkaheadAuthenticator class. """ - auth_module = ("caosdb.connection.authentication." + + auth_module = ("linkahead.connection.authentication." + config["password_method"]) _LOGGER.debug("import auth_module %s", auth_module) try: @@ -371,10 +371,10 @@ def _get_authenticator(**config): def configure_connection(**kwargs): - """Configures the caosdb connection and returns the Connection object. + """Configures the LinkAhead connection and returns the Connection object. The effective configuration is governed by the default values (see - 'Parameters'), the global configuration (see `caosdb.get_config()`) and the + 'Parameters'), the global configuration (see `linkahead.get_config()`) and the parameters which are passed to this function, with ascending priority. The parameters which are listed here, are possibly not sufficient for a @@ -384,7 +384,7 @@ def configure_connection(**kwargs): Parameters ---------- url : str - The url of the CaosDB Server. HTTP and HTTPS urls are allowed. However, + The url of the LinkAhead Server. HTTP and HTTPS urls are allowed. However, it is **highly** recommend to avoid HTTP because passwords and authentication token are send over the network in plain text. @@ -395,7 +395,7 @@ def configure_connection(**kwargs): Password for login if 'plain' is used as password_method. password_method : str - The name of a submodule of caosdb.connection.authentication which + The name of a submodule of linkahead.connection.authentication which implements the AbstractAuthenticator interface. (Default: 'plain') Possible values are, for example: - "plain" Need username and password arguments. @@ -412,7 +412,7 @@ def configure_connection(**kwargs): development purposes! (Default: False) auth_token : str (optional) - An authentication token which has been issued by the CaosDB Server. + An authentication token which has been issued by the LinkAhead Server. Implies `password_method="auth_token"` if set. An example token string would be `["O","OneTimeAuthenticationToken","anonymous",["administration"],[],1592995200000,604800000,"3ZZ4WKRB-5I7DG2Q6-ZZE6T64P-VQ","197d0d081615c52dc18fb323c300d7be077beaad4020773bb58920b55023fa6ee49355e35754a4277b9ac525c882bcd3a22e7227ba36dfcbbdbf8f15f19d1ee9",1,30000]`. https_proxy : str, optional @@ -423,19 +423,19 @@ def configure_connection(**kwargs): using TLS in the tunneled connection nonetheless. Only the connection to the proxy is insecure which is why it is not recommended to use HTTP proxies when authentication against the proxy is necessary. If - unspecified, the https_proxy option of the pycaosdb.ini or the HTTPS_PROXY + unspecified, the https_proxy option of the pylinkahead.ini or the HTTPS_PROXY environment variable are being used. Use `None` to override these options with a no-proxy setting. http_proxy : str, optional Define a proxy for the http connections, e.g. `http://localhost:8888`. - If unspecified, the http_proxy option of the pycaosdb.ini or the + If unspecified, the http_proxy option of the pylinkahead.ini or the HTTP_PROXY environment variable are being used. Use `None` to override these options with a no-proxy setting. - implementation : CaosDBServerConnection + implementation : LinkAheadServerConnection The class which implements the connection. (Default: - _DefaultCaosDBServerConnection) + _DefaultLinkAheadServerConnection) Returns ------- @@ -514,7 +514,7 @@ def _handle_response_status(http_response): elif 399 < status < 500: raise HTTPClientError(msg=standard_message, status=status, body=body) else: - raise CaosDBException(standard_message) + raise LinkAheadException(standard_message) class _Connection(object): # pylint: disable=useless-object-inheritance @@ -522,7 +522,7 @@ class _Connection(object): # pylint: disable=useless-object-inheritance allowing for retrieval, insertion, update, etc. of entities, files, users, roles and much more. - It wrapps an instance of CaosDBServerConnection which actually does the + It wrapps an instance of LinkAheadServerConnection which actually does the work (how, depends on the instance). It is a singleton and should not be instanciated or modified by any client. @@ -549,20 +549,20 @@ class _Connection(object): # pylint: disable=useless-object-inheritance if "implementation" not in config: raise ConfigurationError( - "Missing CaosDBServerConnection implementation. You did not " + "Missing LinkAheadServerConnection implementation. You did not " "specify an `implementation` for the connection.") try: self._delegate_connection = config["implementation"]() if not isinstance(self._delegate_connection, - CaosDBServerConnection): + LinkAheadServerConnection): raise TypeError("The `implementation` callable did not return " - "an instance of CaosDBServerConnection.") + "an instance of LinkAheadServerConnection.") except TypeError as type_err: raise ConfigurationError( - "Bad CaosDBServerConnection implementation. The " + "Bad LinkAheadServerConnection implementation. The " "implementation must be a callable object which returns an " - "instance of `CaosDBServerConnection` (e.g. a constructor " + "instance of `LinkAheadServerConnection` (e.g. a constructor " "or a factory).\n{}".format(type_err.args[0])) self._delegate_connection.configure(**config) @@ -641,7 +641,7 @@ class _Connection(object): # pylint: disable=useless-object-inheritance return http_response def download_file(self, path): - """This function downloads a file via HTTP from the Caosdb file + """This function downloads a file via HTTP from the LinkAhead file system.""" try: uri_segments = ["FileSystem"] diff --git a/src/linkahead/connection/interface.py b/src/linkahead/connection/interface.py index d56900d8022a3753c5acbbf843e2dcd07fb71a0a..4986236971ea468d1d60851c2bf4ae5e4bbf15cb 100644 --- a/src/linkahead/connection/interface.py +++ b/src/linkahead/connection/interface.py @@ -21,16 +21,16 @@ # # ** end header # -"""This module defines the CaosDBServerConnection interface.""" +"""This module defines the LinkAheadServerConnection interface.""" from abc import ABCMeta, abstractmethod, abstractproperty # meta class compatible with Python 2 *and* 3: ABC = ABCMeta('ABC', (object, ), {'__slots__': ()}) -class CaosDBHTTPResponse(ABC): +class LinkAheadHTTPResponse(ABC): """An abstract class which defines a minimal interface for responses of the - CaosDBServer.""" + LinkAheadServer.""" @abstractmethod def read(self, size=-1): @@ -72,18 +72,18 @@ class CaosDBHTTPResponse(ABC): """ -class CaosDBServerConnection(ABC): +class LinkAheadServerConnection(ABC): """Abstract class which defines the interface for sending requests to the - caosdb server.""" + LinkAhead server.""" @abstractmethod def request(self, method, path, headers=None, body=None, **kwargs): """Abstract method. Implement this method for HTTP requests to the - caosdb server. + LinkAhead server. Returns ------- - CaosDBHTTPResponse + LinkAheadHTTPResponse """ @abstractmethod diff --git a/src/linkahead/connection/mockup.py b/src/linkahead/connection/mockup.py index 8da791333fe64d2d68bc62e61567c729ac21496f..4da51444820ee5c913a7033bb91df1107f38ed39 100644 --- a/src/linkahead/connection/mockup.py +++ b/src/linkahead/connection/mockup.py @@ -21,12 +21,12 @@ # # ** end header # -"""Classes and functions to immitate a caosdb server without actually setting +"""Classes and functions to immitate a LinkAhead server without actually setting up a tcp connection.""" from __future__ import unicode_literals, print_function from io import StringIO -from .connection import CaosDBServerConnection, CaosDBHTTPResponse +from .connection import LinkAheadServerConnection, LinkAheadHTTPResponse def _request_log_message(method, path, headers, body, **kwargs): @@ -41,7 +41,7 @@ def _request_log_message(method, path, headers, body, **kwargs): nl2="\n" if body else "") -class MockUpResponse(CaosDBHTTPResponse): +class MockUpResponse(LinkAheadHTTPResponse): """A class for the responses of a request to the MockUpServerConnection.""" def __init__(self, status, headers, body): @@ -70,9 +70,9 @@ class MockUpResponse(CaosDBHTTPResponse): pass -class MockUpServerConnection(CaosDBServerConnection): +class MockUpServerConnection(LinkAheadServerConnection): """The mock-up connection which does not actually connect to anything but - just returns predefined responses which mimic the caosdb server.""" + just returns predefined responses which mimic the LinkAhead server.""" def __init__(self): self.resources = [self._login] diff --git a/src/linkahead/exceptions.py b/src/linkahead/exceptions.py index 97c6d708959e13bbea676ec60063906e15b3d33f..a4bb5ac488214ef788eaf7c926ff319c316f7d1c 100644 --- a/src/linkahead/exceptions.py +++ b/src/linkahead/exceptions.py @@ -31,15 +31,15 @@ dependencies, non-passing consistency checks etc.). from lxml import etree -class CaosDBException(Exception): - """Base class of all CaosDB exceptions.""" +class LinkAheadException(Exception): + """Base class of all LinkAhead exceptions.""" def __init__(self, msg): Exception.__init__(self, msg) self.msg = msg -class ConfigurationError(CaosDBException): +class ConfigurationError(LinkAheadException): """ConfigurationError. Indicates a misconfiguration. @@ -59,27 +59,27 @@ class ConfigurationError(CaosDBException): def __init__(self, msg): super().__init__(msg + ConfigurationError._INFO) - _INFO = ("\n\nPlease check your ~/.pycaosdb.ini and your $PWD/" - ".pycaosdb.ini. Does at least one of them exist and are they correct?") + _INFO = ("\n\nPlease check your ~/.pylinkahead.ini and your $PWD/" + ".pylinkahead.ini. Does at least one of them exist and are they correct?") -class ServerConfigurationException(CaosDBException): +class ServerConfigurationException(LinkAheadException): """The server is configured in a different way than expected. This can be for example unexpected flags or settings or missing extensions. """ -class HTTPClientError(CaosDBException): +class HTTPClientError(LinkAheadException): """HTTPClientError represents 4xx HTTP client errors.""" def __init__(self, msg, status, body): self.status = status self.body = body - CaosDBException.__init__(self, msg) + LinkAheadException.__init__(self, msg) -class HTTPServerError(CaosDBException): +class HTTPServerError(LinkAheadException): """HTTPServerError represents 5xx HTTP server errors.""" def __init__(self, body): @@ -89,14 +89,14 @@ class HTTPServerError(CaosDBException): if error.text is not None: msg = msg + "\n\n" + error.text - CaosDBException.__init__(self, msg) + LinkAheadException.__init__(self, msg) -class CaosDBConnectionError(CaosDBException): +class LinkAheadConnectionError(LinkAheadException): """Connection is not configured or the network is down.""" def __init__(self, msg=None): - CaosDBException.__init__(self, msg) + LinkAheadException.__init__(self, msg) class HTTPURITooLongError(HTTPClientError): @@ -106,14 +106,14 @@ class HTTPURITooLongError(HTTPClientError): HTTPClientError.__init__(self, msg=msg, status=414, body=None) -class LoginFailedError(CaosDBException): +class LoginFailedError(LinkAheadException): """Login failed. Probably, your username/password pair is wrong. """ def __init__(self, msg=None): - CaosDBException.__init__(self, msg=msg) + LinkAheadException.__init__(self, msg=msg) class HTTPForbiddenError(HTTPClientError): @@ -136,14 +136,14 @@ class HTTPResourceNotFoundError(HTTPClientError): HTTPClientError.__init__(self, msg=msg, status=404, body=None) -class MismatchingEntitiesError(CaosDBException): +class MismatchingEntitiesError(LinkAheadException): """Mismatching entities were found during container sync.""" # ######################### Bad query errors ########################### -class BadQueryError(CaosDBException): +class BadQueryError(LinkAheadException): """Base class for query errors that are not transaction errors.""" @@ -158,9 +158,9 @@ class EmptyUniqueQueryError(BadQueryError): # ######################### Transaction errors ######################### -class TransactionError(CaosDBException): +class TransactionError(LinkAheadException): """An error of this type is raised whenever any transaction fails with - one or more entities between client and CaosDB server. More + one or more entities between client and LinkAhead server. More detailed errors are collected as direct and indirect children in the 'errors' list (direct children) and the 'all_errors' set (set of all direct and indirect children). @@ -170,7 +170,7 @@ class TransactionError(CaosDBException): def __init__(self, error=None, msg="An error occured during the transaction.", container=None): - CaosDBException.__init__(self, msg=msg) + LinkAheadException.__init__(self, msg=msg) self.errors = [] self.all_errors = set() self.entities = [] diff --git a/src/linkahead/high_level_api.py b/src/linkahead/high_level_api.py index e7e9beab9b7ed75bc3ba422af8d612b8405819e5..55753b26a0f6662f82c828d7947b21fbcd8e91a3 100644 --- a/src/linkahead/high_level_api.py +++ b/src/linkahead/high_level_api.py @@ -25,16 +25,16 @@ # """ -A high level API for accessing CaosDB entities from within python. +A high level API for accessing LinkAhead entities from within python. This is refactored from apiutils. """ from linkahead.common.datatype import (BOOLEAN, DATETIME, DOUBLE, FILE, INTEGER, - REFERENCE, TEXT, - is_list_datatype, - get_list_datatype, - is_reference) + REFERENCE, TEXT, + is_list_datatype, + get_list_datatype, + is_reference) import linkahead as db from .apiutils import get_type_of_entity_with, create_flat_list @@ -53,30 +53,30 @@ removed in future. Its purpose is to give an impression on how the Python client might be changed.""") -def standard_type_for_high_level_type(high_level_record: "CaosDBPythonEntity", +def standard_type_for_high_level_type(high_level_record: "LinkAheadPythonEntity", return_string: bool = False): """ - For a given CaosDBPythonEntity either return the corresponding - class in the standard CaosDB API or - if return_string is True - return + For a given LinkAheadPythonEntity either return the corresponding + class in the standard LinkAhead API or - if return_string is True - return the role as a string. """ - if type(high_level_record) == CaosDBPythonRecord: + if type(high_level_record) == LinkAheadPythonRecord: if not return_string: return db.Record return "Record" - elif type(high_level_record) == CaosDBPythonFile: + elif type(high_level_record) == LinkAheadPythonFile: if not return_string: return db.File return "File" - elif type(high_level_record) == CaosDBPythonProperty: + elif type(high_level_record) == LinkAheadPythonProperty: if not return_string: return db.Property return "Property" - elif type(high_level_record) == CaosDBPythonRecordType: + elif type(high_level_record) == LinkAheadPythonRecordType: if not return_string: return db.RecordType return "RecordType" - elif type(high_level_record) == CaosDBPythonEntity: + elif type(high_level_record) == LinkAheadPythonEntity: if not return_string: return db.Entity return "Entity" @@ -85,15 +85,15 @@ def standard_type_for_high_level_type(high_level_record: "CaosDBPythonEntity", def high_level_type_for_role(role: str): if role == "Record": - return CaosDBPythonRecord + return LinkAheadPythonRecord if role == "File": - return CaosDBPythonFile + return LinkAheadPythonFile if role == "Property": - return CaosDBPythonProperty + return LinkAheadPythonProperty if role == "RecordType": - return CaosDBPythonRecordType + return LinkAheadPythonRecordType if role == "Entity": - return CaosDBPythonEntity + return LinkAheadPythonEntity raise RuntimeError("Unknown role.") @@ -102,20 +102,20 @@ def high_level_type_for_standard_type(standard_record: db.Entity): raise ValueError() role = standard_record.role if role == "Record" or type(standard_record) == db.Record: - return CaosDBPythonRecord + return LinkAheadPythonRecord elif role == "File" or type(standard_record) == db.File: - return CaosDBPythonFile + return LinkAheadPythonFile elif role == "Property" or type(standard_record) == db.Property: - return CaosDBPythonProperty + return LinkAheadPythonProperty elif role == "RecordType" or type(standard_record) == db.RecordType: - return CaosDBPythonRecordType + return LinkAheadPythonRecordType elif role == "Entity" or type(standard_record) == db.Entity: - return CaosDBPythonEntity + return LinkAheadPythonEntity raise RuntimeError("Incompatible type.") @dataclass -class CaosDBPropertyMetaData: +class LinkAheadPropertyMetaData: # name is already the name of the attribute unit: Optional[str] = None datatype: Optional[str] = None @@ -124,12 +124,12 @@ class CaosDBPropertyMetaData: importance: Optional[str] = None -class CaosDBPythonUnresolved: +class LinkAheadPythonUnresolved: pass @dataclass -class CaosDBPythonUnresolvedParent(CaosDBPythonUnresolved): +class LinkAheadPythonUnresolvedParent(LinkAheadPythonUnresolved): """ Parents can be either given by name or by ID. @@ -141,32 +141,32 @@ class CaosDBPythonUnresolvedParent(CaosDBPythonUnresolved): @dataclass -class CaosDBPythonUnresolvedReference(CaosDBPythonUnresolved): +class LinkAheadPythonUnresolvedReference(LinkAheadPythonUnresolved): def __init__(self, id=None): self.id = id -class CaosDBPythonEntity(object): +class LinkAheadPythonEntity(object): def __init__(self): """ - Initialize a new CaosDBPythonEntity for the high level python api. + Initialize a new LinkAheadPythonEntity for the high level python api. - Parents are either unresolved references or CaosDB RecordTypes. + Parents are either unresolved references or LinkAhead RecordTypes. Properties are stored directly as attributes for the object. Property metadata is maintained in a dctionary _properties_metadata that should never be accessed directly, but only using the get_property_metadata function. If property values are references to other objects, they will be stored as - CaosDBPythonUnresolvedReference objects that can be resolved later into - CaosDBPythonRecords. + LinkAheadPythonUnresolvedReference objects that can be resolved later into + LinkAheadPythonRecords. """ - # Parents are either unresolved references or CaosDB RecordTypes + # Parents are either unresolved references or LinkAhead RecordTypes self._parents: List[Union[ - CaosDBPythonUnresolvedParent, CaosDBPythonRecordType]] = [] - # self._id: int = CaosDBPythonEntity._get_new_id() + LinkAheadPythonUnresolvedParent, LinkAheadPythonRecordType]] = [] + # self._id: int = LinkAheadPythonEntity._get_new_id() self._id: Optional[int] = None self._name: Optional[str] = None self._description: Optional[str] = None @@ -176,7 +176,7 @@ class CaosDBPythonEntity(object): self._path: Optional[str] = None # name: name of property, value: property metadata - self._properties_metadata: Dict[CaosDBPropertyMetaData] = dict() + self._properties_metadata: Dict[LinkAheadPropertyMetaData] = dict() # Store all current attributes as forbidden attributes # which must not be changed by the set_property function. @@ -213,14 +213,14 @@ class CaosDBPythonEntity(object): """ Getter for the file. """ - if type(self) != CaosDBPythonFile: + if type(self) != LinkAheadPythonFile: raise RuntimeError("Please don't use the file attribute for entities" " that are no files.") return self._file @file.setter def file(self, val: str): - if val is not None and type(self) != CaosDBPythonFile: + if val is not None and type(self) != LinkAheadPythonFile: raise RuntimeError("Please don't use the file attribute for entities" " that are no files.") self._file = val @@ -230,14 +230,14 @@ class CaosDBPythonEntity(object): """ Getter for the path. """ - if type(self) != CaosDBPythonFile: + if type(self) != LinkAheadPythonFile: raise RuntimeError("Please don't use the path attribute for entities" " that are no files.") return self._path @path.setter def path(self, val: str): - if val is not None and type(self) != CaosDBPythonFile: + if val is not None and type(self) != LinkAheadPythonFile: raise RuntimeError("Please don't use the path attribute for entities" " that are no files.") self._path = val @@ -294,7 +294,7 @@ class CaosDBPythonEntity(object): else: metadata.__setattr__(k, ent.__getattribute__(k)) - def get_property_metadata(self, prop_name: str) -> CaosDBPropertyMetaData: + def get_property_metadata(self, prop_name: str) -> LinkAheadPropertyMetaData: """ Retrieve the property metadata for the property with name prop_name. @@ -312,7 +312,7 @@ class CaosDBPythonEntity(object): raise RuntimeError("The property with name {} does not exist.".format(prop_name)) if prop_name not in self._properties_metadata: - self._properties_metadata[prop_name] = CaosDBPropertyMetaData() + self._properties_metadata[prop_name] = LinkAheadPropertyMetaData() return self._properties_metadata[prop_name] @@ -407,7 +407,7 @@ class CaosDBPythonEntity(object): Convert val to the correct type which is indicated by the database type string in pr. - References with ids will be turned into CaosDBPythonUnresolvedReference. + References with ids will be turned into LinkAheadPythonUnresolvedReference. """ if val is None: @@ -430,16 +430,16 @@ class CaosDBPythonEntity(object): elif pr == TEXT: return str(val) elif pr == FILE: - return CaosDBPythonUnresolvedReference(val) + return LinkAheadPythonUnresolvedReference(val) elif pr == REFERENCE: - return CaosDBPythonUnresolvedReference(val) + return LinkAheadPythonUnresolvedReference(val) elif pr == DATETIME: return self._parse_datetime(val) elif is_list_datatype(pr): return self._type_converted_list(val, pr, references) else: # Generic references to entities: - return CaosDBPythonUnresolvedReference(val) + return LinkAheadPythonUnresolvedReference(val) def _parse_datetime(self, val: Union[str, datetime]): """ @@ -476,7 +476,7 @@ class CaosDBPythonEntity(object): return [att] def add_parent(self, parent: Union[ - CaosDBPythonUnresolvedParent, "CaosDBPythonRecordType", str]): + LinkAheadPythonUnresolvedParent, "LinkAheadPythonRecordType", str]): """ Add a parent to this entity. Either using an unresolved parent or using a real record type. @@ -487,10 +487,10 @@ class CaosDBPythonEntity(object): """ if isinstance(parent, str): - parent = CaosDBPythonUnresolvedParent(name=parent) + parent = LinkAheadPythonUnresolvedParent(name=parent) if isinstance(parent, int): - parent = CaosDBPythonUnresolvedParent(id=parent) + parent = LinkAheadPythonUnresolvedParent(id=parent) if self.has_parent(parent): raise RuntimeError("Duplicate parent.") @@ -506,7 +506,7 @@ class CaosDBPythonEntity(object): return self._parents def has_parent(self, parent: Union[ - CaosDBPythonUnresolvedParent, "CaosDBPythonRecordType"]): + LinkAheadPythonUnresolvedParent, "LinkAheadPythonRecordType"]): """ Check whether this parent already exists for this entity. @@ -516,10 +516,10 @@ class CaosDBPythonEntity(object): """ if isinstance(parent, str): - parent = CaosDBPythonUnresolvedParent(name=parent) + parent = LinkAheadPythonUnresolvedParent(name=parent) if isinstance(parent, int): - parent = CaosDBPythonUnresolvedParent(id=parent) + parent = LinkAheadPythonUnresolvedParent(id=parent) for p in self._parents: if p.id is not None and p.id == parent.id: @@ -528,8 +528,8 @@ class CaosDBPythonEntity(object): return True return False - def _resolve_caosdb_python_unresolved_reference(self, propval, deep, - references, visited): + def _resolve_linkahead_python_unresolved_reference(self, propval, deep, + references, visited): # This does not make sense for unset ids: if propval.id is None: raise RuntimeError("Unresolved property reference without an ID.") @@ -562,7 +562,7 @@ class CaosDBPythonEntity(object): def resolve_references(self, deep: bool, references: db.Container, visited: Dict[Union[str, int], - "CaosDBPythonEntity"] = None): + "LinkAheadPythonEntity"] = None): """ Resolve this entity's references. This affects unresolved properties as well as unresolved parents. @@ -573,7 +573,7 @@ class CaosDBPythonEntity(object): references: Optional[db.Container] A container with references that might be resolved. If None is passed as the container, this function tries to resolve entities from a running - CaosDB instance directly. + LinkAhead instance directly. """ # This parameter is used in the recursion to keep track of already visited @@ -583,31 +583,31 @@ class CaosDBPythonEntity(object): for parent in self.get_parents(): # TODO - if isinstance(parent, CaosDBPythonUnresolvedParent): + if isinstance(parent, LinkAheadPythonUnresolvedParent): pass for prop in self.get_properties(): propval = self.__getattribute__(prop) # Resolve all previously unresolved attributes that are entities: - if deep and isinstance(propval, CaosDBPythonEntity): + if deep and isinstance(propval, LinkAheadPythonEntity): propval.resolve_references(deep, references) elif isinstance(propval, list): resolvedelements = [] for element in propval: - if deep and isinstance(element, CaosDBPythonEntity): + if deep and isinstance(element, LinkAheadPythonEntity): element.resolve_references(deep, references) resolvedelements.append(element) - if isinstance(element, CaosDBPythonUnresolvedReference): + if isinstance(element, LinkAheadPythonUnresolvedReference): resolvedelements.append( - self._resolve_caosdb_python_unresolved_reference(element, deep, - references, visited)) + self._resolve_linkahead_python_unresolved_reference(element, deep, + references, visited)) else: resolvedelements.append(element) self.__setattr__(prop, resolvedelements) - elif isinstance(propval, CaosDBPythonUnresolvedReference): - val = self._resolve_caosdb_python_unresolved_reference(propval, deep, - references, visited) + elif isinstance(propval, LinkAheadPythonUnresolvedReference): + val = self._resolve_linkahead_python_unresolved_reference(propval, deep, + references, visited) self.__setattr__(prop, val) def get_properties(self): @@ -627,7 +627,7 @@ class CaosDBPythonEntity(object): if "role" in serialization: entity = high_level_type_for_role(serialization["role"])() else: - entity = CaosDBPythonRecord() + entity = LinkAheadPythonRecord() for parent in serialization["parents"]: if "unresolved" in parent: @@ -637,7 +637,7 @@ class CaosDBPythonEntity(object): id = parent["id"] if "name" in parent: name = parent["name"] - entity.add_parent(CaosDBPythonUnresolvedParent( + entity.add_parent(LinkAheadPythonUnresolvedParent( id=id, name=name)) else: raise NotImplementedError() @@ -646,7 +646,7 @@ class CaosDBPythonEntity(object): if baseprop in serialization: entity.__setattr__(baseprop, serialization[baseprop]) - if type(entity) == CaosDBPythonFile: + if type(entity) == LinkAheadPythonFile: entity.file = serialization["file"] entity.path = serialization["path"] @@ -656,7 +656,7 @@ class CaosDBPythonEntity(object): prop = serialization["properties"][p] if isinstance(prop, dict): if "unresolved" in prop: - entity.__setattr__(p, CaosDBPythonUnresolvedReference( + entity.__setattr__(p, LinkAheadPythonUnresolvedReference( id=prop["id"])) else: entity.__setattr__(p, @@ -700,13 +700,13 @@ class CaosDBPythonEntity(object): fulldict = dict() visited[self] = fulldict - # Add CaosDB role: + # Add LinkAhead role: fulldict["role"] = standard_type_for_high_level_type(self, True) for parent in self._parents: - if isinstance(parent, CaosDBPythonEntity): + if isinstance(parent, LinkAheadPythonEntity): parents.append(parent.serialize(without_metadata, visited)) - elif isinstance(parent, CaosDBPythonUnresolvedParent): + elif isinstance(parent, LinkAheadPythonUnresolvedParent): parents.append({"name": parent.name, "id": parent.id, "unresolved": True}) else: @@ -717,7 +717,7 @@ class CaosDBPythonEntity(object): if val is not None: fulldict[baseprop] = val - if type(self) == CaosDBPythonFile: + if type(self) == LinkAheadPythonFile: fulldict["file"] = self.file fulldict["path"] = self.path @@ -730,19 +730,19 @@ class CaosDBPythonEntity(object): metadata[p][f.name] = val val = self.get_property(p) - if isinstance(val, CaosDBPythonUnresolvedReference): + if isinstance(val, LinkAheadPythonUnresolvedReference): properties[p] = {"id": val.id, "unresolved": True} - elif isinstance(val, CaosDBPythonEntity): + elif isinstance(val, LinkAheadPythonEntity): properties[p] = val.serialize(without_metadata, visited) elif isinstance(val, list): serializedelements = [] for element in val: - if isinstance(element, CaosDBPythonUnresolvedReference): + if isinstance(element, LinkAheadPythonUnresolvedReference): elm = dict() elm["id"] = element.id elm["unresolved"] = True serializedelements.append(elm) - elif isinstance(element, CaosDBPythonEntity): + elif isinstance(element, LinkAheadPythonEntity): serializedelements.append( element.serialize(without_metadata, visited)) @@ -769,19 +769,19 @@ class CaosDBPythonEntity(object): # return yaml.dump(self.serialize(True)) -class CaosDBPythonRecord(CaosDBPythonEntity): +class LinkAheadPythonRecord(LinkAheadPythonEntity): pass -class CaosDBPythonRecordType(CaosDBPythonEntity): +class LinkAheadPythonRecordType(LinkAheadPythonEntity): pass -class CaosDBPythonProperty(CaosDBPythonEntity): +class LinkAheadPythonProperty(LinkAheadPythonEntity): pass -class CaosDBMultiProperty: +class LinkAheadMultiProperty: """ This implements a multi property using a python list. """ @@ -790,7 +790,7 @@ class CaosDBMultiProperty: raise NotImplementedError() -class CaosDBPythonFile(CaosDBPythonEntity): +class LinkAheadPythonFile(LinkAheadPythonEntity): def download(self, target=None): if self.id is None: raise RuntimeError("Cannot download file when id is missing.") @@ -802,12 +802,12 @@ BASE_ATTRIBUTES = ( "id", "name", "description", "version", "path", "file") -def _single_convert_to_python_object(robj: CaosDBPythonEntity, +def _single_convert_to_python_object(robj: LinkAheadPythonEntity, entity: db.Entity, references: Optional[db.Container] = None): """ Convert a db.Entity from the standard API to a (previously created) - CaosDBPythonEntity from the high level API. + LinkAheadPythonEntity from the high level API. This method will not resolve any unresolved references, so reference properties as well as parents will become unresolved references in the first place. @@ -815,7 +815,7 @@ def _single_convert_to_python_object(robj: CaosDBPythonEntity, The optional third parameter can be used to resolve references that occur in the converted entities and resolve them to their correct representations. (Entities that are not found remain as - CaosDBPythonUnresolvedReferences.) + LinkAheadPythonUnresolvedReferences.) Returns the input object robj. """ @@ -830,16 +830,16 @@ def _single_convert_to_python_object(robj: CaosDBPythonEntity, robj._set_property_from_entity(prop, entity.get_importance(prop), references) for parent in entity.parents: - robj.add_parent(CaosDBPythonUnresolvedParent(id=parent.id, - name=parent.name)) + robj.add_parent(LinkAheadPythonUnresolvedParent(id=parent.id, + name=parent.name)) return robj def _convert_property_value(propval): - if isinstance(propval, CaosDBPythonUnresolvedReference): + if isinstance(propval, LinkAheadPythonUnresolvedReference): propval = propval.id - elif isinstance(propval, CaosDBPythonEntity): + elif isinstance(propval, LinkAheadPythonEntity): propval = _single_convert_to_entity( standard_type_for_high_level_type(propval)(), propval) elif isinstance(propval, list): @@ -851,19 +851,19 @@ def _convert_property_value(propval): def _single_convert_to_entity(entity: db.Entity, - robj: CaosDBPythonEntity): + robj: LinkAheadPythonEntity): """ - Convert a CaosDBPythonEntity to an entity in standard pylib format. + Convert a LinkAheadPythonEntity to an entity in standard pylib format. entity: db.Entity An empty entity. - robj: CaosDBPythonEntity - The CaosDBPythonEntity that is supposed to be converted to the entity. + robj: LinkAheadPythonEntity + The LinkAheadPythonEntity that is supposed to be converted to the entity. """ for base_attribute in BASE_ATTRIBUTES: - if base_attribute in ("file", "path") and not isinstance(robj, CaosDBPythonFile): + if base_attribute in ("file", "path") and not isinstance(robj, LinkAheadPythonFile): continue # Skip version: @@ -876,9 +876,9 @@ def _single_convert_to_entity(entity: db.Entity, entity.__setattr__(base_attribute, val) for parent in robj.get_parents(): - if isinstance(parent, CaosDBPythonUnresolvedParent): + if isinstance(parent, LinkAheadPythonUnresolvedParent): entity.add_parent(name=parent.name, id=parent.id) - elif isinstance(parent, CaosDBPythonRecordType): + elif isinstance(parent, LinkAheadPythonRecordType): raise NotImplementedError() else: raise RuntimeError("Incompatible class used as parent.") @@ -906,15 +906,15 @@ def convert_to_entity(python_object): # Create a list of objects: return [convert_to_entity(i) for i in python_object] - elif isinstance(python_object, CaosDBPythonRecord): + elif isinstance(python_object, LinkAheadPythonRecord): return _single_convert_to_entity(db.Record(), python_object) - elif isinstance(python_object, CaosDBPythonFile): + elif isinstance(python_object, LinkAheadPythonFile): return _single_convert_to_entity(db.File(), python_object) - elif isinstance(python_object, CaosDBPythonRecordType): + elif isinstance(python_object, LinkAheadPythonRecordType): return _single_convert_to_entity(db.RecordType(), python_object) - elif isinstance(python_object, CaosDBPythonProperty): + elif isinstance(python_object, LinkAheadPythonProperty): return _single_convert_to_entity(db.Property(), python_object) - elif isinstance(python_object, CaosDBPythonEntity): + elif isinstance(python_object, LinkAheadPythonEntity): return _single_convert_to_entity(db.Entity(), python_object) else: raise ValueError("Cannot convert an object of this type.") @@ -923,13 +923,13 @@ def convert_to_entity(python_object): def convert_to_python_object(entity: Union[db.Container, db.Entity], references: Optional[db.Container] = None): """ - Convert either a container of CaosDB entities or a single CaosDB entity + Convert either a container of LinkAhead entities or a single LinkAhead entity into the high level representation. The optional second parameter can be used to resolve references that occur in the converted entities and resolve them to their correct representations. (Entities that are not found remain as - CaosDBPythonUnresolvedReferences.) + LinkAheadPythonUnresolvedReferences.) """ if isinstance(entity, db.Container): # Create a list of objects: @@ -1002,10 +1002,10 @@ def load_external_record(record_name: str): return convert_to_python_object(db.Record(name=record_name).retrieve()) -def create_entity_container(record: CaosDBPythonEntity): +def create_entity_container(record: LinkAheadPythonEntity): """ Convert this record into an entity container in standard format that can be used - to insert or update entities in a running CaosDB instance. + to insert or update entities in a running LinkAhead instance. """ ent = convert_to_entity(record) lse: List[db.Entity] = [ent] diff --git a/src/linkahead/schema-pylinkahead-ini.yml b/src/linkahead/schema-pylinkahead-ini.yml index cb07dfeb84bc16e212100232403b0f66543c73e9..672576a3770fff2a4472a5e2f40578c21f888634 100644 --- a/src/linkahead/schema-pylinkahead-ini.yml +++ b/src/linkahead/schema-pylinkahead-ini.yml @@ -1,4 +1,4 @@ -schema-pycaosdb-ini: +schema-pylinkahead-ini: type: object additionalProperties: false properties: @@ -10,11 +10,11 @@ schema-pycaosdb-ini: type: integer enum: [0, 1, 2] Connection: - description: Settings for the connection to the CaosDB server + description: Settings for the connection to the LinkAhead server additionalProperties: false properties: url: - description: "URL of the CaosDB server. Allowed are HTTP and HTTPS connections. However, since authentication tokens and sometimes even passwords are send in plain text to the server it is **highly** recommended to use HTTPS connections whenever possible. HTTP is ok for testing and debugging." + description: "URL of the LinkAhead server. Allowed are HTTP and HTTPS connections. However, since authentication tokens and sometimes even passwords are send in plain text to the server it is **highly** recommended to use HTTPS connections whenever possible. HTTP is ok for testing and debugging." type: string pattern: http(s)?://[-a-zA-Z0-9\.]+(:[0-9]+)?(/)? examples: ["https://demo.indiscale.com/", "http://localhost:10080/"] @@ -65,7 +65,7 @@ schema-pycaosdb-ini: description: "Define a proxy for the http connections. These are either (non-TLS) HTTP proxies, SOCKS4 proxies, or SOCKS5 proxies. HTTPS proxies are not supported. Note: this option is overridden by the HTTP_PROXY environment variable, if present." implementation: description: This option is used internally and for testing. Do not override. - examples: [_DefaultCaosDBServerConnection] + examples: [_DefaultLinkAheadServerConnection] timeout: type: integer allOf: @@ -98,16 +98,16 @@ schema-pycaosdb-ini: then: required: [url, username] IntegrationTests: - description: "Used by the integration test suite from the caosdb-pyinttest repo." + description: "Used by the integration test suite from the linkahead-pyinttest repo." additionalProperties: true Misc: description: "Some additional configuration settings." additionalProperties: true advancedtools: - description: "Configuration settings for the caosadvancedtools." + description: "Configuration settings for the linkahead-advancedtools." additionalProperties: true caoscrawler: - description: "Configuration settings for the CaosDB Crawler." + description: "Configuration settings for the LinkAhead Crawler." additionalProperties: true sss_helper: description: "Configuration settings for server-side scripting." diff --git a/src/linkahead/utils/checkFileSystemConsistency.py b/src/linkahead/utils/checkFileSystemConsistency.py index ddbb085ac978fb52c93163dfe525b26fcd25a8f5..8b6cfd177055327a1647cacc9ca913a828f54e11 100755 --- a/src/linkahead/utils/checkFileSystemConsistency.py +++ b/src/linkahead/utils/checkFileSystemConsistency.py @@ -53,7 +53,7 @@ class CLIError(Exception): def runCheck(timeout, location): - """ Request the caosdb server to check the file system for consistency. + """ Request the LinkAhead server to check the file system for consistency. location == None means that the whole file system is being checked. Otherwise only a the directory tree under location is being checked. diff --git a/src/linkahead/utils/linkahead_admin.py b/src/linkahead/utils/linkahead_admin.py index e9a2c09b415f96825e8b70acd333ddf8d0a6c74b..f7e3b8b63f18e37e6210f2aa03f34ce5b0f688d4 100755 --- a/src/linkahead/utils/linkahead_admin.py +++ b/src/linkahead/utils/linkahead_admin.py @@ -23,7 +23,7 @@ # ** end header # -"""A small caosdb client with a focus on administration of the server.""" +"""A small LinkAhead client with a focus on administration of the server.""" from __future__ import print_function, unicode_literals @@ -301,22 +301,22 @@ USAGE version=program_version_message) parser.add_argument("--auth-token", metavar="AUTH_TOKEN", dest="auth_token", - help=("A CaosDB authentication token (default: None). " + help=("A LinkAhead authentication token (default: None). " "If the authentication token is passed, the " "`password_method` of the connection is set to " "`auth_token` and the respective configuration " - "from the pycaosdb.ini is effectively being " + "from the pylinkahead.ini is effectively being " "overridden.\nTODO: Also allow passing the token " "via environmenty variables.")) subparsers = parser.add_subparsers( title="commands", metavar="COMMAND", - description="You can invoke the following commands. Print the detailed help for each command with #> caosdb_admin COMMAND -h") + description="You can invoke the following commands. Print the detailed help for each command with #> linkahead_admin COMMAND -h") # users (CRUD) subparser = subparsers.add_parser( "create_user", - help="Create a new user in caosdb's internal user database. You need " + help="Create a new user in LinkAhead's internal user database. You need " " to activate the user before use.") subparser.set_defaults(call=do_create_user) mg = subparser.add_mutually_exclusive_group() diff --git a/src/linkahead/utils/plantuml.py b/src/linkahead/utils/plantuml.py index 1f925cbd1cfc44fadcd610f2e206a9367c2c4b2b..e5432dcebff7bd7aef83d2ad0355b34d82fbf331 100644 --- a/src/linkahead/utils/plantuml.py +++ b/src/linkahead/utils/plantuml.py @@ -113,7 +113,7 @@ def recordtypes_to_plantuml_string(iterable, Parameters ---------- - iterable: iterable of caosdb.Entity + iterable: iterable of linkahead.Entity The objects to be rendered with plantuml. no_shadow : bool, optional @@ -273,7 +273,7 @@ package \"The property P references an instance of D\" <<Rectangle>> { def retrieve_substructure(start_record_types, depth, result_id_set=None, result_container=None, cleanup=True): - """Recursively retrieves CaosDB record types and properties, starting + """Recursively retrieves LinkAhead record types and properties, starting from given initial types up to a specific depth. Parameters diff --git a/src/linkahead/utils/register_tests.py b/src/linkahead/utils/register_tests.py index 3035f69d443b2b075c275a937878e0efc99e9cdd..4c729be5a225022c8d83cb52dbafd5de339e9eb7 100644 --- a/src/linkahead/utils/register_tests.py +++ b/src/linkahead/utils/register_tests.py @@ -24,10 +24,10 @@ from linkahead import administration as admin """ This module implements a registration procedure for integration tests which -need a running CaosDB instance. +need a running LinkAhead instance. -It ensures that tests do not accidentally overwrite data in real CaosDB -instances, as it checks whether the running CaosDB instance is actually the +It ensures that tests do not accidentally overwrite data in real LinkAhead +instances, as it checks whether the running LinkAhead instance is actually the correct one, that should be used for these tests. @@ -44,7 +44,7 @@ information is stored in one of the server properties or otherwise NOTE: you probably need to use pytest with the -s option to be able to register the test interactively. Otherwise, the server property has to be - set before server start-up in the server.conf of the CaosDB server. + set before server start-up in the server.conf of the LinkAhead server. This module is intended to be used with pytest. @@ -65,24 +65,24 @@ def _register_test(): if not isinstance(res, int): raise RuntimeError("Response from server for Info could not be interpreted.") if res > 0: - raise RuntimeError("This instance of CaosDB contains entities already." + raise RuntimeError("This instance of LinkAhead contains entities already." "It must be empty in order to register a new test.") - print("Current host of CaosDB instance is: {}".format( + print("Current host of LinkAhead instance is: {}".format( db.connection.connection.get_connection()._delegate_connection.setup_fields["host"])) answer = input("This method will register your current test with key {} with the currently" - " running instance of CaosDB. Do you want to continue (y/N)?".format( + " running instance of LinkAhead. Do you want to continue (y/N)?".format( TEST_KEY)) if answer != "y": raise RuntimeError("Test registration aborted by user.") - admin.set_server_property("_CAOSDB_INTEGRATION_TEST_SUITE_KEY", + admin.set_server_property("_LINKAHEAD_INTEGRATION_TEST_SUITE_KEY", TEST_KEY) def _get_registered_test_key(): try: - return admin.get_server_property("_CAOSDB_INTEGRATION_TEST_SUITE_KEY") + return admin.get_server_property("_LINKAHEAD_INTEGRATION_TEST_SUITE_KEY") except KeyError: return None @@ -102,7 +102,7 @@ def _assure_test_is_registered(): if TEST_KEY is None: raise RuntimeError("TEST_KEY is not defined.") if not _is_registered(): - answer = input("Do you want to register this instance of CaosDB" + answer = input("Do you want to register this instance of LinkAhead" " with the current test? Do you want to continue (y/N)?") if answer == "y": _register_test() @@ -122,7 +122,7 @@ try: @pytest.fixture def clear_database(): - """Remove Records, RecordTypes, Properties, and Files ONLY IF the CaosDB + """Remove Records, RecordTypes, Properties, and Files ONLY IF the LinkAhead server the current connection points to was registered with the appropriate key. PyTestInfo Records and the corresponding RecordType and Property are preserved. @@ -133,4 +133,4 @@ try: except ImportError: raise Warning("""The register_tests module depends on pytest and is intended to be used in integration test suites for the - caosdb-pylib library only.""") + linkahead-pylib library only.""") diff --git a/src/linkahead/yamlapi.py b/src/linkahead/yamlapi.py index ba1f183dbed9334726d3d9fd5efb0800869b4b46..8b5eda55460ae085de11c6bc2507dd98e578d682 100644 --- a/src/linkahead/yamlapi.py +++ b/src/linkahead/yamlapi.py @@ -22,7 +22,7 @@ # ** end header # -"""!!! Deprecated !!! YAML interface for the database (caosdb)""" +"""!!! Deprecated !!! YAML interface for the database (LinkAhead)""" import yaml from lxml import etree @@ -37,7 +37,7 @@ import warnings def append_sublist(v, newel, def_entity_type): warnings.warn(""" This function is deprecated and will be removed with the next release. - Please use caosdb-advanced-user-tools/models/data_model.py for a + Please use linkahead-advanced-user-tools/models/data_model.py for a similar functionality.""", DeprecationWarning) if v is None: return @@ -53,7 +53,7 @@ def append_sublist(v, newel, def_entity_type): def kv_to_xml(k, v): warnings.warn(""" This function is deprecated and will be removed with the next release. - Please use caosdb-advanced-user-tools/models/data_model.py for a + Please use linkahead-advanced-user-tools/models/data_model.py for a similar functionality.""", DeprecationWarning) newel = Element(k) # code.interact(local=locals()) @@ -76,11 +76,11 @@ def kv_to_xml(k, v): def dict_to_xml(d): """ d: The dictionary (possibly loaded from yaml) - to convert to caosdb-xml. + to convert to linkahead-xml. """ warnings.warn(""" This function is deprecated and will be removed with the next release. - Please use caosdb-advanced-user-tools/models/data_model.py for a + Please use linkahead-advanced-user-tools/models/data_model.py for a similar functionality.""", DeprecationWarning) return kv_to_xml("Entities", d) @@ -88,7 +88,7 @@ def dict_to_xml(d): def yaml_to_xml(yamlstr): warnings.warn(""" This function is deprecated and will be removed with the next release. - Please use caosdb-advanced-user-tools/models/data_model.py for a + Please use linkahead-advanced-user-tools/models/data_model.py for a similar functionality.""", DeprecationWarning) """Load a yaml document from yamlstr and converts it to XML. @@ -105,7 +105,7 @@ def process(text): """Do some replacements on the original file to obtain valid yaml.""" warnings.warn(""" This function is deprecated and will be removed with the next release. - Please use caosdb-advanced-user-tools/models/data_model.py for a + Please use linkahead-advanced-user-tools/models/data_model.py for a similar functionality.""", DeprecationWarning) processed = re.sub( "^(\\s*)-\\s*\\{?(.*)\\}?\\s*$", @@ -121,7 +121,7 @@ def process(text): def yaml_file_to_xml(yamlfilename): warnings.warn(""" This function is deprecated and will be removed with the next release. - Please use caosdb-advanced-user-tools/models/data_model.py for a + Please use linkahead-advanced-user-tools/models/data_model.py for a similar functionality.""", DeprecationWarning) with open(yamlfilename, "r") as f: return yaml_to_xml(process(f.read())) @@ -135,7 +135,7 @@ def insert_yaml_file(yamlfilename, simulate=False): """ warnings.warn(""" This function is deprecated and will be removed with the next release. - Please use caosdb-advanced-user-tools/models/data_model.py for a + Please use linkahead-advanced-user-tools/models/data_model.py for a similar functionality.""", DeprecationWarning) con = get_connection() prs = etree.XMLParser(remove_blank_text=True) diff --git a/tox.ini b/tox.ini index 8212226eef2759c1864a86b8a3ad8f926480db4a..5008eb42b1b99b04d22a1c86478edbd99ef95e69 100644 --- a/tox.ini +++ b/tox.ini @@ -8,7 +8,7 @@ deps = . pytest pytest-cov jsonschema>=4.4.0 -commands=py.test --cov=caosdb -vv {posargs} +commands=py.test --cov=linkahead -vv {posargs} [flake8] max-line-length=100 @@ -16,4 +16,4 @@ max-line-length=100 [pytest] testpaths = unittests xfail_strict = True -addopts = -x -vv --cov=caosdb +addopts = -x -vv --cov=linkahead diff --git a/unittests/broken_configs/pycaosdb1.ini b/unittests/broken_configs/pylinkahead1.ini similarity index 100% rename from unittests/broken_configs/pycaosdb1.ini rename to unittests/broken_configs/pylinkahead1.ini diff --git a/unittests/broken_configs/pycaosdb2.ini b/unittests/broken_configs/pylinkahead2.ini similarity index 100% rename from unittests/broken_configs/pycaosdb2.ini rename to unittests/broken_configs/pylinkahead2.ini diff --git a/unittests/broken_configs/pycaosdb3.ini b/unittests/broken_configs/pylinkahead3.ini similarity index 100% rename from unittests/broken_configs/pycaosdb3.ini rename to unittests/broken_configs/pylinkahead3.ini diff --git a/unittests/broken_configs/pycaosdb4.ini b/unittests/broken_configs/pylinkahead4.ini similarity index 100% rename from unittests/broken_configs/pycaosdb4.ini rename to unittests/broken_configs/pylinkahead4.ini diff --git a/unittests/docker/Dockerfile b/unittests/docker/Dockerfile index 06f9d6c830068a2c1c85caef79c64f899eaefb33..b4b5ecd0af033fd5a24a0935944d485f24fe0265 100644 --- a/unittests/docker/Dockerfile +++ b/unittests/docker/Dockerfile @@ -9,6 +9,7 @@ RUN apt-get update && \ curl pycodestyle \ python3-sphinx ARG COMMIT="dev" -RUN git clone -b dev https://gitlab.indiscale.com/caosdb/src/caosdb-pylib.git && \ - cd caosdb-pylib && git checkout $COMMIT && pip3 install . +# TODO Rename to linkahead +RUN git clone -b dev https://gitlab.indiscale.com/caosdb/src/linkahead-pylib.git linkahead-pylib && \ + cd linkahead-pylib && git checkout $COMMIT && pip3 install . RUN pip3 install recommonmark sphinx-rtd-theme diff --git a/unittests/test_apiutils.py b/unittests/test_apiutils.py index 4c15230d28cf2404c53d3088316b6ddbbaa6a229..bb6f978bb83c4ee32cc485f538b8807c8f7012dd 100644 --- a/unittests/test_apiutils.py +++ b/unittests/test_apiutils.py @@ -30,8 +30,8 @@ import pytest import linkahead as db import linkahead.apiutils from linkahead.apiutils import (apply_to_ids, compare_entities, create_id_query, - empty_diff, EntityMergeConflictError, - resolve_reference, merge_entities) + empty_diff, EntityMergeConflictError, + resolve_reference, merge_entities) from linkahead.common.models import SPECIAL_ATTRIBUTES @@ -60,8 +60,8 @@ def test_id_query(): def test_resolve_reference(): - original_retrieve_entity_with_id = caosdb.apiutils.retrieve_entity_with_id - caosdb.apiutils.retrieve_entity_with_id = lambda eid: db.Record(id=eid) + original_retrieve_entity_with_id = linkahead.apiutils.retrieve_entity_with_id + linkahead.apiutils.retrieve_entity_with_id = lambda eid: db.Record(id=eid) prop = db.Property(id=1, datatype=db.REFERENCE, value=100) prop.is_valid = lambda: True @@ -93,7 +93,7 @@ def test_resolve_reference(): assert no_reference.datatype is db.INTEGER # restore retrive_entity_with_id - caosdb.apiutils.retrieve_entity_with_id = original_retrieve_entity_with_id + linkahead.apiutils.retrieve_entity_with_id = original_retrieve_entity_with_id def test_compare_entities(): diff --git a/unittests/test_authentication_auth_token.py b/unittests/test_authentication_auth_token.py index 356eb53cdc932f0d33ea5ac9153a4e20b8d6ae60..3142f1f9f54230cb19666eeb8ff5809a906f9d49 100644 --- a/unittests/test_authentication_auth_token.py +++ b/unittests/test_authentication_auth_token.py @@ -23,7 +23,7 @@ # """test_authentication_auth_token -Unit tests for the module caosdb.connection.authentication.auth_token +Unit tests for the module linkahead.connection.authentication.auth_token """ from __future__ import unicode_literals diff --git a/unittests/test_authentication_keyring.py b/unittests/test_authentication_keyring.py index d3b074795d7199a177cc44703c62074c7978049f..95f0ad1f61072297a7eacf2e6601ea8ff83e8bbf 100644 --- a/unittests/test_authentication_keyring.py +++ b/unittests/test_authentication_keyring.py @@ -23,7 +23,7 @@ # """test_authentication_keyring. -Tests for the caosdb.connection.authentication.keyring module. +Tests for the linkahead.connection.authentication.keyring module. """ import sys from pytest import raises diff --git a/unittests/test_authentication_pass.py b/unittests/test_authentication_pass.py index f3f5b6717bbb1915cd50d00cea6efba467896fe1..782577b26bb5ae0ed3b8c74cc5ac4b21b59562f0 100644 --- a/unittests/test_authentication_pass.py +++ b/unittests/test_authentication_pass.py @@ -23,11 +23,11 @@ # """test_authentication_pass. -Tests for the caosdb.connection.authentication.pass module. +Tests for the linkahead.connection.authentication.pass module. """ import sys from pytest import raises -_PASSCALLER = "caosdb.connection.authentication.pass" +_PASSCALLER = "linkahead.connection.authentication.pass" __import__(_PASSCALLER) PassCaller = sys.modules[_PASSCALLER].PassCaller diff --git a/unittests/test_authentication_plain.py b/unittests/test_authentication_plain.py index 55fbc45987c66112db00cb8ef82f3e45c6867b4d..fe11787633c9f12ccec9ef27b89e446a0ddeb1b5 100644 --- a/unittests/test_authentication_plain.py +++ b/unittests/test_authentication_plain.py @@ -23,7 +23,7 @@ # """test_authentication_plain. -Unit tests for the modul caosdb.connection.authentication.plain. +Unit tests for the modul linkahead.connection.authentication.plain. """ from __future__ import unicode_literals @@ -67,4 +67,4 @@ def test_plain_has_logger(): assert hasattr(p, "logger") assert "authentication" in p.logger.name assert "connection" in p.logger.name - assert "caosdb" in p.logger.name + assert "linkahead" in p.logger.name diff --git a/unittests/test_authentication_unauthenticated.py b/unittests/test_authentication_unauthenticated.py index efd419b364e0579e6236eee4b14b599d1ae0c24c..e039dc0bc9cd064ffe1d49d9f4e0de2aa7f7cd61 100644 --- a/unittests/test_authentication_unauthenticated.py +++ b/unittests/test_authentication_unauthenticated.py @@ -23,7 +23,7 @@ # """test_authentication_unauthenticated -Unit tests for the module caosdb.connection.authentication.unauthenticated. +Unit tests for the module linkahead.connection.authentication.unauthenticated. """ from __future__ import unicode_literals diff --git a/unittests/test_cached.py b/unittests/test_cached.py index d49b7fb3abfc26047a42fa1cca340c16ba3c55b3..29404eea07a0e9e8be270f45ccf2952a4deac735 100644 --- a/unittests/test_cached.py +++ b/unittests/test_cached.py @@ -19,10 +19,10 @@ # along with this program. If not, see <https://www.gnu.org/licenses/>. # -""" Test the caosdb.cached module """ +""" Test the linkahead.cached module """ from linkahead.cached import (cached_get_entity_by, cache_clear, cache_info, cache_fill, - AccessType, cache_initialize, cached_query) + AccessType, cache_initialize, cached_query) from unittest.mock import patch import linkahead as db from copy import deepcopy @@ -73,7 +73,7 @@ def mocked_gen_query(q, unique): return db.Container().extend(DUMMY_SERVER_CONTENT) -@patch("caosdb.utils.get_entity.get_entity_by_name") +@patch("linkahead.utils.get_entity.get_entity_by_name") def test_get_by_name(mocked_get_by_name): mocked_get_by_name.side_effect = mocked_name_query # first call; not in cache -> mocked_execute is touched @@ -107,7 +107,7 @@ def test_get_by_name(mocked_get_by_name): assert c.id == 103 -@patch("caosdb.utils.get_entity.get_entity_by_id") +@patch("linkahead.utils.get_entity.get_entity_by_id") def test_get_by_id(mocked_get_by_id): mocked_get_by_id.side_effect = mocked_id_query # first call; not in cache -> mocked_execute is touched @@ -142,7 +142,7 @@ def test_get_by_id(mocked_get_by_id): assert c.name == 'c' -@patch("caosdb.cached.get_entity.get_entity_by_path") +@patch("linkahead.cached.get_entity.get_entity_by_path") def test_get_by_path(mocked_get_by_path): mocked_get_by_path.side_effect = mocked_path_query # first call; not in cache -> mocked_execute is touched @@ -176,7 +176,7 @@ def test_get_by_path(mocked_get_by_path): assert c.id == 105 -@patch("caosdb.cached.execute_query") +@patch("linkahead.cached.execute_query") def test_get_by_query(mocked_query): mocked_query.side_effect = mocked_gen_query # test cache initialization @@ -205,7 +205,7 @@ def test_get_by_query(mocked_query): assert cache_info().misses == 2 -@patch("caosdb.cached.execute_query") +@patch("linkahead.cached.execute_query") def test_cached_query(mocked_query): mocked_query.side_effect = mocked_gen_query # test cache initialization @@ -243,7 +243,7 @@ def test_cached_query(mocked_query): assert c[0].id == 101 -@patch("caosdb.utils.get_entity.get_entity_by_name") +@patch("linkahead.utils.get_entity.get_entity_by_name") def test_cache_size(mocked_get_by_name): mocked_get_by_name.side_effect = lambda x: x # first call; not in cache -> mocked_execute is touched diff --git a/unittests/test_configs/pycaosdb-server-side-scripting.ini b/unittests/test_configs/pycaosdb-server-side-scripting.ini deleted file mode 100644 index de2867f8dc66b3e81f10f35e40c36f9cb8591604..0000000000000000000000000000000000000000 --- a/unittests/test_configs/pycaosdb-server-side-scripting.ini +++ /dev/null @@ -1,9 +0,0 @@ -; this is the pycaosdb.ini for the server-side-scripting home. -[Connection] -url = https://caosdb-server:10443 -cacert = /opt/caosdb/cert/caosdb.cert.pem -debug = 0 -timeout = 5000 - -[Misc] -sendmail = /usr/local/bin/sendmail_to_file diff --git a/unittests/test_configs/pycaosdb-IntegrationTests.ini b/unittests/test_configs/pylinkahead-IntegrationTests.ini similarity index 70% rename from unittests/test_configs/pycaosdb-IntegrationTests.ini rename to unittests/test_configs/pylinkahead-IntegrationTests.ini index cb9871708f7f23c489de0cbc8f4fbda15dfa6ad0..0965b4be218703c14bfb2c0091e989af7387051f 100644 --- a/unittests/test_configs/pycaosdb-IntegrationTests.ini +++ b/unittests/test_configs/pylinkahead-IntegrationTests.ini @@ -2,14 +2,14 @@ ## This sections needs to exist in addition to the usual section [IntegrationTests] # test_server_side_scripting.bin_dir.local=/path/to/scripting/bin -test_server_side_scripting.bin_dir.local=/home/myself/test/caosdb-server/scripting/bin -# test_server_side_scripting.bin_dir.server=/opt/caosdb/git/caosdb-server/scripting/bin +test_server_side_scripting.bin_dir.local=/home/myself/test/linkahead-server/scripting/bin +# test_server_side_scripting.bin_dir.server=/opt/linkahead/git/linkahead-server/scripting/bin # # location of the files from the pyinttest perspective # test_files.test_insert_files_in_dir.local=/extroot/test_insert_files_in_dir/ test_files.test_insert_files_in_dir.local=/home/myself/test/debug_advanced/paths/extroot/test_insert_files_in_dir -# # location of the files from the caosdb_servers perspective -test_files.test_insert_files_in_dir.server=/opt/caosdb/mnt/extroot/test_insert_files_in_dir/ +# # location of the files from the LinkAhead server's perspective +test_files.test_insert_files_in_dir.server=/opt/linkahead/mnt/extroot/test_insert_files_in_dir/ ########## Files ################## ## Used by tests of file handling. Specify the path to an existing @@ -19,8 +19,8 @@ test_files.test_insert_files_in_dir.server=/opt/caosdb/mnt/extroot/test_insert_f # location of the files from the pyinttest (i.e. host) perspective #test_files.test_insert_files_in_dir.local=/extroot/test_insert_files_in_dir/ -# location of the files from the caosdb server's perspective -#test_files.test_insert_files_in_dir.server=/opt/caosdb/mnt/extroot/test_insert_files_in_dir/ +# location of the files from the LinkAhead server's perspective +#test_files.test_insert_files_in_dir.server=/opt/linkahead/mnt/extroot/test_insert_files_in_dir/ # # location of the one-time tokens from the pyinttest's perspective # test_authentication.admin_token_crud = /authtoken/admin_token_crud.txt diff --git a/unittests/test_configs/pycaosdb-empty.ini b/unittests/test_configs/pylinkahead-empty.ini similarity index 100% rename from unittests/test_configs/pycaosdb-empty.ini rename to unittests/test_configs/pylinkahead-empty.ini diff --git a/unittests/test_configs/pycaosdb-indiscale-demo.ini b/unittests/test_configs/pylinkahead-indiscale-demo.ini similarity index 100% rename from unittests/test_configs/pycaosdb-indiscale-demo.ini rename to unittests/test_configs/pylinkahead-indiscale-demo.ini diff --git a/unittests/test_configs/pycaosdb-real-world-1.ini b/unittests/test_configs/pylinkahead-real-world-1.ini similarity index 77% rename from unittests/test_configs/pycaosdb-real-world-1.ini rename to unittests/test_configs/pylinkahead-real-world-1.ini index e524f1d3465c61d89ae4a4dda54536a722f99837..bfdb48bb56de6e834af020d5ee6da082a91050f2 100644 --- a/unittests/test_configs/pycaosdb-real-world-1.ini +++ b/unittests/test_configs/pylinkahead-real-world-1.ini @@ -1,6 +1,6 @@ [Connection] url = https://localhost:10443 -cacert = /opt/caosdb/cert/caosdb.cert.pem +cacert = /opt/linkahead/cert/caosdb.cert.pem debug = 0 timeout = 5000 @@ -10,7 +10,7 @@ entity_loan.curator_mail_from=crawler-test@example.com entity_loan.curator_mail_to=crawler-test@example.com [sss_helper] -external_uri = https://caosdb.example.com:443 +external_uri = https://linkahead.example.com:443 [advancedtools] crawler.from_mail=admin@example.com diff --git a/unittests/test_configs/pycaosdb-real-world-2.ini b/unittests/test_configs/pylinkahead-real-world-2.ini similarity index 89% rename from unittests/test_configs/pycaosdb-real-world-2.ini rename to unittests/test_configs/pylinkahead-real-world-2.ini index 5ebd115a4a4de189d22180130acca2a4b78b6daf..b9ebb85a4e114f1e1aeabf74a7e11d6f0c2cdbd2 100644 --- a/unittests/test_configs/pycaosdb-real-world-2.ini +++ b/unittests/test_configs/pylinkahead-real-world-2.ini @@ -1,6 +1,6 @@ [Connection] url = https://samplemanager.example.com:443 -cacert = /opt/caosdb/cert/caosdb.cert.pem +cacert = /opt/linkahead/cert/caosdb.cert.pem debug = 0 timeout = 5000 [Misc] diff --git a/unittests/test_configs/pylinkahead-server-side-scripting.ini b/unittests/test_configs/pylinkahead-server-side-scripting.ini new file mode 100644 index 0000000000000000000000000000000000000000..74dbb3eb97d4e7df90223779481f3632c8fab7a3 --- /dev/null +++ b/unittests/test_configs/pylinkahead-server-side-scripting.ini @@ -0,0 +1,9 @@ +; this is the pylinkahead.ini for the server-side-scripting home. +[Connection] +url = https://linkahead-server:10443 +cacert = /opt/linkahead/cert/caosdb.cert.pem +debug = 0 +timeout = 5000 + +[Misc] +sendmail = /usr/local/bin/sendmail_to_file diff --git a/unittests/test_configs/pycaosdb1.ini b/unittests/test_configs/pylinkahead1.ini similarity index 79% rename from unittests/test_configs/pycaosdb1.ini rename to unittests/test_configs/pylinkahead1.ini index dcfa7c21fac735d81ab92b33f0abd31df25fc1ad..bd9b085dcf4e47c3a55c2521d0c4bf05dcd532ef 100644 --- a/unittests/test_configs/pycaosdb1.ini +++ b/unittests/test_configs/pylinkahead1.ini @@ -1,6 +1,6 @@ [Connection] cacert=/very/long/path/to/self/signed/pem/file/caosdb.ca.pem url=https://hostname:8833/playground -password_identifier=SECTION/caosdb +password_identifier=SECTION/linkahead username=username password_method=pass diff --git a/unittests/test_configs/pycaosdb2.ini b/unittests/test_configs/pylinkahead2.ini similarity index 100% rename from unittests/test_configs/pycaosdb2.ini rename to unittests/test_configs/pylinkahead2.ini diff --git a/unittests/test_configs/pycaosdb3.ini b/unittests/test_configs/pylinkahead3.ini similarity index 100% rename from unittests/test_configs/pycaosdb3.ini rename to unittests/test_configs/pylinkahead3.ini diff --git a/unittests/test_configs/pycaosdb4.ini b/unittests/test_configs/pylinkahead4.ini similarity index 100% rename from unittests/test_configs/pycaosdb4.ini rename to unittests/test_configs/pylinkahead4.ini diff --git a/unittests/test_configs/pycaosdb5.ini b/unittests/test_configs/pylinkahead5.ini similarity index 100% rename from unittests/test_configs/pycaosdb5.ini rename to unittests/test_configs/pylinkahead5.ini diff --git a/unittests/test_configs/pycaosdb6.ini b/unittests/test_configs/pylinkahead6.ini similarity index 100% rename from unittests/test_configs/pycaosdb6.ini rename to unittests/test_configs/pylinkahead6.ini diff --git a/unittests/test_configuration.py b/unittests/test_configuration.py index 6ef147a85d25d0ead19b15060b4d27122461d1a4..53dc0d648777b50e1108ebacf83db59bea35b086 100644 --- a/unittests/test_configuration.py +++ b/unittests/test_configuration.py @@ -33,34 +33,34 @@ from pytest import raises def temp_ini_files(): created_temp_ini_cwd = False created_temp_ini_home = False - if not isfile(join(getcwd(), "pycaosdb.ini")): - open("pycaosdb.ini", 'a').close() # create temporary ini file + if not isfile(join(getcwd(), "pylinkahead.ini")): + open("pylinkahead.ini", 'a').close() # create temporary ini file created_temp_ini_cwd = True - if not isfile(expanduser("~/.pycaosdb.ini")): - open(expanduser("~/.pycaosdb.ini"), 'a').close() # create temporary ini file in home directory + if not isfile(expanduser("~/.pylinkahead.ini")): + open(expanduser("~/.pylinkahead.ini"), 'a').close() # create temporary ini file in home directory created_temp_ini_home = True yield 0 if created_temp_ini_cwd: - remove("pycaosdb.ini") + remove("pylinkahead.ini") if created_temp_ini_home: - remove(expanduser("~/.pycaosdb.ini")) - environ["PYCAOSDBINI"] = "~/.pycaosdb.ini" + remove(expanduser("~/.pylinkahead.ini")) + environ["PYLINKAHEADINI"] = "~/.pylinkahead.ini" def test_config_ini_via_envvar(temp_ini_files): with raises(KeyError): - environ["PYCAOSDBINI"] + environ["PYLINKAHEADINI"] - environ["PYCAOSDBINI"] = "bla bla" - assert environ["PYCAOSDBINI"] == "bla bla" + environ["PYLINKAHEADINI"] = "bla bla" + assert environ["PYLINKAHEADINI"] == "bla bla" # test wrong configuration file in envvar - assert not expanduser(environ["PYCAOSDBINI"]) in db.configuration._read_config_files() + assert not expanduser(environ["PYLINKAHEADINI"]) in db.configuration._read_config_files() # test good configuration file in envvar - environ["PYCAOSDBINI"] = "~/.pycaosdb.ini" - assert expanduser("~/.pycaosdb.ini") in db.configuration._read_config_files() + environ["PYLINKAHEADINI"] = "~/.pylinkahead.ini" + assert expanduser("~/.pylinkahead.ini") in db.configuration._read_config_files() # test without envvar - environ.pop("PYCAOSDBINI") - assert expanduser("~/.pycaosdb.ini") in db.configuration._read_config_files() + environ.pop("PYLINKAHEADINI") + assert expanduser("~/.pylinkahead.ini") in db.configuration._read_config_files() # test configuration file in cwd - assert join(getcwd(), "pycaosdb.ini") in db.configuration._read_config_files() + assert join(getcwd(), "pylinkahead.ini") in db.configuration._read_config_files() diff --git a/unittests/test_connection.py b/unittests/test_connection.py index a31ca6268fba1bdfa1b7b349aeff88d3fbca88de..ce442d16c5f5e550f89f3124e9a5f6e83e70e078 100644 --- a/unittests/test_connection.py +++ b/unittests/test_connection.py @@ -21,7 +21,7 @@ # # ** end header # -"""Test caosdb.connection.""" +"""Test linkahead.connection.""" # pylint: disable=missing-docstring from __future__ import print_function, unicode_literals @@ -31,14 +31,14 @@ from builtins import bytes, str # pylint: disable=redefined-builtin from linkahead import execute_query from linkahead.configuration import _reset_config, get_config from linkahead.connection.authentication.interface import CredentialsAuthenticator -from linkahead.connection.connection import (CaosDBServerConnection, - _DefaultCaosDBServerConnection, - configure_connection) +from linkahead.connection.connection import (LinkAheadServerConnection, + _DefaultLinkAheadServerConnection, + configure_connection) from linkahead.connection.mockup import (MockUpResponse, MockUpServerConnection, - _request_log_message) + _request_log_message) from linkahead.connection.utils import make_uri_path, quote, urlencode from linkahead.exceptions import (ConfigurationError, LoginFailedError, - CaosDBConnectionError) + LinkAheadConnectionError) from nose.tools import assert_equal as eq from nose.tools import assert_false as falz from nose.tools import assert_is_not_none as there @@ -117,7 +117,7 @@ def test_configure_connection(): tru(hasattr(configure_connection, "__call__")) c = configure_connection() there(c) - tru(isinstance(c._delegate_connection, _DefaultCaosDBServerConnection)) + tru(isinstance(c._delegate_connection, _DefaultLinkAheadServerConnection)) tru(isinstance(c._authenticator, CredentialsAuthenticator)) c = configure_connection( @@ -127,11 +127,11 @@ def test_configure_connection(): def test_configure_connection_bad_url(): configure_connection(url="https://localhost:8888") - with raises(CaosDBConnectionError) as exc_info: + with raises(LinkAheadConnectionError) as exc_info: configure_connection(url="ftp://localhost:8888") assert exc_info.value.args[0].startswith( "The connection url is expected to be a http or https url") - with raises(CaosDBConnectionError) as exc_info: + with raises(LinkAheadConnectionError) as exc_info: configure_connection(url="localhost:8888") assert exc_info.value.args[0].startswith( "The connection url is expected to be a http or https url") @@ -139,15 +139,15 @@ def test_configure_connection_bad_url(): def test_connection_interface(): with raiz(TypeError) as cm: - CaosDBServerConnection() - eq(cm.exception.args[0][:55], - "Can't instantiate abstract class CaosDBServerConnection") + LinkAheadServerConnection() + eq(cm.exception.args[0][:58], + "Can't instantiate abstract class LinkAheadServerConnection") - tru(hasattr(CaosDBServerConnection, "request")) - tru(hasattr(CaosDBServerConnection.request, "__call__")) + tru(hasattr(LinkAheadServerConnection, "request")) + tru(hasattr(LinkAheadServerConnection.request, "__call__")) - tru(hasattr(CaosDBServerConnection, "configure")) - tru(hasattr(CaosDBServerConnection.configure, "__call__")) + tru(hasattr(LinkAheadServerConnection, "configure")) + tru(hasattr(LinkAheadServerConnection.configure, "__call__")) def test_use_mockup_implementation(): @@ -258,7 +258,7 @@ def test_missing_implementation(): with raises(ConfigurationError) as exc_info: connection.configure() assert exc_info.value.args[0].startswith( - "Missing CaosDBServerConnection implementation.") + "Missing LinkAheadServerConnection implementation.") def test_bad_implementation_not_callable(): @@ -266,7 +266,7 @@ def test_bad_implementation_not_callable(): with raises(ConfigurationError) as exc_info: connection.configure(implementation=None) assert exc_info.value.args[0].startswith( - "Bad CaosDBServerConnection implementation.") + "Bad LinkAheadServerConnection implementation.") assert "'NoneType' object is not callable" in exc_info.value.args[0] @@ -275,9 +275,9 @@ def test_bad_implementation_wrong_class(): with raises(ConfigurationError) as exc_info: connection.configure(implementation=dict) assert exc_info.value.args[0].startswith( - "Bad CaosDBServerConnection implementation.") + "Bad LinkAheadServerConnection implementation.") assert ("The `implementation` callable did not return an instance of " - "CaosDBServerConnection.") in exc_info.value.args[0] + "LinkAheadServerConnection.") in exc_info.value.args[0] def test_missing_auth_method(): diff --git a/unittests/test_connection_utils.py b/unittests/test_connection_utils.py index e07eab4251c5be3764a9e46cc27b1c09d96cd5cc..a7ceb3b08000c69469efd059da6dcb87a1cce1b1 100644 --- a/unittests/test_connection_utils.py +++ b/unittests/test_connection_utils.py @@ -21,7 +21,7 @@ # # ** end header # -"""Test caosdb.connection.utils.""" +"""Test linkahead.connection.utils.""" # pylint: disable=missing-docstring from __future__ import unicode_literals, print_function from pytest import raises @@ -31,10 +31,10 @@ from nose.tools import (assert_equal as eq, assert_raises as raiz, assert_true from linkahead.exceptions import ConfigurationError, LoginFailedError from linkahead.connection.utils import parse_auth_token, auth_token_to_cookie from linkahead.connection.connection import ( - configure_connection, CaosDBServerConnection, - _DefaultCaosDBServerConnection) + configure_connection, LinkAheadServerConnection, + _DefaultLinkAheadServerConnection) from linkahead.connection.mockup import (MockUpServerConnection, MockUpResponse, - _request_log_message) + _request_log_message) from linkahead.configuration import get_config, _reset_config from linkahead.connection.authentication.interface import CredentialsAuthenticator from linkahead import execute_query diff --git a/unittests/test_high_level_api.py b/unittests/test_high_level_api.py index 69bb987937cc6a88d692f27d1b6e8ce4ad4d8efa..f1c4b18c4802ddbd2b0af737af6ba945cd647aaa 100644 --- a/unittests/test_high_level_api.py +++ b/unittests/test_high_level_api.py @@ -26,13 +26,13 @@ import linkahead as db from linkahead.high_level_api import (convert_to_entity, convert_to_python_object, new_high_level_entity) -from linkahead.high_level_api import (CaosDBPythonUnresolvedParent, - CaosDBPythonUnresolvedReference, - CaosDBPythonRecord, CaosDBPythonFile, +from linkahead.high_level_api import (LinkAheadPythonUnresolvedParent, + LinkAheadPythonUnresolvedReference, + LinkAheadPythonRecord, LinkAheadPythonFile, high_level_type_for_standard_type, standard_type_for_high_level_type, high_level_type_for_role, - CaosDBPythonEntity) + LinkAheadPythonEntity) from linkahead.apiutils import compare_entities from linkahead.common.datatype import (is_list_datatype, @@ -92,25 +92,25 @@ def test_convert_record(): assert obj.c == 18 assert obj.has_parent("bla") is True - assert obj.has_parent(CaosDBPythonUnresolvedParent(name="bla")) is True + assert obj.has_parent(LinkAheadPythonUnresolvedParent(name="bla")) is True # Check the has_parent function: assert obj.has_parent("test") is False - assert obj.has_parent(CaosDBPythonUnresolvedParent(name="test")) is False + assert obj.has_parent(LinkAheadPythonUnresolvedParent(name="test")) is False # duplicate parent with pytest.raises(RuntimeError): obj.add_parent("bla") # add parent with just an id: - obj.add_parent(CaosDBPythonUnresolvedParent(id=225)) + obj.add_parent(LinkAheadPythonUnresolvedParent(id=225)) assert obj.has_parent(225) is True - assert obj.has_parent(CaosDBPythonUnresolvedParent(id=225)) is True + assert obj.has_parent(LinkAheadPythonUnresolvedParent(id=225)) is True assert obj.has_parent(226) is False - assert obj.has_parent(CaosDBPythonUnresolvedParent(id=228)) is False + assert obj.has_parent(LinkAheadPythonUnresolvedParent(id=228)) is False # same with just a name: - obj.add_parent(CaosDBPythonUnresolvedParent(name="another")) + obj.add_parent(LinkAheadPythonUnresolvedParent(name="another")) assert obj.has_parent("another") is True @@ -164,7 +164,7 @@ def test_convert_with_references(): obj = convert_to_python_object(r) # Parent does not automatically lead to a datatype: assert obj.get_property_metadata("ref").datatype is "bla" - assert isinstance(obj.ref, CaosDBPythonUnresolvedReference) + assert isinstance(obj.ref, LinkAheadPythonUnresolvedReference) assert obj.ref.id == 27 @@ -186,19 +186,19 @@ def test_resolve_references(): # Nothing is going to be resolved: obj.resolve_references(False, db.Container()) - assert isinstance(obj.ref, CaosDBPythonUnresolvedReference) + assert isinstance(obj.ref, LinkAheadPythonUnresolvedReference) assert obj.ref.id == 27 assert obj.ref_false == 27 # deep == True does not help: obj.resolve_references(True, db.Container()) - assert isinstance(obj.ref, CaosDBPythonUnresolvedReference) + assert isinstance(obj.ref, LinkAheadPythonUnresolvedReference) assert obj.ref.id == 27 # But adding the reference container will do: obj.resolve_references(False, references) - assert not isinstance(obj.ref, CaosDBPythonUnresolvedReference) - assert isinstance(obj.ref, CaosDBPythonRecord) + assert not isinstance(obj.ref, LinkAheadPythonUnresolvedReference) + assert isinstance(obj.ref, LinkAheadPythonRecord) assert obj.ref.id == 27 assert obj.ref.a == 57 # Datatypes will not automatically be set: @@ -210,27 +210,27 @@ def test_resolve_references(): ref.add_property(name="ref", value=225, datatype="bla") obj = convert_to_python_object(r) - assert isinstance(obj.ref, CaosDBPythonUnresolvedReference) + assert isinstance(obj.ref, LinkAheadPythonUnresolvedReference) obj.resolve_references(False, references) - assert not isinstance(obj.ref, CaosDBPythonUnresolvedReference) - assert isinstance(obj.ref.ref, CaosDBPythonUnresolvedReference) + assert not isinstance(obj.ref, LinkAheadPythonUnresolvedReference) + assert isinstance(obj.ref.ref, LinkAheadPythonUnresolvedReference) assert obj.ref.ref.id == 225 # Will not help, because ref2 is missing in container: obj.resolve_references(True, references) - assert not isinstance(obj.ref, CaosDBPythonUnresolvedReference) - assert isinstance(obj.ref.ref, CaosDBPythonUnresolvedReference) + assert not isinstance(obj.ref, LinkAheadPythonUnresolvedReference) + assert isinstance(obj.ref.ref, LinkAheadPythonUnresolvedReference) assert obj.ref.ref.id == 225 references.append(ref2) obj.resolve_references(False, references) - assert not isinstance(obj.ref, CaosDBPythonUnresolvedReference) - assert isinstance(obj.ref.ref, CaosDBPythonUnresolvedReference) + assert not isinstance(obj.ref, LinkAheadPythonUnresolvedReference) + assert isinstance(obj.ref.ref, LinkAheadPythonUnresolvedReference) assert obj.ref.ref.id == 225 obj.resolve_references(True, references) - assert not isinstance(obj.ref, CaosDBPythonUnresolvedReference) - assert not isinstance(obj.ref.ref, CaosDBPythonUnresolvedReference) + assert not isinstance(obj.ref, LinkAheadPythonUnresolvedReference) + assert not isinstance(obj.ref.ref, LinkAheadPythonUnresolvedReference) assert obj.ref.ref.c == "test" # Test circular dependencies: @@ -303,7 +303,7 @@ def test_base_properties(): def test_empty(): r = db.Record() obj = convert_to_python_object(r) - assert isinstance(obj, CaosDBPythonRecord) + assert isinstance(obj, LinkAheadPythonRecord) assert len(obj.get_properties()) == 0 assert len(obj.get_parents()) == 0 @@ -347,7 +347,7 @@ def test_files(): r = db.File() obj = convert_to_python_object(r) print(type(obj)) - assert isinstance(obj, CaosDBPythonFile) + assert isinstance(obj, LinkAheadPythonFile) assert len(obj.get_properties()) == 0 assert len(obj.get_parents()) == 0 @@ -359,7 +359,7 @@ def test_files(): obj = convert_to_python_object(r) assert r.path == "test.dat" assert r.file == "/local/path/test.dat" - assert isinstance(obj, CaosDBPythonFile) + assert isinstance(obj, LinkAheadPythonFile) assert obj.path == "test.dat" assert obj.file == "/local/path/test.dat" @@ -385,7 +385,7 @@ def test_files(): rec = db.Record() rec.add_property(name="testfile", value=2, datatype=db.FILE) obj = convert_to_python_object(rec) - assert type(obj.testfile) == CaosDBPythonUnresolvedReference + assert type(obj.testfile) == LinkAheadPythonUnresolvedReference assert obj.testfile.id == 2 assert obj.get_property_metadata("testfile").datatype == db.FILE @@ -467,8 +467,8 @@ def test_list_types(): assert len(obj.a) == 3 assert obj.get_property_metadata("a").datatype == "LIST<TestReference>" for i in range(3): - assert type(obj.a[i]) == CaosDBPythonUnresolvedReference - assert obj.a == [CaosDBPythonUnresolvedReference(id=i) for i in [1, 2, 4]] + assert type(obj.a[i]) == LinkAheadPythonUnresolvedReference + assert obj.a == [LinkAheadPythonUnresolvedReference(id=i) for i in [1, 2, 4]] # Try resolving: @@ -478,8 +478,8 @@ def test_list_types(): assert len(obj.a) == 3 assert obj.get_property_metadata("a").datatype == "LIST<TestReference>" for i in range(3): - assert type(obj.a[i]) == CaosDBPythonUnresolvedReference - assert obj.a == [CaosDBPythonUnresolvedReference(id=i) for i in [1, 2, 4]] + assert type(obj.a[i]) == LinkAheadPythonUnresolvedReference + assert obj.a == [LinkAheadPythonUnresolvedReference(id=i) for i in [1, 2, 4]] references = db.Container() for i in [1, 2, 4]: @@ -492,7 +492,7 @@ def test_list_types(): assert len(obj.a) == 3 assert obj.get_property_metadata("a").datatype == "LIST<TestReference>" for i in range(3): - assert type(obj.a[i]) == CaosDBPythonRecord + assert type(obj.a[i]) == LinkAheadPythonRecord assert obj.a[0].val == "1 bla" @@ -523,15 +523,15 @@ def test_list_types(): # Test utility functions: def test_type_conversion(): - assert high_level_type_for_standard_type(db.Record()) == CaosDBPythonRecord - assert high_level_type_for_standard_type(db.Entity()) == CaosDBPythonEntity - assert standard_type_for_high_level_type(CaosDBPythonRecord()) == db.Record - assert standard_type_for_high_level_type(CaosDBPythonEntity()) == db.Entity - assert standard_type_for_high_level_type(CaosDBPythonFile(), True) == "File" - assert standard_type_for_high_level_type(CaosDBPythonRecord(), True) == "Record" - assert high_level_type_for_role("Record") == CaosDBPythonRecord - assert high_level_type_for_role("Entity") == CaosDBPythonEntity - assert high_level_type_for_role("File") == CaosDBPythonFile + assert high_level_type_for_standard_type(db.Record()) == LinkAheadPythonRecord + assert high_level_type_for_standard_type(db.Entity()) == LinkAheadPythonEntity + assert standard_type_for_high_level_type(LinkAheadPythonRecord()) == db.Record + assert standard_type_for_high_level_type(LinkAheadPythonEntity()) == db.Entity + assert standard_type_for_high_level_type(LinkAheadPythonFile(), True) == "File" + assert standard_type_for_high_level_type(LinkAheadPythonRecord(), True) == "Record" + assert high_level_type_for_role("Record") == LinkAheadPythonRecord + assert high_level_type_for_role("Entity") == LinkAheadPythonEntity + assert high_level_type_for_role("File") == LinkAheadPythonFile with pytest.raises(RuntimeError, match="Unknown role."): high_level_type_for_role("jkaldjfkaldsjf") @@ -556,11 +556,11 @@ def test_deserialization(): obj = convert_to_python_object(r) serial = obj.serialize() - obj_des = CaosDBPythonEntity.deserialize(serial) + obj_des = LinkAheadPythonEntity.deserialize(serial) assert obj_des.name == "test" assert obj_des.id == 17 - assert obj_des.has_parent(CaosDBPythonUnresolvedParent(name="bla")) + assert obj_des.has_parent(LinkAheadPythonUnresolvedParent(name="bla")) print(obj) print(obj_des) @@ -574,7 +574,7 @@ def test_deserialization(): obj = convert_to_python_object(f) serial = obj.serialize() - obj_des = CaosDBPythonEntity.deserialize(serial) + obj_des = LinkAheadPythonEntity.deserialize(serial) assert obj_des.file == "bla.test" assert obj_des.path == "/test/n/bla.test" @@ -593,7 +593,7 @@ def test_deserialization(): obj = convert_to_python_object(r) serial = obj.serialize() - obj_des = CaosDBPythonEntity.deserialize(serial) + obj_des = LinkAheadPythonEntity.deserialize(serial) assert obj.serialize() == obj_des.serialize() diff --git a/unittests/test_utils.py b/unittests/test_utils.py index cd91de597820aabc4b894bfd0972490c1b4e2212..3d8e2896247f66c98f1461c1a1e91baca5f01cb6 100644 --- a/unittests/test_utils.py +++ b/unittests/test_utils.py @@ -21,7 +21,7 @@ # # ** end header # -"""Tests for caosdb.common.utils.""" +"""Tests for linkahead.common.utils.""" from __future__ import unicode_literals from lxml.etree import Element from linkahead.common.utils import xml2str diff --git a/unittests/test_versioning.py b/unittests/test_versioning.py index 2862d9026f93881b552a4b32525142cd107cc434..4fbe96d3a9abbeba80a530f4049aefc8d19036e8 100644 --- a/unittests/test_versioning.py +++ b/unittests/test_versioning.py @@ -32,7 +32,7 @@ from lxml import etree def test_constructor(): v = Version(id="1234abcd", date="2020-01-01T20:15:00.000UTC", - username="testuser", realm="CaosDB", is_head=True, + username="testuser", realm="LinkAhead", is_head=True, predecessors=[Version(id="2345abdc", date="2020-01-01T20:00:00.000UTC")], successors=[Version(id="3465abdc", @@ -40,7 +40,7 @@ def test_constructor(): assert v.id == "1234abcd" assert v.date == "2020-01-01T20:15:00.000UTC" assert v.username == "testuser" - assert v.realm == "CaosDB" + assert v.realm == "LinkAhead" assert v.is_head is True assert isinstance(v.predecessors, list) assert isinstance(v.predecessors[0], Version)