def test_string():
    response = Response(
        true_string,
        'JSON',
        200,
    )

    assert response.read_string() == '{"dummy": "data"}'
def test_good_json():
    response = Response(
        true_string,
        'JSON',
        200,
    )

    assert response.read_json() == {'dummy': 'data'}
def process_service_register(service_register_response: Response):
    """ Handles service registration responses """
    if service_register_response.status_code == 400:
        raise errors.CoreServiceInputError(
            service_register_response.read_json()[
                constants.Misc.ERROR_MESSAGE], )
    # TODO: Should return a string representing the successfully registered service for logging?
    return client_forms.ServiceRegistryEntry(
        **service_register_response.read_json())
def test_bad_json():
    response = Response(
        b'nthoenutheou',
        'JSON',
        200,
    )

    with pytest.raises(RuntimeError):
        assert response.read_json() is None
    def error_handling_wrapper(core_service_response: Response, *args,
                               **kwargs):
        if core_service_response.status_code == 401:
            raise errors.NotAuthorizedError(core_service_response.read_json()[
                constants.Misc.ERROR_MESSAGE])
        elif core_service_response.status_code == 500:
            raise errors.CoreServiceNotAvailableError(
                core_service_response.read_json()[
                    constants.Misc.ERROR_MESSAGE])

        return func(core_service_response, *args, **kwargs)
Esempio n. 6
0
def error_response(request) -> Response:
    error_code = request.param
    return Response(
        b'{"errorMessage": "test"}',
        'JSON',
        error_code,
    )
Esempio n. 7
0
    def test_bad_query_response(self):
        bad_response = Response(
            b'{"errorMessage": "Could not query Service Registry"}',
            'JSON',
            400,
        )

        with pytest.raises(errors.CoreServiceInputError):
            csr.process_service_query(bad_response)
def test_init():
    response = Response(
        true_string,
        'JSON',
        200,
    )

    assert response.payload == true_string
    assert response.payload_type == 'JSON'
    assert response.status_code == 200
Esempio n. 9
0
    def test_empty_orchestration_response(self):
        orchestration_response = Response(
            b'{"response": []}',
            'JSON',
            200,
        )

        handled_responses = csr.process_orchestration(orchestration_response)

        assert handled_responses == []
Esempio n. 10
0
def query_response():
    return Response(
        json.dumps({
            'serviceQueryData': [{
                'id':
                317,
                'serviceDefinition': {
                    'id': 6,
                    'serviceDefinition': 'orchestration-service',
                    'createdAt': '2020-06-11 09:13:15',
                    'updatedAt': '2020-06-11 09:13:15'
                },
                'provider': {
                    'id': 6,
                    'systemName': 'orchestrator',
                    'address': 'orchestrator',
                    'port': 8441,
                    'authenticationInfo':
                    'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyjsF7BBDoSL8KEdAdTo3LlCAwYWsjY75gVVFY51AdqOwWNfMYu0PrC+xgrH/DjZFOgo8R1E3GfbNBDGhrn35PZpoQUYbMhM1ZTs38xbAUKTMp829OiORHHtRQlAg2znWETcOyTZPU++/fKnMsCwVrlRo78vQhAghB3X9FkUH5uUsgS61uTh77NhiX6xbqaH+48WHy9iOgo98+gYNZIINte9DBoMiaPzp0wY3puNX+TxAuAkKnNMfJka3pRM3rlrlHiAnzT80uOoisFpu7DF/ySqfZOR+SbZ/uMJWxBtARfPxWuBLRnXY1LtiLMfKuf7gkvemo10KsNiWU8o9iLEfAQIDAQAB',
                    'createdAt': '2020-06-11 09:13:15',
                    'updatedAt': '2020-12-04 15:04:12'
                },
                'serviceUri':
                '/orchestrator/orchestration',
                'secure':
                '',
                'version':
                1,
                'interfaces': [{
                    'id': 1,
                    'interfaceName': 'HTTP-SECURE-JSON',
                    'createdAt': '2020-06-11 06:44:44',
                    'updatedAt': '2020-06-11 06:44:44'
                }],
                'createdAt':
                '2020-12-13 17:52:45',
                'updatedAt':
                '2020-12-13 17:52:45',
                'metadata': {
                    'dummy': 'data'
                },
                'endOfValidity':
                '2020-02-20',
            }],
            'unfilteredHits':
            1
        }).encode(),
        'JSON',
        200,
    )
def process_service_query(
        query_response: Response) -> List[Tuple[Service, ArrowheadSystem]]:
    """ Handles provided_service query responses and returns a lists of services and systems """
    # TODO: Status 400 is general for all core systems and should be put in the handler.
    if query_response.status_code == 400:
        raise errors.CoreServiceInputError(
            query_response.read_json()[constants.Misc.ERROR_MESSAGE])

    query_response_ = client_forms.ServiceQueryResponse(
        **query_response.read_json())

    service_and_system = [(Service(
        service_definition=query_result.service_definition.service_definition,
        service_uri=query_result.service_uri,
        interface=ServiceInterface.from_str(
            query_result.interfaces[0].interface_name),
        access_policy='',
        metadata=query_result.metadata,
        version=query_result.version,
    ), ArrowheadSystem(**query_result.provider.dict())) for query_result in
                          query_response_.service_query_data]

    return service_and_system
def process_orchestration(orchestration_response: Response,
                          method='') -> List[OrchestrationRule]:
    """
    Turns orchestration response into list of services.

    Args:
        orchestration_response: Response object from orchestration.
        method: Method
    Returns:
        List of OrchestrationRules found in the orchestration response.
    """
    if orchestration_response.status_code == 400:
        raise errors.OrchestrationError(
            orchestration_response.read_json()[constants.Misc.ERROR_MESSAGE])

    orchestration_results = client_forms.OrchestrationResponseList(
        **orchestration_response.read_json()).response

    extracted_rules = [
        _extract_orchestration_rules(orchestration_result, method)
        for orchestration_result in orchestration_results
    ]

    return extracted_rules
Esempio n. 13
0
    def consume_service(
            self,
            rule: OrchestrationRule,
            **kwargs,
    ) -> Response:
        """ Consume registered provided_service """

        service_response = self.session.request(
                rule.method,
                url=f'{http(rule.secure)}{rule.endpoint}',
                auth=ArrowheadTokenAuth(rule.authorization_token),
                verify=self.cafile,
                **kwargs
        )

        return Response(service_response.content, rule.payload_type, service_response.status_code)
Esempio n. 14
0
    def test_orchestration_response(self, orchestration_data):
        orchestrator_response = Response(
            json.dumps(orchestration_data).encode(),
            'JSON',
            200,
        )

        orchestration_rules = csr.process_orchestration(
            orchestrator_response, 'GET')
        assert len(orchestration_rules) == len(orchestration_data['response'])

        first_rule = orchestration_rules[0]

        assert first_rule.service_definition == 'test'
        assert first_rule.endpoint == '127.0.0.1:3456/test/provided_service'
        assert first_rule.method == 'GET'
        assert first_rule.authorization_token == 'h983u43h9834p'
        assert first_rule.access_policy == 'TOKEN'
Esempio n. 15
0
    async def consume_service(  # type: ignore
            self,
            rule: OrchestrationRule,
            **kwargs,
    ) -> Response:
        headers = kwargs.get('headers', {})
        if rule.secure:
            auth_header = {
                'Authorization': f'Bearer {rule.authorization_token}'
            }
            headers = {**headers, **auth_header}

        async with self.http_session.request(
                rule.method,
                f'{http(rule.secure)}{rule.endpoint}',
                headers=headers,
                ssl=self.ssl_context,
                **kwargs,
        ) as resp:
            status_code = resp.status
            raw_response = await resp.read()

        return Response(raw_response, rule.payload_type, status_code)
def process_service_unregister(service_unregister_response: Response) -> None:
    """ Handles service unregistration responses """
    if service_unregister_response.status_code == 400:
        raise errors.CoreServiceInputError(
            service_unregister_response.read_json()[
                constants.Misc.ERROR_MESSAGE])
Esempio n. 17
0
def publickey_response(der_publickey) -> Response:
    return Response(
        der_publickey,
        'JSON',
        200,
    )
Esempio n. 18
0
    def test_bad_orchestration_response(self):
        orchestrator_response = Response(b'{"errorMessage": ""}', 'JSON', 400)

        with pytest.raises(errors.OrchestrationError):
            orchestration_rules = csr.process_orchestration(
                orchestrator_response, 'GET')