From 01ce5d5f099fa51d1bb352c76cd1757537cb3339 Mon Sep 17 00:00:00 2001 From: Alexey Petrovsky Date: Tue, 16 Nov 2021 18:17:33 +0300 Subject: [PATCH 01/16] Implement json_serialize and json_deserialize methods for ErrorResponse --- agrirouter/onboarding/dto.py | 35 +++++++++++++++++++++++++++++++---- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/agrirouter/onboarding/dto.py b/agrirouter/onboarding/dto.py index d2b34bed..4fb95e33 100644 --- a/agrirouter/onboarding/dto.py +++ b/agrirouter/onboarding/dto.py @@ -159,18 +159,45 @@ def __repr__(self): class ErrorResponse: + CODE = "" + MESSAGE = "" + TARGET = "" + DETAILS = "" + def __init__(self, *, - code, - message, - target, - details + code: str = None, + message: str = None, + target: str = None, + details: str = None ): self.code = code self.message = message self.target = target self.details = details + def json_serialize(self) -> dict: + return { + self.CODE: self.code, + self.MESSAGE: self.message, + self.TARGET: self.target, + self.DETAILS: self.details + } + + def json_deserialize(self, data: Union[str, dict]) -> None: + data = data if type(data) == dict else json.loads(data) + for key, value in data.items(): + if key == self.CODE: + self.code = value + elif key == self.MESSAGE: + self.message = value + elif key == self.TARGET: + self.target = value + elif key == self.DETAILS: + self.details = value + else: + raise WrongFieldError(f"Unknown field {key} for ErrorResponse class") + def get_code(self) -> str: return self.code From b6fadacc6aafbb164de0ffce897efd5d96598834 Mon Sep 17 00:00:00 2001 From: Alexey Petrovsky Date: Tue, 16 Nov 2021 18:23:19 +0300 Subject: [PATCH 02/16] Refactor serialize_json and deserialize_json methods in SoftwareOnboardingResponse --- agrirouter/onboarding/response.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/agrirouter/onboarding/response.py b/agrirouter/onboarding/response.py index 44a4f5b5..43e42a8d 100644 --- a/agrirouter/onboarding/response.py +++ b/agrirouter/onboarding/response.py @@ -63,6 +63,7 @@ class SoftwareOnboardingResponse(BaseOnboardingResonse): SENSOR_ALTERNATE_ID = "sensorAlternateId" CONNECTION_CRITERIA = "connectionCriteria" AUTHENTICATION = "authentication" + ERROR = "error" def __init__(self, http_response: Response = None): if http_response: @@ -130,6 +131,10 @@ def set_capability_alternate_id(self, capability_alternate_id: str): self.capability_alternate_id = capability_alternate_id def json_serialize(self): + if self.error: + return { + self.ERROR: self.error + } return { self.DEVICE_ALTERNATE_ID: self.device_alternate_id, self.CAPABILITY_ALTERNATE_ID: self.capability_alternate_id, @@ -155,6 +160,10 @@ def json_deserialize(self, data: Union[dict, str]): authentication = Authentication() authentication.json_deserialize(value) self.authentication = authentication + elif key == self.ERROR: + error_response = ErrorResponse() + error_response.json_deserialize(value) + self.error = error_response else: raise WrongFieldError(f"Unknown field `{key}` for {self.__class__}") From d7f7a4a2bb4690535cdd08aaed50699627db2b55 Mon Sep 17 00:00:00 2001 From: Alexey Petrovsky Date: Tue, 16 Nov 2021 18:24:30 +0300 Subject: [PATCH 03/16] Move CommectionCrietria and Authentication tests to tests/test_onboarding/test_dto module --- tests/onboarding_test/test_dto.py | 281 ++++++++++++++++++++++++++++++ 1 file changed, 281 insertions(+) create mode 100644 tests/onboarding_test/test_dto.py diff --git a/tests/onboarding_test/test_dto.py b/tests/onboarding_test/test_dto.py new file mode 100644 index 00000000..0259f9fd --- /dev/null +++ b/tests/onboarding_test/test_dto.py @@ -0,0 +1,281 @@ +"""Tests agrirouter/onboarding/dto.py""" +from agrirouter.onboarding.dto import ConnectionCriteria, Authentication, ErrorResponse +from agrirouter.messaging.exceptions import WrongFieldError +import pytest + + +class TestConnectionCriteria: + + def test_json_deserialize_from_valid_dict(self): + client_id = "1" + commands = "commands" + gateway_id = "3" + host = "localhost" + measures = "test_measures" + port = "80" + + test_object = ConnectionCriteria() + + data = {"client_id": "1", "commands": "commands", "gateway_id": "3", "host": "localhost", "port": "80", + "measures": "test_measures"} + + test_object.json_deserialize(data) + assert test_object + assert test_object.gateway_id == gateway_id + assert test_object.client_id == client_id + assert test_object.commands == commands + assert test_object.host == host + assert test_object.measures == measures + assert test_object.port == port + + def test_json_deserialize_from_invalid_dict(self): + test_object = ConnectionCriteria() + + with pytest.raises(WrongFieldError): + test_object.json_deserialize({"client_id": "1", "commands": "commands", "wrong_key": "localhost"}) + + def test_json_deserialize_from_valid_json(self): + client_id = "1" + commands = "commands" + gateway_id = "3" + host = "localhost" + measures = "test_measures" + port = "80" + + json_data = '{"client_id": "1", "commands": "commands", "gateway_id": "3", "host": "localhost", "port": "80",' \ + '"measures": "test_measures"}' + + test_object = ConnectionCriteria() + test_object.json_deserialize(json_data) + assert test_object + assert test_object.gateway_id == gateway_id + assert test_object.client_id == client_id + assert test_object.commands == commands + assert test_object.host == host + assert test_object.measures == measures + assert test_object.port == port + + def test_json_deserialize_from_invalid_json(self): + json_data = '{"client_id": "1", "commands": "commands", "wrong_key": "localhost"}' + test_object = ConnectionCriteria() + + with pytest.raises(WrongFieldError): + assert test_object.json_deserialize(json_data) + + def test_json_serialize(self): + client_id = "1" + commands = "commands" + gateway_id = "3" + host = "localhost" + measures = "test_measures" + port = "80" + + test_object = ConnectionCriteria( + client_id=client_id, + commands=commands, + gateway_id=gateway_id, + host=host, + measures=measures, + port=port + ) + + serialized_data = test_object.json_serialize() + assert serialized_data["gateway_id"] == gateway_id + assert serialized_data["client_id"] == client_id + assert serialized_data["commands"] == commands + assert serialized_data["host"] == host + assert serialized_data["measures"] == measures + assert serialized_data["port"] == port + + +class TestAuthentication: + def test_json_deserialize(self): + type = "type" + secret = "secret" + certificate = "certificate" + test_object = Authentication( + type=type, + secret=secret, + ) + test_object.json_deserialize({"certificate": certificate}) + assert test_object + assert test_object.type == type + assert test_object.secret == secret + assert test_object.certificate == certificate + + test_object_1 = Authentication(type=type, certificate=certificate) + test_object_1.json_deserialize({"secret": secret}) + assert test_object_1 + assert test_object_1.type == type + assert test_object_1.secret == secret + assert test_object_1.certificate == certificate + + test_object_2 = Authentication(secret=secret, certificate=certificate) + test_object_2.json_deserialize({"type": type}) + assert test_object_2 + assert test_object_2.type == type + assert test_object_2.secret == secret + assert test_object_2.certificate == certificate + + test_object_2 = Authentication( + secret=secret, + ) + test_object_2.json_deserialize({"type": type}) + assert test_object_2 + assert test_object_2.type == type + assert test_object_2.secret == secret + assert test_object_2.certificate is None + + with pytest.raises(WrongFieldError): + assert test_object_2.json_deserialize({"wrong_key": certificate}) + + def test_json_deserialize_from_valid_dict(self): + type = "type" + secret = "secret" + certificate = "certificate" + + test_object = Authentication() + + test_object.json_deserialize({"certificate": certificate, "type": type, "secret": secret}) + + assert test_object + assert test_object.type == type + assert test_object.secret == secret + assert test_object.certificate == certificate + + test_object_1 = Authentication(type=type, certificate=certificate) + test_object_1.json_deserialize({"secret": secret}) + assert test_object_1 + assert test_object_1.type == type + assert test_object_1.secret == secret + assert test_object_1.certificate == certificate + + test_object_2 = Authentication(secret=secret, certificate=certificate) + test_object_2.json_deserialize({"type": type}) + assert test_object_2 + assert test_object_2.type == type + assert test_object_2.secret == secret + assert test_object_2.certificate == certificate + + test_object_2 = Authentication( + secret=secret, + ) + test_object_2.json_deserialize({"type": type}) + assert test_object_2 + assert test_object_2.type == type + assert test_object_2.secret == secret + assert test_object_2.certificate is None + + def test_json_deserialize_from_invalid_dict(self): + test_object = Authentication() + + with pytest.raises(WrongFieldError): + test_object.json_deserialize({"type": "type", "secret": "secret", "wrong_key": "certificate"}) + + def test_json_deserialize_from_valid_json(self): + type = "type" + secret = "secret" + certificate = "certificate" + + test_object = Authentication() + json_data = '{"certificate": "certificate", "type": "type", "secret": "secret"}' + + test_object.json_deserialize(json_data) + + assert test_object + assert test_object.type == type + assert test_object.secret == secret + assert test_object.certificate == certificate + + def test_json_deserialize_from_invalid_json(self): + json_data = '{"type": "type", "secret": "secret", "wrong_key": "certificate"}' + test_object = ConnectionCriteria() + + with pytest.raises(WrongFieldError): + assert test_object.json_deserialize(json_data) + + def test_json_serialize(self): + type = "type" + secret = "secret" + certificate = "certificate" + + test_object = Authentication( + type=type, + secret=secret, + certificate=certificate + ) + + serialized_data = test_object.json_serialize() + + assert serialized_data + assert serialized_data["type"] == type + assert serialized_data["secret"] == secret + assert serialized_data["certificate"] == certificate + + +class TestErrorResponse: + + def test_json_deserialize_from_valid_dict(self): + code = "400" + message = "message" + target = "target" + details = "details" + + data = {"code": code, "message": message, "target": target, "details": details} + + test_object = ErrorResponse() + test_object.json_deserialize(data) + assert test_object + assert test_object.code == code + assert test_object.message == message + assert test_object.target == target + assert test_object.details == details + + def test_json_deserialize_from_invalid_dict(self): + data = {"code": "401", "message": "message", "wrong_field": "target"} + test_object = ErrorResponse() + + with pytest.raises(WrongFieldError): + assert test_object.json_deserialize(data) + + def test_json_deserialize_from_valid_json(self): + code = "400" + message = "message" + target = "target" + details = "details" + + json_data = '{"code": "400", "message": "message", "target": "target", "details": "details"}' + + test_object = ErrorResponse() + test_object.json_deserialize(json_data) + assert test_object + assert test_object.code == code + assert test_object.message == message + assert test_object.target == target + assert test_object.details == details + + def test_json_deserialize_from_invalid_json(self): + json_data = '{"code": "401", "message": "message", "wrong_field": "target"}' + test_object = ErrorResponse() + + with pytest.raises(WrongFieldError): + assert test_object.json_deserialize(json_data) + + def test_json_serialize(self): + code = "400" + message = "message" + target = "target" + details = "details" + + test_object = ErrorResponse( + code=code, + message=message, + target=target, + details=details + ) + + serialized_data = test_object.json_serialize() + assert serialized_data["code"] == code + assert serialized_data["client_id"] == message + assert serialized_data["target"] == target + assert serialized_data["details"] == details From d58b2035616e6a1d17d3083968b22f8503124ba2 Mon Sep 17 00:00:00 2001 From: Alexey Petrovsky Date: Tue, 16 Nov 2021 18:25:11 +0300 Subject: [PATCH 04/16] Improve test for Authentication Token. Remove redundant tests --- tests/auth_test/test_dto.py | 107 ++++++++---------------------------- 1 file changed, 23 insertions(+), 84 deletions(-) diff --git a/tests/auth_test/test_dto.py b/tests/auth_test/test_dto.py index 8daa2c97..9497abbd 100644 --- a/tests/auth_test/test_dto.py +++ b/tests/auth_test/test_dto.py @@ -1,15 +1,11 @@ """Tests agrirouter/auth/dto.py""" -from agrirouter.onboarding.dto import ( - AuthorizationToken, - ConnectionCriteria, - Authentication, -) +from agrirouter.auth.dto import AuthorizationToken from agrirouter.messaging.exceptions import WrongFieldError import pytest class TestAuthorizationToken: - def test_json_deserialize(self): + def test_json_deserialize_from_valid_dict(self): account = "account" regcode = "regcode" expires = "01-01-2021" @@ -48,90 +44,33 @@ def test_json_deserialize(self): assert test_object_3.account is None assert test_object_3.regcode == regcode assert test_object_3.expires == expires - with pytest.raises(WrongFieldError): - assert test_object_3.json_deserialize({"wrong_key": regcode}) - - -class TestConnectionCriteria: - def test_json_deserialize(self): - client_id = "1" - commands = "commands" - gateway_id = "3" - host = "localhost" - measures = "test_measures" - port = "80" - test_object = ConnectionCriteria( - gateway_id=gateway_id, - client_id=client_id, - host=host, - measures=measures, - port=port, - ) - test_object.json_deserialize({"commands": commands}) - assert test_object - assert test_object.gateway_id == gateway_id - assert test_object.client_id == client_id - assert test_object.commands == commands - assert test_object.host == host - assert test_object.measures == measures - assert test_object.port == port - test_object_1 = ConnectionCriteria( - gateway_id=gateway_id, - client_id=client_id, - commands=commands, - measures=measures, - port=port, - ) + def test_json_deserialize_from_invalid_dict(self): + account = "account" + regcode = "regcode" + expires = "01-01-2021" + test_object = AuthorizationToken() - test_object_1.json_deserialize({"host": host}) - assert test_object_1 - assert test_object_1.gateway_id == gateway_id - assert test_object_1.client_id == client_id - assert test_object_1.commands == commands - assert test_object_1.host == host - assert test_object_1.measures == measures - assert test_object_1.port == port with pytest.raises(WrongFieldError): - assert test_object_1.json_deserialize({"wrong_key": measures}) + test_object.json_deserialize({"regcode": regcode, "expires": expires, "wrong_key": account}) + def test_json_deserialize_from_valid_json(self): + account = "account" + regcode = "regcode" + expires = "01-01-2021" -class TestAuthentication: - def test_json_deserialize(self): - type = "type" - secret = "secret" - certificate = "certificate" - test_object = Authentication( - type=type, - secret=secret, - ) - test_object.json_deserialize({"certificate": certificate}) - assert test_object - assert test_object.type == type - assert test_object.secret == secret - assert test_object.certificate == certificate + json_data = '{"account": "account", "regcode": "regcode", "expires": "01-01-2021"}' - test_object_1 = Authentication(type=type, certificate=certificate) - test_object_1.json_deserialize({"secret": secret}) - assert test_object_1 - assert test_object_1.type == type - assert test_object_1.secret == secret - assert test_object_1.certificate == certificate + test_object = AuthorizationToken() + test_object.json_deserialize(json_data) + assert test_object + assert test_object.account == account + assert test_object.regcode == regcode + assert test_object.expires == expires - test_object_2 = Authentication(secret=secret, certificate=certificate) - test_object_2.json_deserialize({"type": type}) - assert test_object_2 - assert test_object_2.type == type - assert test_object_2.secret == secret - assert test_object_2.certificate == certificate + def test_json_deserialize_from_invalid_json(self): + json_data = '{"account": "account", "regcode": "regcode", "wrong_key": "01-01-2021"}' + test_object = AuthorizationToken() - test_object_2 = Authentication( - secret=secret, - ) - test_object_2.json_deserialize({"type": type}) - assert test_object_2 - assert test_object_2.type == type - assert test_object_2.secret == secret - assert test_object_2.certificate is None with pytest.raises(WrongFieldError): - assert test_object_2.json_deserialize({"wrong_key": certificate}) + assert test_object.json_deserialize(json_data) From 5e8f1bd058b1e66bf36c7c2b173d6ffab30447db Mon Sep 17 00:00:00 2001 From: Alexey Petrovsky Date: Tue, 16 Nov 2021 18:28:57 +0300 Subject: [PATCH 05/16] Fix ErrorResponse. Fix TestErrorResponse --- agrirouter/onboarding/dto.py | 8 ++++---- tests/onboarding_test/test_dto.py | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/agrirouter/onboarding/dto.py b/agrirouter/onboarding/dto.py index 4fb95e33..224f8b5c 100644 --- a/agrirouter/onboarding/dto.py +++ b/agrirouter/onboarding/dto.py @@ -159,10 +159,10 @@ def __repr__(self): class ErrorResponse: - CODE = "" - MESSAGE = "" - TARGET = "" - DETAILS = "" + CODE = "code" + MESSAGE = "message" + TARGET = "target" + DETAILS = "details" def __init__(self, *, diff --git a/tests/onboarding_test/test_dto.py b/tests/onboarding_test/test_dto.py index 0259f9fd..93c8f325 100644 --- a/tests/onboarding_test/test_dto.py +++ b/tests/onboarding_test/test_dto.py @@ -276,6 +276,6 @@ def test_json_serialize(self): serialized_data = test_object.json_serialize() assert serialized_data["code"] == code - assert serialized_data["client_id"] == message + assert serialized_data["message"] == message assert serialized_data["target"] == target assert serialized_data["details"] == details From 1e59f832079364a297b353a0f5b8a4317dbf7516 Mon Sep 17 00:00:00 2001 From: Alexey Petrovsky Date: Tue, 16 Nov 2021 18:30:49 +0300 Subject: [PATCH 06/16] Fix test for ConnectionCriteria --- tests/onboarding_test/test_dto.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/onboarding_test/test_dto.py b/tests/onboarding_test/test_dto.py index 93c8f325..2ddbdb74 100644 --- a/tests/onboarding_test/test_dto.py +++ b/tests/onboarding_test/test_dto.py @@ -16,7 +16,7 @@ def test_json_deserialize_from_valid_dict(self): test_object = ConnectionCriteria() - data = {"client_id": "1", "commands": "commands", "gateway_id": "3", "host": "localhost", "port": "80", + data = {"clientId": "1", "commands": "commands", "gatewayId": "3", "host": "localhost", "port": "80", "measures": "test_measures"} test_object.json_deserialize(data) @@ -32,7 +32,7 @@ def test_json_deserialize_from_invalid_dict(self): test_object = ConnectionCriteria() with pytest.raises(WrongFieldError): - test_object.json_deserialize({"client_id": "1", "commands": "commands", "wrong_key": "localhost"}) + test_object.json_deserialize({"clientId": "1", "commands": "commands", "wrong_key": "localhost"}) def test_json_deserialize_from_valid_json(self): client_id = "1" @@ -42,7 +42,7 @@ def test_json_deserialize_from_valid_json(self): measures = "test_measures" port = "80" - json_data = '{"client_id": "1", "commands": "commands", "gateway_id": "3", "host": "localhost", "port": "80",' \ + json_data = '{"clientId": "1", "commands": "commands", "gatewayId": "3", "host": "localhost", "port": "80",' \ '"measures": "test_measures"}' test_object = ConnectionCriteria() @@ -80,8 +80,8 @@ def test_json_serialize(self): ) serialized_data = test_object.json_serialize() - assert serialized_data["gateway_id"] == gateway_id - assert serialized_data["client_id"] == client_id + assert serialized_data["gatewayId"] == gateway_id + assert serialized_data["clientId"] == client_id assert serialized_data["commands"] == commands assert serialized_data["host"] == host assert serialized_data["measures"] == measures From 1ce7d2ca4d91a214288f5816f528076ec51a1d51 Mon Sep 17 00:00:00 2001 From: Alexey Petrovsky Date: Tue, 16 Nov 2021 19:11:26 +0300 Subject: [PATCH 07/16] Rename tests/auth_test/test_auth_dto.py --- tests/auth_test/{test_dto.py => test_auth_dto.py} | 0 tests/onboarding_test/{test_dto.py => test_onboarding_dto.py} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename tests/auth_test/{test_dto.py => test_auth_dto.py} (100%) rename tests/onboarding_test/{test_dto.py => test_onboarding_dto.py} (100%) diff --git a/tests/auth_test/test_dto.py b/tests/auth_test/test_auth_dto.py similarity index 100% rename from tests/auth_test/test_dto.py rename to tests/auth_test/test_auth_dto.py diff --git a/tests/onboarding_test/test_dto.py b/tests/onboarding_test/test_onboarding_dto.py similarity index 100% rename from tests/onboarding_test/test_dto.py rename to tests/onboarding_test/test_onboarding_dto.py From cc469b3b176a084bd2a7f1b8e9f24d15288e8ae7 Mon Sep 17 00:00:00 2001 From: Alexey Petrovsky Date: Tue, 16 Nov 2021 19:48:48 +0300 Subject: [PATCH 08/16] Fix auth tests --- tests/auth_test/test_auth.py | 47 ++++++++++++++++++++++-------------- 1 file changed, 29 insertions(+), 18 deletions(-) diff --git a/tests/auth_test/test_auth.py b/tests/auth_test/test_auth.py index 8ab7cf28..350e951e 100644 --- a/tests/auth_test/test_auth.py +++ b/tests/auth_test/test_auth.py @@ -9,34 +9,45 @@ ENV, application_id, ) -from re import search +import re class TestAuthorization: - def test_extract_auth_response(self): + def test_extract_query_params(self): auth_client = Authorization(ENV, public_key=public_key, private_key=private_key) - assert search( - " Date: Tue, 16 Nov 2021 20:26:18 +0300 Subject: [PATCH 09/16] Add valid_response_signature, valid_response_token test constants --- tests/constants.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/tests/constants.py b/tests/constants.py index 91234322..87f11cbb 100644 --- a/tests/constants.py +++ b/tests/constants.py @@ -110,3 +110,11 @@ "mwIDAQAB\n" "-----END PUBLIC KEY-----" ) + +valid_response_signature = "Sp5VyQpD%2FJUEEzi%2Bjc%2BUwGrfWcKiWsbPke8281oadqJ1HlzfPjZNXNeLZxgrPrnmlQoI%2FGkgaYHgjeX3OFneZKhKgDnb80mTUkidFyx%2F72V3mxfvlmOFrZmDYSOhtNg1LsAv%2BP%2FZRMkDCjfSx99vaiYyXc%2FAl8zFSgH0eBphrY2Vh4Rle5O4bOQYSjOdLXY%2FWVjv68R7KH3cdX%2FnC9PbYrT92VY5Nzl7gdeX%2FcXSULGrh7pGOZj6cFJMtl6R%2BqwMIitVaumNqrSktv3Xmv6DKTUbcMbHEJNlexi98RXJMci8O7bdNH7dumoHdOyjlIFlt4SPIahHmPnu4lIYd5grbw%3D%3D" +valid_response_token = ( + "eyJhY2NvdW50IjoiMGJhMjRlZWUtYzMwYi00N2U1LWJkYzktNzcwM" + "2NmYjEzNmEwIiwicmVnY29kZSI6IjhlYWNiMTk4ZmMiLCJleHBpcm" + "VzIjoiMjAyMS0wOS0yM1QxNjowODo0My44ODhaIn0=" + ) +# http://fuf.me/?state=1f9eebe5-7085-4d46-b911-0701a62a371e&token=eyJhY2NvdW50IjoiZmIyOTIxZGUtNTkyYS00OWJhLWJlNWUtOTQwNDQ0MzBiYzk2IiwicmVnY29kZSI6Ijk3ZjQzOTQ2NDUiLCJleHBpcmVzIjoiMjAyMS0xMS0xNlQxOTowOTo0MC4xMzNaIn0%3D&signature= \ No newline at end of file From e48994152d2d3327bef0c7d6e726c6502d1a1489 Mon Sep 17 00:00:00 2001 From: Alexey Petrovsky Date: Tue, 16 Nov 2021 20:26:57 +0300 Subject: [PATCH 10/16] Add and refactored tests for auth/test_response --- tests/auth_test/test_response.py | 56 +++++++++++++++++++++++++++----- tests/constants.py | 11 +++++-- 2 files changed, 56 insertions(+), 11 deletions(-) diff --git a/tests/auth_test/test_response.py b/tests/auth_test/test_response.py index c4b17fae..886ca293 100644 --- a/tests/auth_test/test_response.py +++ b/tests/auth_test/test_response.py @@ -1,19 +1,57 @@ """Tests agrirouter/auth/response.py""" import re + +import pytest + from agrirouter.auth.response import AuthResponse +from tests.constants import valid_response_signature, valid_response_token, public_key def test_decode_token(): - token = ( - "eyJhY2NvdW50IjoiMGJhMjRlZWUtYzMwYi00N2U1LWJkYzktNzcwM" - "2NmYjEzNmEwIiwicmVnY29kZSI6IjhlYWNiMTk4ZmMiLCJleHBpcm" - "VzIjoiMjAyMS0wOS0yM1QxNjowODo0My44ODhaIn0=" - ) - decoded_token = AuthResponse.decode_token(token) - assert re.search(r"[\w]", decoded_token["regcode"]) - assert re.search(r"[\w]", decoded_token["account"]) + + decoded_token = AuthResponse.decode_token(valid_response_token) + assert re.search(r"[\w]", decoded_token.regcode) + assert re.search(r"[\w]", decoded_token.account) + assert decoded_token.expires + + +def test_verify(authorization): + state = "46c81f94-d117-4658-9a38-a85692448219" + token = valid_response_token + signature = valid_response_signature + + auth_response = AuthResponse({"state": state, + "signature": signature, + "token": token}) + + assert auth_response.signature + assert auth_response.token + assert not auth_response.error + + with pytest.raises(PermissionError): + auth_response.is_valid + auth_response.verify(public_key) + assert auth_response.is_valid def test_get_auth_result(authorization): - assert AuthResponse(authorization).get_auth_result()["credentials"] + state = "46c81f94-d117-4658-9a38-a85692448219" + token = valid_response_token + signature = valid_response_signature + + auth_response = AuthResponse({"state": state, + "signature": signature, + "token": token}) + + auth_result = auth_response.get_auth_result() + + assert auth_result.token == token + assert auth_result.state == state + assert auth_result.signature == signature + assert not auth_result.error + assert auth_result.decoded_token + + assert re.search(r"[\w]", auth_result.decoded_token.regcode) + assert re.search(r"[\w]", auth_result.decoded_token.account) + assert auth_result.decoded_token.expires diff --git a/tests/constants.py b/tests/constants.py index 87f11cbb..5651f23d 100644 --- a/tests/constants.py +++ b/tests/constants.py @@ -111,10 +111,17 @@ "-----END PUBLIC KEY-----" ) -valid_response_signature = "Sp5VyQpD%2FJUEEzi%2Bjc%2BUwGrfWcKiWsbPke8281oadqJ1HlzfPjZNXNeLZxgrPrnmlQoI%2FGkgaYHgjeX3OFneZKhKgDnb80mTUkidFyx%2F72V3mxfvlmOFrZmDYSOhtNg1LsAv%2BP%2FZRMkDCjfSx99vaiYyXc%2FAl8zFSgH0eBphrY2Vh4Rle5O4bOQYSjOdLXY%2FWVjv68R7KH3cdX%2FnC9PbYrT92VY5Nzl7gdeX%2FcXSULGrh7pGOZj6cFJMtl6R%2BqwMIitVaumNqrSktv3Xmv6DKTUbcMbHEJNlexi98RXJMci8O7bdNH7dumoHdOyjlIFlt4SPIahHmPnu4lIYd5grbw%3D%3D" +# taken from auth_result_url +valid_response_signature = ( + "SUL9SQMWAfG4%2FEyT0rejkRfAyioxJIOs4sxI5wxeB8TkIiv0MR6YFKw1tPIkM4ll" + "uZKHEIgr5WvM3b3SvII9TtEbzZf995R8GIlNP6yyP51TF%2F4vZMbkMjq%2B2g1o0qw%2FyuDQcGz1RpOJWCuBOjMXu9quzGO" + "8xvDW7LjrN%2BMA9rzJZYb1toNf51O0eO4BDWL5L1oLvrKrqvaErKcIoRJtTVJ51awOWMARDkGZahcRdWrZbdGUbQwIyKJQu4" + "vH8%2B4ytlyXPSWEYwKE2VFoAjhzWsKODdRRxDbNNLWsW8sxKamdXjSOC8inHUFsFNoxLbwZEnKROm2s3OfKGYuibXOpXw%3D%3D" +) + +# taken from auth_result_url valid_response_token = ( "eyJhY2NvdW50IjoiMGJhMjRlZWUtYzMwYi00N2U1LWJkYzktNzcwM" "2NmYjEzNmEwIiwicmVnY29kZSI6IjhlYWNiMTk4ZmMiLCJleHBpcm" "VzIjoiMjAyMS0wOS0yM1QxNjowODo0My44ODhaIn0=" ) -# http://fuf.me/?state=1f9eebe5-7085-4d46-b911-0701a62a371e&token=eyJhY2NvdW50IjoiZmIyOTIxZGUtNTkyYS00OWJhLWJlNWUtOTQwNDQ0MzBiYzk2IiwicmVnY29kZSI6Ijk3ZjQzOTQ2NDUiLCJleHBpcmVzIjoiMjAyMS0xMS0xNlQxOTowOTo0MC4xMzNaIn0%3D&signature= \ No newline at end of file From 23e7b9fd4a1e4d2c38dd9d9e5909763cca975d0b Mon Sep 17 00:00:00 2001 From: Alexey Petrovsky Date: Tue, 16 Nov 2021 20:46:01 +0300 Subject: [PATCH 11/16] Add tests for signatures --- tests/onboarding_test/test_signature.py | 27 +++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/tests/onboarding_test/test_signature.py b/tests/onboarding_test/test_signature.py index 7dbf93a8..e275d5d9 100644 --- a/tests/onboarding_test/test_signature.py +++ b/tests/onboarding_test/test_signature.py @@ -2,11 +2,26 @@ import pytest import re -from agrirouter.onboarding.signature import create_signature -from tests.constants import private_key, wrong_private_key +from cryptography.exceptions import InvalidSignature -def test_create_signature(): - assert re.search(r"[\w]", create_signature("127.0.0.1", private_key)) - with pytest.raises(ValueError): - assert re.search(r"[\w]", create_signature("127.0.0.1", wrong_private_key)) +from agrirouter.onboarding.signature import create_signature, verify_signature +from tests.constants import private_key, wrong_private_key, public_key, valid_response_signature + + +def test_create_signature_ok(): + signature = create_signature( + "REQUEST CONTENT", private_key) + raised = False + try: + verify_signature( + "REQUEST CONTENT", bytes.fromhex(signature), public_key) + except InvalidSignature: + raised = True + assert not raised + + +def test_verify_signature_fail(): + with pytest.raises(InvalidSignature): + verify_signature( + "REQUEST CONTENT", b"wrong_signature", public_key) From 308f1671253647a8f61bd5f462fd37c0cb5cdc73 Mon Sep 17 00:00:00 2001 From: Alexey Petrovsky Date: Wed, 17 Nov 2021 18:44:18 +0300 Subject: [PATCH 12/16] Improve test_decode tests --- tests/messaging_test/test_decode.py | 39 ++++++++++++++++++++++++++--- 1 file changed, 35 insertions(+), 4 deletions(-) diff --git a/tests/messaging_test/test_decode.py b/tests/messaging_test/test_decode.py index 77d62143..71fc70f0 100644 --- a/tests/messaging_test/test_decode.py +++ b/tests/messaging_test/test_decode.py @@ -2,6 +2,7 @@ import pytest +from agrirouter.generated.messaging.response.response_pb2 import ResponseEnvelope from agrirouter.messaging.decode import decode_response from agrirouter.messaging.decode import decode_details @@ -10,12 +11,42 @@ def test_decode_response(): - pass + json_response = json.loads(MESSAGING_RESULT) + message = decode_response(json_response[0]["command"]["message"].encode()) + assert message.response_payload + assert message.response_envelope + + assert message.response_payload.details + + assert message.response_payload.details.type_url == "types.agrirouter.com/agrirouter.response.payload.account.ListEndpointsResponse" + assert message.response_payload.details.value == b'\nx\n$d704a443-99f7-47b4-be55-e2fa09689ebe\x12$PythonSDK_dev - 2021-10-25, 10:51:18\x1a\x0bapplication"\x06active2\x15urn:myapp:snr00003234\n{\n$185cd97b-ed0b-4e75-a6e2-6be1cdd38a06\x12$PythonSDK_dev - 2021-10-21, 21:41:24\x1a\x0bapplication"\x06active2\x18urn:myapp:snr00003234sdf' + + assert message.response_envelope.response_code == 200 + assert message.response_envelope.type == ResponseEnvelope.ResponseBodyType.Value("ENDPOINTS_LISTING") + assert message.response_envelope.application_message_id == "95e35a4f-c5c8-4541-8189-76be33497445" + assert message.response_envelope.message_id == "537623fc-f66f-479b-a2ba-ecf3e5c7f8e0" + + assert message.response_envelope.timestamp + assert message.response_envelope.timestamp.seconds == 1635347156 + assert message.response_envelope.timestamp.nanos == 912000000 def test_decode_details(): json_response = json.loads(MESSAGING_RESULT) message = decode_response(json_response[0]["command"]["message"].encode()) - decoded_details = decode_details(message.response_payload.details) - print(decoded_details) - assert False + details = message.response_payload.details + decoded_details = decode_details(details) + + assert decoded_details.endpoints + assert len(decoded_details.endpoints) == 2 + assert decoded_details[0].endpoint_id == "d704a443-99f7-47b4-be55-e2fa09689ebe" + assert decoded_details[0].endpoint_name == "PythonSDK_dev - 2021-10-25, 10:51:18" + assert decoded_details[0].endpoint_type == "application" + assert decoded_details[0].status == "active" + assert decoded_details[0].external_id == "urn:myapp:snr00003234" + + assert decoded_details[1].endpoint_id == "185cd97b-ed0b-4e75-a6e2-6be1cdd38a06" + assert decoded_details[1].endpoint_name == "PythonSDK_dev - 2021-10-21, 21:41:24" + assert decoded_details[1].endpoint_type == "application" + assert decoded_details[1].status == "active" + assert decoded_details[1].external_id == "urn:myapp:snr00003234sdf" From 704bd4c774c91f3b97e32cf629ad10c543d9eaae Mon Sep 17 00:00:00 2001 From: Alexey Petrovsky Date: Thu, 18 Nov 2021 13:21:42 +0300 Subject: [PATCH 13/16] Fix test_decode_details --- tests/messaging_test/test_decode.py | 22 +- .../messaging_test/test_messaging_services.py | 240 ------------------ 2 files changed, 11 insertions(+), 251 deletions(-) delete mode 100644 tests/messaging_test/test_messaging_services.py diff --git a/tests/messaging_test/test_decode.py b/tests/messaging_test/test_decode.py index 71fc70f0..61c62506 100644 --- a/tests/messaging_test/test_decode.py +++ b/tests/messaging_test/test_decode.py @@ -39,14 +39,14 @@ def test_decode_details(): assert decoded_details.endpoints assert len(decoded_details.endpoints) == 2 - assert decoded_details[0].endpoint_id == "d704a443-99f7-47b4-be55-e2fa09689ebe" - assert decoded_details[0].endpoint_name == "PythonSDK_dev - 2021-10-25, 10:51:18" - assert decoded_details[0].endpoint_type == "application" - assert decoded_details[0].status == "active" - assert decoded_details[0].external_id == "urn:myapp:snr00003234" - - assert decoded_details[1].endpoint_id == "185cd97b-ed0b-4e75-a6e2-6be1cdd38a06" - assert decoded_details[1].endpoint_name == "PythonSDK_dev - 2021-10-21, 21:41:24" - assert decoded_details[1].endpoint_type == "application" - assert decoded_details[1].status == "active" - assert decoded_details[1].external_id == "urn:myapp:snr00003234sdf" + assert decoded_details.endpoints[0].endpoint_id == "d704a443-99f7-47b4-be55-e2fa09689ebe" + assert decoded_details.endpoints[0].endpoint_name == "PythonSDK_dev - 2021-10-25, 10:51:18" + assert decoded_details.endpoints[0].endpoint_type == "application" + assert decoded_details.endpoints[0].status == "active" + assert decoded_details.endpoints[0].external_id == "urn:myapp:snr00003234" + + assert decoded_details.endpoints[1].endpoint_id == "185cd97b-ed0b-4e75-a6e2-6be1cdd38a06" + assert decoded_details.endpoints[1].endpoint_name == "PythonSDK_dev - 2021-10-21, 21:41:24" + assert decoded_details.endpoints[1].endpoint_type == "application" + assert decoded_details.endpoints[1].status == "active" + assert decoded_details.endpoints[1].external_id == "urn:myapp:snr00003234sdf" diff --git a/tests/messaging_test/test_messaging_services.py b/tests/messaging_test/test_messaging_services.py deleted file mode 100644 index 4d5a5e15..00000000 --- a/tests/messaging_test/test_messaging_services.py +++ /dev/null @@ -1,240 +0,0 @@ -import pytest -from google.protobuf.timestamp_pb2 import Timestamp - -from agrirouter import CapabilityParameters, CapabilityService, QueryHeaderService, QueryHeaderParameters -from agrirouter.generated.messaging.request.payload.feed.feed_requests_pb2 import ValidityPeriod - -from agrirouter.generated.messaging.request.payload.endpoint.capabilities_pb2 import CapabilitySpecification -from agrirouter.messaging.builders import CapabilityBuilder -from agrirouter.messaging.decode import decode_response, decode_details -from agrirouter.messaging.services.commons import HttpMessagingService -from agrirouter.messaging.services.http.outbox import OutboxService -from agrirouter.onboarding.response import SoftwareOnboardingResponse -from agrirouter.utils.uuid_util import new_uuid -from tests.sleeper import let_agrirouter_process_the_message - -onboarding_response = SoftwareOnboardingResponse() -onboarding_response.json_deserialize('{"deviceAlternateId":"e2b512f3-9930-4461-b35f-2cdcc7f017fd","capabilityAlternateId":"523e4623-68d2-43d4-a0cc-e2ada2f68b5e","sensorAlternateId":"185cd97b-ed0b-4e75-a6e2-6be1cdd38a06","connectionCriteria":{"gatewayId":"3","measures":"https://dke-qa.eu10.cp.iot.sap/iot/gateway/rest/measures/e2b512f3-9930-4461-b35f-2cdcc7f017fd","commands":"https://dke-qa.eu10.cp.iot.sap/iot/gateway/rest/commands/e2b512f3-9930-4461-b35f-2cdcc7f017fd"},"authentication":{"type":"PEM","secret":"VXHfXV7g#3COYT1Q5YkTxrRXo1IjdN8xSZ3O","certificate":"-----BEGIN ENCRYPTED PRIVATE KEY-----\nMIIE6zAdBgoqhkiG9w0BDAEDMA8ECHlX0q4qf0tSAgMCAAAEggTI4XIOXehAN02J\nwUrHPe2BCGEqXvyA2QzWMBkqYRm7d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Nxyllk6ExpQWiczLiOY5jXnQulX51+k=\n-----END CERTIFICATE-----\n"}}') -account_id = "fb2921de-592a-49ba-be5e-94044430bc96" -certification_version_id = "edd5d6b7-45bb-4471-898e-ff9c2a7bf56f" -application_id = "8c947a45-c57d-42d2-affc-206e21d63a50" - - -def test_given_task_data_capabilities_capability_service_http(): - messaging_service = HttpMessagingService() - capability_parameters = CapabilityParameters( - application_id=application_id, - certification_version_id=certification_version_id, - enable_push_notification=1, - capability_parameters=CapabilityBuilder().with_task_data( - CapabilitySpecification.Direction.Value("SEND_RECEIVE") - ).build(), - onboarding_response=onboarding_response, - application_message_id=new_uuid(), - application_message_seq_no=1, - ) - capability_service = CapabilityService(messaging_service) - messaging_result = capability_service.send(capability_parameters) - assert messaging_result.get_messages_ids() - assert 1 == len(messaging_result.get_messages_ids()) - - -# def test_list_endpoint_service_http(): -# messaging_service = HttpMessagingService() -# list_endpoint_parameters = ListEndpointsParameters( -# technical_message_type=CapabilityType.ISO_11783_TASKDATA_ZIP.value, -# direction=ListEndpointsQuery.Direction.Value("SEND_RECEIVE"), -# filtered=False, -# onboarding_response=onboarding_response, -# application_message_id=new_uuid(), -# application_message_seq_no=1, -# ) -# list_endpoint_service = ListEndpointsService(messaging_service) -# messaging_result = list_endpoint_service.send(list_endpoint_parameters) -# return messaging_result -# -# -# def test_list_endpoint_service_mqtt(): -# client = MqttClient(on_message_callback=foo, client_id="fb2921de-592a-49ba-be5e-94044430bc96") -# messaging_service = MqttMessagingService(onboarding_response, client) -# list_endpoint_parameters = ListEndpointsParameters( -# technical_message_type=CapabilityType.ISO_11783_TASKDATA_ZIP.value, -# direction=ListEndpointsQuery.Direction.Value("SEND_RECEIVE"), -# filtered=False, -# onboarding_response=onboarding_response, -# application_message_id=new_uuid(), -# application_message_seq_no=1, -# ) -# list_endpoint_service = ListEndpointsService(messaging_service) -# messaging_result = list_endpoint_service.send(list_endpoint_parameters) -# return messaging_result -# -# -# def test_valid_subscription_service_http(): -# messaging_service = HttpMessagingService() -# subscription_service = SubscriptionService(messaging_service) -# items = [] -# for tmt in [CapabilityType.DOC_PDF.value, CapabilityType.ISO_11783_TASKDATA_ZIP.value]: -# subscription_item = Subscription.MessageTypeSubscriptionItem(technical_message_type=tmt) -# items.append(subscription_item) -# subscription_parameters = SubscriptionParameters( -# subscription_items=items, -# onboarding_response=onboarding_response, -# application_message_id=new_uuid(), -# application_message_seq_no=1, -# ) -# messaging_result = subscription_service.send(subscription_parameters) -# return messaging_result - - -def test_query_header_message_http(): - messaging_service = HttpMessagingService() - query_header_service = QueryHeaderService(messaging_service) - sent_from = Timestamp() - sent_to = Timestamp() - validity_period = ValidityPeriod(sent_from=sent_from, sent_to=sent_to) - query_header_parameters = QueryHeaderParameters( - message_ids=[new_uuid(), new_uuid()], - senders=[new_uuid(), new_uuid()], - validity_period=validity_period, - onboarding_response=onboarding_response, - application_message_id=new_uuid(), - application_message_seq_no=1, - ) - messaging_result = query_header_service.send(query_header_parameters) - return messaging_result - - -def test_given_validity_and_missing_messages_query_messages_service_http(): - messaging_service = HttpMessagingService() - query_header_service = QueryHeaderService(messaging_service) - sent_from = Timestamp() - sent_to = Timestamp() - validity_period = ValidityPeriod(sent_from=sent_from, sent_to=sent_to) - query_header_parameters = QueryHeaderParameters( - validity_period=validity_period, - onboarding_response=onboarding_response, - application_message_id=new_uuid(), - application_message_seq_no=1, - ) - messaging_result = query_header_service.send(query_header_parameters) - assert messaging_result.get_messages_ids() - assert 1 == len(messaging_result.get_messages_ids()) - - let_agrirouter_process_the_message() - - outbox_service = OutboxService() - outbox_response = outbox_service.fetch(onboarding_response) - assert 200 == outbox_response.status_code - - messages = outbox_response.messages - assert len(messages) == 1 - assert messages[0].command.message - - decoded_message = decode_response(outbox_response.messages[0].command.message) - assert 204 == decoded_message.response_envelope.response_code - - decoded_details = decode_details(decoded_message.response_payload.details) - assert decoded_details - - query_metrics = decoded_details.query_metrics - assert 0 == query_metrics.total_messages_in_query - - -def test_given_invalid_sender_id_query_messages_service_http(): - messaging_service = HttpMessagingService() - query_header_service = QueryHeaderService(messaging_service) - query_header_parameters = QueryHeaderParameters( - onboarding_response=onboarding_response, - application_message_id=new_uuid(), - application_message_seq_no=1, - ) - messaging_result = query_header_service.send(query_header_parameters) - assert messaging_result.get_messages_ids() - assert 1 == len(messaging_result.get_messages_ids()) - - let_agrirouter_process_the_message() - - outbox_service = OutboxService() - outbox_response = outbox_service.fetch(onboarding_response) - assert 200 == outbox_response.status_code - - messages = outbox_response.messages - assert len(messages) == 1 - assert messages[0].command.message - - decoded_message = decode_response(outbox_response.messages[0].command.message) - assert 204 == decoded_message.response_envelope.response_code - - decoded_details = decode_details(decoded_message.response_payload.details) - assert decoded_details - - query_metrics = decoded_details.query_metrics - assert 0 == query_metrics.total_messages_in_query - - -def test_given_invalid_message_id_query_messages_service_http(): - messaging_service = HttpMessagingService() - query_header_service = QueryHeaderService(messaging_service) - query_header_parameters = QueryHeaderParameters( - onboarding_response=onboarding_response, - application_message_id=new_uuid(), - application_message_seq_no=1, - ) - messaging_result = query_header_service.send(query_header_parameters) - assert messaging_result.get_messages_ids() - assert 1 == len(messaging_result.get_messages_ids()) - - let_agrirouter_process_the_message() - - outbox_service = OutboxService() - outbox_response = outbox_service.fetch(onboarding_response) - assert 200 == outbox_response.status_code - - messages = outbox_response.messages - assert len(messages) == 1 - assert messages[0].command.message - - decoded_message = decode_response(outbox_response.messages[0].command.message) - assert 204 == decoded_message.response_envelope.response_code - - decoded_details = decode_details(decoded_message.response_payload.details) - assert decoded_details - - query_metrics = decoded_details.query_metrics - assert 0 == query_metrics.total_messages_in_query - - -def test_given_missing_filter_criteria_id_query_messages_service_http(): - messaging_service = HttpMessagingService() - query_header_service = QueryHeaderService(messaging_service) - query_header_parameters = QueryHeaderParameters( - onboarding_response=onboarding_response, - application_message_id=new_uuid(), - application_message_seq_no=1, - ) - messaging_result = query_header_service.send(query_header_parameters) - assert messaging_result.get_messages_ids() - assert 1 == len(messaging_result.get_messages_ids()) - - let_agrirouter_process_the_message() - - outbox_service = OutboxService() - outbox_response = outbox_service.fetch(onboarding_response) - assert 200 == outbox_response.status_code - - messages = outbox_response.messages - assert len(messages) == 1 - assert messages[0].command.message - - decoded_message = decode_response(outbox_response.messages[0].command.message) - assert 400 == decoded_message.response_envelope.response_code - - decoded_details = decode_details(decoded_message.response_payload.details) - assert decoded_details - - assert 1 == len(decoded_details.messages) - - for message in decoded_details.messages: - assert "VAL_000017" == message.message_code - assert message.message == "Query does not contain any filtering criteria: messageIds, senders or validityPeriod. Information required to process message is missing or malformed." From d86cf4f969d0f6724e1cb9be5828b5b1bee3b93f Mon Sep 17 00:00:00 2001 From: Alexey Petrovsky Date: Thu, 18 Nov 2021 13:31:30 +0300 Subject: [PATCH 14/16] Fix test_onboarding --- tests/messaging_test/test_decode.py | 1 - tests/onboarding_test/test_onboarding.py | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/messaging_test/test_decode.py b/tests/messaging_test/test_decode.py index 61c62506..bd2aa5da 100644 --- a/tests/messaging_test/test_decode.py +++ b/tests/messaging_test/test_decode.py @@ -1,5 +1,4 @@ import json - import pytest from agrirouter.generated.messaging.response.response_pb2 import ResponseEnvelope diff --git a/tests/onboarding_test/test_onboarding.py b/tests/onboarding_test/test_onboarding.py index c92e8f80..d14e8b15 100644 --- a/tests/onboarding_test/test_onboarding.py +++ b/tests/onboarding_test/test_onboarding.py @@ -1,7 +1,7 @@ """Test agrirouter/onboarding/onboarding.py""" from agrirouter.onboarding.exceptions import WrongCertificationType, WrongGateWay -from agrirouter.onboarding.onboarding import SoftwareOnboarding, CUOnboarding +from agrirouter.onboarding.onboarding import SoftwareOnboarding from agrirouter.onboarding.parameters import SoftwareOnboardingParameter from agrirouter.onboarding.enums import GateWays, CertificateTypes from tests.constants import public_key, private_key, ENV, application_id From b0c0ba3058ec8c6cd3c1c0e16a7b76a46f3782b3 Mon Sep 17 00:00:00 2001 From: Alexey Petrovsky Date: Thu, 18 Nov 2021 13:31:48 +0300 Subject: [PATCH 15/16] Implement test_encode --- tests/messaging_test/test_encode.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 tests/messaging_test/test_encode.py diff --git a/tests/messaging_test/test_encode.py b/tests/messaging_test/test_encode.py new file mode 100644 index 00000000..886f4965 --- /dev/null +++ b/tests/messaging_test/test_encode.py @@ -0,0 +1,26 @@ +from google.protobuf.any_pb2 import Any + +from agrirouter.generated.commons.message_pb2 import Message, Messages +from agrirouter.generated.messaging.request.request_pb2 import RequestEnvelope, RequestPayloadWrapper +from agrirouter.messaging.decode import read_properties_buffers_from_input_stream +from agrirouter.messaging.encode import write_proto_parts_to_buffer + + +def test_write_proto_parts_to_buffer(): + mode = 1 + tmt = "TMT" + team_set_context_id = "team_set_context_id" + type_url = "type_url" + + message = Message(message="Test message", message_code="Test message code") + messages = Messages(messages=[message]) + + envelope = RequestEnvelope(mode=mode, technical_message_type=tmt, team_set_context_id=team_set_context_id) + payload = RequestPayloadWrapper(details=Any(type_url=type_url, value=messages.SerializeToString())) + + buffer = write_proto_parts_to_buffer([envelope, payload]) + result = read_properties_buffers_from_input_stream(buffer) + + assert len(result) == 2 + assert len(result[0]) == envelope.ByteSize() + assert len(result[1]) == payload.ByteSize() From de4ae40d8fe055aa8b779d12412f2f6f09f05413 Mon Sep 17 00:00:00 2001 From: Alexey Petrovsky Date: Thu, 18 Nov 2021 13:51:43 +0300 Subject: [PATCH 16/16] Fix test_environments --- tests/enviroments_test/test_environments.py | 78 +++------------------ 1 file changed, 11 insertions(+), 67 deletions(-) diff --git a/tests/enviroments_test/test_environments.py b/tests/enviroments_test/test_environments.py index 8619bdc4..c866f1ad 100644 --- a/tests/enviroments_test/test_environments.py +++ b/tests/enviroments_test/test_environments.py @@ -64,32 +64,14 @@ def test_get_agrirouter_login_url(self): ) def test_get_secured_onboarding_authorization_url(self): + redirect_uri = "www.my_redirect.com" + response_type = "response_type" assert ProductionEnvironment().get_secured_onboarding_authorization_url( - application_id, str, "state", auth_result_url - ) == ProductionEnvironment._ENV_BASE_URL + ProductionEnvironment._SECURED_ONBOARDING_AUTHORIZATION_LINK_TEMPLATE.format( + application_id, response_type, "state", redirect_uri + ) == "https://goto.my-agrirouter.com/application/{application_id}/authorize?response_type={response_type}&state={state}".format( application_id=application_id, - response_type=str, - state="state", - redirect_uri=auth_result_url, - ) - with pytest.raises(AssertionError): - assert ProductionEnvironment().get_secured_onboarding_authorization_url( - application_id, str, "state", auth_result_url - ) == ProductionEnvironment._ENV_BASE_URL + ProductionEnvironment._SECURED_ONBOARDING_AUTHORIZATION_LINK_TEMPLATE.format( - application_id=application_id, - response_type=str, - state="123", - redirect_uri=auth_result_url, - ) - with pytest.raises(AssertionError): - assert ProductionEnvironment().get_secured_onboarding_authorization_url( - application_id, dict, "state", auth_result_url - ) == ProductionEnvironment._ENV_BASE_URL + ProductionEnvironment._SECURED_ONBOARDING_AUTHORIZATION_LINK_TEMPLATE.format( - application_id=application_id, - response_type=str, - state="state", - redirect_uri=auth_result_url, - ) + response_type=response_type, + state="state") + f"&redirect_uri={redirect_uri}" def test_get_mqtt_server_url(self): assert ProductionEnvironment().get_mqtt_server_url( @@ -97,18 +79,6 @@ def test_get_mqtt_server_url(self): ) == ProductionEnvironment._MQTT_URL_TEMPLATE.format( host="localhost", port="5000" ) - with pytest.raises(AssertionError): - assert ProductionEnvironment().get_mqtt_server_url( - "localhost", "5000" - ) == ProductionEnvironment._MQTT_URL_TEMPLATE.format( - host="127.0.0.1", port="5000" - ) - with pytest.raises(AssertionError): - assert ProductionEnvironment().get_mqtt_server_url( - "localhost", "5000" - ) == ProductionEnvironment._MQTT_URL_TEMPLATE.format( - host="localhost", port="80" - ) def test_get_env_public_key(self): assert ( @@ -169,45 +139,19 @@ def test_get_agrirouter_login_url(self): ) def test_get_secured_onboarding_authorization_url(self): + redirect_uri = "www.my_redirect.com" + response_type = "response_type" assert QAEnvironment().get_secured_onboarding_authorization_url( - application_id, str, "state", auth_result_url + application_id, response_type, "state", redirect_uri ) == QAEnvironment._ENV_BASE_URL + QAEnvironment._SECURED_ONBOARDING_AUTHORIZATION_LINK_TEMPLATE.format( application_id=application_id, - response_type=str, - state="state", - redirect_uri=auth_result_url, - ) - with pytest.raises(AssertionError): - assert QAEnvironment().get_secured_onboarding_authorization_url( - application_id, str, "state", auth_result_url - ) == QAEnvironment._ENV_BASE_URL + QAEnvironment._SECURED_ONBOARDING_AUTHORIZATION_LINK_TEMPLATE.format( - application_id=application_id, - response_type=str, - state="123", - redirect_uri=auth_result_url, - ) - with pytest.raises(AssertionError): - assert QAEnvironment().get_secured_onboarding_authorization_url( - application_id, dict, "state", auth_result_url - ) == QAEnvironment._ENV_BASE_URL + QAEnvironment._SECURED_ONBOARDING_AUTHORIZATION_LINK_TEMPLATE.format( - application_id=application_id, - response_type=str, - state="state", - redirect_uri=auth_result_url, - ) + response_type=response_type, + state="state") + f"&redirect_uri={redirect_uri}" def test_get_mqtt_server_url(self): assert QAEnvironment().get_mqtt_server_url( "localhost", "5000" ) == QAEnvironment._MQTT_URL_TEMPLATE.format(host="localhost", port="5000") - with pytest.raises(AssertionError): - assert QAEnvironment().get_mqtt_server_url( - "localhost", "5000" - ) == QAEnvironment._MQTT_URL_TEMPLATE.format(host="127.0.0.1", port="5000") - with pytest.raises(AssertionError): - assert QAEnvironment().get_mqtt_server_url( - "localhost", "5000" - ) == QAEnvironment._MQTT_URL_TEMPLATE.format(host="localhost", port="80") def test_get_env_public_key(self): assert QAEnvironment().get_env_public_key() == QAEnvironment.AR_PUBLIC_KEY