def _create_client(connect_responses):
        response_iterator = iter(connect_responses)

        def _execute_http_call(self, method, url, kwargs):
            res = next(response_iterator)

            query, ordering, select = _parse_qs(url)
            if res.query:
                assert query == res.query, 'RQL query does not match.'
            if res.ordering:
                assert ordering == res.ordering, 'RQL ordering does not match.'
            if res.select:
                assert select == res.select, 'RQL select does not match.'

            mock_kwargs = {
                'match_querystring': False,
            }
            if res.count is not None:
                end = 0 if res.count == 0 else res.count - 1
                mock_kwargs['status'] = 200
                mock_kwargs['headers'] = {
                    'Content-Range': f'items 0-{end}/{res.count}'
                }
                mock_kwargs['json'] = []

            if isinstance(res.value, Iterable):
                count = len(res.value)
                end = 0 if count == 0 else count - 1
                mock_kwargs['status'] = 200
                mock_kwargs['json'] = res.value
                mock_kwargs['headers'] = {
                    'Content-Range': f'items 0-{end}/{count}'
                }
            elif isinstance(res.value, dict):
                mock_kwargs['status'] = res.status or 200
                mock_kwargs['json'] = res.value
            elif res.value is None:
                if res.exception:
                    mock_kwargs['body'] = res.exception
                else:
                    mock_kwargs['status'] = res.status or 200
            else:
                mock_kwargs['status'] = res.status or 200
                mock_kwargs['body'] = str(res.value)

            with responses.RequestsMock() as rsps:
                rsps.add(
                    method.upper(),
                    url,
                    **mock_kwargs,
                )

                self.response = requests.request(method, url, **kwargs)
                if self.response.status_code >= 400:
                    self.response.raise_for_status()

        client = ConnectClient('Key', use_specs=False)
        client._execute_http_call = MethodType(_execute_http_call, client)
        return client
 def test_suspend_pass(self):
     request = TestUtils.get_response("create_purchase_request_body.json")
     response = TestUtils.get_response(
         "purchase_subscription_response.json")
     client = ConnectClient('Key', use_specs=False)
     result = Suspend.process_request(request, client)
     self.assertDictEqual(result, response)
# -*- coding: utf-8 -*-
#
# Copyright (c) {% now 'utc', '%Y' %}, {{ cookiecutter.author }}
# All rights reserved.
#
import unittest
from cnct import ConnectClient
from unittest.mock import patch, MagicMock
from tests.test_util import TestUtils
from connect_processor.app.suspend import Suspend

client = ConnectClient('Key', use_specs=False)


class TestSuspend(unittest.TestCase):
    # //////////////////////
    # SUSPEND UNIT TESTS
    # /////////////////////

    @patch(
        'connect_processor.app.utils.utils.Utils.approve_fulfillment_request',
        MagicMock(return_value=TestUtils.get_response(
            "purchase_subscription_response.json")))
    @patch('connect_processor.app.utils.utils.Utils._get_template_by_product',
           MagicMock(return_value="TL-###-###-###"))
    def test_suspend_pass(self):
        request = TestUtils.get_response("create_purchase_request_body.json")
        response = TestUtils.get_response(
            "purchase_subscription_response.json")
        result = Suspend.process_request(request, client)
        self.assertDictEqual(result, response)
Ejemplo n.º 4
0
project_manager = __import__('connect_processor.app', globals(), locals(), [
    'purchase', 'change', 'cancel', 'suspend', 'resume', 'tier_fulfillment',
    'report_usage'
], 0)

# The processor.py is the entry point of Processor execution
if __name__ == '__main__':

    # Reading the config.json file in the Processor
    config_file = Utils.get_config_file()
    # apiEndpoint is the API End-point of Connect
    connect_api_url = config_file['connectApiEndpoint'],
    # apiKey is the API key for authorization created in Integrations menu of Connect
    connect_key = config_file['connectApiKey'],
    # Products are the list of IDs of the products which needs to be processed by this Processor
    client = ConnectClient(api_key=connect_key[0], endpoint=connect_api_url[0])

    # If the Product has parameters of scope 'Tier' then Tier use case implementation will be required.
    # Make sure the project has the Tier use case included during project creation
    # The Tier Config Requests (TCR) needs to be processed first and then the corresponding Fulfillment Requests
    if hasattr(project_manager, 'tier_fulfillment'):
        # Filter to fetch the Tier-Config-Request (TCR) for this product
        # The processor needs to process only the TCRs in Pending status

        query_tcr = R()
        query_tcr &= R().configuration.product.id.oneof(Globals.PRODUCTS)
        query_tcr &= R().configuration.connection.type.oneof(
            Globals.ENVIRONMENT)
        query_tcr &= R().status.oneof(['pending'])
        tc_requests = client.ns('tier').collection('config-requests').filter(
            query_tcr)
    except Exception as err:
        if len(err.args) > 0:
            Utils.save_error(client, Utils.get_basic_value(request, 'id'), err.args[0])
        raise err


# The processor.py is the entry point of Processor execution
if __name__ == '__main__':

    # Reading the config.json file in the Processor
    config_file = Utils.get_config_file()
    # apiEndpoint is the API End-point of Connect
    connect_api_url = config_file['connectApiEndpoint'],
    # apiKey is the API key for authorization created in Integrations menu of Connect
    connect_key = config_file['connectApiKey'],
    # Products are the list of IDs of the products which needs to be processed by this Processor
    client = ConnectClient(api_key=connect_key[0], endpoint=connect_api_url[0])

    # Filter to fetch all the subscription Fulfillment requests from Connect that need to be processed by this Processor
    query = R()
    query &= R().asset.product.id.oneof(Globals.PRODUCTS)
    query &= R().asset.connection.type.oneof(Globals.ENVIRONMENT)
    query &= R().status.oneof(['pending'])

    # Applying the filter
    requests = client.collection('requests').filter(query)

    # Processing each request
    for request in requests:
        process_request()