From d5537d91abc9aced57358e1f802cc4c47517c702 Mon Sep 17 00:00:00 2001 From: Hongyu Li Date: Fri, 30 Apr 2021 11:51:46 -0400 Subject: [PATCH 1/2] add black formatting --- .gitignore | 1 + Taskfile.yml | 5 +++++ pylintrc | 6 ++++-- requirements-dev.txt | 1 + setup.cfg | 5 +++-- 5 files changed, 14 insertions(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index fecb95be..3bab1d39 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ dist/ *.xml htmlcov/ .pylint.d/ +.cache/ \ No newline at end of file diff --git a/Taskfile.yml b/Taskfile.yml index 150f4a40..93bc411b 100644 --- a/Taskfile.yml +++ b/Taskfile.yml @@ -36,3 +36,8 @@ tasks: - rm -rf build - rm -f dist/* - python3 setup.py bdist_wheel + + format: + desc: Format code using black + cmds: + - ./scripts/builder.sh black archivist examples unittests diff --git a/pylintrc b/pylintrc index f8dcdca5..72c87351 100644 --- a/pylintrc +++ b/pylintrc @@ -142,7 +142,9 @@ disable=print-statement, invalid-name, bad-classmethod-argument, bad-mcs-classmethod-argument, - no-self-argument + no-self-argument, + bad-continuation, + bad-whitespace # Enable the message, report, category or checker with the given id(s). You can # either give multiple identifier separated by comma (,) or put this option @@ -328,7 +330,7 @@ indent-after-paren=4 indent-string=' ' # Maximum number of characters on a single line. -max-line-length=100 +max-line-length=100 # Maximum number of lines in a module. max-module-lines=1000 diff --git a/requirements-dev.txt b/requirements-dev.txt index 9a481200..af7206f7 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -2,6 +2,7 @@ # code quality autopep8==1.5.5 +black==21.4b2 coverage==5.4 pycodestyle==2.6.0 pylint==2.6.0 diff --git a/setup.cfg b/setup.cfg index 54e5db15..74f3debd 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,3 +1,4 @@ [pycodestyle] -ignore = E128, E225, E265, E266, E402, E501, E713, E722, E741, W504, -statistics = True \ No newline at end of file +ignore = E128, E203, E225, E265, E266, E402, E501, E713, E722, E741, W504, +statistics = True +max-line-length = 88 \ No newline at end of file From 940969b0147ee78ea3f555fd7dd911bd3cc6369e Mon Sep 17 00:00:00 2001 From: Hongyu Li Date: Tue, 4 May 2021 10:47:21 -0400 Subject: [PATCH 2/2] reformatted python code --- archivist/access_policies.py | 106 +++--- archivist/archivist.py | 57 +-- archivist/assets.py | 93 +++-- archivist/attachments.py | 39 +- archivist/confirm.py | 24 +- archivist/constants.py | 4 +- archivist/errors.py | 52 +-- archivist/events.py | 95 +++-- archivist/locations.py | 76 ++-- archivist/logger.py | 7 +- examples/create_asset/create_asset.py | 32 +- examples/create_event/create_event.py | 42 ++- examples/filter_assets/filter_assets.py | 4 +- examples/filter_events/filter_event.py | 4 +- examples/get_asset/get_asset.py | 6 +- unittests/__init__.py | 4 +- unittests/mock_response.py | 8 +- unittests/testarchivist.py | 476 ++++++++++++------------ unittests/testassets.py | 321 ++++++++-------- unittests/testattachments.py | 79 ++-- unittests/testerrors.py | 58 +-- unittests/testevents.py | 367 +++++++++--------- unittests/testlocations.py | 182 +++++---- 23 files changed, 1058 insertions(+), 1078 deletions(-) diff --git a/archivist/access_policies.py b/archivist/access_policies.py index acd21515..97ba3a13 100644 --- a/archivist/access_policies.py +++ b/archivist/access_policies.py @@ -10,119 +10,119 @@ ASSETS_LABEL, ) -DEFAULT_PAGE_SIZE=500 +DEFAULT_PAGE_SIZE = 500 class _AccessPoliciesClient: - """docstring - """ + """docstring""" + def __init__(self, archivist): - """docstring - """ + """docstring""" self._archivist = archivist def create(self, request): - """docstring - """ + """docstring""" - return AccessPolicy(**self._archivist.post( - f"{ACCESS_POLICIES_SUBPATH}/{ACCESS_POLICIES_LABEL}", - request, - )) + return AccessPolicy( + **self._archivist.post( + f"{ACCESS_POLICIES_SUBPATH}/{ACCESS_POLICIES_LABEL}", + request, + ) + ) def read(self, identity): - """docstring - """ - return AccessPolicy(**self._archivist.get( - ACCESS_POLICIES_SUBPATH, - identity, - )) + """docstring""" + return AccessPolicy( + **self._archivist.get( + ACCESS_POLICIES_SUBPATH, + identity, + ) + ) def update(self, identity, request): - """docstring - """ - return AccessPolicy(**self._archivist.patch( - ACCESS_POLICIES_SUBPATH, - identity, - request, - )) + """docstring""" + return AccessPolicy( + **self._archivist.patch( + ACCESS_POLICIES_SUBPATH, + identity, + request, + ) + ) def delete(self, identity): - """docstring - """ + """docstring""" return self._archivist.delete(ACCESS_POLICIES_SUBPATH, identity) @staticmethod def __query(props): - """docstring - """ + """docstring""" query = props or {} return query def count(self, *, query=None): - """docstring - """ + """docstring""" return self._archivist.count( f"{ACCESS_POLICIES_SUBPATH}/{ACCESS_POLICIES_LABEL}", - query=self.__query(query) + query=self.__query(query), ) def list(self, *, page_size=DEFAULT_PAGE_SIZE, query=None): - """docstring - """ + """docstring""" return ( - AccessPolicy(**a) for a in self._archivist.list( + AccessPolicy(**a) + for a in self._archivist.list( f"{ACCESS_POLICIES_SUBPATH}/{ACCESS_POLICIES_LABEL}", ACCESS_POLICIES_LABEL, page_size=page_size, - query=self.__query(query) + query=self.__query(query), ) ) # additional queries on different endpoints def count_matching_assets(self, access_policy_id, *, query=None): - """docstring - """ + """docstring""" return self._archivist.count( SEP.join((ACCESS_POLICIES_SUBPATH, access_policy_id, ASSETS_LABEL)), ASSETS_LABEL, - query=self.__query(query) + query=self.__query(query), ) - def list_matching_assets(self, access_policy_id, *, page_size=DEFAULT_PAGE_SIZE, query=None): - """docstring - """ + def list_matching_assets( + self, access_policy_id, *, page_size=DEFAULT_PAGE_SIZE, query=None + ): + """docstring""" return ( - AccessPolicy(**a) for a in self._archivist.list( + AccessPolicy(**a) + for a in self._archivist.list( SEP.join((ACCESS_POLICIES_SUBPATH, access_policy_id, ASSETS_LABEL)), ASSETS_LABEL, page_size=page_size, - query=self.__query(query) + query=self.__query(query), ) ) def count_matching_access_policies(self, asset_id, *, query=None): - """docstring - """ + """docstring""" return self._archivist.count( SEP.join((ACCESS_POLICIES_SUBPATH, asset_id, ACCESS_POLICIES_LABEL)), ACCESS_POLICIES_LABEL, - query=self.__query(query) + query=self.__query(query), ) - def list_matching_access_policies(self, asset_id, *, page_size=DEFAULT_PAGE_SIZE, query=None): - """docstring - """ + def list_matching_access_policies( + self, asset_id, *, page_size=DEFAULT_PAGE_SIZE, query=None + ): + """docstring""" return ( - AccessPolicy(**a) for a in self._archivist.list( + AccessPolicy(**a) + for a in self._archivist.list( SEP.join((ACCESS_POLICIES_SUBPATH, asset_id, ASSETS_LABEL)), ACCESS_POLICIES_LABEL, page_size=page_size, - query=self.__query(query) + query=self.__query(query), ) ) class AccessPolicy(dict): - """AccessPolicy object - """ + """AccessPolicy object""" diff --git a/archivist/archivist.py b/archivist/archivist.py index 450a33bc..e958e6cb 100644 --- a/archivist/archivist.py +++ b/archivist/archivist.py @@ -44,19 +44,17 @@ class Archivist: # pylint: disable=too-many-instance-attributes Either auth or cert must be specified """ + def __init__(self, url, *, auth=None, cert=None, verify=True): - """docstring - """ - self._headers = {'content-type': 'application/json'} + """docstring""" + self._headers = {"content-type": "application/json"} if auth is not None: - self._headers['authorization'] = 'Bearer ' + auth.strip() + self._headers["authorization"] = "Bearer " + auth.strip() self._url = url self._verify = verify if not cert and not auth: - raise ArchivistIllegalArgumentError( - "Either auth or cert must be specified" - ) + raise ArchivistIllegalArgumentError("Either auth or cert must be specified") if cert and auth: raise ArchivistIllegalArgumentError( @@ -65,9 +63,7 @@ def __init__(self, url, *, auth=None, cert=None, verify=True): if cert: if not os_path_isfile(cert): - raise ArchivistNotFoundError( - f"Cert file {cert} does not exist" - ) + raise ArchivistNotFoundError(f"Cert file {cert} does not exist") self._cert = cert @@ -78,31 +74,26 @@ def __init__(self, url, *, auth=None, cert=None, verify=True): @property def headers(self): - """docstring - """ + """docstring""" return self._headers @property def url(self): - """docstring - """ + """docstring""" return self._url @property def verify(self): - """docstring - """ + """docstring""" return self._verify @property def cert(self): - """docstring - """ + """docstring""" return self._cert def __add_headers(self, headers): - """docstring - """ + """docstring""" if headers is not None: newheaders = {**self.headers, **headers} else: @@ -182,11 +173,11 @@ def post_file(self, path, fd, mtype): multipart = MultipartEncoder( fields={ - 'file': ('filename', fd, mtype), + "file": ("filename", fd, mtype), } ) headers = { - 'content-type': multipart.content_type, + "content-type": multipart.content_type, } response = requests.post( SEP.join((self.url, ROOT, path)), @@ -242,7 +233,7 @@ def patch(self, subpath, identity, request, *, headers=None): def __list(self, path, args, *, headers=None): if args: - path = '?'.join((path, args)) + path = "?".join((path, args)) response = requests.get( SEP.join((self.url, ROOT, path)), @@ -258,10 +249,8 @@ def __list(self, path, args, *, headers=None): @staticmethod def __query(query): - return query and '&'.join( - sorted( - f"{k}={v}" for k, v in flatten(query, reducer='dot').items() - ) + return query and "&".join( + sorted(f"{k}={v}" for k, v in flatten(query, reducer="dot").items()) ) def get_by_signature(self, path, field, query, *, headers=None): @@ -281,9 +270,7 @@ def get_by_signature(self, path, field, query, *, headers=None): response = self.__list( path, - '&'.join( - (a for a in (paging, qry) if a) - ), + "&".join((a for a in (paging, qry) if a)), headers=headers, ) @@ -311,15 +298,13 @@ def count(self, path, *, query=None): paging = "page_size=1" qry = self.__query(query) - headers = {HEADERS_REQUEST_TOTAL_COUNT: 'true'} + headers = {HEADERS_REQUEST_TOTAL_COUNT: "true"} # v2/assets?page_size=10&something=something... response = self.__list( path, - '&'.join( - (a for a in (paging, qry) if a) - ), + "&".join((a for a in (paging, qry) if a)), headers=headers, ) @@ -348,9 +333,7 @@ def list(self, path, field, *, page_size=None, query=None, headers=None): while True: response = self.__list( path, - '&'.join( - (a for a in (paging, qry) if a) - ), + "&".join((a for a in (paging, qry) if a)), headers=headers, ) data = response.json() diff --git a/archivist/assets.py b/archivist/assets.py index 0b857f01..6e5fdbe8 100644 --- a/archivist/assets.py +++ b/archivist/assets.py @@ -11,24 +11,22 @@ ) from .confirm import wait_for_confirmation, wait_for_confirmed -DEFAULT_PAGE_SIZE=500 +DEFAULT_PAGE_SIZE = 500 class _AssetsClient: - """docstring - """ + """docstring""" + def __init__(self, archivist): - """docstring - """ + """docstring""" self._archivist = archivist def create(self, behaviours, attrs, confirm=False): - """docstring - """ + """docstring""" return self.create_from_data( { - 'behaviours': behaviours, - 'attributes': attrs, + "behaviours": behaviours, + "attributes": attrs, }, confirm=confirm, ) @@ -39,92 +37,91 @@ def create_from_data(self, data, confirm=False): read request from data stream suitable for reading data from a file using json.load or yaml.load """ - asset = Asset(**self._archivist.post( - f"{ASSETS_SUBPATH}/{ASSETS_LABEL}", - data, - )) + asset = Asset( + **self._archivist.post( + f"{ASSETS_SUBPATH}/{ASSETS_LABEL}", + data, + ) + ) if not confirm: return asset - return wait_for_confirmation(self, asset['identity']) + return wait_for_confirmation(self, asset["identity"]) def read(self, identity): - """docstring - """ + """docstring""" return Asset(**self._archivist.get(ASSETS_SUBPATH, identity)) @staticmethod def __query(props, attrs): - """docstring - """ + """docstring""" query = deepcopy(props) if props else {} if attrs: - query['attributes'] = attrs + query["attributes"] = attrs return query def count(self, *, props=None, attrs=None): - """docstring - """ + """docstring""" return self._archivist.count( - f"{ASSETS_SUBPATH}/{ASSETS_LABEL}", - query=self.__query(props, attrs) + f"{ASSETS_SUBPATH}/{ASSETS_LABEL}", query=self.__query(props, attrs) ) def wait_for_confirmed(self, *, props=None, attrs=None): - """docstring - """ + """docstring""" return wait_for_confirmed(self, props=props, attrs=attrs) def list(self, *, page_size=DEFAULT_PAGE_SIZE, props=None, attrs=None): - """docstring - """ + """docstring""" return ( - Asset(**a) for a in self._archivist.list( + Asset(**a) + for a in self._archivist.list( f"{ASSETS_SUBPATH}/{ASSETS_LABEL}", ASSETS_LABEL, page_size=page_size, - query=self.__query(props, attrs) + query=self.__query(props, attrs), ) ) def read_by_signature(self, *, props=None, attrs=None): - """docstring - """ - return Asset(**self._archivist.get_by_signature( - f"{ASSETS_SUBPATH}/{ASSETS_LABEL}", - ASSETS_LABEL, - query=self.__query(props, attrs) - )) + """docstring""" + return Asset( + **self._archivist.get_by_signature( + f"{ASSETS_SUBPATH}/{ASSETS_LABEL}", + ASSETS_LABEL, + query=self.__query(props, attrs), + ) + ) class Asset(dict): - """docstring - """ + """docstring""" + @property def primary_image(self): - """docstring - """ + """docstring""" try: - attachments = self['attributes']['arc_attachments'] + attachments = self["attributes"]["arc_attachments"] except (KeyError, TypeError): pass else: return next( # pragma: no cover - (a for a in attachments - if 'arc_display_name' in a - if a['arc_display_name'] == "arc_primary_image"), - None + ( + a + for a in attachments + if "arc_display_name" in a + if a["arc_display_name"] == "arc_primary_image" + ), + None, ) return None @property def name(self): - """docstring - """ + """docstring""" try: - name = self['attributes']['arc_display_name'] + name = self["attributes"]["arc_display_name"] except (KeyError, TypeError): pass else: diff --git a/archivist/attachments.py b/archivist/attachments.py index bf520aae..c5c3d353 100644 --- a/archivist/attachments.py +++ b/archivist/attachments.py @@ -8,31 +8,30 @@ class _AttachmentsClient: - def __init__(self, archivist): - """docstring - """ + """docstring""" self._archivist = archivist - def upload(self, fd, *, mtype='image/jpg'): - """docstring - """ - return Attachment(**self._archivist.post_file( - f"{ATTACHMENTS_SUBPATH}/{ATTACHMENTS_LABEL}", - fd, - mtype, - )) + def upload(self, fd, *, mtype="image/jpg"): + """docstring""" + return Attachment( + **self._archivist.post_file( + f"{ATTACHMENTS_SUBPATH}/{ATTACHMENTS_LABEL}", + fd, + mtype, + ) + ) def download(self, identity, fd): - """docstring - """ - return Attachment(**self._archivist.get_file( - ATTACHMENTS_SUBPATH, - identity, - fd, - )) + """docstring""" + return Attachment( + **self._archivist.get_file( + ATTACHMENTS_SUBPATH, + identity, + fd, + ) + ) class Attachment(dict): - """Attachment object - """ + """Attachment object""" diff --git a/archivist/confirm.py b/archivist/confirm.py index 9b5c537b..5c0c3ddb 100644 --- a/archivist/confirm.py +++ b/archivist/confirm.py @@ -16,7 +16,7 @@ from .errors import ArchivistUnconfirmedError from .logger import LOGGER -MAX_TIME=1200 +MAX_TIME = 1200 def __lookup_max_time(): @@ -25,14 +25,16 @@ def __lookup_max_time(): def __backoff_handler(details): LOGGER.debug("MAX_TIME %s", MAX_TIME) - LOGGER.debug("Backing off {wait:0.1f} seconds afters {tries} tries " - "calling function {target} with args {args} and kwargs " - "{kwargs}".format(**details)) + LOGGER.debug( + "Backing off {wait:0.1f} seconds afters {tries} tries " + "calling function {target} with args {args} and kwargs " + "{kwargs}".format(**details) + ) def __on_giveup_confirmation(details): - identity = details['args'][1] - elapsed = details['elapsed'] + identity = details["args"][1] + elapsed = details["elapsed"] raise ArchivistUnconfirmedError( f"confirmation for {identity} timed out after {elapsed} seconds" ) @@ -46,8 +48,7 @@ def __on_giveup_confirmation(details): on_giveup=__on_giveup_confirmation, ) def wait_for_confirmation(self, identity): - """docstring - """ + """docstring""" entity = self.read(identity) if CONFIRMATION_STATUS not in entity: @@ -67,9 +68,9 @@ def wait_for_confirmation(self, identity): def __on_giveup_confirmed(details): - self = details['args'][0] + self = details["args"][0] count = self.pending_count - elapsed = details['elapsed'] + elapsed = details["elapsed"] raise ArchivistUnconfirmedError( f"{count} pending assets still present after {elapsed} seconds" ) @@ -83,8 +84,7 @@ def __on_giveup_confirmed(details): on_giveup=__on_giveup_confirmed, ) def wait_for_confirmed(self, *, props=None, **kwargs): - """docstring - """ + """docstring""" newprops = deepcopy(props) if props else {} newprops[CONFIRMATION_STATUS] = CONFIRMATION_PENDING diff --git a/archivist/constants.py b/archivist/constants.py index 1aabbec5..cd1da344 100644 --- a/archivist/constants.py +++ b/archivist/constants.py @@ -6,8 +6,8 @@ ROOT = "archivist" SEP = "/" -HEADERS_REQUEST_TOTAL_COUNT='x-request-total-count' -HEADERS_TOTAL_COUNT='x-total-count' +HEADERS_REQUEST_TOTAL_COUNT = "x-request-total-count" +HEADERS_TOTAL_COUNT = "x-total-count" CONFIRMATION_STATUS = "confirmation_status" CONFIRMATION_PENDING = "PENDING" diff --git a/archivist/errors.py b/archivist/errors.py index 65fe2803..306db2fc 100644 --- a/archivist/errors.py +++ b/archivist/errors.py @@ -6,98 +6,86 @@ class ArchivistError(Exception): - """Base exception fot=r archivist package - """ + """Base exception fot=r archivist package""" class ArchivistBadFieldError(ArchivistError): - """Incorrect field name in list() method - """ + """Incorrect field name in list() method""" class ArchivistUnconfirmedError(ArchivistError): - """asset or event failed to confirm after fixed timeout - """ + """asset or event failed to confirm after fixed timeout""" class ArchivistIllegalArgumentError(ArchivistError): - """Option al keyword arguments are inconsistent - """ + """Option al keyword arguments are inconsistent""" class ArchivistBadRequestError(ArchivistError): - """Ill-formed request or validation error (400) - """ + """Ill-formed request or validation error (400)""" class ArchivistDuplicateError(ArchivistError): - """Read by signature returns more than one asset - """ + """Read by signature returns more than one asset""" class ArchivistUnauthenticatedError(ArchivistError): - """user is unknown 401) - """ + """user is unknown 401)""" class ArchivistForbiddenError(ArchivistError): - """User does not have permission (403) - """ + """User does not have permission (403)""" class ArchivistNotFoundError(ArchivistError): - """Enetity does not exist (404) - """ + """Enetity does not exist (404)""" class Archivist4xxError(ArchivistError): - """Any other 4xx error - """ + """Any other 4xx error""" class ArchivistNotImplementedError(ArchivistError): - """Illegal REST verb (501) - """ + """Illegal REST verb (501)""" class ArchivistUnavailableError(ArchivistError): - """Service is unavailable REST verb (503) - """ + """Service is unavailable REST verb (503)""" class Archivist5xxError(ArchivistError): - """Any other 5xx error - """ + """Any other 5xx error""" def __identity(response): identity = "unknown" if response.request: req = response.request - body = getattr(req, 'body', None) + body = getattr(req, "body", None) if body: body = json.loads(body) - identity = body.get('identity', "unknown") + identity = body.get("identity", "unknown") return identity def parse_response(response): - """Return exception if appropriate - """ + """Return exception if appropriate""" status_code = response.status_code if status_code < 400: return None - text = response.text or '' + text = response.text or "" if 400 <= status_code < 500: return { 400: ArchivistBadRequestError(f"{text} ({status_code})"), 401: ArchivistUnauthenticatedError(f"{text} ({status_code})"), 403: ArchivistForbiddenError(f"{text} ({status_code})"), - 404: ArchivistNotFoundError(f"{__identity(response)} not found ({status_code})"), + 404: ArchivistNotFoundError( + f"{__identity(response)} not found ({status_code})" + ), }.get(status_code, Archivist4xxError(f"{text} ({status_code})")) if 500 <= status_code < 600: diff --git a/archivist/events.py b/archivist/events.py index 73ea3b6f..af751a6d 100644 --- a/archivist/events.py +++ b/archivist/events.py @@ -11,21 +11,18 @@ ) from .confirm import wait_for_confirmation, wait_for_confirmed -DEFAULT_PAGE_SIZE=500 +DEFAULT_PAGE_SIZE = 500 class _EventsClient: - """docstring - """ + """docstring""" def __init__(self, archivist): - """docstring - """ + """docstring""" self._archivist = archivist def create(self, asset_id, props, attrs, *, asset_attrs=None, confirm=False): - """docstring - """ + """docstring""" return self.create_from_data( asset_id, self.__query(props, attrs, asset_attrs), @@ -38,46 +35,48 @@ def create_from_data(self, asset_id, data, *, confirm=False): read request from data stream suitable for reading data from json.load,yaml.load from a file """ - event = Event(**self._archivist.post( - SEP.join((ASSETS_SUBPATH, asset_id, EVENTS_LABEL)), - data, - )) + event = Event( + **self._archivist.post( + SEP.join((ASSETS_SUBPATH, asset_id, EVENTS_LABEL)), + data, + ) + ) if not confirm: return event - return wait_for_confirmation(self, event['identity']) + return wait_for_confirmation(self, event["identity"]) def read(self, identity): - """docstring - """ - return Event(**self._archivist.get( - ASSETS_SUBPATH, - identity, - )) + """docstring""" + return Event( + **self._archivist.get( + ASSETS_SUBPATH, + identity, + ) + ) @staticmethod def __query(props, attrs, asset_attrs): - """docstring - """ + """docstring""" query = deepcopy(props) if props else {} if attrs: - query['event_attributes'] = attrs + query["event_attributes"] = attrs if asset_attrs: - query['asset_attributes'] = asset_attrs + query["asset_attributes"] = asset_attrs return query - def count(self, *, asset_id=ASSETS_WILDCARD, props=None, attrs=None, asset_attrs=None): - """docstring - """ + def count( + self, *, asset_id=ASSETS_WILDCARD, props=None, attrs=None, asset_attrs=None + ): + """docstring""" return self._archivist.count( SEP.join((ASSETS_SUBPATH, asset_id, EVENTS_LABEL)), - query=self.__query(props, attrs, asset_attrs) + query=self.__query(props, attrs, asset_attrs), ) def wait_for_confirmed(self, *, asset_id=ASSETS_WILDCARD, props=None, attrs=None): - """docstring - """ + """docstring""" return wait_for_confirmed(self, asset_id=asset_id, props=props, attrs=attrs) def list( @@ -89,14 +88,14 @@ def list( attrs=None, asset_attrs=None, ): - """docstring - """ + """docstring""" return ( - Event(**a) for a in self._archivist.list( + Event(**a) + for a in self._archivist.list( SEP.join((ASSETS_SUBPATH, asset_id, EVENTS_LABEL)), EVENTS_LABEL, page_size=page_size, - query=self.__query(props, attrs, asset_attrs) + query=self.__query(props, attrs, asset_attrs), ) ) @@ -108,32 +107,31 @@ def read_by_signature( attrs=None, asset_attrs=None, ): - """docstring - """ - return Event(**self._archivist.get_by_signature( - SEP.join((ASSETS_SUBPATH, asset_id, EVENTS_LABEL)), - EVENTS_LABEL, - query=self.__query(props, attrs, asset_attrs) - )) + """docstring""" + return Event( + **self._archivist.get_by_signature( + SEP.join((ASSETS_SUBPATH, asset_id, EVENTS_LABEL)), + EVENTS_LABEL, + query=self.__query(props, attrs, asset_attrs), + ) + ) class Event(dict): - """docstring - """ + """docstring""" @property def when(self): - """docstring - """ + """docstring""" try: - when = self['timestamp_declared'] + when = self["timestamp_declared"] except KeyError: pass else: return when try: - when = self['timestamp_accepted'] + when = self["timestamp_accepted"] except KeyError: pass else: @@ -143,18 +141,17 @@ def when(self): @property def who(self): - """docstring - """ + """docstring""" try: - who = self['principal_declared']['display_name'] + who = self["principal_declared"]["display_name"] except (KeyError, TypeError): pass else: return who try: - who = self['principal_accepted']['display_name'] + who = self["principal_accepted"]["display_name"] except (KeyError, TypeError): pass else: diff --git a/archivist/locations.py b/archivist/locations.py index c30f7612..5d391c44 100644 --- a/archivist/locations.py +++ b/archivist/locations.py @@ -5,82 +5,78 @@ from .constants import LOCATIONS_SUBPATH, LOCATIONS_LABEL -DEFAULT_PAGE_SIZE=500 +DEFAULT_PAGE_SIZE = 500 class _LocationsClient: - """docstring - """ + """docstring""" + def __init__(self, archivist): - """docstring - """ + """docstring""" self._archivist = archivist def create(self, props, *, attrs=None): - """docstring - """ - return self.create_from_data( - self.__query(props, attrs) - ) + """docstring""" + return self.create_from_data(self.__query(props, attrs)) def create_from_data(self, data): """docstring read request from data stream """ - return Location(**self._archivist.post( - f"{LOCATIONS_SUBPATH}/{LOCATIONS_LABEL}", - data, - )) + return Location( + **self._archivist.post( + f"{LOCATIONS_SUBPATH}/{LOCATIONS_LABEL}", + data, + ) + ) def read(self, identity): - """docstring - """ - return Location(**self._archivist.get( - LOCATIONS_SUBPATH, - identity, - )) + """docstring""" + return Location( + **self._archivist.get( + LOCATIONS_SUBPATH, + identity, + ) + ) @staticmethod def __query(props, attrs): - """docstring - """ + """docstring""" query = props or {} if attrs: - query['attributes'] = attrs + query["attributes"] = attrs return query def count(self, *, props=None, attrs=None): - """docstring - """ + """docstring""" return self._archivist.count( - f"{LOCATIONS_SUBPATH}/{LOCATIONS_LABEL}", - query=self.__query(props, attrs) + f"{LOCATIONS_SUBPATH}/{LOCATIONS_LABEL}", query=self.__query(props, attrs) ) def list(self, *, page_size=DEFAULT_PAGE_SIZE, props=None, attrs=None): - """docstring - """ + """docstring""" return ( - Location(**a) for a in self._archivist.list( + Location(**a) + for a in self._archivist.list( f"{LOCATIONS_SUBPATH}/{LOCATIONS_LABEL}", LOCATIONS_LABEL, page_size=page_size, - query=self.__query(props, attrs) + query=self.__query(props, attrs), ) ) def read_by_signature(self, *, props=None, attrs=None): - """docstring - """ - return Location(**self._archivist.get_by_signature( - f"{LOCATIONS_SUBPATH}/{LOCATIONS_LABEL}", - LOCATIONS_LABEL, - query=self.__query(props, attrs) - )) + """docstring""" + return Location( + **self._archivist.get_by_signature( + f"{LOCATIONS_SUBPATH}/{LOCATIONS_LABEL}", + LOCATIONS_LABEL, + query=self.__query(props, attrs), + ) + ) class Location(dict): - """Location object - """ + """Location object""" diff --git a/archivist/logger.py b/archivist/logger.py index 27e011c1..3fd35b70 100644 --- a/archivist/logger.py +++ b/archivist/logger.py @@ -8,11 +8,8 @@ # base logger from which all loggers are propagated LOGGER = logging.getLogger() -LOGFMT = ( - '%(asctime)s.%(msecs)03d|%(threadName)s' - '|%(levelname)s|%(name)s|%(message)s' -) -DATEFMT = '%Y-%m-%d %H:%M:%S' +LOGFMT = "%(asctime)s.%(msecs)03d|%(threadName)s|%(levelname)s|%(name)s|%(message)s" +DATEFMT = "%Y-%m-%d %H:%M:%S" def set_logger(level): diff --git a/examples/create_asset/create_asset.py b/examples/create_asset/create_asset.py index f89469a9..91fc5d8a 100644 --- a/examples/create_asset/create_asset.py +++ b/examples/create_asset/create_asset.py @@ -38,19 +38,25 @@ def create_asset(arch): "arc_display_name": "display_name", # Asset's display name in the user interface "arc_description": "display_description", # Asset's description in the user interface "arc_display_type": "desplay_type", # Arc_display_type is a free text field - # allowing the creator of - # an asset to specify the asset - # type or class. Be careful when setting this: - # assets are grouped by type and - # sharing policies can be - # configured to share assets based on - # their arc_display_type. - # So a mistake here can result in asset data being - # under- or over-shared. + # allowing the creator of + # an asset to specify the asset + # type or class. Be careful when setting this: + # assets are grouped by type and + # sharing policies can be + # configured to share assets based on + # their arc_display_type. + # So a mistake here can result in asset data being + # under- or over-shared. "some_custom_attribute": "value" # You can add any custom value as long as - # it does not start with arc_ + # it does not start with arc_ } - behaviours = ["Attachments", "Firmware", "LocationUpdate", "Maintenance", "RecordEvidence"] + behaviours = [ + "Attachments", + "Firmware", + "LocationUpdate", + "Maintenance", + "RecordEvidence", + ] # The first argument is the behaviours of the asset # The second argument is the attributes of the asset @@ -65,12 +71,12 @@ def create_asset(arch): def main(): - """ Main function of create asset. + """Main function of create asset. Parse in user input of url and auth token and use them to create an example archivist connection and create an asset. """ - with open(".auth_token", mode='r') as tokenfile: + with open(".auth_token", mode="r") as tokenfile: authtoken = tokenfile.read().strip() # Initialize connection to Archivist diff --git a/examples/create_event/create_event.py b/examples/create_event/create_event.py index a5089a06..52c1ec2e 100644 --- a/examples/create_event/create_event.py +++ b/examples/create_event/create_event.py @@ -53,8 +53,8 @@ def create_event(arch, asset): "principal_declared": { "issuer": "idp.synsation.io/1234", "subject": "phil.b", - "email": "phil.b@synsation.io" - } + "email": "phil.b@synsation.io", + }, } attrs = { # Required Details of the RecordEvidence request @@ -63,10 +63,10 @@ def create_event(arch, asset): "arc_evidence": "DVA Conformance Report attached", # Example Client can add any additional information in further attributes, # including free text or attachments - "conformance_report": "blobs/e2a1d16c-03cd-45a1-8cd0-690831df1273" + "conformance_report": "blobs/e2a1d16c-03cd-45a1-8cd0-690831df1273", } - return arch.events.create(asset['identity'], props=props, attrs=attrs) + return arch.events.create(asset["identity"], props=props, attrs=attrs) def create_asset(arch): @@ -82,19 +82,25 @@ def create_asset(arch): "arc_display_name": "display_name", # Asset's display name in the user interface "arc_description": "display_description", # Asset's description in the user interface "arc_display_type": "desplay_type", # Arc_display_type is a free text field - # allowing the creator of - # an asset to specify the asset - # type or class. Be careful when setting this: - # assets are grouped by type and - # sharing policies can be - # configured to share assets based on - # their arc_display_type. - # So a mistake here can result in asset data being - # under- or over-shared. + # allowing the creator of + # an asset to specify the asset + # type or class. Be careful when setting this: + # assets are grouped by type and + # sharing policies can be + # configured to share assets based on + # their arc_display_type. + # So a mistake here can result in asset data being + # under- or over-shared. "some_custom_attribute": "value" # You can add any custom value as long as - # it does not start with arc_ + # it does not start with arc_ } - behaviours = ["Attachments", "Firmware", "LocationUpdate", "Maintenance", "RecordEvidence"] + behaviours = [ + "Attachments", + "Firmware", + "LocationUpdate", + "Maintenance", + "RecordEvidence", + ] # The first argument is the behaviours of the asset # The second argument is the attributes of the asset @@ -109,14 +115,14 @@ def create_asset(arch): def main(): - """ Main function of create event. + """Main function of create event. Parse in user input of url and auth token and use them to create an example archivist connection and create an asset. The main function then uses the asset to create an event for the asset and fetch the event. """ - with open(".auth_token", mode='r') as tokenfile: + with open(".auth_token", mode="r") as tokenfile: authtoken = tokenfile.read().strip() # Initialize connection to Archivist @@ -129,7 +135,7 @@ def main(): # Create a new event new_event = create_event(arch, new_asset) # Fetch the event - unused_event = arch.events.read(new_event['identity']) + unused_event = arch.events.read(new_event["identity"]) if __name__ == "__main__": diff --git a/examples/filter_assets/filter_assets.py b/examples/filter_assets/filter_assets.py index 64584fc8..f1f12b58 100644 --- a/examples/filter_assets/filter_assets.py +++ b/examples/filter_assets/filter_assets.py @@ -29,14 +29,14 @@ def main(): - """ Main function of filtering assets. + """Main function of filtering assets. Parse in user input of url and auth token and use them to create an example archivist connection and passed-in properties attributes to filter all assets of the selected properties and attributes through function get_matching_assets. """ - with open(".auth_token", mode='r') as tokenfile: + with open(".auth_token", mode="r") as tokenfile: authtoken = tokenfile.read().strip() # Initialize connection to Archivist diff --git a/examples/filter_events/filter_event.py b/examples/filter_events/filter_event.py index b6fdbc7d..9e9de32d 100644 --- a/examples/filter_events/filter_event.py +++ b/examples/filter_events/filter_event.py @@ -28,7 +28,7 @@ def main(): - """ Main function of filtering events. + """Main function of filtering events. Parse in user input of url and auth token and use them to create an example archivist connection and passed-in properties @@ -36,7 +36,7 @@ def main(): attributes through function get_matching_events. """ - with open(".auth_token", mode='r') as tokenfile: + with open(".auth_token", mode="r") as tokenfile: authtoken = tokenfile.read().strip() # Initialize connection to Archivist diff --git a/examples/get_asset/get_asset.py b/examples/get_asset/get_asset.py index 7813223f..f5471b61 100644 --- a/examples/get_asset/get_asset.py +++ b/examples/get_asset/get_asset.py @@ -28,12 +28,12 @@ def main(): - """ Main function of get_asset. + """Main function of get_asset. Parse in user input of url and auth token and use them to create an example archivist connection and fetch all assets. """ - with open(".auth_token", mode='r') as tokenfile: + with open(".auth_token", mode="r") as tokenfile: authtoken = tokenfile.read().strip() # Initialize connection to Archivist @@ -42,7 +42,7 @@ def main(): auth=authtoken, ) for asset in arch.assets.list(): - print("asset id:", asset['identity']) + print("asset id:", asset["identity"]) if __name__ == "__main__": diff --git a/unittests/__init__.py b/unittests/__init__.py index 0518c6a8..c5479051 100644 --- a/unittests/__init__.py +++ b/unittests/__init__.py @@ -1,3 +1,3 @@ -''' +""" Unit tests -''' +""" diff --git a/unittests/mock_response.py b/unittests/mock_response.py index 19a80301..93405ea6 100644 --- a/unittests/mock_response.py +++ b/unittests/mock_response.py @@ -1,6 +1,6 @@ -''' +""" Mock response object -''' +""" import json @@ -8,7 +8,9 @@ class MockResponse(dict): - def __init__(self, status_code, request=None, headers=None, iter_content=None, **kwargs): + def __init__( + self, status_code, request=None, headers=None, iter_content=None, **kwargs + ): super().__init__(**kwargs) self.status_code = status_code self._headers = headers diff --git a/unittests/testarchivist.py b/unittests/testarchivist.py index c90671a2..159cfc06 100644 --- a/unittests/testarchivist.py +++ b/unittests/testarchivist.py @@ -1,6 +1,6 @@ -''' +""" Test archivist -''' +""" from io import BytesIO from unittest import TestCase, mock @@ -24,13 +24,14 @@ class TestArchivist(TestCase): - ''' + """ Test Archivist class - ''' + """ + def test_archivist(self): - ''' + """ Test default archivist creation - ''' + """ arch = Archivist("url", auth="authauthauth") self.assertEqual( arch.url, @@ -40,8 +41,8 @@ def test_archivist(self): self.assertEqual( arch.headers, { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", + "content-type": "application/json", + "authorization": "Bearer authauthauth", }, msg="Incorrect auth headers", ) @@ -51,9 +52,9 @@ def test_archivist(self): ) def test_archivist_no_verify(self): - ''' + """ Test archivist creation with no verify - ''' + """ arch = Archivist("url", auth="authauthauth", verify=False) self.assertFalse( arch.verify, @@ -61,33 +62,33 @@ def test_archivist_no_verify(self): ) def test_archivist_with_neither_auth_and_cert(self): - ''' + """ Test archivist creation with both auth and cert - ''' + """ with self.assertRaises(ArchivistIllegalArgumentError): arch = Archivist("url") def test_archivist_with_both_auth_and_cert(self): - ''' + """ Test archivist creation with both auth and cert - ''' + """ with self.assertRaises(ArchivistIllegalArgumentError): arch = Archivist("url", auth="authauthauth", cert="/path/to/file") - @mock.patch('archivist.archivist.os_path_isfile') + @mock.patch("archivist.archivist.os_path_isfile") def test_archivist_with_nonexistent_cert(self, mock_isfile): - ''' + """ Test archivist creation with nonexistent cert - ''' + """ mock_isfile.return_value = False with self.assertRaises(ArchivistNotFoundError): arch = Archivist("url", cert="/path/to/file") - @mock.patch('archivist.archivist.os_path_isfile') + @mock.patch("archivist.archivist.os_path_isfile") def test_archivist_with_existent_cert(self, mock_isfile): - ''' + """ Test archivist creation with cert - ''' + """ mock_isfile.return_value = True arch = Archivist("url", cert="/path/to/file") self.assertEqual( @@ -98,57 +99,59 @@ def test_archivist_with_existent_cert(self, mock_isfile): class TestArchivistMethods(TestCase): - ''' + """ Test Archivist base method class - ''' + """ + def setUp(self): self.arch = Archivist("url", auth="authauthauth") class TestArchivistPost(TestArchivistMethods): - ''' + """ Test Archivist POST method - ''' - @mock.patch('requests.post') + """ + + @mock.patch("requests.post") def test_post(self, mock_post): - ''' + """ Test default post method - ''' + """ request = {"field1": "value1"} mock_post.return_value = MockResponse(200, request=request) resp = self.arch.post("path/path", request) self.assertEqual( tuple(mock_post.call_args), ( - (f"url/{ROOT}/path/path", ), + (f"url/{ROOT}/path/path",), { - 'data': '{"field1": "value1"}', - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", + "data": '{"field1": "value1"}', + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="POST method called incorrectly", ) - @mock.patch('requests.post') + @mock.patch("requests.post") def test_post_with_error(self, mock_post): - ''' + """ Test post method with error - ''' + """ request = {"field1": "value1"} mock_post.return_value = MockResponse(400, request=request, field1="value1") with self.assertRaises(ArchivistBadRequestError): resp = self.arch.post("path/path", request) - @mock.patch('requests.post') + @mock.patch("requests.post") def test_post_with_headers(self, mock_post): - ''' + """ Test default post method - ''' + """ request = {"field1": "value1"} mock_post.return_value = MockResponse(200, request=request) resp = self.arch.post( @@ -159,26 +162,26 @@ def test_post_with_headers(self, mock_post): self.assertEqual( tuple(mock_post.call_args), ( - (f"url/{ROOT}/path/path", ), + (f"url/{ROOT}/path/path",), { - 'data': '{"field1": "value1"}', - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", + "data": '{"field1": "value1"}', + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", "headerfield1": "headervalue1", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="POST method called incorrectly", ) - @mock.patch('requests.post') + @mock.patch("requests.post") def test_post_file(self, mock_post): - ''' + """ Test default post_file method - ''' + """ mock_post.return_value = MockResponse(200) resp = self.arch.post_file( "path/path", @@ -201,17 +204,17 @@ def test_post_file(self, mock_post): 4, msg="Incorrect number of keyword arguments", ) - headers = kwargs.get('headers') + headers = kwargs.get("headers") self.assertNotEqual( headers, None, msg="Header does not exist", ) self.assertTrue( - headers['content-type'].startswith('multipart/form-data'), + headers["content-type"].startswith("multipart/form-data"), msg="Incorrect content-type", ) - data = kwargs.get('data') + data = kwargs.get("data") self.assertIsNotNone( data, msg="Incorrect data", @@ -221,27 +224,27 @@ def test_post_file(self, mock_post): fields, msg="Incorrect fields", ) - myfile = fields.get('file') + myfile = fields.get("file") self.assertIsNotNone( myfile, msg="Incorrect file key", ) self.assertEqual( myfile[0], - 'filename', + "filename", msg="Incorrect filename", ) self.assertEqual( myfile[2], - 'image/jpg', + "image/jpg", msg="Incorrect mimetype", ) - @mock.patch('requests.post') + @mock.patch("requests.post") def test_post_file_with_error(self, mock_post): - ''' + """ Test post method with error - ''' + """ mock_post.return_value = MockResponse(400) with self.assertRaises(ArchivistBadRequestError): resp = self.arch.post_file( @@ -252,46 +255,48 @@ def test_post_file_with_error(self, mock_post): class TestArchivistGet(TestArchivistMethods): - ''' + """ Test Archivist Get method - ''' - @mock.patch('requests.get') + """ + + @mock.patch("requests.get") def test_get(self, mock_get): - ''' + """ Test default get method - ''' + """ mock_get.return_value = MockResponse(200) resp = self.arch.get("path/path", "entity/xxxxxxxx") self.assertEqual( tuple(mock_get.call_args), ( - (f"url/{ROOT}/path/path/entity/xxxxxxxx", ), + (f"url/{ROOT}/path/path/entity/xxxxxxxx",), { - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="GET method called incorrectly", ) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_get_with_error(self, mock_get): - ''' + """ Test get method with error - ''' + """ mock_get.return_value = MockResponse(404, identity="entity/xxxxxxxx") with self.assertRaises(ArchivistNotFoundError): resp = self.arch.get("path/path", "entity/xxxxxxxx") - @mock.patch('requests.get') + @mock.patch("requests.get") def test_get_file(self, mock_get): - ''' + """ Test default get method - ''' + """ + def iter_content(): i = 0 @@ -317,35 +322,35 @@ def filedata(chunk_size=4096): # pylint: disable=unused-argument self.assertEqual( tuple(mock_get.call_args), ( - (f"url/{ROOT}/path/path/entity/xxxxxxxx", ), + (f"url/{ROOT}/path/path/entity/xxxxxxxx",), { - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", }, - 'verify': True, - 'cert': None, - 'stream': True, + "verify": True, + "cert": None, + "stream": True, }, ), msg="GET method called incorrectly", ) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_get_file_with_error(self, mock_get): - ''' + """ Test get method with error - ''' + """ mock_get.return_value = MockResponse(404, identity="entity/xxxxxxxx") with self.assertRaises(ArchivistNotFoundError): with BytesIO() as fd: resp = self.arch.get_file("path/path", "entity/xxxxxxxx", fd) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_get_with_headers(self, mock_get): - ''' + """ Test default get method - ''' + """ mock_get.return_value = MockResponse(200) resp = self.arch.get( "path/path", @@ -355,15 +360,15 @@ def test_get_with_headers(self, mock_get): self.assertEqual( tuple(mock_get.call_args), ( - (f"url/{ROOT}/path/path/id/xxxxxxxx", ), + (f"url/{ROOT}/path/path/id/xxxxxxxx",), { - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", "headerfield1": "headervalue1", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="GET method called incorrectly", @@ -371,46 +376,47 @@ def test_get_with_headers(self, mock_get): class TestArchivistDelete(TestArchivistMethods): - ''' + """ Test Archivist Delete method - ''' - @mock.patch('requests.delete') + """ + + @mock.patch("requests.delete") def test_delete(self, mock_delete): - ''' + """ Test default delete method - ''' + """ mock_delete.return_value = MockResponse(200) resp = self.arch.delete("path/path", "entity/xxxxxxxx") self.assertEqual( tuple(mock_delete.call_args), ( - (f"url/{ROOT}/path/path/entity/xxxxxxxx", ), + (f"url/{ROOT}/path/path/entity/xxxxxxxx",), { - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="DELETE method called incorrectly", ) - @mock.patch('requests.delete') + @mock.patch("requests.delete") def test_delete_with_error(self, mock_delete): - ''' + """ Test delete method with error - ''' + """ mock_delete.return_value = MockResponse(404, identity="entity/xxxxxxxx") with self.assertRaises(ArchivistNotFoundError): resp = self.arch.delete("path/path", "entity/xxxxxxxx") - @mock.patch('requests.delete') + @mock.patch("requests.delete") def test_delete_with_headers(self, mock_delete): - ''' + """ Test default delete method - ''' + """ mock_delete.return_value = MockResponse(200) resp = self.arch.delete( "path/path", @@ -420,15 +426,15 @@ def test_delete_with_headers(self, mock_delete): self.assertEqual( tuple(mock_delete.call_args), ( - (f"url/{ROOT}/path/path/id/xxxxxxxx", ), + (f"url/{ROOT}/path/path/id/xxxxxxxx",), { - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", "headerfield1": "headervalue1", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="DELETE method called incorrectly", @@ -436,49 +442,50 @@ def test_delete_with_headers(self, mock_delete): class TestArchivistPatch(TestArchivistMethods): - ''' + """ Test Archivist PATCH method - ''' - @mock.patch('requests.patch') + """ + + @mock.patch("requests.patch") def test_patch(self, mock_patch): - ''' + """ Test default patch method - ''' + """ request = {"field1": "value1"} mock_patch.return_value = MockResponse(200, request=request) resp = self.arch.patch("path/path", "entity/xxxx", request) self.assertEqual( tuple(mock_patch.call_args), ( - (f"url/{ROOT}/path/path/entity/xxxx", ), + (f"url/{ROOT}/path/path/entity/xxxx",), { - 'data': '{"field1": "value1"}', - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", + "data": '{"field1": "value1"}', + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="POST method called incorrectly", ) - @mock.patch('requests.patch') + @mock.patch("requests.patch") def test_patch_with_error(self, mock_patch): - ''' + """ Test post method with error - ''' + """ request = {"field1": "value1"} mock_patch.return_value = MockResponse(400, request=request, field1="value1") with self.assertRaises(ArchivistBadRequestError): resp = self.arch.patch("path/path", "entity/xxxx", request) - @mock.patch('requests.patch') + @mock.patch("requests.patch") def test_patch_with_headers(self, mock_patch): - ''' + """ Test default patch method - ''' + """ request = {"field1": "value1"} mock_patch.return_value = MockResponse(200, request=request) resp = self.arch.patch( @@ -490,16 +497,16 @@ def test_patch_with_headers(self, mock_patch): self.assertEqual( tuple(mock_patch.call_args), ( - (f"url/{ROOT}/path/path/entity/xxxx", ), + (f"url/{ROOT}/path/path/entity/xxxx",), { - 'data': '{"field1": "value1"}', - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", + "data": '{"field1": "value1"}', + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", "headerfield1": "headervalue1", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="PATCH method called incorrectly", @@ -507,14 +514,15 @@ def test_patch_with_headers(self, mock_patch): class TestArchivistCount(TestArchivistMethods): - ''' + """ Test Archivist count method - ''' - @mock.patch('requests.get') + """ + + @mock.patch("requests.get") def test_count(self, mock_get): - ''' + """ Test default count method - ''' + """ mock_get.return_value = MockResponse( 200, headers={HEADERS_TOTAL_COUNT: 1}, @@ -531,11 +539,11 @@ def test_count(self, mock_get): msg="incorrect count", ) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_count_with_error(self, mock_get): - ''' + """ Test default count method with error - ''' + """ mock_get.return_value = MockResponse( 400, things=[ @@ -549,14 +557,15 @@ def test_count_with_error(self, mock_get): class TestArchivistList(TestArchivistMethods): - ''' + """ Test Archivist list method - ''' - @mock.patch('requests.get') + """ + + @mock.patch("requests.get") def test_list(self, mock_get): - ''' + """ Test default list method - ''' + """ mock_get.return_value = MockResponse( 200, things=[ @@ -576,24 +585,24 @@ def test_list(self, mock_get): self.assertEqual( tuple(a), ( - (f"url/{ROOT}/path/path", ), + (f"url/{ROOT}/path/path",), { - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="GET method called incorrectly", ) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_list_with_error(self, mock_get): - ''' + """ Test default list method with error - ''' + """ mock_get.return_value = MockResponse( 400, things=[ @@ -606,11 +615,11 @@ def test_list_with_error(self, mock_get): with self.assertRaises(ArchivistBadRequestError): responses = [r for r in listing] - @mock.patch('requests.get') + @mock.patch("requests.get") def test_list_with_bad_field(self, mock_get): - ''' + """ Test default list method with error - ''' + """ mock_get.return_value = MockResponse( 200, things=[ @@ -623,11 +632,11 @@ def test_list_with_bad_field(self, mock_get): with self.assertRaises(ArchivistBadFieldError): responses = [r for r in listing] - @mock.patch('requests.get') + @mock.patch("requests.get") def test_list_with_headers(self, mock_get): - ''' + """ Test default list method - ''' + """ mock_get.return_value = MockResponse( 200, things=[ @@ -651,25 +660,25 @@ def test_list_with_headers(self, mock_get): self.assertEqual( tuple(a), ( - (f"url/{ROOT}/path/path", ), + (f"url/{ROOT}/path/path",), { - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", "headerfield1": "headervalue1", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="GET method called incorrectly", ) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_list_with_query(self, mock_get): - ''' + """ Test default list method - ''' + """ mock_get.return_value = MockResponse( 200, things=[ @@ -693,24 +702,24 @@ def test_list_with_query(self, mock_get): self.assertEqual( tuple(a), ( - (f"url/{ROOT}/path/path?queryfield1=queryvalue1", ), + (f"url/{ROOT}/path/path?queryfield1=queryvalue1",), { - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="GET method called incorrectly", ) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_list_with_page_size(self, mock_get): - ''' + """ Test default list method - ''' + """ values = ("value10", "value11") mock_get.return_value = MockResponse( 200, @@ -738,14 +747,14 @@ def test_list_with_page_size(self, mock_get): self.assertEqual( tuple(a), ( - (f"url/{ROOT}/path/path?page_size=2", ), + (f"url/{ROOT}/path/path?page_size=2",), { - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="GET method called incorrectly", @@ -753,19 +762,19 @@ def test_list_with_page_size(self, mock_get): for i, r in enumerate(responses): self.assertEqual( - r['field1'], + r["field1"], values[i], msg="Incorrect response body value", ) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_list_with_multiple_pages(self, mock_get): - ''' + """ Test default list method - ''' + """ values = ("value10", "value11", "value12", "value13") paging = ("page_size=2", "page_token=token") - mock_get.side_effect =[ + mock_get.side_effect = [ MockResponse( 200, things=[ @@ -805,14 +814,14 @@ def test_list_with_multiple_pages(self, mock_get): self.assertEqual( tuple(a), ( - (f"url/{ROOT}/path/path?{paging[i]}", ), + (f"url/{ROOT}/path/path?{paging[i]}",), { - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="GET method called incorrectly", @@ -820,21 +829,22 @@ def test_list_with_multiple_pages(self, mock_get): for i, r in enumerate(responses): self.assertEqual( - r['field1'], + r["field1"], values[i], msg="Incorrect response body value", ) class TestArchivistSignature(TestArchivistMethods): - ''' + """ Test Archivist get_by_signature method - ''' - @mock.patch('requests.get') + """ + + @mock.patch("requests.get") def test_get_by_signature(self, mock_get): - ''' + """ Test default get_by_signature method - ''' + """ mock_get.return_value = MockResponse( 200, things=[ @@ -848,36 +858,38 @@ def test_get_by_signature(self, mock_get): self.assertEqual( tuple(a), ( - (f"url/{ROOT}/path/path?page_size=2&field1=value1", ), + (f"url/{ROOT}/path/path?page_size=2&field1=value1",), { - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="GET method called incorrectly", ) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_get_by_signature_not_found(self, mock_get): - ''' + """ Test default get_by_signature method - ''' + """ mock_get.return_value = MockResponse( 200, things=[], ) with self.assertRaises(ArchivistNotFoundError): - entity = self.arch.get_by_signature("path/path", "things", {"field1": "value1"}) + entity = self.arch.get_by_signature( + "path/path", "things", {"field1": "value1"} + ) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_get_by_signature_duplicate(self, mock_get): - ''' + """ Test default get_by_signature method - ''' + """ mock_get.return_value = MockResponse( 200, things=[ @@ -890,13 +902,15 @@ def test_get_by_signature_duplicate(self, mock_get): ], ) with self.assertRaises(ArchivistDuplicateError): - entity = self.arch.get_by_signature("path/path", "things", {"field1": "value1"}) + entity = self.arch.get_by_signature( + "path/path", "things", {"field1": "value1"} + ) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_get_by_signature_with_bad_field(self, mock_get): - ''' + """ Test default list method with error - ''' + """ mock_get.return_value = MockResponse( 200, things=[ @@ -906,4 +920,6 @@ def test_get_by_signature_with_bad_field(self, mock_get): ], ) with self.assertRaises(ArchivistBadFieldError): - entity = self.arch.get_by_signature("path/path", "badthings", {"field1": "value1"}) + entity = self.arch.get_by_signature( + "path/path", "badthings", {"field1": "value1"} + ) diff --git a/unittests/testassets.py b/unittests/testassets.py index 5b99b4f3..803b4b12 100644 --- a/unittests/testassets.py +++ b/unittests/testassets.py @@ -1,6 +1,6 @@ -''' +""" Test archivist -''' +""" import json @@ -28,24 +28,26 @@ BEHAVIOURS = [ "Firmware", "Maintenance", - "RecordEvidence", "LocationUpdate", "Attachments", + "RecordEvidence", + "LocationUpdate", + "Attachments", ] PRIMARY_IMAGE = { "arc_display_name": "arc_primary_image", "arc_attachment_identity": "blobs/87b1a84c-1c6f-442b-923e-a97516f4d275", "arc_hash_alg": "SHA256", - "arc_hash_value": "246c316e2cd6971ce5c83a3e61f9880fa6e2f14ae2976ee03500eb282fd03a60" + "arc_hash_value": "246c316e2cd6971ce5c83a3e61f9880fa6e2f14ae2976ee03500eb282fd03a60", } SECONDARY_IMAGE = { "arc_display_name": "arc_secondary_image", "arc_attachment_identity": "blobs/87b1a84c-1c6f-442b-923e-a97516f4d275", "arc_hash_alg": "SHA256", - "arc_hash_value": "246c316e2cd6971ce5c83a3e61f9880fa6e2f14ae2976ee03500eb282fd03a60" + "arc_hash_value": "246c316e2cd6971ce5c83a3e61f9880fa6e2f14ae2976ee03500eb282fd03a60", } TERTIARY_IMAGE = { "arc_attachment_identity": "blobs/87b1a84c-1c6f-442b-923e-a97516f4d275", "arc_hash_alg": "SHA256", - "arc_hash_value": "246c316e2cd6971ce5c83a3e61f9880fa6e2f14ae2976ee03500eb282fd03a60" + "arc_hash_value": "246c316e2cd6971ce5c83a3e61f9880fa6e2f14ae2976ee03500eb282fd03a60", } ASSET_NAME = "tcl.ppj.003" BASE_ATTRS = { @@ -74,52 +76,53 @@ **BASE_ATTRS, } -IDENTITY = f'{ASSETS_LABEL}/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' +IDENTITY = f"{ASSETS_LABEL}/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" SUBPATH = f"{ASSETS_SUBPATH}/{ASSETS_LABEL}" # TBD: add properties as well REQUEST = { - 'behaviours': BEHAVIOURS, - 'attributes': ATTRS, + "behaviours": BEHAVIOURS, + "attributes": ATTRS, } REQUEST_DATA = json.dumps(REQUEST) RESPONSE = { - 'identity': IDENTITY, - 'behaviours': BEHAVIOURS, - 'attributes': ATTRS, - 'confirmation_status': 'CONFIRMED', + "identity": IDENTITY, + "behaviours": BEHAVIOURS, + "attributes": ATTRS, + "confirmation_status": "CONFIRMED", } RESPONSE_NO_ATTACHMENTS = { - 'identity': IDENTITY, - 'behaviours': BEHAVIOURS, - 'attributes': ATTRS_NO_ATTACHMENTS, - 'confirmation_status': 'CONFIRMED', + "identity": IDENTITY, + "behaviours": BEHAVIOURS, + "attributes": ATTRS_NO_ATTACHMENTS, + "confirmation_status": "CONFIRMED", } RESPONSE_NO_CONFIRMATION = { - 'identity': IDENTITY, - 'behaviours': BEHAVIOURS, - 'attributes': ATTRS, + "identity": IDENTITY, + "behaviours": BEHAVIOURS, + "attributes": ATTRS, } RESPONSE_PENDING = { - 'identity': IDENTITY, - 'behaviours': BEHAVIOURS, - 'attributes': ATTRS, - 'confirmation_status': 'PENDING', + "identity": IDENTITY, + "behaviours": BEHAVIOURS, + "attributes": ATTRS, + "confirmation_status": "PENDING", } RESPONSE_FAILED = { - 'identity': IDENTITY, - 'behaviours': BEHAVIOURS, - 'attributes': ATTRS, - 'confirmation_status': 'FAILED', + "identity": IDENTITY, + "behaviours": BEHAVIOURS, + "attributes": ATTRS, + "confirmation_status": "FAILED", } class TestAssets(TestCase): - ''' + """ Test Archivist Assets Create method - ''' + """ + maxDiff = None def setUp(self): @@ -130,31 +133,26 @@ def setUp(self): def tearDown(self): confirm.MAX_TIME = self.confirm_MAX_TIME - @mock.patch('requests.post') + @mock.patch("requests.post") def test_assets_create(self, mock_post): - ''' + """ Test asset creation - ''' + """ mock_post.return_value = MockResponse(200, **RESPONSE) asset = self.arch.assets.create(BEHAVIOURS, ATTRS, confirm=False) self.assertEqual( tuple(mock_post.call_args), ( - ( - ( - f"url/{ROOT}/{ASSETS_SUBPATH}" - f"/{ASSETS_LABEL}" - ), - ), + ((f"url/{ROOT}/{ASSETS_SUBPATH}" f"/{ASSETS_LABEL}"),), { "data": REQUEST_DATA, - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="CREATE method called incorrectly", @@ -175,12 +173,12 @@ def test_assets_create(self, mock_post): msg="Incorrect name property", ) - @mock.patch('requests.get') - @mock.patch('requests.post') + @mock.patch("requests.get") + @mock.patch("requests.post") def test_assets_create_with_confirmation(self, mock_post, mock_get): - ''' + """ Test asset creation - ''' + """ mock_post.return_value = MockResponse(200, **RESPONSE) mock_get.return_value = MockResponse(200, **RESPONSE) asset = self.arch.assets.create(BEHAVIOURS, ATTRS, confirm=True) @@ -190,34 +188,34 @@ def test_assets_create_with_confirmation(self, mock_post, mock_get): msg="CREATE method called incorrectly", ) - @mock.patch('requests.get') - @mock.patch('requests.post') + @mock.patch("requests.get") + @mock.patch("requests.post") def test_assets_create_with_confirmation_no_confirmed_status( - self, - mock_post, - mock_get, + self, + mock_post, + mock_get, ): - ''' + """ Test asset confirmation - ''' + """ mock_post.return_value = MockResponse(200, **RESPONSE) mock_get.return_value = MockResponse(200, **RESPONSE_NO_CONFIRMATION) with self.assertRaises(ArchivistUnconfirmedError): asset = self.arch.assets.create(BEHAVIOURS, ATTRS, confirm=True) - @mock.patch('requests.get') - @mock.patch('requests.post') + @mock.patch("requests.get") + @mock.patch("requests.post") def test_assets_create_with_confirmation_pending_status( - self, - mock_post, - mock_get, + self, + mock_post, + mock_get, ): - ''' + """ Test asset confirmation - ''' + """ mock_post.return_value = MockResponse(200, **RESPONSE) - mock_get.side_effect =[ + mock_get.side_effect = [ MockResponse(200, **RESPONSE_PENDING), MockResponse(200, **RESPONSE), ] @@ -228,36 +226,36 @@ def test_assets_create_with_confirmation_pending_status( msg="CREATE method called incorrectly", ) - @mock.patch('requests.get') - @mock.patch('requests.post') + @mock.patch("requests.get") + @mock.patch("requests.post") def test_assets_create_with_confirmation_failed_status( - self, - mock_post, - mock_get, + self, + mock_post, + mock_get, ): - ''' + """ Test asset confirmation - ''' + """ mock_post.return_value = MockResponse(200, **RESPONSE) - mock_get.side_effect =[ + mock_get.side_effect = [ MockResponse(200, **RESPONSE_PENDING), MockResponse(200, **RESPONSE_FAILED), ] with self.assertRaises(ArchivistUnconfirmedError): asset = self.arch.assets.create(BEHAVIOURS, ATTRS, confirm=True) - @mock.patch('requests.get') - @mock.patch('requests.post') + @mock.patch("requests.get") + @mock.patch("requests.post") def test_assets_create_with_confirmation_always_pending_status( - self, - mock_post, - mock_get, + self, + mock_post, + mock_get, ): - ''' + """ Test asset confirmation - ''' + """ mock_post.return_value = MockResponse(200, **RESPONSE) - mock_get.side_effect =[ + mock_get.side_effect = [ MockResponse(200, **RESPONSE_PENDING), MockResponse(200, **RESPONSE_PENDING), MockResponse(200, **RESPONSE_PENDING), @@ -269,11 +267,11 @@ def test_assets_create_with_confirmation_always_pending_status( with self.assertRaises(ArchivistUnconfirmedError): asset = self.arch.assets.create(BEHAVIOURS, ATTRS, confirm=True) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_assets_read_with_out_primary_image(self, mock_get): - ''' + """ Test asset reading - ''' + """ mock_get.return_value = MockResponse(200, **RESPONSE_NO_ATTACHMENTS) asset = self.arch.assets.read(IDENTITY) @@ -291,11 +289,11 @@ def test_assets_read_with_out_primary_image(self, mock_get): msg="There should be no name property", ) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_assets_count(self, mock_get): - ''' + """ Test asset counting - ''' + """ mock_get.return_value = MockResponse( 200, headers={HEADERS_TOTAL_COUNT: 1}, @@ -313,30 +311,25 @@ def test_assets_count(self, mock_get): self.assertEqual( tuple(mock_get.call_args), ( - ( - ( - f"url/{ROOT}/{SUBPATH}" - "?page_size=1" - ), - ), + ((f"url/{ROOT}/{SUBPATH}" "?page_size=1"),), { - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", - HEADERS_REQUEST_TOTAL_COUNT: 'true', + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", + HEADERS_REQUEST_TOTAL_COUNT: "true", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="GET method called incorrectly", ) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_assets_count_with_props_query(self, mock_get): - ''' + """ Test asset counting - ''' + """ mock_get.return_value = MockResponse( 200, headers={HEADERS_TOTAL_COUNT: 1}, @@ -346,7 +339,9 @@ def test_assets_count_with_props_query(self, mock_get): ) count = self.arch.assets.count( - props={'confirmation_status': 'CONFIRMED', }, + props={ + "confirmation_status": "CONFIRMED", + }, ) self.assertEqual( tuple(mock_get.call_args), @@ -359,23 +354,23 @@ def test_assets_count_with_props_query(self, mock_get): ), ), { - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", - HEADERS_REQUEST_TOTAL_COUNT: 'true', + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", + HEADERS_REQUEST_TOTAL_COUNT: "true", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="GET method called incorrectly", ) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_assets_count_with_attrs_query(self, mock_get): - ''' + """ Test asset counting - ''' + """ mock_get.return_value = MockResponse( 200, headers={HEADERS_TOTAL_COUNT: 1}, @@ -398,26 +393,26 @@ def test_assets_count_with_attrs_query(self, mock_get): ), ), { - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", - HEADERS_REQUEST_TOTAL_COUNT: 'true', + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", + HEADERS_REQUEST_TOTAL_COUNT: "true", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="GET method called incorrectly", ) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_assets_wait_for_confirmed(self, mock_get): - ''' + """ Test asset counting - ''' + """ ## last call to get looks for FAILED assets - status = ('PENDING', 'PENDING', 'FAILED') - mock_get.side_effect =[ + status = ("PENDING", "PENDING", "FAILED") + mock_get.side_effect = [ MockResponse( 200, headers={HEADERS_TOTAL_COUNT: 2}, @@ -450,25 +445,25 @@ def test_assets_wait_for_confirmed(self, mock_get): ), ), { - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", - HEADERS_REQUEST_TOTAL_COUNT: 'true', + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", + HEADERS_REQUEST_TOTAL_COUNT: "true", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="GET method called incorrectly", ) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_assets_wait_for_confirmed_timeout(self, mock_get): - ''' + """ Test asset counting - ''' + """ ## last call to get looks for FAILED assets - mock_get.side_effect =[ + mock_get.side_effect = [ MockResponse( 200, headers={HEADERS_TOTAL_COUNT: 2}, @@ -517,13 +512,13 @@ def test_assets_wait_for_confirmed_timeout(self, mock_get): with self.assertRaises(ArchivistUnconfirmedError): self.arch.assets.wait_for_confirmed() - @mock.patch('requests.get') + @mock.patch("requests.get") def test_assets_wait_for_confirmed_failed(self, mock_get): - ''' + """ Test asset counting - ''' + """ ## last call to get looks for FAILED assets - mock_get.side_effect =[ + mock_get.side_effect = [ MockResponse( 200, headers={HEADERS_TOTAL_COUNT: 2}, @@ -548,11 +543,11 @@ def test_assets_wait_for_confirmed_failed(self, mock_get): with self.assertRaises(ArchivistUnconfirmedError): self.arch.assets.wait_for_confirmed() - @mock.patch('requests.get') + @mock.patch("requests.get") def test_assets_list(self, mock_get): - ''' + """ Test asset listing - ''' + """ mock_get.return_value = MockResponse( 200, assets=[ @@ -578,24 +573,24 @@ def test_assets_list(self, mock_get): self.assertEqual( tuple(a), ( - (f"url/{ROOT}/{SUBPATH}?page_size={DEFAULT_PAGE_SIZE}", ), + (f"url/{ROOT}/{SUBPATH}?page_size={DEFAULT_PAGE_SIZE}",), { - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="GET method called incorrectly", ) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_assets_list_with_query(self, mock_get): - ''' + """ Test asset listing - ''' + """ mock_get.return_value = MockResponse( 200, assets=[ @@ -604,7 +599,9 @@ def test_assets_list_with_query(self, mock_get): ) listing = self.arch.assets.list( - props={'confirmation_status': 'CONFIRMED', }, + props={ + "confirmation_status": "CONFIRMED", + }, attrs={"arc_firmware_version": "1.0"}, ) assets = [a for a in listing] @@ -633,22 +630,22 @@ def test_assets_list_with_query(self, mock_get): ), ), { - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="GET method called incorrectly", ) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_assets_read_by_signature(self, mock_get): - ''' + """ Test asset listing - ''' + """ mock_get.return_value = MockResponse( 200, assets=[ @@ -666,14 +663,14 @@ def test_assets_read_by_signature(self, mock_get): self.assertEqual( tuple(mock_get.call_args), ( - (f"url/{ROOT}/{SUBPATH}?page_size=2", ), + (f"url/{ROOT}/{SUBPATH}?page_size=2",), { - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="GET method called incorrectly", diff --git a/unittests/testattachments.py b/unittests/testattachments.py index da20f292..eff368ce 100644 --- a/unittests/testattachments.py +++ b/unittests/testattachments.py @@ -1,6 +1,6 @@ -''' +""" Test archivist -''' +""" from io import BytesIO import json @@ -13,91 +13,89 @@ PROPS = { - "hash": { - "alg": "SHA256", - "value": "xxxxxxxxxxxxxxxxxxxxxxx" - }, + "hash": {"alg": "SHA256", "value": "xxxxxxxxxxxxxxxxxxxxxxx"}, "mime_type": "image/jpeg", "timestamp_accepted": "2019-11-07T15:31:49Z", "size": 31424, } -IDENTITY = f'{ATTACHMENTS_LABEL}/xxxxxxxx' -SUBPATH = f'{ATTACHMENTS_SUBPATH}/{ATTACHMENTS_LABEL}' +IDENTITY = f"{ATTACHMENTS_LABEL}/xxxxxxxx" +SUBPATH = f"{ATTACHMENTS_SUBPATH}/{ATTACHMENTS_LABEL}" RESPONSE = { **PROPS, - 'identity': IDENTITY, + "identity": IDENTITY, } REQUEST_DATA = json.dumps(PROPS) class TestAttachments(TestCase): - ''' + """ Test Archivist Attachments Create method - ''' + """ + maxDiff = None def setUp(self): self.arch = Archivist("url", auth="authauthauth") self.mockstream = BytesIO(b"somelongstring") - @mock.patch('requests.post') + @mock.patch("requests.post") def test_attachments_upload(self, mock_post): - ''' + """ Test attachment upload - ''' + """ mock_post.return_value = MockResponse(200, **RESPONSE) attachment = self.arch.attachments.upload(self.mockstream) args, kwargs = mock_post.call_args self.assertEqual( args, - (f'url/{ROOT}/{SUBPATH}',), + (f"url/{ROOT}/{SUBPATH}",), msg="UPLOAD method called incorrectly", ) self.assertTrue( - 'headers' in kwargs, + "headers" in kwargs, msg="UPLOAD no headers found", ) - headers = kwargs['headers'] + headers = kwargs["headers"] self.assertTrue( - 'authorization' in headers, + "authorization" in headers, msg="UPLOAD no authorization found", ) self.assertEqual( - headers['authorization'], - 'Bearer authauthauth', + headers["authorization"], + "Bearer authauthauth", msg="UPLOAD incorrect authorization", ) self.assertTrue( - headers['content-type'].startswith('multipart/form-data;'), + headers["content-type"].startswith("multipart/form-data;"), msg="UPLOAD incorrect content-type", ) self.assertTrue( - kwargs['verify'], + kwargs["verify"], msg="UPLOAD method called incorrectly", ) self.assertIsNone( - kwargs['cert'], + kwargs["cert"], msg="UPLOAD method called incorrectly", ) self.assertTrue( - 'data' in kwargs, + "data" in kwargs, msg="UPLOAD no data found", ) - fields = kwargs['data'].fields + fields = kwargs["data"].fields self.assertTrue( - 'file' in fields, + "file" in fields, msg="UPLOAD no file found", ) self.assertEqual( - fields['file'][0], - 'filename', + fields["file"][0], + "filename", msg="UPLOAD incorrect filename", ) self.assertEqual( - fields['file'][2], - 'image/jpg', + fields["file"][2], + "image/jpg", msg="UPLOAD incorrect filetype", ) self.assertEqual( @@ -106,11 +104,12 @@ def test_attachments_upload(self, mock_post): msg="UPLOAD method called incorrectly", ) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_attachments_download(self, mock_get): - ''' + """ Test attachment download - ''' + """ + def iter_content(): i = 0 @@ -136,19 +135,19 @@ def filedata(chunk_size=4096): # pylint: disable=unused-argument args, kwargs = mock_get.call_args self.assertEqual( args, - (f'url/{ROOT}/{ATTACHMENTS_SUBPATH}/{IDENTITY}',), + (f"url/{ROOT}/{ATTACHMENTS_SUBPATH}/{IDENTITY}",), msg="DOWNLOAD method called incorrectly", ) self.assertEqual( kwargs, { - 'cert': None, - 'headers': { - 'authorization': 'Bearer authauthauth', - 'content-type': 'application/json', + "cert": None, + "headers": { + "authorization": "Bearer authauthauth", + "content-type": "application/json", }, - 'stream': True, - 'verify': True, + "stream": True, + "verify": True, }, msg="DOWNLOAD method called incorrectly", ) diff --git a/unittests/testerrors.py b/unittests/testerrors.py index 4d4cee63..1607956f 100644 --- a/unittests/testerrors.py +++ b/unittests/testerrors.py @@ -1,6 +1,6 @@ -''' +""" Test archivist -''' +""" # pylint: disable=attribute-defined-outside-init # pylint: disable=missing-docstring @@ -27,13 +27,14 @@ class TestErrors(TestCase): - ''' + """ Test exceptions for archivist - ''' + """ + def test_errors_200(self): - ''' + """ Test errors - ''' + """ response = MockResponse(200) error = parse_response(response) self.assertEqual( @@ -43,9 +44,9 @@ def test_errors_200(self): ) def test_errors_300(self): - ''' + """ Test errors - ''' + """ response = MockResponse(300) error = parse_response(response) self.assertEqual( @@ -55,9 +56,9 @@ def test_errors_300(self): ) def test_errors_400(self): - ''' + """ Test errors - ''' + """ response = MockResponse(400, error="some error") error = parse_response(response) self.assertIsNotNone( @@ -73,9 +74,9 @@ def test_errors_400(self): ) def test_errors_401(self): - ''' + """ Test errors - ''' + """ response = MockResponse(401, error="some error") error = parse_response(response) self.assertIsNotNone( @@ -91,9 +92,9 @@ def test_errors_401(self): ) def test_errors_403(self): - ''' + """ Test errors - ''' + """ response = MockResponse(403, error="some error") error = parse_response(response) self.assertIsNotNone( @@ -108,14 +109,15 @@ def test_errors_403(self): ) def test_errors_404(self): - ''' + """ Test errors - ''' + """ + class Object: pass request = Object() - request.body = json.dumps({'identity': 'entity/xxxxx'}) + request.body = json.dumps({"identity": "entity/xxxxx"}) response = MockResponse( 404, request=request, @@ -130,14 +132,14 @@ class Object: raise error self.assertEqual( str(ex.exception), - 'entity/xxxxx not found (404)', + "entity/xxxxx not found (404)", msg="incorrect error", ) def test_errors_4xx(self): - ''' + """ Test errors - ''' + """ response = MockResponse(405, error="some error") error = parse_response(response) self.assertIsNotNone( @@ -153,9 +155,9 @@ def test_errors_4xx(self): ) def test_errors_500(self): - ''' + """ Test errors - ''' + """ response = MockResponse(500, error="some error") error = parse_response(response) self.assertIsNotNone( @@ -171,9 +173,9 @@ def test_errors_500(self): ) def test_errors_501(self): - ''' + """ Test errors - ''' + """ response = MockResponse(501, error="some error") error = parse_response(response) self.assertIsNotNone( @@ -189,9 +191,9 @@ def test_errors_501(self): ) def test_errors_503(self): - ''' + """ Test errors - ''' + """ response = MockResponse(503, error="some error") error = parse_response(response) self.assertIsNotNone( @@ -207,9 +209,9 @@ def test_errors_503(self): ) def test_errors_600(self): - ''' + """ Test errors - ''' + """ response = MockResponse(600, error="some error") error = parse_response(response) self.assertIsNotNone( diff --git a/unittests/testevents.py b/unittests/testevents.py index afd78199..bb497167 100644 --- a/unittests/testevents.py +++ b/unittests/testevents.py @@ -1,6 +1,6 @@ -''' +""" Test archivist -''' +""" import json from unittest import TestCase, mock @@ -88,88 +88,89 @@ ], } ASSET_ATTRS = { - "external_container": 'assets/xxxx', + "external_container": "assets/xxxx", } -IDENTITY = f'{ASSET_ID}/{EVENTS_LABEL}/xxxxxxxxxxxxxxxxxxxx' +IDENTITY = f"{ASSET_ID}/{EVENTS_LABEL}/xxxxxxxxxxxxxxxxxxxx" REQUEST = { **PROPS, - 'event_attributes': EVENT_ATTRS, + "event_attributes": EVENT_ATTRS, } REQUEST_DATA = json.dumps(REQUEST) REQUEST_WITH_ASSET_ATTRS = { **REQUEST, - 'asset_attributes': ASSET_ATTRS, + "asset_attributes": ASSET_ATTRS, } REQUEST_DATA_WITH_ASSET_ATTRS = json.dumps(REQUEST_WITH_ASSET_ATTRS) REQUEST_WITH_NO_PRINCIPAL = { **PROPS_WITH_NO_PRINCIPAL, - 'event_attributes': EVENT_ATTRS, + "event_attributes": EVENT_ATTRS, } REQUEST_WITH_NO_PRINCIPAL_DATA = json.dumps(REQUEST_WITH_NO_PRINCIPAL) RESPONSE = { **PROPS, - 'identity': IDENTITY, - 'event_attributes': EVENT_ATTRS, - 'confirmation_status': 'CONFIRMED', + "identity": IDENTITY, + "event_attributes": EVENT_ATTRS, + "confirmation_status": "CONFIRMED", } RESPONSE_WITH_ASSET_ATTRS = { **RESPONSE, - 'asset_attributes': ASSET_ATTRS, + "asset_attributes": ASSET_ATTRS, } RESPONSE_NO_CONFIRMATION = { **PROPS, - 'identity': IDENTITY, - 'event_attributes': EVENT_ATTRS, + "identity": IDENTITY, + "event_attributes": EVENT_ATTRS, } RESPONSE_PENDING = { **PROPS, - 'identity': IDENTITY, - 'event_attributes': EVENT_ATTRS, - 'confirmation_status': 'PENDING', + "identity": IDENTITY, + "event_attributes": EVENT_ATTRS, + "confirmation_status": "PENDING", } RESPONSE_FAILED = { **PROPS, - 'identity': IDENTITY, - 'event_attributes': EVENT_ATTRS, - 'confirmation_status': 'FAILED', + "identity": IDENTITY, + "event_attributes": EVENT_ATTRS, + "confirmation_status": "FAILED", } RESPONSE_WITH_NO_TIMESTAMP = { **PROPS_WITH_NO_TIMESTAMP, - 'identity': IDENTITY, - 'event_attributes': EVENT_ATTRS, - 'confirmation_status': 'CONFIRMED', + "identity": IDENTITY, + "event_attributes": EVENT_ATTRS, + "confirmation_status": "CONFIRMED", } RESPONSE_WITH_TIMESTAMP_ACCEPTED = { **PROPS_WITH_TIMESTAMP_ACCEPTED, - 'identity': IDENTITY, - 'event_attributes': EVENT_ATTRS, - 'confirmation_status': 'CONFIRMED', + "identity": IDENTITY, + "event_attributes": EVENT_ATTRS, + "confirmation_status": "CONFIRMED", } RESPONSE_WITH_PRINCIPAL_DECLARED = { **PROPS_WITH_PRINCIPAL_DECLARED, - 'identity': IDENTITY, - 'event_attributes': EVENT_ATTRS, - 'confirmation_status': 'CONFIRMED', + "identity": IDENTITY, + "event_attributes": EVENT_ATTRS, + "confirmation_status": "CONFIRMED", } RESPONSE_WITH_NO_PRINCIPAL = { **PROPS_WITH_NO_PRINCIPAL, - 'identity': IDENTITY, - 'event_attributes': EVENT_ATTRS, - 'confirmation_status': 'CONFIRMED', + "identity": IDENTITY, + "event_attributes": EVENT_ATTRS, + "confirmation_status": "CONFIRMED", } class TestEvent(TestCase): - ''' + """ Test Archivist Events Create method - ''' + """ + maxDiff = None def test_event_who_accepted(self): @@ -222,9 +223,10 @@ def test_event_when_none(self): class TestEvents(TestCase): - ''' + """ Test Archivist Events Create method - ''' + """ + maxDiff = None def setUp(self): @@ -235,11 +237,11 @@ def setUp(self): def tearDown(self): confirm.MAX_TIME = self.confirm_MAX_TIME - @mock.patch('requests.post') + @mock.patch("requests.post") def test_events_create(self, mock_post): - ''' + """ Test event creation - ''' + """ mock_post.return_value = MockResponse(200, **RESPONSE) event = self.arch.events.create(ASSET_ID, PROPS, EVENT_ATTRS, confirm=False) @@ -255,12 +257,12 @@ def test_events_create(self, mock_post): ), { "data": REQUEST_DATA, - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="CREATE method called incorrectly", @@ -271,11 +273,11 @@ def test_events_create(self, mock_post): msg="CREATE method called incorrectly", ) - @mock.patch('requests.post') + @mock.patch("requests.post") def test_events_create_with_asset_attrs(self, mock_post): - ''' + """ Test event creation - ''' + """ mock_post.return_value = MockResponse(200, **RESPONSE_WITH_ASSET_ATTRS) event = self.arch.events.create( @@ -297,12 +299,12 @@ def test_events_create_with_asset_attrs(self, mock_post): ), { "data": REQUEST_DATA_WITH_ASSET_ATTRS, - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="CREATE method called incorrectly", @@ -313,12 +315,12 @@ def test_events_create_with_asset_attrs(self, mock_post): msg="CREATE method called incorrectly", ) - @mock.patch('requests.get') - @mock.patch('requests.post') + @mock.patch("requests.get") + @mock.patch("requests.post") def test_events_create_with_confirmation(self, mock_post, mock_get): - ''' + """ Test event creation - ''' + """ mock_post.return_value = MockResponse(200, **RESPONSE) mock_get.return_value = MockResponse(200, **RESPONSE) @@ -329,34 +331,34 @@ def test_events_create_with_confirmation(self, mock_post, mock_get): msg="CREATE method called incorrectly", ) - @mock.patch('requests.get') - @mock.patch('requests.post') + @mock.patch("requests.get") + @mock.patch("requests.post") def test_events_create_with_confirmation_no_confirmed_status( - self, - mock_post, - mock_get, + self, + mock_post, + mock_get, ): - ''' + """ Test asset confirmation - ''' + """ mock_post.return_value = MockResponse(200, **RESPONSE) mock_get.return_value = MockResponse(200, **RESPONSE_NO_CONFIRMATION) with self.assertRaises(ArchivistUnconfirmedError): event = self.arch.events.create(ASSET_ID, PROPS, EVENT_ATTRS, confirm=True) - @mock.patch('requests.get') - @mock.patch('requests.post') + @mock.patch("requests.get") + @mock.patch("requests.post") def test_events_create_with_confirmation_pending_status( - self, - mock_post, - mock_get, + self, + mock_post, + mock_get, ): - ''' + """ Test asset confirmation - ''' + """ mock_post.return_value = MockResponse(200, **RESPONSE) - mock_get.side_effect =[ + mock_get.side_effect = [ MockResponse(200, **RESPONSE_PENDING), MockResponse(200, **RESPONSE), ] @@ -367,36 +369,36 @@ def test_events_create_with_confirmation_pending_status( msg="CREATE method called incorrectly", ) - @mock.patch('requests.get') - @mock.patch('requests.post') + @mock.patch("requests.get") + @mock.patch("requests.post") def test_events_create_with_confirmation_failed_status( - self, - mock_post, - mock_get, + self, + mock_post, + mock_get, ): - ''' + """ Test asset confirmation - ''' + """ mock_post.return_value = MockResponse(200, **RESPONSE) - mock_get.side_effect =[ + mock_get.side_effect = [ MockResponse(200, **RESPONSE_PENDING), MockResponse(200, **RESPONSE_FAILED), ] with self.assertRaises(ArchivistUnconfirmedError): event = self.arch.events.create(ASSET_ID, PROPS, EVENT_ATTRS, confirm=True) - @mock.patch('requests.get') - @mock.patch('requests.post') + @mock.patch("requests.get") + @mock.patch("requests.post") def test_events_create_with_confirmation_always_pending_status( - self, - mock_post, - mock_get, + self, + mock_post, + mock_get, ): - ''' + """ Test asset confirmation - ''' + """ mock_post.return_value = MockResponse(200, **RESPONSE) - mock_get.side_effect =[ + mock_get.side_effect = [ MockResponse(200, **RESPONSE_PENDING), MockResponse(200, **RESPONSE_PENDING), MockResponse(200, **RESPONSE_PENDING), @@ -409,11 +411,11 @@ def test_events_create_with_confirmation_always_pending_status( with self.assertRaises(ArchivistUnconfirmedError): event = self.arch.events.create(ASSET_ID, PROPS, EVENT_ATTRS, confirm=True) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_events_read(self, mock_get): - ''' + """ Test event counting - ''' + """ mock_get.return_value = MockResponse(200, **RESPONSE) event = self.arch.events.read(IDENTITY) @@ -428,12 +430,12 @@ def test_events_read(self, mock_get): ), ), { - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="GET method called incorrectly", @@ -444,11 +446,11 @@ def test_events_read(self, mock_get): msg="GET method called incorrectly", ) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_events_read_with_no_principal(self, mock_get): - ''' + """ Test event counting - ''' + """ mock_get.return_value = MockResponse(200, **RESPONSE) event = self.arch.events.read(IDENTITY) @@ -458,11 +460,11 @@ def test_events_read_with_no_principal(self, mock_get): msg="GET method called incorrectly", ) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_events_count(self, mock_get): - ''' + """ Test event counting - ''' + """ mock_get.return_value = MockResponse( 200, headers={HEADERS_TOTAL_COUNT: 1}, @@ -489,23 +491,23 @@ def test_events_count(self, mock_get): ), ), { - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", - HEADERS_REQUEST_TOTAL_COUNT: 'true', + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", + HEADERS_REQUEST_TOTAL_COUNT: "true", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="GET method called incorrectly", ) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_events_count_with_props_query(self, mock_get): - ''' + """ Test event counting - ''' + """ mock_get.return_value = MockResponse( 200, headers={HEADERS_TOTAL_COUNT: 1}, @@ -516,7 +518,9 @@ def test_events_count_with_props_query(self, mock_get): count = self.arch.events.count( asset_id=ASSET_ID, - props={'confirmation_status': 'CONFIRMED', }, + props={ + "confirmation_status": "CONFIRMED", + }, ) self.assertEqual( tuple(mock_get.call_args), @@ -531,23 +535,23 @@ def test_events_count_with_props_query(self, mock_get): ), ), { - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", - HEADERS_REQUEST_TOTAL_COUNT: 'true', + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", + HEADERS_REQUEST_TOTAL_COUNT: "true", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="GET method called incorrectly", ) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_events_count_with_attrs_query(self, mock_get): - ''' + """ Test event counting - ''' + """ mock_get.return_value = MockResponse( 200, headers={HEADERS_TOTAL_COUNT: 1}, @@ -573,23 +577,23 @@ def test_events_count_with_attrs_query(self, mock_get): ), ), { - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", - HEADERS_REQUEST_TOTAL_COUNT: 'true', + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", + HEADERS_REQUEST_TOTAL_COUNT: "true", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="GET method called incorrectly", ) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_events_count_with_wildcard_asset(self, mock_get): - ''' + """ Test event counting - ''' + """ mock_get.return_value = MockResponse( 200, headers={HEADERS_TOTAL_COUNT: 1}, @@ -614,26 +618,26 @@ def test_events_count_with_wildcard_asset(self, mock_get): ), ), { - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", - HEADERS_REQUEST_TOTAL_COUNT: 'true', + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", + HEADERS_REQUEST_TOTAL_COUNT: "true", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="GET method called incorrectly", ) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_events_wait_for_confirmed(self, mock_get): - ''' + """ Test event counting - ''' + """ ## last call to get looks for FAILED assets - status = ('PENDING', 'PENDING', 'FAILED') - mock_get.side_effect =[ + status = ("PENDING", "PENDING", "FAILED") + mock_get.side_effect = [ MockResponse( 200, headers={HEADERS_TOTAL_COUNT: 2}, @@ -668,23 +672,23 @@ def test_events_wait_for_confirmed(self, mock_get): ), ), { - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", - HEADERS_REQUEST_TOTAL_COUNT: 'true', + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", + HEADERS_REQUEST_TOTAL_COUNT: "true", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="GET method called incorrectly", ) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_events_list(self, mock_get): - ''' + """ Test event listing - ''' + """ mock_get.return_value = MockResponse( 200, events=[ @@ -719,23 +723,22 @@ def test_events_list(self, mock_get): ), ), { - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="GET method called incorrectly", - ) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_events_list_with_query(self, mock_get): - ''' + """ Test event listing - ''' + """ mock_get.return_value = MockResponse( 200, events=[ @@ -745,7 +748,9 @@ def test_events_list_with_query(self, mock_get): listing = self.arch.events.list( asset_id=ASSET_ID, - props={'confirmation_status': 'CONFIRMED', }, + props={ + "confirmation_status": "CONFIRMED", + }, attrs={"arc_firmware_version": "1.0"}, ) events = [a for a in listing] @@ -776,22 +781,22 @@ def test_events_list_with_query(self, mock_get): ), ), { - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="GET method called incorrectly", ) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_events_list_with_wildcard_asset(self, mock_get): - ''' + """ Test event listing - ''' + """ mock_get.return_value = MockResponse( 200, events=[ @@ -800,7 +805,9 @@ def test_events_list_with_wildcard_asset(self, mock_get): ) listing = self.arch.events.list( - props={'confirmation_status': 'CONFIRMED', }, + props={ + "confirmation_status": "CONFIRMED", + }, attrs={"arc_firmware_version": "1.0"}, ) events = [a for a in listing] @@ -831,22 +838,22 @@ def test_events_list_with_wildcard_asset(self, mock_get): ), ), { - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="GET method called incorrectly", ) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_events_read_by_signature(self, mock_get): - ''' + """ Test event listing - ''' + """ mock_get.return_value = MockResponse( 200, events=[ @@ -873,12 +880,12 @@ def test_events_read_by_signature(self, mock_get): ), ), { - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="GET method called incorrectly", diff --git a/unittests/testlocations.py b/unittests/testlocations.py index eea1fe3d..62224446 100644 --- a/unittests/testlocations.py +++ b/unittests/testlocations.py @@ -1,6 +1,6 @@ -''' +""" Test archivist -''' +""" import json from unittest import TestCase, mock @@ -34,57 +34,54 @@ "address": "Bridgewater, Somerset", "facility_type": "Manufacture", "support_email": "support@macclesfield.com", - "support_phone": "123 456 789" + "support_phone": "123 456 789", } -IDENTITY = f'{LOCATIONS_LABEL}/xxxxxxxx' -SUBPATH = f'{LOCATIONS_SUBPATH}/{LOCATIONS_LABEL}' +IDENTITY = f"{LOCATIONS_LABEL}/xxxxxxxx" +SUBPATH = f"{LOCATIONS_SUBPATH}/{LOCATIONS_LABEL}" RESPONSE = { **PROPS, - 'identity': IDENTITY, - 'attributes': ATTRS, + "identity": IDENTITY, + "attributes": ATTRS, } REQUEST = { **PROPS, - 'attributes': ATTRS, + "attributes": ATTRS, } REQUEST_DATA = json.dumps(REQUEST) class TestLocations(TestCase): - ''' + """ Test Archivist Locations Create method - ''' + """ + maxDiff = None def setUp(self): self.arch = Archivist("url", auth="authauthauth") - @mock.patch('requests.post') + @mock.patch("requests.post") def test_locations_create(self, mock_post): - ''' + """ Test location creation - ''' + """ mock_post.return_value = MockResponse(200, **RESPONSE) location = self.arch.locations.create(PROPS, attrs=ATTRS) self.assertEqual( tuple(mock_post.call_args), ( - ( - ( - f"url/{ROOT}/{SUBPATH}" - ), - ), + ((f"url/{ROOT}/{SUBPATH}"),), { - 'data': REQUEST_DATA, - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", + "data": REQUEST_DATA, + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="CREATE method called incorrectly", @@ -95,48 +92,44 @@ def test_locations_create(self, mock_post): msg="CREATE method called incorrectly", ) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_locations_read(self, mock_get): - ''' + """ Test asset reading - ''' + """ mock_get.return_value = MockResponse(200, **RESPONSE) asset = self.arch.locations.read(IDENTITY) self.assertEqual( tuple(mock_get.call_args), ( - ( - ( - f"url/{ROOT}/{LOCATIONS_SUBPATH}/{IDENTITY}" - ), - ), + ((f"url/{ROOT}/{LOCATIONS_SUBPATH}/{IDENTITY}"),), { - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="GET method called incorrectly", ) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_locations_read_with_error(self, mock_get): - ''' + """ Test read method with error - ''' + """ mock_get.return_value = MockResponse(400) with self.assertRaises(ArchivistBadRequestError): resp = self.arch.locations.read(IDENTITY) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_locations_count(self, mock_get): - ''' + """ Test location counting - ''' + """ mock_get.return_value = MockResponse( 200, headers={HEADERS_TOTAL_COUNT: 1}, @@ -149,20 +142,15 @@ def test_locations_count(self, mock_get): self.assertEqual( tuple(mock_get.call_args), ( - ( - ( - f"url/{ROOT}/{SUBPATH}" - "?page_size=1" - ), - ), + ((f"url/{ROOT}/{SUBPATH}" "?page_size=1"),), { - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", - HEADERS_REQUEST_TOTAL_COUNT: 'true', + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", + HEADERS_REQUEST_TOTAL_COUNT: "true", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="GET method called incorrectly", @@ -173,11 +161,11 @@ def test_locations_count(self, mock_get): msg="Incorrect count", ) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_locations_count_with_props_query(self, mock_get): - ''' + """ Test location counting - ''' + """ mock_get.return_value = MockResponse( 200, headers={HEADERS_TOTAL_COUNT: 1}, @@ -200,23 +188,23 @@ def test_locations_count_with_props_query(self, mock_get): ), ), { - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", - HEADERS_REQUEST_TOTAL_COUNT: 'true', + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", + HEADERS_REQUEST_TOTAL_COUNT: "true", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="GET method called incorrectly", ) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_locations_count_with_attrs_query(self, mock_get): - ''' + """ Test location counting - ''' + """ mock_get.return_value = MockResponse( 200, headers={HEADERS_TOTAL_COUNT: 1}, @@ -239,23 +227,23 @@ def test_locations_count_with_attrs_query(self, mock_get): ), ), { - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", - HEADERS_REQUEST_TOTAL_COUNT: 'true', + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", + HEADERS_REQUEST_TOTAL_COUNT: "true", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="GET method called incorrectly", ) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_locations_list(self, mock_get): - ''' + """ Test location listing - ''' + """ mock_get.return_value = MockResponse( 200, locations=[ @@ -283,22 +271,22 @@ def test_locations_list(self, mock_get): ( (f"url/{ROOT}/{SUBPATH}?page_size={DEFAULT_PAGE_SIZE}",), { - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="GET method called incorrectly", ) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_locations_list_with_query(self, mock_get): - ''' + """ Test location listing - ''' + """ mock_get.return_value = MockResponse( 200, locations=[ @@ -336,22 +324,22 @@ def test_locations_list_with_query(self, mock_get): ), ), { - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="GET method called incorrectly", ) - @mock.patch('requests.get') + @mock.patch("requests.get") def test_locations_read_by_signature(self, mock_get): - ''' + """ Test location read_by_signature - ''' + """ mock_get.return_value = MockResponse( 200, locations=[ @@ -371,12 +359,12 @@ def test_locations_read_by_signature(self, mock_get): ( (f"url/{ROOT}/{SUBPATH}?page_size=2",), { - 'headers': { - 'content-type': 'application/json', - 'authorization': "Bearer authauthauth", + "headers": { + "content-type": "application/json", + "authorization": "Bearer authauthauth", }, - 'verify': True, - 'cert': None, + "verify": True, + "cert": None, }, ), msg="GET method called incorrectly",