Example #1
0
    def __init__(self, client_id=None, passphrase=None, api_url=None, api_sandbox_url=None, sandbox=None,
                 timeout=30.0, storage_strategy=None, proxies=None):
        if sandbox or mangopay.sandbox:
            self.api_url = api_sandbox_url or mangopay.api_sandbox_url
        else:
            self.api_url = api_url or mangopay.api_url

        self.client_id = client_id or mangopay.client_id
        self.passphrase = passphrase or mangopay.passphrase
        self.auth_manager = AuthorizationTokenManager(self, storage_strategy)
        self.timeout = timeout
        self.proxies = proxies
Example #2
0
    def __init__(self, client_id=None, apikey=None, api_url=None, api_sandbox_url=None, sandbox=None,
                 timeout=30.0, storage_strategy=None, proxies=None):
        global rate_limits
        rate_limits = None
        if (sandbox is None and mangopay.sandbox) or sandbox:
            self.api_url = api_sandbox_url or mangopay.api_sandbox_url
        else:
            self.api_url = api_url or mangopay.api_url

        self.client_id = client_id or mangopay.client_id
        self.apikey = apikey or mangopay.apikey
        self.auth_manager = AuthorizationTokenManager(self, storage_strategy)
        self.timeout = timeout
        self.proxies = proxies
Example #3
0
    def __init__(self, client_id=None, apikey=None, api_url=None, api_sandbox_url=None, sandbox=None,
                 timeout=30.0, storage_strategy=None, proxies=None):
        if sandbox or mangopay.sandbox:
            self.api_url = api_sandbox_url or mangopay.api_sandbox_url
        else:
            self.api_url = api_url or mangopay.api_url

        self.client_id = client_id or mangopay.client_id
        self.apikey = apikey or mangopay.apikey
        self.auth_manager = AuthorizationTokenManager(self, storage_strategy)
        self.timeout = timeout
        self.proxies = proxies
Example #4
0
class APIRequest(object):
    def __init__(self,
                 client_id=None,
                 apikey=None,
                 api_url=None,
                 api_sandbox_url=None,
                 sandbox=None,
                 timeout=30.0,
                 storage_strategy=None,
                 proxies=None):
        global rate_limits
        rate_limits = None
        if (sandbox is None and mangopay.sandbox) or sandbox:
            self.api_url = api_sandbox_url or mangopay.api_sandbox_url
        else:
            self.api_url = api_url or mangopay.api_url

        self.client_id = client_id or mangopay.client_id
        self.apikey = apikey or mangopay.apikey
        self.auth_manager = AuthorizationTokenManager(self, storage_strategy)
        self.timeout = timeout
        self.proxies = proxies

    def set_rate_limit(self, rate_limit):
        global rate_limits
        rate_limits = rate_limit

    def get_rate_limits(self):
        return rate_limits

    def request(self,
                method,
                url,
                data=None,
                idempotency_key=None,
                oauth_request=False,
                **params):
        return self.custom_request(method, url, data, idempotency_key,
                                   oauth_request, True, **params)

    def custom_request(self,
                       method,
                       url,
                       data=None,
                       idempotency_key=None,
                       oauth_request=False,
                       is_mangopay_request=False,
                       **params):
        params = params or {}

        headers = {}

        if is_mangopay_request:
            headers['User-Agent'] = 'MangoPay V2 Python/' + str(
                mangopay.package_version)
            if oauth_request:
                headers['Authorization'] = self.auth_manager.basic_token()
                headers['Content-Type'] = 'application/x-www-form-urlencoded'
            else:
                headers['Authorization'] = self.auth_manager.get_token()
                headers['Content-Type'] = 'application/json'

            if idempotency_key:
                headers['Idempotency-Key'] = idempotency_key
        else:
            if "data_XXX" in params:
                params[str("data")] = params[str("data_XXX")]
                params.__delitem__(str("data_XXX"))
                headers['Content-Type'] = 'application/x-www-form-urlencoded'

        truncated_data = None

        encoded_params = urlrequest.urlencode(params)

        if is_mangopay_request:
            if oauth_request:
                url = self.api_url + url
            else:
                url = self._absolute_url(url, encoded_params)
        else:
            url = '%s?%s' % (url, encoded_params)

        if data or data == {}:
            truncated_data = truncatechars(copy.copy(data))

            data = json.dumps(data, default=lambda x: x.to_api_json())

        logger.debug('DATA[IN -> %s]\n\t- headers: %s\n\t- content: %s', url,
                     headers, truncated_data)

        ts = time.time()

        # signal:
        request_started.send(url=url,
                             data=truncated_data,
                             headers=headers,
                             method=method)

        try:
            result = requests_session.request(method,
                                              url,
                                              data=data,
                                              headers=headers,
                                              timeout=self.timeout,
                                              proxies=self.proxies)
        except ConnectionError as e:
            msg = '{}'.format(e)

            if msg:
                msg = '%s: %s' % (type(e).__name__, msg)
            else:
                msg = type(e).__name__

            reraise_as(APIError(msg))

        except Timeout as e:
            msg = '{}'.format(e)

            if msg:
                msg = '%s: %s' % (type(e).__name__, msg)
            else:
                msg = type(e).__name__

            reraise_as(APIError(msg))
        laps = time.time() - ts

        # signal:
        request_finished.send(url=url,
                              data=truncated_data,
                              headers=headers,
                              method=method,
                              result=result,
                              laps=laps)

        logger.debug(
            'DATA[OUT -> %s][%2.3f seconds]\n\t- status_code: %s\n\t- headers: %s\n\t- content: %s',
            url, laps, result.status_code, result.headers,
            result.text if hasattr(result, 'text') else result.content)

        self.read_response_headers(result.headers)

        if result.status_code not in (requests.codes.ok,
                                      requests.codes.not_found,
                                      requests.codes.created,
                                      requests.codes.accepted,
                                      requests.codes.no_content):
            self._create_apierror(result,
                                  url=url,
                                  data=truncated_data,
                                  method=method)
        elif result.status_code == requests.codes.no_content:
            return result, None
        else:
            if result.content:
                try:
                    content = result.content

                    if six.PY3:
                        content = content.decode('utf-8')

                    return result, json.loads(content)
                except ValueError:
                    if result.content.startswith(b'data='):
                        return result.content
                    self._create_decodeerror(result, url=url)
            else:
                self._create_decodeerror(result, url=url)

    def init_rate_limits(self):
        rate_limits = [
            RateLimit(15),
            RateLimit(30),
            RateLimit(60),
            RateLimit(24 * 60)
        ]
        return rate_limits

    def read_response_headers(self, headers):
        update_rate_limits = None

        for k, v in headers.items():
            lower_case_header = k.lower()
            if lower_case_header == "x-ratelimit-remaining":
                if update_rate_limits is None:
                    update_rate_limits = self.init_rate_limits()
                calls_remaining = list(eval(v))
                update_rate_limits[0].calls_remaining = int(calls_remaining[3])
                update_rate_limits[1].calls_remaining = int(calls_remaining[2])
                update_rate_limits[2].calls_remaining = int(calls_remaining[1])
                update_rate_limits[3].calls_remaining = int(calls_remaining[0])

            if lower_case_header == "x-ratelimit":
                if update_rate_limits is None:
                    update_rate_limits = self.init_rate_limits()
                calls_made = list(eval(v))
                update_rate_limits[0].calls_made = int(calls_made[3])
                update_rate_limits[1].calls_made = int(calls_made[2])
                update_rate_limits[2].calls_made = int(calls_made[1])
                update_rate_limits[3].calls_made = int(calls_made[0])

            if lower_case_header == "x-ratelimit-reset":
                if update_rate_limits is None:
                    update_rate_limits = self.init_rate_limits()
                reset_times = list(eval(v))
                update_rate_limits[0].reset_time_millis = int(reset_times[3])
                update_rate_limits[1].reset_time_millis = int(reset_times[2])
                update_rate_limits[2].reset_time_millis = int(reset_times[1])
                update_rate_limits[3].reset_time_millis = int(reset_times[0])

        if update_rate_limits is not None:
            self.set_rate_limit(update_rate_limits)

    def _absolute_url(self, url, encoded_params):
        pattern = '%s%s%s'

        if encoded_params:
            pattern = '%s%s?%s'

        return pattern % (self.api_url, self._construct_api_url(url),
                          encoded_params)

    def _construct_api_url(self, relative_url):
        return '%s%s' % (self.client_id, relative_url)

    def _create_apierror(self, result, url=None, data=None, method=None):
        text = result.text if hasattr(result, 'text') else result.content

        status_code = result.status_code

        headers = result.headers

        logger.error(
            'API ERROR: status_code: %s | url: %s | method: %s | data: %r | headers: %s | content: %s',
            status_code,
            url,
            method,
            data,
            headers,
            text,
        )

        request_error.send(url=url, status_code=status_code, headers=headers)

        try:
            content = result.json()
        except ValueError:
            content = None

        raise APIError(text,
                       code=status_code,
                       content=content,
                       headers=headers)

    def _create_decodeerror(self, result, url=None):

        text = result.text if hasattr(result, 'text') else result.content

        status_code = result.status_code

        headers = result.headers

        logger.error(
            'DECODE ERROR: status_code: %s | headers: %s | content: %s',
            status_code,
            headers,
            text,
        )

        request_error.send(url=url, status_code=status_code, headers=headers)

        try:
            content = result.json()
        except ValueError:
            content = None

        raise DecodeError(text,
                          code=status_code,
                          headers=headers,
                          content=content)
Example #5
0
class APIRequest(object):
    def __init__(self, client_id=None, apikey=None, api_url=None, api_sandbox_url=None, sandbox=None,
                 timeout=30.0, storage_strategy=None, proxies=None):
        if sandbox or mangopay.sandbox:
            self.api_url = api_sandbox_url or mangopay.api_sandbox_url
        else:
            self.api_url = api_url or mangopay.api_url

        self.client_id = client_id or mangopay.client_id
        self.apikey = apikey or mangopay.apikey
        self.auth_manager = AuthorizationTokenManager(self, storage_strategy)
        self.timeout = timeout
        self.proxies = proxies

    def request(self, method, url, data=None, idempotency_key=None, oauth_request=False, **params):
        return self.custom_request(method, url, data, idempotency_key, oauth_request, True, **params)

    def custom_request(self, method, url, data=None, idempotency_key=None, oauth_request=False,
                       is_mangopay_request=False, **params):
        params = params or {}

        headers = {}

        if is_mangopay_request:
            headers['User-Agent'] = 'MangoPay V2 Python/' + str(mangopay.package_version)
            if oauth_request:
                headers['Authorization'] = self.auth_manager.basic_token()
                headers['Content-Type'] = 'application/x-www-form-urlencoded'
            else:
                headers['Authorization'] = self.auth_manager.get_token()
                headers['Content-Type'] = 'application/json'

            if idempotency_key:
                headers['Idempotency-Key'] = idempotency_key
        else:
            if "data_XXX" in params:
                params[str("data")] = params[str("data_XXX")]
                params.__delitem__(str("data_XXX"))

        truncated_data = None

        encoded_params = urlrequest.urlencode(params)

        if is_mangopay_request:
            if oauth_request:
                url = self.api_url + url
            else:
                url = self._absolute_url(url, encoded_params)
        else:
            url = '%s?%s' % (url, encoded_params)

        if data or data == {}:
            truncated_data = truncatechars(copy.copy(data))

            data = json.dumps(data, default=lambda x: x.to_api_json())

        logger.debug('DATA[IN -> %s]\n\t- headers: %s\n\t- content: %s' % (url, headers, truncated_data))

        ts = time.time()

        # signal:
        request_started.send(url=url, data=truncated_data, headers=headers, method=method)

        try:
            result = requests_session.request(method, url,
                                              data=data,
                                              headers=headers,
                                              timeout=self.timeout,
                                              proxies=self.proxies)
        except ConnectionError as e:
            msg = '{}'.format(e)

            if msg:
                msg = '%s: %s' % (type(e).__name__, msg)
            else:
                msg = type(e).__name__

            reraise_as(APIError(msg))

        except Timeout as e:
            msg = '{}'.format(e)

            if msg:
                msg = '%s: %s' % (type(e).__name__, msg)
            else:
                msg = type(e).__name__

            reraise_as(APIError(msg))
        laps = time.time() - ts

        # signal:
        request_finished.send(url=url,
                              data=truncated_data,
                              headers=headers,
                              method=method,
                              result=result,
                              laps=laps)

        logger.debug('DATA[OUT -> %s][%2.3f seconds]\n\t- status_code: %s\n\t- headers: %s\n\t- content: %s' % (
            url,
            laps,
            result.status_code,
            result.headers,
            result.text if hasattr(result, 'text') else result.content)
        )

        if result.status_code not in (requests.codes.ok, requests.codes.not_found,
                                      requests.codes.created, requests.codes.accepted,
                                      requests.codes.no_content):
            self._create_apierror(result, url=url, data=truncated_data, method=method)
        elif result.status_code == requests.codes.no_content:
            return result, None
        else:
            if result.content:
                try:
                    content = result.content

                    if six.PY3:
                        content = content.decode('utf-8')

                    return result, json.loads(content)
                except ValueError:
                    if result.content.startswith(b'data='):
                        return result.content
                    self._create_decodeerror(result, url=url)
            else:
                self._create_decodeerror(result, url=url)

    def _absolute_url(self, url, encoded_params):
        pattern = '%s%s%s'

        if encoded_params:
            pattern = '%s%s?%s'

        return pattern % (self.api_url, self._construct_api_url(url), encoded_params)

    def _construct_api_url(self, relative_url):
        return '%s%s' % (self.client_id, relative_url)

    def _create_apierror(self, result, url=None, data=None, method=None):
        text = result.text if hasattr(result, 'text') else result.content

        status_code = result.status_code

        headers = result.headers

        logger.error('API ERROR: status_code: %s | url: %s | method: %s | data: %r | headers: %s | content: %s' % (
            status_code,
            url,
            method,
            data,
            headers,
            text
        ))

        request_error.send(url=url, status_code=status_code, headers=headers)

        try:
            content = result.json()
        except ValueError:
            content = None

        raise APIError(text, code=status_code, content=content)

    def _create_decodeerror(self, result, url=None):

        text = result.text if hasattr(result, 'text') else result.content

        status_code = result.status_code

        headers = result.headers

        logger.error('DECODE ERROR: status_code: %s | headers: %s | content: %s' % (status_code,
                                                                                    headers,
                                                                                    text))

        request_error.send(url=url, status_code=status_code, headers=headers)

        try:
            content = result.json()
        except ValueError:
            content = None

        raise DecodeError(text,
                          code=status_code,
                          headers=headers,
                          content=content)
class APIRequest(object):
    def __init__(self,
                 client_id=None,
                 passphrase=None,
                 api_url=None,
                 api_sandbox_url=None,
                 sandbox=True,
                 timeout=30.0,
                 storage_strategy=None,
                 proxies=None):
        if sandbox:
            self.api_url = api_sandbox_url or mangopay.api_sandbox_url
        else:
            self.api_url = api_url or mangopay.api_url

        self.client_id = client_id or mangopay.client_id
        self.passphrase = passphrase or mangopay.passphrase
        self.auth_manager = AuthorizationTokenManager(self, storage_strategy)
        self.timeout = timeout
        self.proxies = proxies

    def request(self,
                method,
                url,
                data=None,
                idempotency_key=None,
                oauth_request=False,
                **params):
        params = params or {}

        headers = {}

        headers['User-Agent'] = 'MangoPay V2 Python/' + str(
            mangopay.package_version)
        if oauth_request:
            headers['Authorization'] = self.auth_manager.basic_token()
            headers['Content-Type'] = 'application/x-www-form-urlencoded'
        else:
            headers['Authorization'] = self.auth_manager.get_token()
            headers['Content-Type'] = 'application/json'

        if idempotency_key:
            headers['Idempotency-Key'] = idempotency_key

        truncated_data = None

        encoded_params = urlrequest.urlencode(params)

        if oauth_request:
            url = self.api_url + url
        else:
            url = self._absolute_url(url, encoded_params)

        if data or data == {}:
            truncated_data = truncatechars(copy.copy(data))

            data = json.dumps(data)

        logger.info('DATA[IN -> %s]\n\t- headers: %s\n\t- content: %s' %
                    (url, headers, truncated_data))

        ts = time.time()

        # signal:
        request_started.send(url=url,
                             data=truncated_data,
                             headers=headers,
                             method=method)

        try:
            result = requests_session.request(method,
                                              url,
                                              data=data,
                                              headers=headers,
                                              timeout=self.timeout,
                                              proxies=self.proxies)
        except ConnectionError as e:
            msg = '{}'.format(e)

            if msg:
                msg = '%s: %s' % (type(e).__name__, msg)
            else:
                msg = type(e).__name__

            reraise_as(APIError(msg))

        except Timeout as e:
            msg = '{}'.format(e)

            if msg:
                msg = '%s: %s' % (type(e).__name__, msg)
            else:
                msg = type(e).__name__

            reraise_as(APIError(msg))
        laps = time.time() - ts

        # signal:
        request_finished.send(url=url,
                              data=truncated_data,
                              headers=headers,
                              method=method,
                              result=result,
                              laps=laps)

        logger.info(
            'DATA[OUT -> %s][%2.3f seconds]\n\t- status_code: %s\n\t- headers: %s\n\t- content: %s'
            % (url, laps, result.status_code, result.headers,
               result.text if hasattr(result, 'text') else result.content))

        if result.status_code not in (requests.codes.ok,
                                      requests.codes.not_found,
                                      requests.codes.created,
                                      requests.codes.accepted,
                                      requests.codes.no_content):
            self._create_apierror(result,
                                  url=url,
                                  data=truncated_data,
                                  method=method)
        elif result.status_code == requests.codes.no_content:
            return result, None
        else:
            if result.content:
                try:
                    content = result.content

                    if six.PY3:
                        content = content.decode('utf-8')

                    return result, json.loads(content)
                except ValueError:
                    self._create_decodeerror(result, url=url)
            else:
                self._create_decodeerror(result, url=url)

    def _absolute_url(self, url, encoded_params):
        pattern = '%s%s%s'

        if encoded_params:
            pattern = '%s%s?%s'

        return pattern % (self.api_url, self._construct_api_url(url),
                          encoded_params)

    def _construct_api_url(self, relative_url):
        return '%s%s' % (self.client_id, relative_url)

    def _create_apierror(self, result, url=None, data=None, method=None):
        text = result.text if hasattr(result, 'text') else result.content

        status_code = result.status_code

        headers = result.headers

        logger.error(
            'API ERROR: status_code: %s | url: %s | method: %s | data: %r | headers: %s | content: %s'
            % (status_code, url, method, data, headers, text))

        request_error.send(url=url, status_code=status_code, headers=headers)

        try:
            content = result.json()
        except ValueError:
            content = None

        raise APIError(text, code=status_code, content=content)

    def _create_decodeerror(self, result, url=None):

        text = result.text if hasattr(result, 'text') else result.content

        status_code = result.status_code

        headers = result.headers

        logger.error(
            'DECODE ERROR: status_code: %s | headers: %s | content: %s' %
            (status_code, headers, text))

        request_error.send(url=url, status_code=status_code, headers=headers)

        try:
            content = result.json()
        except ValueError:
            content = None

        raise DecodeError(text,
                          code=status_code,
                          headers=headers,
                          content=content)
class BaseTestLive(unittest.TestCase):
    _john = None
    _johns_account = None
    _johns_wallet = None
    _johns_kyc_document = None
    _oauth_manager = AuthorizationTokenManager(get_default_handler(),
                                               StaticStorageStrategy())
    _johns_report = None

    def setUp(self):
        BaseTestLive.get_john()

    @staticmethod
    def get_johns_report(recreate=False):
        if BaseTestLive._johns_report is None or recreate:
            report = Report()
            report.report_type = 'TRANSACTION'
            report.filters = ReportFilters()
            report.filters.author_id = BaseTestLive._john.id
            BaseTestLive._johns_report = Report(**report.save())
        return BaseTestLive._johns_report

    @staticmethod
    def get_johns_account(recreate=False):
        if BaseTestLive._johns_account is None or recreate:
            account = BankAccount()
            account.owner_name = BaseTestLive._john.first_name + ' ' + BaseTestLive._john.last_name
            account.user = BaseTestLive._john
            account.type = 'IBAN'
            account.owner_address = BaseTestLive._john.address
            account.iban = 'FR7618829754160173622224154'
            account.bic = 'CMBRFR2BCME'
            BaseTestLive._johns_account = BankAccount(**account.save())
        return BaseTestLive._johns_account

    @staticmethod
    def get_john(recreate=False):
        if BaseTestLive._john is None or recreate:
            user = NaturalUser()
            user.first_name = 'John'
            user.last_name = 'Doe'
            user.birthday = 188352000
            user.email = "*****@*****.**"
            user.address = Address(address_line_1='AddressLine1',
                                   address_line_2='AddressLine2',
                                   city='City',
                                   region='Region',
                                   postal_code='11222',
                                   country='FR')
            user.nationality = 'FR'
            user.country_of_residence = 'FR'
            user.occupation = 'programmer'
            user.income_range = '1'
            user.person_type = 'NATURAL'
            BaseTestLive._john = NaturalUser(**user.save())
        return BaseTestLive._john

    @staticmethod
    def get_johns_kyc_document(recreate=False):
        if BaseTestLive._johns_kyc_document is None or recreate:
            document = Document()
            document.type = 'IDENTITY_PROOF'
            document.user_id = BaseTestLive.get_john().id
            BaseTestLive._johns_kyc_document = Document(**document.save())
        return BaseTestLive._johns_kyc_document

    @staticmethod
    def get_johns_wallet(recreate=False):
        if BaseTestLive._johns_wallet is None or recreate:
            wallet = Wallet()
            wallet.owners = (BaseTestLive._john, )
            wallet.currency = 'EUR'
            wallet.description = 'WALLET IN EUR'
            BaseTestLive._johns_wallet = Wallet(**wallet.save())
        return BaseTestLive._johns_wallet

    @staticmethod
    def get_oauth_manager():
        return BaseTestLive._oauth_manager
class BaseTestLive(unittest.TestCase):
    _john = None
    _johns_account = None
    _johns_wallet = None
    _johns_kyc_document = None
    _oauth_manager = AuthorizationTokenManager(get_default_handler(),
                                               StaticStorageStrategy())
    _johns_report = None
    _johns_transfer = None
    _johns_payout = None
    _johns_payin = None
    _johns_card = None
    _johns_card_3dsecure = None

    _user_legal = None
    _ubo_declaration = None
    _ubo = None

    _client_account = None

    def setUp(self):
        BaseTestLive.get_john()
        BaseTestLive.get_user_legal()

    @staticmethod
    def get_user_legal(recreate=False, terms=False):
        if BaseTestLive._user_legal is None or recreate:
            legal = LegalUser()
            legal.name = 'MatrixSampleOrg_PythonSDK'
            legal.email = '*****@*****.**'
            legal.legal_person_type = "BUSINESS"
            legal.legal_representative_first_name = "Mango"
            legal.legal_representative_last_name = 'Pay'
            legal.legal_representative_email = '*****@*****.**'
            legal.person_type = 'LEGAL'
            legal.headquarters_address = Address(address_line_1='AddressLine1',
                                                 address_line_2='AddressLine2',
                                                 city='City',
                                                 region='Region',
                                                 postal_code='11222',
                                                 country='FR')
            legal.legal_representative_birthday = 1300186358
            legal.legal_representative_nationality = 'FR'
            legal.legal_representative_country_of_residence = 'FR'
            legal.company_number = 123456789
            legal.tag = 'Python SDK Unit Test'
            legal.terms_and_conditions_accepted = terms
            legal.user_category = 'OWNER'
            BaseTestLive._user_legal = LegalUser(**legal.save())
        return BaseTestLive._user_legal

    @staticmethod
    def get_ubo_declaration(recreate=False):
        if BaseTestLive._ubo_declaration is None or recreate:
            legal_user = BaseTestLive.get_user_legal()
            params = {"user_id": legal_user.id}
            BaseTestLive._ubo_declaration = UboDeclaration(
                **UboDeclaration().create(**params))
        return BaseTestLive._ubo_declaration

    @staticmethod
    def get_ubo(recreate=False):
        if BaseTestLive._ubo is None or recreate:
            address = Address(address_line_1='AddressLine1',
                              address_line_2='AddressLine2',
                              city='City',
                              region='Region',
                              postal_code='11222',
                              country='FR')
            params = {
                "user": BaseTestLive.get_user_legal(True),
                "ubo_declaration": BaseTestLive.get_ubo_declaration(True),
                "first_name": "Victor",
                "last_name": "Hugo",
                "address": address,
                "birthday": date(1970, 1, 15),
                "nationality": "FR",
                "birthplace": Birthplace(city='Paris', country='FR'),
                "isActive": True
            }
            BaseTestLive._ubo = Ubo.create(**params)
        return BaseTestLive._ubo

    @staticmethod
    def get_johns_report(recreate=False):
        if BaseTestLive._johns_report is None or recreate:
            report = ReportTransactions()
            report.report_type = 'transactions'
            report.filters = ReportTransactionsFilters()
            report.filters.author_id = BaseTestLive._john.id
            BaseTestLive._johns_report = ReportTransactions(**report.save())
        return BaseTestLive._johns_report

    @staticmethod
    def get_johns_account(recreate=False):
        if BaseTestLive._johns_account is None or recreate:
            account = BankAccount()
            account.owner_name = BaseTestLive._john.first_name + ' ' + BaseTestLive._john.last_name
            account.user = BaseTestLive._john
            account.type = 'IBAN'
            account.owner_address = BaseTestLive._john.address
            account.iban = 'FR7630004000031234567890143'
            account.bic = 'BNPAFRPP'
            BaseTestLive._johns_account = BankAccount(**account.save())
        return BaseTestLive._johns_account

    @staticmethod
    def get_client_bank_account(recreate=False):
        if BaseTestLive._client_account is None or recreate:
            account = BankAccount()
            account.owner_name = 'Joe Blogs'
            account.type = 'IBAN'

            account.owner_address = Address()
            account.owner_address.address_line_1 = "Main Street"
            account.owner_address.address_line_2 = "no. 5 ap. 6"
            account.owner_address.country = "FR"
            account.owner_address.city = "Lyon"
            account.owner_address.postal_code = "65400"

            account.iban = 'FR7630004000031234567890143'
            account.bic = 'BNPAFRPP'
            account.tag = 'custom meta'

            account.create_client_bank_account()

            BaseTestLive._client_account = BankAccount(
                **account.create_client_bank_account())

        return BaseTestLive._client_account

    @staticmethod
    def get_john(recreate=False, terms=False):
        if BaseTestLive._john is None or recreate:
            user = NaturalUser()
            user.first_name = 'John'
            user.last_name = 'Doe'
            user.birthday = 188352000
            user.email = "*****@*****.**"
            user.address = Address(address_line_1='AddressLine1',
                                   address_line_2='AddressLine2',
                                   city='City',
                                   region='Region',
                                   postal_code='11222',
                                   country='FR')
            user.nationality = 'FR'
            user.country_of_residence = 'FR'
            user.occupation = 'programmer'
            user.income_range = '1'
            user.person_type = 'NATURAL'
            user.terms_and_conditions_accepted = terms
            user.user_category = 'OWNER'
            BaseTestLive._john = NaturalUser(**user.save())
        return BaseTestLive._john

    @staticmethod
    def get_johns_kyc_document(recreate=False):
        if BaseTestLive._johns_kyc_document is None or recreate:
            document = Document()
            document.type = 'IDENTITY_PROOF'
            document.user_id = BaseTestLive.get_john().id
            BaseTestLive._johns_kyc_document = Document(**document.save())
        return BaseTestLive._johns_kyc_document

    @staticmethod
    def get_johns_wallet(recreate=False):
        if BaseTestLive._johns_wallet is None or recreate:
            BaseTestLive._johns_wallet = BaseTestLive.create_new_wallet()
        return BaseTestLive._johns_wallet

    @staticmethod
    def create_new_wallet():
        wallet = Wallet()
        wallet.owners = (BaseTestLive._john, )
        wallet.currency = 'EUR'
        wallet.description = 'WALLET IN EUR'
        return Wallet(**wallet.save())

    @staticmethod
    def get_johns_transfer(recreate=False):
        if BaseTestLive._johns_transfer is None or recreate:
            john = BaseTestLive.get_john()
            wallet1 = BaseTestLive.get_johns_wallet()
            wallet2 = BaseTestLive.create_new_wallet()

            transfer = Transfer()
            transfer.author = john
            transfer.tag = 'DefaultTag'
            transfer.credited_user = john
            transfer.debited_funds = Money(amount=1, currency='EUR')
            transfer.fees = Money(amount=0, currency='EUR')
            transfer.debited_wallet = wallet1
            transfer.credited_wallet = wallet2
            BaseTestLive._johns_transfer = Transfer(**transfer.save())
        return BaseTestLive._johns_transfer

    @staticmethod
    def get_johns_payout(recreate=False):
        if BaseTestLive._johns_payout is None or recreate:
            john = BaseTestLive.get_john()
            wallet = BaseTestLive.get_johns_wallet()
            account = BaseTestLive.get_johns_account()

            payout = BankWirePayOut()
            payout.debited_wallet = wallet
            payout.author = john
            payout.credited_user = john
            payout.tag = 'DefaultTag'
            payout.debited_funds = Money(amount=10, currency='EUR')
            payout.fees = Money(amount=5, currency='EUR')
            payout.bank_account = account
            payout.bank_wire_ref = 'User payment'
            payout.payment_type = 'BANK_WIRE'
            BaseTestLive._johns_payout = BankWirePayOut(**payout.save())
        return BaseTestLive._johns_payout

    @staticmethod
    def get_johns_payin(recreate=False):
        if BaseTestLive._johns_payin is None or recreate:
            wallet = BaseTestLive.get_johns_wallet()
            payin = CardWebPayIn()
            payin.credited_wallet = wallet
            payin.author = BaseTestLive.get_john()
            payin.debited_funds = Money(amount=10000, currency='EUR')
            payin.fees = Money(amount=0, currency='EUR')
            payin.card_type = 'CB_VISA_MASTERCARD'
            payin.return_url = 'https://test.com'
            payin.template_url = 'https://TemplateURL.com'
            payin.secure_mode = 'DEFAULT'
            payin.culture = 'fr'
            BaseTestLive._johns_payin = CardWebPayIn(**payin.save())
        return BaseTestLive._johns_payin

    @staticmethod
    def get_johns_card(recreate=False):
        if BaseTestLive._johns_card is None or recreate:
            card_params = {"user": BaseTestLive.get_john(), "currency": 'EUR'}
            card_registration = CardRegistration(**card_params)
            card_registration.save()

            params = {
                "data_XXX": card_registration.preregistration_data,
                "accessKeyRef": card_registration.access_key,
                "cardNumber": '4970101122334422',
                "cardExpirationDate": '1224',
                "cardCvx": '123'
            }
            response = APIRequest().custom_request(
                'POST', card_registration.card_registration_url, None, None,
                False, False, **params)
            card_registration.registration_data = response
            card_registration.save()
            BaseTestLive._johns_card = card_registration.card
        return BaseTestLive._johns_card

    @staticmethod
    def get_johns_card_3dsecure(recreate=False):
        if BaseTestLive._johns_card_3dsecure is None or recreate:
            card_params = {"user": BaseTestLive.get_john(), "currency": 'EUR'}
            card_registration = CardRegistration(**card_params)
            card_registration.save()

            params = {
                "data_XXX": card_registration.preregistration_data,
                "accessKeyRef": card_registration.access_key,
                "cardNumber": '4970105191923460',
                "cardExpirationDate": '1224',
                "cardCvx": '123'
            }
            response = APIRequest().custom_request(
                'POST', card_registration.card_registration_url, None, None,
                False, False, **params)
            card_registration.registration_data = response
            card_registration.save()
            BaseTestLive._johns_card = card_registration.card
        return BaseTestLive._johns_card

    @staticmethod
    def get_oauth_manager():
        return BaseTestLive._oauth_manager

    def test_handler(self):
        api_url = "test_api_url"
        sandbox_url = "test_sandbox_url"

        sandbox_handler = APIRequest(api_sandbox_url=sandbox_url,
                                     api_url=api_url,
                                     sandbox=True)

        non_sandbox_handler = APIRequest(api_sandbox_url=sandbox_url,
                                         api_url=api_url,
                                         sandbox=False)

        self.assertEqual(api_url, non_sandbox_handler.api_url)
        self.assertEqual(sandbox_url, sandbox_handler.api_url)
class BaseTestLive(unittest.TestCase):
    _john = None
    _johns_account = None
    _johns_wallet = None
    _johns_kyc_document = None
    _oauth_manager = AuthorizationTokenManager(get_default_handler(),
                                               StaticStorageStrategy())
    _johns_report = None
    _johns_transfer = None
    _johns_payout = None
    _johns_payin = None
    _johns_card = None

    def setUp(self):
        BaseTestLive.get_john()

    @staticmethod
    def get_johns_report(recreate=False):
        if BaseTestLive._johns_report is None or recreate:
            report = ReportTransactions()
            report.report_type = 'transactions'
            report.filters = ReportTransactionsFilters()
            report.filters.author_id = BaseTestLive._john.id
            BaseTestLive._johns_report = ReportTransactions(**report.save())
        return BaseTestLive._johns_report

    @staticmethod
    def get_johns_account(recreate=False):
        if BaseTestLive._johns_account is None or recreate:
            account = BankAccount()
            account.owner_name = BaseTestLive._john.first_name + ' ' + BaseTestLive._john.last_name
            account.user = BaseTestLive._john
            account.type = 'IBAN'
            account.owner_address = BaseTestLive._john.address
            account.iban = 'FR7618829754160173622224154'
            account.bic = 'CMBRFR2BCME'
            BaseTestLive._johns_account = BankAccount(**account.save())
        return BaseTestLive._johns_account

    @staticmethod
    def get_john(recreate=False):
        if BaseTestLive._john is None or recreate:
            user = NaturalUser()
            user.first_name = 'John'
            user.last_name = 'Doe'
            user.birthday = 188352000
            user.email = "*****@*****.**"
            user.address = Address(address_line_1='AddressLine1',
                                   address_line_2='AddressLine2',
                                   city='City',
                                   region='Region',
                                   postal_code='11222',
                                   country='FR')
            user.nationality = 'FR'
            user.country_of_residence = 'FR'
            user.occupation = 'programmer'
            user.income_range = '1'
            user.person_type = 'NATURAL'
            BaseTestLive._john = NaturalUser(**user.save())
        return BaseTestLive._john

    @staticmethod
    def get_johns_kyc_document(recreate=False):
        if BaseTestLive._johns_kyc_document is None or recreate:
            document = Document()
            document.type = 'IDENTITY_PROOF'
            document.user_id = BaseTestLive.get_john().id
            BaseTestLive._johns_kyc_document = Document(**document.save())
        return BaseTestLive._johns_kyc_document

    @staticmethod
    def get_johns_wallet(recreate=False):
        if BaseTestLive._johns_wallet is None or recreate:
            BaseTestLive._johns_wallet = BaseTestLive.create_new_wallet()
        return BaseTestLive._johns_wallet

    @staticmethod
    def create_new_wallet():
        wallet = Wallet()
        wallet.owners = (BaseTestLive._john, )
        wallet.currency = 'EUR'
        wallet.description = 'WALLET IN EUR'
        return Wallet(**wallet.save())

    @staticmethod
    def get_johns_transfer(recreate=False):
        if BaseTestLive._johns_transfer is None or recreate:
            john = BaseTestLive.get_john()
            wallet1 = BaseTestLive.get_johns_wallet()
            wallet2 = BaseTestLive.create_new_wallet()

            transfer = Transfer()
            transfer.author = john
            transfer.tag = 'DefaultTag'
            transfer.credited_user = john
            transfer.debited_funds = Money(amount=1, currency='EUR')
            transfer.fees = Money(amount=0, currency='EUR')
            transfer.debited_wallet = wallet1
            transfer.credited_wallet = wallet2
            BaseTestLive._johns_transfer = Transfer(**transfer.save())
        return BaseTestLive._johns_transfer

    @staticmethod
    def get_johns_payout(recreate=False):
        if BaseTestLive._johns_payout is None or recreate:
            john = BaseTestLive.get_john()
            wallet = BaseTestLive.get_johns_wallet()
            account = BaseTestLive.get_johns_account()

            payout = BankWirePayOut()
            payout.debited_wallet = wallet
            payout.author = john
            payout.credited_user = john
            payout.tag = 'DefaultTag'
            payout.debited_funds = Money(amount=10, currency='EUR')
            payout.fees = Money(amount=5, currency='EUR')
            payout.bank_account = account
            payout.bank_wire_ref = 'User payment'
            payout.payment_type = 'BANK_WIRE'
            BaseTestLive._johns_payout = BankWirePayOut(**payout.save())
        return BaseTestLive._johns_payout

    @staticmethod
    def get_johns_payin(recreate=False):
        if BaseTestLive._johns_payin is None or recreate:
            wallet = BaseTestLive.get_johns_wallet()
            payin = CardWebPayIn()
            payin.credited_wallet = wallet
            payin.author = BaseTestLive.get_john()
            payin.debited_funds = Money(amount=10000, currency='EUR')
            payin.fees = Money(amount=0, currency='EUR')
            payin.card_type = 'CB_VISA_MASTERCARD'
            payin.return_url = 'https://test.com'
            payin.template_url = 'https://TemplateURL.com'
            payin.secure_mode = 'DEFAULT'
            payin.culture = 'fr'
            BaseTestLive._johns_payin = CardWebPayIn(**payin.save())
        return BaseTestLive._johns_payin

    @staticmethod
    def get_johns_card(recreate=False):
        if BaseTestLive._johns_card is None or recreate:
            card_params = {"user": BaseTestLive.get_john(), "currency": 'EUR'}
            card_registration = CardRegistration(**card_params)
            card_registration.save()

            params = {
                "data_XXX": card_registration.preregistration_data,
                "accessKeyRef": card_registration.access_key,
                "cardNumber": '4970101122334422',
                "cardExpirationDate": '1224',
                "cardCvx": '123'
            }
            response = APIRequest().custom_request(
                'POST', card_registration.card_registration_url, None, None,
                False, False, **params)
            card_registration.registration_data = response
            card_registration.save()
            BaseTestLive._johns_card = card_registration.card
        return BaseTestLive._johns_card

    @staticmethod
    def get_oauth_manager():
        return BaseTestLive._oauth_manager