diff --git a/examples/charge.py b/examples/charge.py index 272a11007..a653ca4b9 100644 --- a/examples/charge.py +++ b/examples/charge.py @@ -1,8 +1,13 @@ +from __future__ import absolute_import, division, print_function + +import os + import stripe -stripe.api_key = 'tGN0bIwXnHdwOa85VABjPdSn8nWY7G7I' -print "Attempting charge..." +stripe.api_key = os.environ.get('STRIPE_SECRET_KEY') + +print("Attempting charge...") resp = stripe.Charge.create( amount=200, @@ -11,4 +16,4 @@ description='customer@gmail.com' ) -print 'Success: %r' % (resp, ) +print('Success: %r' % (resp)) diff --git a/examples/oauth.py b/examples/oauth.py index c8c43f097..a9a3ce990 100644 --- a/examples/oauth.py +++ b/examples/oauth.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import os import stripe diff --git a/examples/proxy.py b/examples/proxy.py index ac115d036..b85d7f349 100644 --- a/examples/proxy.py +++ b/examples/proxy.py @@ -1,26 +1,30 @@ +from __future__ import absolute_import, division, print_function + +import os + import stripe -stripe.api_key = 'tGN0bIwXnHdwOa85VABjPdSn8nWY7G7I' +stripe.api_key = os.environ.get('STRIPE_SECRET_KEY') -print( "Attempting charge..." ) +print("Attempting charge...") stripe.proxy = { "http": "http://:@:", - "https": "http://:@:" } - -clients = ( - stripe.http_client.RequestsClient( - verify_ssl_certs= stripe.verify_ssl_certs, - proxy= stripe.proxy ) - , - stripe.http_client.PycurlClient( - verify_ssl_certs= stripe.verify_ssl_certs, - proxy= stripe.proxy ) - , - stripe.http_client.Urllib2Client( - verify_ssl_certs= stripe.verify_ssl_certs, - proxy= stripe.proxy ) ) + "https": "http://:@:", +} + +clients = ( + stripe.http_client.RequestsClient( + verify_ssl_certs=stripe.verify_ssl_certs, + proxy=stripe.proxy), + stripe.http_client.PycurlClient( + verify_ssl_certs=stripe.verify_ssl_certs, + proxy=stripe.proxy), + stripe.http_client.Urllib2Client( + verify_ssl_certs=stripe.verify_ssl_certs, + proxy=stripe.proxy), +) for c in clients: stripe.default_http_client = c @@ -30,4 +34,4 @@ card='tok_visa', description='customer@gmail.com' ) - print( 'Success: %s, %r' % ( c.name, resp, ) ) + print('Success: %s, %r' % (c.name, resp)) diff --git a/examples/webhooks.py b/examples/webhooks.py index 25bba33aa..024cf24be 100644 --- a/examples/webhooks.py +++ b/examples/webhooks.py @@ -1,10 +1,11 @@ -from __future__ import print_function +from __future__ import absolute_import, division, print_function import os import stripe from flask import Flask, request + stripe.api_key = os.environ.get('STRIPE_SECRET_KEY') webhook_secret = os.environ.get('WEBHOOK_SECRET') diff --git a/setup.py b/setup.py index 12a6671b3..ca371f44a 100644 --- a/setup.py +++ b/setup.py @@ -61,7 +61,6 @@ install_requires=install_requires, test_suite='stripe.test.all', tests_require=['unittest2', 'mock'], - use_2to3=True, classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", diff --git a/stripe/__init__.py b/stripe/__init__.py index 88edf993d..aec51c41b 100644 --- a/stripe/__init__.py +++ b/stripe/__init__.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + # Stripe Python bindings # API docs at http://stripe.com/docs/api # Authors: diff --git a/stripe/api_requestor.py b/stripe/api_requestor.py index 0caac71f1..97a2cccdd 100644 --- a/stripe/api_requestor.py +++ b/stripe/api_requestor.py @@ -1,14 +1,15 @@ +from __future__ import absolute_import, division, print_function + import calendar import datetime import platform import time -import urllib -import urlparse import warnings import stripe -from stripe import error, oauth_error, http_client, version, util +from stripe import error, oauth_error, http_client, version, util, six from stripe.multipart_data_generator import MultipartDataGenerator +from stripe.six.moves.urllib.parse import urlencode, urlsplit, urlunsplit def _encode_datetime(dttime): @@ -22,13 +23,13 @@ def _encode_datetime(dttime): def _encode_nested_dict(key, data, fmt='%s[%s]'): d = {} - for subkey, subvalue in data.iteritems(): + for subkey, subvalue in six.iteritems(data): d[fmt % (key, subkey)] = subvalue return d def _api_encode(data): - for key, value in data.iteritems(): + for key, value in six.iteritems(data): key = util.utf8(key) if value is None: continue @@ -53,12 +54,12 @@ def _api_encode(data): def _build_api_url(url, query): - scheme, netloc, path, base_query, fragment = urlparse.urlsplit(url) + scheme, netloc, path, base_query, fragment = urlsplit(url) if base_query: query = '%s&%s' % (base_query, query) - return urlparse.urlunsplit((scheme, netloc, path, query, fragment)) + return urlunsplit((scheme, netloc, path, query, fragment)) class APIRequestor(object): @@ -124,7 +125,7 @@ def encode(cls, d): 'If you need public access to this function, please email us ' 'at support@stripe.com.', DeprecationWarning) - return urllib.urlencode(list(_api_encode(d))) + return urlencode(list(_api_encode(d))) @classmethod def build_url(cls, url, params): @@ -165,7 +166,7 @@ def handle_error_response(self, rbody, rcode, resp, rheaders): # OAuth errors are a JSON object where `error` is a string. In # contrast, in API errors, `error` is a hash with sub-keys. We use # this property to distinguish between OAuth and API errors. - if isinstance(error_data, basestring): + if isinstance(error_data, six.string_types): err = self.specific_oauth_error( rbody, rcode, resp, rheaders, error_data) @@ -300,7 +301,7 @@ def request_raw(self, method, url, params=None, supplied_headers=None): abs_url = '%s%s' % (self.api_base, url) - encoded_params = urllib.urlencode(list(_api_encode(params or {}))) + encoded_params = urlencode(list(_api_encode(params or {}))) if method == 'get' or method == 'delete': if params: @@ -326,7 +327,7 @@ def request_raw(self, method, url, params=None, supplied_headers=None): headers = self.request_headers(my_api_key, method) if supplied_headers is not None: - for key, value in supplied_headers.items(): + for key, value in six.iteritems(supplied_headers): headers[key] = value util.log_info('Request to Stripe api', method=method, path=abs_url) diff --git a/stripe/api_resources/__init__.py b/stripe/api_resources/__init__.py index ed8d5d271..556121a76 100644 --- a/stripe/api_resources/__init__.py +++ b/stripe/api_resources/__init__.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + # flake8: noqa from stripe.api_resources.list_object import ListObject diff --git a/stripe/api_resources/abstract/__init__.py b/stripe/api_resources/abstract/__init__.py index 72d4324bc..60caf8950 100644 --- a/stripe/api_resources/abstract/__init__.py +++ b/stripe/api_resources/abstract/__init__.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + # flake8: noqa from stripe.api_resources.abstract.api_resource import APIResource diff --git a/stripe/api_resources/abstract/api_resource.py b/stripe/api_resources/abstract/api_resource.py index 0bf71ba66..04d49fa14 100644 --- a/stripe/api_resources/abstract/api_resource.py +++ b/stripe/api_resources/abstract/api_resource.py @@ -1,7 +1,8 @@ -import urllib +from __future__ import absolute_import, division, print_function -from stripe import error, util +from stripe import error, util, six from stripe.stripe_object import StripeObject +from stripe.six.moves.urllib.parse import quote_plus class APIResource(StripeObject): @@ -22,7 +23,7 @@ def class_name(cls): raise NotImplementedError( 'APIResource is an abstract class. You should perform ' 'actions on its subclasses (e.g. Charge, Customer)') - return str(urllib.quote_plus(cls.__name__.lower())) + return str(quote_plus(cls.__name__.lower())) @classmethod def class_url(cls): @@ -32,7 +33,7 @@ def class_url(cls): def instance_url(self): id = self.get('id') - if not isinstance(id, basestring): + if not isinstance(id, six.string_types): raise error.InvalidRequestError( 'Could not determine which URL to request: %s instance ' 'has invalid ID: %r, %s. ID should be of type `str` (or' @@ -40,5 +41,5 @@ def instance_url(self): id = util.utf8(id) base = self.class_url() - extn = urllib.quote_plus(id) + extn = quote_plus(id) return "%s/%s" % (base, extn) diff --git a/stripe/api_resources/abstract/createable_api_resource.py b/stripe/api_resources/abstract/createable_api_resource.py index 666e4b3da..d0179beee 100644 --- a/stripe/api_resources/abstract/createable_api_resource.py +++ b/stripe/api_resources/abstract/createable_api_resource.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + from stripe.api_resources.abstract.api_resource import APIResource from stripe import api_requestor, util diff --git a/stripe/api_resources/abstract/deletable_api_resource.py b/stripe/api_resources/abstract/deletable_api_resource.py index 851038795..38d077b48 100644 --- a/stripe/api_resources/abstract/deletable_api_resource.py +++ b/stripe/api_resources/abstract/deletable_api_resource.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + from stripe.api_resources.abstract.api_resource import APIResource diff --git a/stripe/api_resources/abstract/listable_api_resource.py b/stripe/api_resources/abstract/listable_api_resource.py index 895975d91..0189520fa 100644 --- a/stripe/api_resources/abstract/listable_api_resource.py +++ b/stripe/api_resources/abstract/listable_api_resource.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import warnings from stripe import api_requestor, util diff --git a/stripe/api_resources/abstract/nested_resource_class_methods.py b/stripe/api_resources/abstract/nested_resource_class_methods.py index 8048143bc..1d1b89e32 100644 --- a/stripe/api_resources/abstract/nested_resource_class_methods.py +++ b/stripe/api_resources/abstract/nested_resource_class_methods.py @@ -1,6 +1,7 @@ -import urllib +from __future__ import absolute_import, division, print_function from stripe import api_requestor, util +from stripe.six.moves.urllib.parse import quote_plus def nested_resource_class_methods(resource, path=None, operations=None): @@ -11,10 +12,10 @@ def nested_resource_class_methods(resource, path=None, operations=None): def wrapper(cls): def nested_resource_url(cls, id, nested_id=None): - url = "%s/%s/%s" % (cls.class_url(), urllib.quote_plus(id), - urllib.quote_plus(path)) + url = "%s/%s/%s" % (cls.class_url(), quote_plus(id), + quote_plus(path)) if nested_id is not None: - url += "/%s" % urllib.quote_plus(nested_id) + url += "/%s" % quote_plus(nested_id) return url resource_url_method = "%ss_url" % resource setattr(cls, resource_url_method, classmethod(nested_resource_url)) diff --git a/stripe/api_resources/abstract/singleton_api_resource.py b/stripe/api_resources/abstract/singleton_api_resource.py index 1658cc3cb..c02cf5455 100644 --- a/stripe/api_resources/abstract/singleton_api_resource.py +++ b/stripe/api_resources/abstract/singleton_api_resource.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + from stripe.api_resources.abstract.api_resource import APIResource diff --git a/stripe/api_resources/abstract/updateable_api_resource.py b/stripe/api_resources/abstract/updateable_api_resource.py index 159b0a672..ccd222ba1 100644 --- a/stripe/api_resources/abstract/updateable_api_resource.py +++ b/stripe/api_resources/abstract/updateable_api_resource.py @@ -1,7 +1,8 @@ -import urllib +from __future__ import absolute_import, division, print_function from stripe import api_requestor, util from stripe.api_resources.abstract.api_resource import APIResource +from stripe.six.moves.urllib.parse import quote_plus class UpdateableAPIResource(APIResource): @@ -19,7 +20,7 @@ def _modify(cls, url, api_key=None, idempotency_key=None, @classmethod def modify(cls, sid, **params): - url = "%s/%s" % (cls.class_url(), urllib.quote_plus(util.utf8(sid))) + url = "%s/%s" % (cls.class_url(), quote_plus(util.utf8(sid))) return cls._modify(url, **params) def save(self, idempotency_key=None): diff --git a/stripe/api_resources/abstract/verify_mixin.py b/stripe/api_resources/abstract/verify_mixin.py index 35687d4d8..29936d7ae 100644 --- a/stripe/api_resources/abstract/verify_mixin.py +++ b/stripe/api_resources/abstract/verify_mixin.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + from stripe import util diff --git a/stripe/api_resources/account.py b/stripe/api_resources/account.py index a5bdd1e94..e256ede7a 100644 --- a/stripe/api_resources/account.py +++ b/stripe/api_resources/account.py @@ -1,4 +1,4 @@ -import urllib +from __future__ import absolute_import, division, print_function from stripe import oauth, util from stripe.api_resources.abstract import CreateableAPIResource @@ -7,6 +7,8 @@ from stripe.api_resources.abstract import ListableAPIResource from stripe.api_resources.abstract import nested_resource_class_methods +from stripe.six.moves.urllib.parse import quote_plus + @nested_resource_class_methods( 'external_account', @@ -33,7 +35,7 @@ def _build_instance_url(cls, sid): return "/v1/account" sid = util.utf8(sid) base = cls.class_url() - extn = urllib.quote_plus(sid) + extn = quote_plus(sid) return "%s/%s" % (base, extn) def instance_url(self): diff --git a/stripe/api_resources/alipay_account.py b/stripe/api_resources/alipay_account.py index 6b2624258..08728d4bc 100644 --- a/stripe/api_resources/alipay_account.py +++ b/stripe/api_resources/alipay_account.py @@ -1,10 +1,12 @@ -import urllib +from __future__ import absolute_import, division, print_function from stripe import util from stripe.api_resources.customer import Customer from stripe.api_resources.abstract import DeletableAPIResource from stripe.api_resources.abstract import UpdateableAPIResource +from stripe.six.moves.urllib.parse import quote_plus + class AlipayAccount(UpdateableAPIResource, DeletableAPIResource): OBJECT_NAME = 'alipay_account' @@ -12,11 +14,11 @@ class AlipayAccount(UpdateableAPIResource, DeletableAPIResource): @classmethod def _build_instance_url(cls, customer, sid): token = util.utf8(sid) - extn = urllib.quote_plus(token) + extn = quote_plus(token) customer = util.utf8(customer) base = Customer.class_url() - owner_extn = urllib.quote_plus(customer) + owner_extn = quote_plus(customer) return "%s/%s/sources/%s" % (base, owner_extn, extn) diff --git a/stripe/api_resources/apple_pay_domain.py b/stripe/api_resources/apple_pay_domain.py index 71df719bc..38bb1e5dd 100644 --- a/stripe/api_resources/apple_pay_domain.py +++ b/stripe/api_resources/apple_pay_domain.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + from stripe.api_resources.abstract import CreateableAPIResource from stripe.api_resources.abstract import DeletableAPIResource from stripe.api_resources.abstract import ListableAPIResource diff --git a/stripe/api_resources/application_fee.py b/stripe/api_resources/application_fee.py index a96492d4a..8b7923e24 100644 --- a/stripe/api_resources/application_fee.py +++ b/stripe/api_resources/application_fee.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + from stripe import util from stripe.api_resources.abstract import ListableAPIResource from stripe.api_resources.abstract import nested_resource_class_methods diff --git a/stripe/api_resources/application_fee_refund.py b/stripe/api_resources/application_fee_refund.py index ef8748be4..c0721ebe9 100644 --- a/stripe/api_resources/application_fee_refund.py +++ b/stripe/api_resources/application_fee_refund.py @@ -1,9 +1,11 @@ -import urllib +from __future__ import absolute_import, division, print_function from stripe import util from stripe.api_resources import ApplicationFee from stripe.api_resources.abstract import UpdateableAPIResource +from stripe.six.moves.urllib.parse import quote_plus + class ApplicationFeeRefund(UpdateableAPIResource): OBJECT_NAME = 'fee_refund' @@ -13,8 +15,8 @@ def _build_instance_url(cls, fee, sid): fee = util.utf8(fee) sid = util.utf8(sid) base = ApplicationFee.class_url() - cust_extn = urllib.quote_plus(fee) - extn = urllib.quote_plus(sid) + cust_extn = quote_plus(fee) + extn = quote_plus(sid) return "%s/%s/refunds/%s" % (base, cust_extn, extn) @classmethod diff --git a/stripe/api_resources/balance.py b/stripe/api_resources/balance.py index cb887e7be..45bb8d6f1 100644 --- a/stripe/api_resources/balance.py +++ b/stripe/api_resources/balance.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + from stripe.api_resources.abstract import SingletonAPIResource diff --git a/stripe/api_resources/balance_transaction.py b/stripe/api_resources/balance_transaction.py index 54de3dfd1..6af698570 100644 --- a/stripe/api_resources/balance_transaction.py +++ b/stripe/api_resources/balance_transaction.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + from stripe.api_resources.abstract import ListableAPIResource diff --git a/stripe/api_resources/bank_account.py b/stripe/api_resources/bank_account.py index 0cc435b14..ea0997b10 100644 --- a/stripe/api_resources/bank_account.py +++ b/stripe/api_resources/bank_account.py @@ -1,4 +1,4 @@ -import urllib +from __future__ import absolute_import, division, print_function from stripe import error, util from stripe.api_resources.account import Account @@ -6,6 +6,7 @@ from stripe.api_resources.abstract import UpdateableAPIResource from stripe.api_resources.abstract import DeletableAPIResource from stripe.api_resources.abstract import VerifyMixin +from stripe.six.moves.urllib.parse import quote_plus class BankAccount(UpdateableAPIResource, DeletableAPIResource, VerifyMixin): @@ -13,19 +14,19 @@ class BankAccount(UpdateableAPIResource, DeletableAPIResource, VerifyMixin): def instance_url(self): token = util.utf8(self.id) - extn = urllib.quote_plus(token) + extn = quote_plus(token) if hasattr(self, 'customer'): customer = util.utf8(self.customer) base = Customer.class_url() - owner_extn = urllib.quote_plus(customer) + owner_extn = quote_plus(customer) class_base = "sources" elif hasattr(self, 'account'): account = util.utf8(self.account) base = Account.class_url() - owner_extn = urllib.quote_plus(account) + owner_extn = quote_plus(account) class_base = "external_accounts" else: diff --git a/stripe/api_resources/bitcoin_receiver.py b/stripe/api_resources/bitcoin_receiver.py index 78de6424e..c51326782 100644 --- a/stripe/api_resources/bitcoin_receiver.py +++ b/stripe/api_resources/bitcoin_receiver.py @@ -1,4 +1,4 @@ -import urllib +from __future__ import absolute_import, division, print_function from stripe import util from stripe.api_resources.customer import Customer @@ -6,6 +6,7 @@ from stripe.api_resources.abstract import DeletableAPIResource from stripe.api_resources.abstract import UpdateableAPIResource from stripe.api_resources.abstract import ListableAPIResource +from stripe.six.moves.urllib.parse import quote_plus class BitcoinReceiver(CreateableAPIResource, UpdateableAPIResource, @@ -14,12 +15,12 @@ class BitcoinReceiver(CreateableAPIResource, UpdateableAPIResource, def instance_url(self): token = util.utf8(self.id) - extn = urllib.quote_plus(token) + extn = quote_plus(token) if hasattr(self, 'customer'): customer = util.utf8(self.customer) base = Customer.class_url() - cust_extn = urllib.quote_plus(customer) + cust_extn = quote_plus(customer) return "%s/%s/sources/%s" % (base, cust_extn, extn) else: base = BitcoinReceiver.class_url() diff --git a/stripe/api_resources/bitcoin_transaction.py b/stripe/api_resources/bitcoin_transaction.py index 37367e3a2..31353f609 100644 --- a/stripe/api_resources/bitcoin_transaction.py +++ b/stripe/api_resources/bitcoin_transaction.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + from stripe.stripe_object import StripeObject diff --git a/stripe/api_resources/card.py b/stripe/api_resources/card.py index 76e86297e..e4c9346f3 100644 --- a/stripe/api_resources/card.py +++ b/stripe/api_resources/card.py @@ -1,4 +1,4 @@ -import urllib +from __future__ import absolute_import, division, print_function from stripe import error, util from stripe.api_resources.account import Account @@ -6,6 +6,7 @@ from stripe.api_resources.recipient import Recipient from stripe.api_resources.abstract import UpdateableAPIResource from stripe.api_resources.abstract import DeletableAPIResource +from stripe.six.moves.urllib.parse import quote_plus class Card(UpdateableAPIResource, DeletableAPIResource): @@ -13,26 +14,26 @@ class Card(UpdateableAPIResource, DeletableAPIResource): def instance_url(self): token = util.utf8(self.id) - extn = urllib.quote_plus(token) + extn = quote_plus(token) if hasattr(self, 'customer'): customer = util.utf8(self.customer) base = Customer.class_url() - owner_extn = urllib.quote_plus(customer) + owner_extn = quote_plus(customer) class_base = "sources" elif hasattr(self, 'recipient'): recipient = util.utf8(self.recipient) base = Recipient.class_url() - owner_extn = urllib.quote_plus(recipient) + owner_extn = quote_plus(recipient) class_base = "cards" elif hasattr(self, 'account'): account = util.utf8(self.account) base = Account.class_url() - owner_extn = urllib.quote_plus(account) + owner_extn = quote_plus(account) class_base = "external_accounts" else: diff --git a/stripe/api_resources/charge.py b/stripe/api_resources/charge.py index 19eb1c1be..8e1848464 100644 --- a/stripe/api_resources/charge.py +++ b/stripe/api_resources/charge.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + from stripe import api_requestor, util from stripe.api_resources.abstract import CreateableAPIResource from stripe.api_resources.abstract import UpdateableAPIResource diff --git a/stripe/api_resources/country_spec.py b/stripe/api_resources/country_spec.py index 9ab721ef4..ddc68f722 100644 --- a/stripe/api_resources/country_spec.py +++ b/stripe/api_resources/country_spec.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + from stripe.api_resources import abstract diff --git a/stripe/api_resources/coupon.py b/stripe/api_resources/coupon.py index c4bc9baf5..76af02c0f 100644 --- a/stripe/api_resources/coupon.py +++ b/stripe/api_resources/coupon.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + from stripe.api_resources.abstract import CreateableAPIResource from stripe.api_resources.abstract import DeletableAPIResource from stripe.api_resources.abstract import UpdateableAPIResource diff --git a/stripe/api_resources/customer.py b/stripe/api_resources/customer.py index 19b912302..449021614 100644 --- a/stripe/api_resources/customer.py +++ b/stripe/api_resources/customer.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import warnings from stripe import api_requestor, util diff --git a/stripe/api_resources/dispute.py b/stripe/api_resources/dispute.py index 7f28942f0..d6c7ccae1 100644 --- a/stripe/api_resources/dispute.py +++ b/stripe/api_resources/dispute.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + from stripe import util from stripe.api_resources.abstract import CreateableAPIResource from stripe.api_resources.abstract import UpdateableAPIResource diff --git a/stripe/api_resources/ephemeral_key.py b/stripe/api_resources/ephemeral_key.py index 31845635d..ce7d0c0c6 100644 --- a/stripe/api_resources/ephemeral_key.py +++ b/stripe/api_resources/ephemeral_key.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import warnings from stripe import api_requestor, util diff --git a/stripe/api_resources/event.py b/stripe/api_resources/event.py index 5ba3f66a2..dc82f8445 100644 --- a/stripe/api_resources/event.py +++ b/stripe/api_resources/event.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + from stripe.api_resources import abstract diff --git a/stripe/api_resources/exchange_rate.py b/stripe/api_resources/exchange_rate.py index c0703f997..56935c25c 100644 --- a/stripe/api_resources/exchange_rate.py +++ b/stripe/api_resources/exchange_rate.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + from stripe.api_resources.abstract import ListableAPIResource diff --git a/stripe/api_resources/file_upload.py b/stripe/api_resources/file_upload.py index 8b4b1b0f8..22fa0e780 100644 --- a/stripe/api_resources/file_upload.py +++ b/stripe/api_resources/file_upload.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe import api_requestor, util from stripe.api_resources.abstract import ListableAPIResource diff --git a/stripe/api_resources/invoice.py b/stripe/api_resources/invoice.py index 9131cab86..f7acd0f2e 100644 --- a/stripe/api_resources/invoice.py +++ b/stripe/api_resources/invoice.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + from stripe import api_requestor, util from stripe.api_resources.abstract import CreateableAPIResource from stripe.api_resources.abstract import UpdateableAPIResource diff --git a/stripe/api_resources/invoice_item.py b/stripe/api_resources/invoice_item.py index a3e5ed820..3ed5defae 100644 --- a/stripe/api_resources/invoice_item.py +++ b/stripe/api_resources/invoice_item.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + from stripe.api_resources.abstract import CreateableAPIResource from stripe.api_resources.abstract import DeletableAPIResource from stripe.api_resources.abstract import UpdateableAPIResource diff --git a/stripe/api_resources/list_object.py b/stripe/api_resources/list_object.py index 1672ab3cd..a956238bb 100644 --- a/stripe/api_resources/list_object.py +++ b/stripe/api_resources/list_object.py @@ -1,9 +1,12 @@ -import urllib +from __future__ import absolute_import, division, print_function + import warnings from stripe import util from stripe.stripe_object import StripeObject +from stripe.six.moves.urllib.parse import quote_plus + class ListObject(StripeObject): OBJECT_NAME = 'list' @@ -41,7 +44,7 @@ def create(self, idempotency_key=None, **params): def retrieve(self, id, **params): base = self.get('url') id = util.utf8(id) - extn = urllib.quote_plus(id) + extn = quote_plus(id) url = "%s/%s" % (base, extn) return self.request('get', url, params) diff --git a/stripe/api_resources/login_link.py b/stripe/api_resources/login_link.py index ad709e6d1..3483725dd 100644 --- a/stripe/api_resources/login_link.py +++ b/stripe/api_resources/login_link.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + from stripe.stripe_object import StripeObject diff --git a/stripe/api_resources/order.py b/stripe/api_resources/order.py index 408071b50..5c15a815b 100644 --- a/stripe/api_resources/order.py +++ b/stripe/api_resources/order.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + from stripe import util from stripe.api_resources.abstract import CreateableAPIResource from stripe.api_resources.abstract import UpdateableAPIResource diff --git a/stripe/api_resources/order_return.py b/stripe/api_resources/order_return.py index 7792dbaad..be578e338 100644 --- a/stripe/api_resources/order_return.py +++ b/stripe/api_resources/order_return.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + from stripe.api_resources.abstract import ListableAPIResource diff --git a/stripe/api_resources/payout.py b/stripe/api_resources/payout.py index 3aaabbf6f..8227c4573 100644 --- a/stripe/api_resources/payout.py +++ b/stripe/api_resources/payout.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + from stripe.api_resources.abstract import CreateableAPIResource from stripe.api_resources.abstract import UpdateableAPIResource from stripe.api_resources.abstract import ListableAPIResource diff --git a/stripe/api_resources/plan.py b/stripe/api_resources/plan.py index b3caa1fee..0a1b4a388 100644 --- a/stripe/api_resources/plan.py +++ b/stripe/api_resources/plan.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + from stripe.api_resources.abstract import CreateableAPIResource from stripe.api_resources.abstract import DeletableAPIResource from stripe.api_resources.abstract import UpdateableAPIResource diff --git a/stripe/api_resources/product.py b/stripe/api_resources/product.py index f3ada6050..c988a3cf0 100644 --- a/stripe/api_resources/product.py +++ b/stripe/api_resources/product.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + from stripe.api_resources.abstract import CreateableAPIResource from stripe.api_resources.abstract import DeletableAPIResource from stripe.api_resources.abstract import UpdateableAPIResource diff --git a/stripe/api_resources/recipient.py b/stripe/api_resources/recipient.py index c17480f14..ebd4dba2b 100644 --- a/stripe/api_resources/recipient.py +++ b/stripe/api_resources/recipient.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + from stripe.api_resources.transfer import Transfer from stripe.api_resources.abstract import CreateableAPIResource from stripe.api_resources.abstract import DeletableAPIResource diff --git a/stripe/api_resources/recipient_transfer.py b/stripe/api_resources/recipient_transfer.py index 434891a09..853db18e6 100644 --- a/stripe/api_resources/recipient_transfer.py +++ b/stripe/api_resources/recipient_transfer.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + from stripe.stripe_object import StripeObject diff --git a/stripe/api_resources/refund.py b/stripe/api_resources/refund.py index d1f3d425a..5e29bad40 100644 --- a/stripe/api_resources/refund.py +++ b/stripe/api_resources/refund.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + from stripe.api_resources.abstract import CreateableAPIResource from stripe.api_resources.abstract import UpdateableAPIResource from stripe.api_resources.abstract import ListableAPIResource diff --git a/stripe/api_resources/reversal.py b/stripe/api_resources/reversal.py index 61cbf4d49..74d4e3712 100644 --- a/stripe/api_resources/reversal.py +++ b/stripe/api_resources/reversal.py @@ -1,8 +1,9 @@ -import urllib +from __future__ import absolute_import, division, print_function from stripe import util from stripe.api_resources.transfer import Transfer from stripe.api_resources.abstract import UpdateableAPIResource +from stripe.six.moves.urllib.parse import quote_plus class Reversal(UpdateableAPIResource): @@ -12,8 +13,8 @@ def instance_url(self): token = util.utf8(self.id) transfer = util.utf8(self.transfer) base = Transfer.class_url() - cust_extn = urllib.quote_plus(transfer) - extn = urllib.quote_plus(token) + cust_extn = quote_plus(transfer) + extn = quote_plus(token) return "%s/%s/reversals/%s" % (base, cust_extn, extn) @classmethod diff --git a/stripe/api_resources/sku.py b/stripe/api_resources/sku.py index ddc8f9166..988cc3e52 100644 --- a/stripe/api_resources/sku.py +++ b/stripe/api_resources/sku.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + from stripe.api_resources.abstract import CreateableAPIResource from stripe.api_resources.abstract import DeletableAPIResource from stripe.api_resources.abstract import UpdateableAPIResource diff --git a/stripe/api_resources/source.py b/stripe/api_resources/source.py index 11ac7ba3b..879d13c9f 100644 --- a/stripe/api_resources/source.py +++ b/stripe/api_resources/source.py @@ -1,4 +1,5 @@ -import urllib +from __future__ import absolute_import, division, print_function + import warnings from stripe import util @@ -6,6 +7,7 @@ from stripe.api_resources.abstract import CreateableAPIResource from stripe.api_resources.abstract import UpdateableAPIResource from stripe.api_resources.abstract import VerifyMixin +from stripe.six.moves.urllib.parse import quote_plus class Source(CreateableAPIResource, UpdateableAPIResource, VerifyMixin): @@ -13,10 +15,10 @@ class Source(CreateableAPIResource, UpdateableAPIResource, VerifyMixin): def detach(self, **params): if hasattr(self, 'customer') and self.customer: - extn = urllib.quote_plus(util.utf8(self.id)) + extn = quote_plus(util.utf8(self.id)) customer = util.utf8(self.customer) base = Customer.class_url() - owner_extn = urllib.quote_plus(customer) + owner_extn = quote_plus(customer) url = "%s/%s/sources/%s" % (base, owner_extn, extn) self.refresh_from(self.request('delete', url, params)) diff --git a/stripe/api_resources/source_transaction.py b/stripe/api_resources/source_transaction.py index fc04a6c26..582e9b1d5 100644 --- a/stripe/api_resources/source_transaction.py +++ b/stripe/api_resources/source_transaction.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + from stripe.stripe_object import StripeObject diff --git a/stripe/api_resources/subscription.py b/stripe/api_resources/subscription.py index 05ee52a4a..e0e7a0f1c 100644 --- a/stripe/api_resources/subscription.py +++ b/stripe/api_resources/subscription.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + from stripe import api_requestor, util from stripe.api_resources.abstract import CreateableAPIResource from stripe.api_resources.abstract import DeletableAPIResource diff --git a/stripe/api_resources/subscription_item.py b/stripe/api_resources/subscription_item.py index 99711b99b..fbfc4f574 100644 --- a/stripe/api_resources/subscription_item.py +++ b/stripe/api_resources/subscription_item.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + from stripe.api_resources.abstract import CreateableAPIResource from stripe.api_resources.abstract import DeletableAPIResource from stripe.api_resources.abstract import UpdateableAPIResource diff --git a/stripe/api_resources/three_d_secure.py b/stripe/api_resources/three_d_secure.py index 4735c8392..e7fa283b3 100644 --- a/stripe/api_resources/three_d_secure.py +++ b/stripe/api_resources/three_d_secure.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + from stripe.api_resources.abstract import CreateableAPIResource diff --git a/stripe/api_resources/token.py b/stripe/api_resources/token.py index 88ff0af87..5411d20ef 100644 --- a/stripe/api_resources/token.py +++ b/stripe/api_resources/token.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + from stripe.api_resources.abstract import CreateableAPIResource diff --git a/stripe/api_resources/transfer.py b/stripe/api_resources/transfer.py index f7504c36b..92cdab749 100644 --- a/stripe/api_resources/transfer.py +++ b/stripe/api_resources/transfer.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + from stripe.api_resources.abstract import CreateableAPIResource from stripe.api_resources.abstract import UpdateableAPIResource from stripe.api_resources.abstract import ListableAPIResource diff --git a/stripe/error.py b/stripe/error.py index 748c51e52..ef64a3803 100644 --- a/stripe/error.py +++ b/stripe/error.py @@ -1,5 +1,6 @@ -# Exceptions -import sys +from __future__ import absolute_import, division, print_function + +from stripe import six class StripeError(Exception): @@ -29,7 +30,7 @@ def __unicode__(self): else: return self._message - if sys.version_info > (3, 0): + if six.PY3: def __str__(self): return self.__unicode__() else: diff --git a/stripe/http_client.py b/stripe/http_client.py index 3b6f4d0e6..859c1a8b0 100644 --- a/stripe/http_client.py +++ b/stripe/http_client.py @@ -1,17 +1,19 @@ +from __future__ import absolute_import, division, print_function + import os import sys import textwrap import warnings import email -from stripe import error, util +from stripe import error, util, six # - Requests is the preferred HTTP library # - Google App Engine has urlfetch # - Use Pycurl if it's there (at least it verifies SSL certs) # - Fall back to urllib2 with a warning if needed try: - import urllib2 + from stripe.six.moves import urllib except ImportError: # Try to load in urllib2, but don't sweat it if it's not available. pass @@ -52,7 +54,7 @@ urlfetch = None # proxy support for the pycurl client -from urlparse import urlparse +from stripe.six.moves.urllib.parse import urlparse def new_default_http_client(*args, **kwargs): @@ -240,7 +242,7 @@ def parse_headers(self, data): return {} raw_headers = data.split('\r\n', 1)[1] headers = email.message_from_string(raw_headers) - return dict((k.lower(), v) for k, v in dict(headers).iteritems()) + return dict((k.lower(), v) for k, v in six.iteritems(dict(headers))) def request(self, method, url, headers, post_data=None): b = util.io.BytesIO() @@ -281,8 +283,10 @@ def request(self, method, url, headers, post_data=None): self._curl.setopt(pycurl.NOSIGNAL, 1) self._curl.setopt(pycurl.CONNECTTIMEOUT, 30) self._curl.setopt(pycurl.TIMEOUT, 80) - self._curl.setopt(pycurl.HTTPHEADER, ['%s: %s' % (k, v) - for k, v in headers.iteritems()]) + self._curl.setopt( + pycurl.HTTPHEADER, + ['%s: %s' % (k, v) for k, v in six.iteritems(dict(headers))] + ) if self._verify_ssl_certs: self._curl.setopt(pycurl.CAINFO, os.path.join( os.path.dirname(__file__), 'data/ca-certificates.crt')) @@ -335,10 +339,7 @@ def _get_proxy(self, url): class Urllib2Client(HTTPClient): - if sys.version_info >= (3, 0): - name = 'urllib.request' - else: - name = 'urllib2' + name = 'urllib.request' def __init__(self, verify_ssl_certs=True, proxy=None): super(Urllib2Client, self).__init__( @@ -346,14 +347,14 @@ def __init__(self, verify_ssl_certs=True, proxy=None): # prepare and cache proxy tied opener here self._opener = None if self._proxy: - proxy = urllib2.ProxyHandler(self._proxy) - self._opener = urllib2.build_opener(proxy) + proxy = urllib.request.ProxyHandler(self._proxy) + self._opener = urllib.request.build_opener(proxy) def request(self, method, url, headers, post_data=None): - if sys.version_info >= (3, 0) and isinstance(post_data, basestring): + if six.PY3 and isinstance(post_data, six.string_types): post_data = post_data.encode('utf-8') - req = urllib2.Request(url, post_data, headers) + req = urllib.request.Request(url, post_data, headers) if method not in ('get', 'post'): req.get_method = lambda: method.upper() @@ -363,17 +364,17 @@ def request(self, method, url, headers, post_data=None): # otherwise, fall to the default urllib opener. response = self._opener.open(req) \ if self._opener \ - else urllib2.urlopen(req) + else urllib.request.urlopen(req) rbody = response.read() rcode = response.code headers = dict(response.info()) - except urllib2.HTTPError as e: + except urllib.error.HTTPError as e: rcode = e.code rbody = e.read() headers = dict(e.info()) - except (urllib2.URLError, ValueError) as e: + except (urllib.error.URLError, ValueError) as e: self._handle_request_error(e) - lh = dict((k.lower(), v) for k, v in dict(headers).iteritems()) + lh = dict((k.lower(), v) for k, v in six.iteritems(dict(headers))) return rbody, rcode, lh def _handle_request_error(self, e): diff --git a/stripe/importer.py b/stripe/importer.py index 1f7d33875..79ebcc62a 100644 --- a/stripe/importer.py +++ b/stripe/importer.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import warnings warnings.warn("The importers module is deprecated and will be removed in " diff --git a/stripe/multipart_data_generator.py b/stripe/multipart_data_generator.py index d07d5d4ab..6c3e1fe2d 100644 --- a/stripe/multipart_data_generator.py +++ b/stripe/multipart_data_generator.py @@ -1,7 +1,10 @@ +from __future__ import absolute_import, division, print_function + import random -import sys import io +from stripe import six + class MultipartDataGenerator(object): def __init__(self, chunk_size=1028): @@ -11,7 +14,7 @@ def __init__(self, chunk_size=1028): self.chunk_size = chunk_size def add_params(self, params): - for key, value in params.iteritems(): + for key, value in six.iteritems(params): if value is None: continue @@ -50,7 +53,7 @@ def get_post_data(self): return self.data.getvalue() def _write(self, value): - if sys.version_info < (3,): + if six.PY2: binary_type = str text_type = unicode else: diff --git a/stripe/oauth.py b/stripe/oauth.py index 0e63fd7d6..e9324debe 100644 --- a/stripe/oauth.py +++ b/stripe/oauth.py @@ -1,6 +1,7 @@ -import urllib +from __future__ import absolute_import, division, print_function from stripe import api_requestor, connect_api_base, error +from stripe.six.moves.urllib.parse import urlencode class OAuth(object): @@ -30,7 +31,7 @@ def authorize_url(**params): OAuth._set_client_id(params) if 'response_type' not in params: params['response_type'] = 'code' - query = urllib.urlencode(list(api_requestor._api_encode(params))) + query = urlencode(list(api_requestor._api_encode(params))) url = connect_api_base + path + '?' + query return url diff --git a/stripe/oauth_error.py b/stripe/oauth_error.py index 5c44ad7c6..1c75ea816 100644 --- a/stripe/oauth_error.py +++ b/stripe/oauth_error.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + from stripe.error import StripeError diff --git a/stripe/resource.py b/stripe/resource.py index 66747585e..3f19537c1 100644 --- a/stripe/resource.py +++ b/stripe/resource.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + # # This module doesn't serve much purpose anymore. It's only here to maintain # backwards compatibility. diff --git a/stripe/six.py b/stripe/six.py new file mode 100644 index 000000000..6bf4fd381 --- /dev/null +++ b/stripe/six.py @@ -0,0 +1,891 @@ +# Copyright (c) 2010-2017 Benjamin Peterson +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +"""Utilities for writing code that runs on Python 2 and 3""" + +from __future__ import absolute_import + +import functools +import itertools +import operator +import sys +import types + +__author__ = "Benjamin Peterson " +__version__ = "1.11.0" + + +# Useful for very coarse version differentiation. +PY2 = sys.version_info[0] == 2 +PY3 = sys.version_info[0] == 3 +PY34 = sys.version_info[0:2] >= (3, 4) + +if PY3: + string_types = str, + integer_types = int, + class_types = type, + text_type = str + binary_type = bytes + + MAXSIZE = sys.maxsize +else: + string_types = basestring, + integer_types = (int, long) + class_types = (type, types.ClassType) + text_type = unicode + binary_type = str + + if sys.platform.startswith("java"): + # Jython always uses 32 bits. + MAXSIZE = int((1 << 31) - 1) + else: + # It's possible to have sizeof(long) != sizeof(Py_ssize_t). + class X(object): + + def __len__(self): + return 1 << 31 + try: + len(X()) + except OverflowError: + # 32-bit + MAXSIZE = int((1 << 31) - 1) + else: + # 64-bit + MAXSIZE = int((1 << 63) - 1) + del X + + +def _add_doc(func, doc): + """Add documentation to a function.""" + func.__doc__ = doc + + +def _import_module(name): + """Import module, returning the module after the last dot.""" + __import__(name) + return sys.modules[name] + + +class _LazyDescr(object): + + def __init__(self, name): + self.name = name + + def __get__(self, obj, tp): + result = self._resolve() + setattr(obj, self.name, result) # Invokes __set__. + try: + # This is a bit ugly, but it avoids running this again by + # removing this descriptor. + delattr(obj.__class__, self.name) + except AttributeError: + pass + return result + + +class MovedModule(_LazyDescr): + + def __init__(self, name, old, new=None): + super(MovedModule, self).__init__(name) + if PY3: + if new is None: + new = name + self.mod = new + else: + self.mod = old + + def _resolve(self): + return _import_module(self.mod) + + def __getattr__(self, attr): + _module = self._resolve() + value = getattr(_module, attr) + setattr(self, attr, value) + return value + + +class _LazyModule(types.ModuleType): + + def __init__(self, name): + super(_LazyModule, self).__init__(name) + self.__doc__ = self.__class__.__doc__ + + def __dir__(self): + attrs = ["__doc__", "__name__"] + attrs += [attr.name for attr in self._moved_attributes] + return attrs + + # Subclasses should override this + _moved_attributes = [] + + +class MovedAttribute(_LazyDescr): + + def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None): + super(MovedAttribute, self).__init__(name) + if PY3: + if new_mod is None: + new_mod = name + self.mod = new_mod + if new_attr is None: + if old_attr is None: + new_attr = name + else: + new_attr = old_attr + self.attr = new_attr + else: + self.mod = old_mod + if old_attr is None: + old_attr = name + self.attr = old_attr + + def _resolve(self): + module = _import_module(self.mod) + return getattr(module, self.attr) + + +class _SixMetaPathImporter(object): + + """ + A meta path importer to import six.moves and its submodules. + + This class implements a PEP302 finder and loader. It should be compatible + with Python 2.5 and all existing versions of Python3 + """ + + def __init__(self, six_module_name): + self.name = six_module_name + self.known_modules = {} + + def _add_module(self, mod, *fullnames): + for fullname in fullnames: + self.known_modules[self.name + "." + fullname] = mod + + def _get_module(self, fullname): + return self.known_modules[self.name + "." + fullname] + + def find_module(self, fullname, path=None): + if fullname in self.known_modules: + return self + return None + + def __get_module(self, fullname): + try: + return self.known_modules[fullname] + except KeyError: + raise ImportError("This loader does not know module " + fullname) + + def load_module(self, fullname): + try: + # in case of a reload + return sys.modules[fullname] + except KeyError: + pass + mod = self.__get_module(fullname) + if isinstance(mod, MovedModule): + mod = mod._resolve() + else: + mod.__loader__ = self + sys.modules[fullname] = mod + return mod + + def is_package(self, fullname): + """ + Return true, if the named module is a package. + + We need this method to get correct spec objects with + Python 3.4 (see PEP451) + """ + return hasattr(self.__get_module(fullname), "__path__") + + def get_code(self, fullname): + """Return None + + Required, if is_package is implemented""" + self.__get_module(fullname) # eventually raises ImportError + return None + get_source = get_code # same as get_code + +_importer = _SixMetaPathImporter(__name__) + + +class _MovedItems(_LazyModule): + + """Lazy loading of moved objects""" + __path__ = [] # mark as package + + +_moved_attributes = [ + MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"), + MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"), + MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"), + MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"), + MovedAttribute("intern", "__builtin__", "sys"), + MovedAttribute("map", "itertools", "builtins", "imap", "map"), + MovedAttribute("getcwd", "os", "os", "getcwdu", "getcwd"), + MovedAttribute("getcwdb", "os", "os", "getcwd", "getcwdb"), + MovedAttribute("getoutput", "commands", "subprocess"), + MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"), + MovedAttribute("reload_module", "__builtin__", "importlib" if PY34 else "imp", "reload"), + MovedAttribute("reduce", "__builtin__", "functools"), + MovedAttribute("shlex_quote", "pipes", "shlex", "quote"), + MovedAttribute("StringIO", "StringIO", "io"), + MovedAttribute("UserDict", "UserDict", "collections"), + MovedAttribute("UserList", "UserList", "collections"), + MovedAttribute("UserString", "UserString", "collections"), + MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), + MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), + MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"), + MovedModule("builtins", "__builtin__"), + MovedModule("configparser", "ConfigParser"), + MovedModule("copyreg", "copy_reg"), + MovedModule("dbm_gnu", "gdbm", "dbm.gnu"), + MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"), + MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), + MovedModule("http_cookies", "Cookie", "http.cookies"), + MovedModule("html_entities", "htmlentitydefs", "html.entities"), + MovedModule("html_parser", "HTMLParser", "html.parser"), + MovedModule("http_client", "httplib", "http.client"), + MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"), + MovedModule("email_mime_image", "email.MIMEImage", "email.mime.image"), + MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"), + MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"), + MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"), + MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"), + MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"), + MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"), + MovedModule("cPickle", "cPickle", "pickle"), + MovedModule("queue", "Queue"), + MovedModule("reprlib", "repr"), + MovedModule("socketserver", "SocketServer"), + MovedModule("_thread", "thread", "_thread"), + MovedModule("tkinter", "Tkinter"), + MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"), + MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"), + MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"), + MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"), + MovedModule("tkinter_tix", "Tix", "tkinter.tix"), + MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"), + MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"), + MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"), + MovedModule("tkinter_colorchooser", "tkColorChooser", + "tkinter.colorchooser"), + MovedModule("tkinter_commondialog", "tkCommonDialog", + "tkinter.commondialog"), + MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"), + MovedModule("tkinter_font", "tkFont", "tkinter.font"), + MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"), + MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", + "tkinter.simpledialog"), + MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"), + MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"), + MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"), + MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"), + MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"), + MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"), +] +# Add windows specific modules. +if sys.platform == "win32": + _moved_attributes += [ + MovedModule("winreg", "_winreg"), + ] + +for attr in _moved_attributes: + setattr(_MovedItems, attr.name, attr) + if isinstance(attr, MovedModule): + _importer._add_module(attr, "moves." + attr.name) +del attr + +_MovedItems._moved_attributes = _moved_attributes + +moves = _MovedItems(__name__ + ".moves") +_importer._add_module(moves, "moves") + + +class Module_six_moves_urllib_parse(_LazyModule): + + """Lazy loading of moved objects in six.moves.urllib_parse""" + + +_urllib_parse_moved_attributes = [ + MovedAttribute("ParseResult", "urlparse", "urllib.parse"), + MovedAttribute("SplitResult", "urlparse", "urllib.parse"), + MovedAttribute("parse_qs", "urlparse", "urllib.parse"), + MovedAttribute("parse_qsl", "urlparse", "urllib.parse"), + MovedAttribute("urldefrag", "urlparse", "urllib.parse"), + MovedAttribute("urljoin", "urlparse", "urllib.parse"), + MovedAttribute("urlparse", "urlparse", "urllib.parse"), + MovedAttribute("urlsplit", "urlparse", "urllib.parse"), + MovedAttribute("urlunparse", "urlparse", "urllib.parse"), + MovedAttribute("urlunsplit", "urlparse", "urllib.parse"), + MovedAttribute("quote", "urllib", "urllib.parse"), + MovedAttribute("quote_plus", "urllib", "urllib.parse"), + MovedAttribute("unquote", "urllib", "urllib.parse"), + MovedAttribute("unquote_plus", "urllib", "urllib.parse"), + MovedAttribute("unquote_to_bytes", "urllib", "urllib.parse", "unquote", "unquote_to_bytes"), + MovedAttribute("urlencode", "urllib", "urllib.parse"), + MovedAttribute("splitquery", "urllib", "urllib.parse"), + MovedAttribute("splittag", "urllib", "urllib.parse"), + MovedAttribute("splituser", "urllib", "urllib.parse"), + MovedAttribute("splitvalue", "urllib", "urllib.parse"), + MovedAttribute("uses_fragment", "urlparse", "urllib.parse"), + MovedAttribute("uses_netloc", "urlparse", "urllib.parse"), + MovedAttribute("uses_params", "urlparse", "urllib.parse"), + MovedAttribute("uses_query", "urlparse", "urllib.parse"), + MovedAttribute("uses_relative", "urlparse", "urllib.parse"), +] +for attr in _urllib_parse_moved_attributes: + setattr(Module_six_moves_urllib_parse, attr.name, attr) +del attr + +Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes + +_importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"), + "moves.urllib_parse", "moves.urllib.parse") + + +class Module_six_moves_urllib_error(_LazyModule): + + """Lazy loading of moved objects in six.moves.urllib_error""" + + +_urllib_error_moved_attributes = [ + MovedAttribute("URLError", "urllib2", "urllib.error"), + MovedAttribute("HTTPError", "urllib2", "urllib.error"), + MovedAttribute("ContentTooShortError", "urllib", "urllib.error"), +] +for attr in _urllib_error_moved_attributes: + setattr(Module_six_moves_urllib_error, attr.name, attr) +del attr + +Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes + +_importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"), + "moves.urllib_error", "moves.urllib.error") + + +class Module_six_moves_urllib_request(_LazyModule): + + """Lazy loading of moved objects in six.moves.urllib_request""" + + +_urllib_request_moved_attributes = [ + MovedAttribute("urlopen", "urllib2", "urllib.request"), + MovedAttribute("install_opener", "urllib2", "urllib.request"), + MovedAttribute("build_opener", "urllib2", "urllib.request"), + MovedAttribute("pathname2url", "urllib", "urllib.request"), + MovedAttribute("url2pathname", "urllib", "urllib.request"), + MovedAttribute("getproxies", "urllib", "urllib.request"), + MovedAttribute("Request", "urllib2", "urllib.request"), + MovedAttribute("OpenerDirector", "urllib2", "urllib.request"), + MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"), + MovedAttribute("ProxyHandler", "urllib2", "urllib.request"), + MovedAttribute("BaseHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"), + MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"), + MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"), + MovedAttribute("FileHandler", "urllib2", "urllib.request"), + MovedAttribute("FTPHandler", "urllib2", "urllib.request"), + MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"), + MovedAttribute("UnknownHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"), + MovedAttribute("urlretrieve", "urllib", "urllib.request"), + MovedAttribute("urlcleanup", "urllib", "urllib.request"), + MovedAttribute("URLopener", "urllib", "urllib.request"), + MovedAttribute("FancyURLopener", "urllib", "urllib.request"), + MovedAttribute("proxy_bypass", "urllib", "urllib.request"), + MovedAttribute("parse_http_list", "urllib2", "urllib.request"), + MovedAttribute("parse_keqv_list", "urllib2", "urllib.request"), +] +for attr in _urllib_request_moved_attributes: + setattr(Module_six_moves_urllib_request, attr.name, attr) +del attr + +Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes + +_importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"), + "moves.urllib_request", "moves.urllib.request") + + +class Module_six_moves_urllib_response(_LazyModule): + + """Lazy loading of moved objects in six.moves.urllib_response""" + + +_urllib_response_moved_attributes = [ + MovedAttribute("addbase", "urllib", "urllib.response"), + MovedAttribute("addclosehook", "urllib", "urllib.response"), + MovedAttribute("addinfo", "urllib", "urllib.response"), + MovedAttribute("addinfourl", "urllib", "urllib.response"), +] +for attr in _urllib_response_moved_attributes: + setattr(Module_six_moves_urllib_response, attr.name, attr) +del attr + +Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes + +_importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"), + "moves.urllib_response", "moves.urllib.response") + + +class Module_six_moves_urllib_robotparser(_LazyModule): + + """Lazy loading of moved objects in six.moves.urllib_robotparser""" + + +_urllib_robotparser_moved_attributes = [ + MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"), +] +for attr in _urllib_robotparser_moved_attributes: + setattr(Module_six_moves_urllib_robotparser, attr.name, attr) +del attr + +Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes + +_importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"), + "moves.urllib_robotparser", "moves.urllib.robotparser") + + +class Module_six_moves_urllib(types.ModuleType): + + """Create a six.moves.urllib namespace that resembles the Python 3 namespace""" + __path__ = [] # mark as package + parse = _importer._get_module("moves.urllib_parse") + error = _importer._get_module("moves.urllib_error") + request = _importer._get_module("moves.urllib_request") + response = _importer._get_module("moves.urllib_response") + robotparser = _importer._get_module("moves.urllib_robotparser") + + def __dir__(self): + return ['parse', 'error', 'request', 'response', 'robotparser'] + +_importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"), + "moves.urllib") + + +def add_move(move): + """Add an item to six.moves.""" + setattr(_MovedItems, move.name, move) + + +def remove_move(name): + """Remove item from six.moves.""" + try: + delattr(_MovedItems, name) + except AttributeError: + try: + del moves.__dict__[name] + except KeyError: + raise AttributeError("no such move, %r" % (name,)) + + +if PY3: + _meth_func = "__func__" + _meth_self = "__self__" + + _func_closure = "__closure__" + _func_code = "__code__" + _func_defaults = "__defaults__" + _func_globals = "__globals__" +else: + _meth_func = "im_func" + _meth_self = "im_self" + + _func_closure = "func_closure" + _func_code = "func_code" + _func_defaults = "func_defaults" + _func_globals = "func_globals" + + +try: + advance_iterator = next +except NameError: + def advance_iterator(it): + return it.next() +next = advance_iterator + + +try: + callable = callable +except NameError: + def callable(obj): + return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) + + +if PY3: + def get_unbound_function(unbound): + return unbound + + create_bound_method = types.MethodType + + def create_unbound_method(func, cls): + return func + + Iterator = object +else: + def get_unbound_function(unbound): + return unbound.im_func + + def create_bound_method(func, obj): + return types.MethodType(func, obj, obj.__class__) + + def create_unbound_method(func, cls): + return types.MethodType(func, None, cls) + + class Iterator(object): + + def next(self): + return type(self).__next__(self) + + callable = callable +_add_doc(get_unbound_function, + """Get the function out of a possibly unbound function""") + + +get_method_function = operator.attrgetter(_meth_func) +get_method_self = operator.attrgetter(_meth_self) +get_function_closure = operator.attrgetter(_func_closure) +get_function_code = operator.attrgetter(_func_code) +get_function_defaults = operator.attrgetter(_func_defaults) +get_function_globals = operator.attrgetter(_func_globals) + + +if PY3: + def iterkeys(d, **kw): + return iter(d.keys(**kw)) + + def itervalues(d, **kw): + return iter(d.values(**kw)) + + def iteritems(d, **kw): + return iter(d.items(**kw)) + + def iterlists(d, **kw): + return iter(d.lists(**kw)) + + viewkeys = operator.methodcaller("keys") + + viewvalues = operator.methodcaller("values") + + viewitems = operator.methodcaller("items") +else: + def iterkeys(d, **kw): + return d.iterkeys(**kw) + + def itervalues(d, **kw): + return d.itervalues(**kw) + + def iteritems(d, **kw): + return d.iteritems(**kw) + + def iterlists(d, **kw): + return d.iterlists(**kw) + + viewkeys = operator.methodcaller("viewkeys") + + viewvalues = operator.methodcaller("viewvalues") + + viewitems = operator.methodcaller("viewitems") + +_add_doc(iterkeys, "Return an iterator over the keys of a dictionary.") +_add_doc(itervalues, "Return an iterator over the values of a dictionary.") +_add_doc(iteritems, + "Return an iterator over the (key, value) pairs of a dictionary.") +_add_doc(iterlists, + "Return an iterator over the (key, [values]) pairs of a dictionary.") + + +if PY3: + def b(s): + return s.encode("latin-1") + + def u(s): + return s + unichr = chr + import struct + int2byte = struct.Struct(">B").pack + del struct + byte2int = operator.itemgetter(0) + indexbytes = operator.getitem + iterbytes = iter + import io + StringIO = io.StringIO + BytesIO = io.BytesIO + _assertCountEqual = "assertCountEqual" + if sys.version_info[1] <= 1: + _assertRaisesRegex = "assertRaisesRegexp" + _assertRegex = "assertRegexpMatches" + else: + _assertRaisesRegex = "assertRaisesRegex" + _assertRegex = "assertRegex" +else: + def b(s): + return s + # Workaround for standalone backslash + + def u(s): + return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape") + unichr = unichr + int2byte = chr + + def byte2int(bs): + return ord(bs[0]) + + def indexbytes(buf, i): + return ord(buf[i]) + iterbytes = functools.partial(itertools.imap, ord) + import StringIO + StringIO = BytesIO = StringIO.StringIO + _assertCountEqual = "assertItemsEqual" + _assertRaisesRegex = "assertRaisesRegexp" + _assertRegex = "assertRegexpMatches" +_add_doc(b, """Byte literal""") +_add_doc(u, """Text literal""") + + +def assertCountEqual(self, *args, **kwargs): + return getattr(self, _assertCountEqual)(*args, **kwargs) + + +def assertRaisesRegex(self, *args, **kwargs): + return getattr(self, _assertRaisesRegex)(*args, **kwargs) + + +def assertRegex(self, *args, **kwargs): + return getattr(self, _assertRegex)(*args, **kwargs) + + +if PY3: + exec_ = getattr(moves.builtins, "exec") + + def reraise(tp, value, tb=None): + try: + if value is None: + value = tp() + if value.__traceback__ is not tb: + raise value.with_traceback(tb) + raise value + finally: + value = None + tb = None + +else: + def exec_(_code_, _globs_=None, _locs_=None): + """Execute code in a namespace.""" + if _globs_ is None: + frame = sys._getframe(1) + _globs_ = frame.f_globals + if _locs_ is None: + _locs_ = frame.f_locals + del frame + elif _locs_ is None: + _locs_ = _globs_ + exec("""exec _code_ in _globs_, _locs_""") + + exec_("""def reraise(tp, value, tb=None): + try: + raise tp, value, tb + finally: + tb = None +""") + + +if sys.version_info[:2] == (3, 2): + exec_("""def raise_from(value, from_value): + try: + if from_value is None: + raise value + raise value from from_value + finally: + value = None +""") +elif sys.version_info[:2] > (3, 2): + exec_("""def raise_from(value, from_value): + try: + raise value from from_value + finally: + value = None +""") +else: + def raise_from(value, from_value): + raise value + + +print_ = getattr(moves.builtins, "print", None) +if print_ is None: + def print_(*args, **kwargs): + """The new-style print function for Python 2.4 and 2.5.""" + fp = kwargs.pop("file", sys.stdout) + if fp is None: + return + + def write(data): + if not isinstance(data, basestring): + data = str(data) + # If the file has an encoding, encode unicode with it. + if (isinstance(fp, file) and + isinstance(data, unicode) and + fp.encoding is not None): + errors = getattr(fp, "errors", None) + if errors is None: + errors = "strict" + data = data.encode(fp.encoding, errors) + fp.write(data) + want_unicode = False + sep = kwargs.pop("sep", None) + if sep is not None: + if isinstance(sep, unicode): + want_unicode = True + elif not isinstance(sep, str): + raise TypeError("sep must be None or a string") + end = kwargs.pop("end", None) + if end is not None: + if isinstance(end, unicode): + want_unicode = True + elif not isinstance(end, str): + raise TypeError("end must be None or a string") + if kwargs: + raise TypeError("invalid keyword arguments to print()") + if not want_unicode: + for arg in args: + if isinstance(arg, unicode): + want_unicode = True + break + if want_unicode: + newline = unicode("\n") + space = unicode(" ") + else: + newline = "\n" + space = " " + if sep is None: + sep = space + if end is None: + end = newline + for i, arg in enumerate(args): + if i: + write(sep) + write(arg) + write(end) +if sys.version_info[:2] < (3, 3): + _print = print_ + + def print_(*args, **kwargs): + fp = kwargs.get("file", sys.stdout) + flush = kwargs.pop("flush", False) + _print(*args, **kwargs) + if flush and fp is not None: + fp.flush() + +_add_doc(reraise, """Reraise an exception.""") + +if sys.version_info[0:2] < (3, 4): + def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, + updated=functools.WRAPPER_UPDATES): + def wrapper(f): + f = functools.wraps(wrapped, assigned, updated)(f) + f.__wrapped__ = wrapped + return f + return wrapper +else: + wraps = functools.wraps + + +def with_metaclass(meta, *bases): + """Create a base class with a metaclass.""" + # This requires a bit of explanation: the basic idea is to make a dummy + # metaclass for one level of class instantiation that replaces itself with + # the actual metaclass. + class metaclass(type): + + def __new__(cls, name, this_bases, d): + return meta(name, bases, d) + + @classmethod + def __prepare__(cls, name, this_bases): + return meta.__prepare__(name, bases) + return type.__new__(metaclass, 'temporary_class', (), {}) + + +def add_metaclass(metaclass): + """Class decorator for creating a class with a metaclass.""" + def wrapper(cls): + orig_vars = cls.__dict__.copy() + slots = orig_vars.get('__slots__') + if slots is not None: + if isinstance(slots, str): + slots = [slots] + for slots_var in slots: + orig_vars.pop(slots_var) + orig_vars.pop('__dict__', None) + orig_vars.pop('__weakref__', None) + return metaclass(cls.__name__, cls.__bases__, orig_vars) + return wrapper + + +def python_2_unicode_compatible(klass): + """ + A decorator that defines __unicode__ and __str__ methods under Python 2. + Under Python 3 it does nothing. + + To support Python 2 and 3 with a single code base, define a __str__ method + returning text and apply this decorator to the class. + """ + if PY2: + if '__str__' not in klass.__dict__: + raise ValueError("@python_2_unicode_compatible cannot be applied " + "to %s because it doesn't define __str__()." % + klass.__name__) + klass.__unicode__ = klass.__str__ + klass.__str__ = lambda self: self.__unicode__().encode('utf-8') + return klass + + +# Complete the moves implementation. +# This code is at the end of this module to speed up module loading. +# Turn this module into a package. +__path__ = [] # required for PEP 302 and PEP 451 +__package__ = __name__ # see PEP 366 @ReservedAssignment +if globals().get("__spec__") is not None: + __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable +# Remove other six meta path importers, since they cause problems. This can +# happen if six is removed from sys.modules and then reloaded. (Setuptools does +# this for some reason.) +if sys.meta_path: + for i, importer in enumerate(sys.meta_path): + # Here's some real nastiness: Another "instance" of the six module might + # be floating around. Therefore, we can't use isinstance() to check for + # the six meta path importer, since the other six instance will have + # inserted an importer with different class. + if (type(importer).__name__ == "_SixMetaPathImporter" and + importer.name == __name__): + del sys.meta_path[i] + break + del i, importer +# Finally, add the importer to the meta path import hook. +sys.meta_path.append(_importer) diff --git a/stripe/stripe_object.py b/stripe/stripe_object.py index b86435369..4f54d324b 100644 --- a/stripe/stripe_object.py +++ b/stripe/stripe_object.py @@ -1,9 +1,10 @@ -import sys +from __future__ import absolute_import, division, print_function + import warnings from copy import deepcopy import stripe -from stripe import api_requestor, util +from stripe import api_requestor, util, six def _compute_diff(current, previous): @@ -104,7 +105,7 @@ def __getitem__(self, k): "the result returned by Stripe's API, probably as a " "result of a save(). The attributes currently " "available on this object are: %s" % - (k, k, ', '.join(self.keys()))) + (k, k, ', '.join(list(self.keys())))) else: raise err @@ -169,7 +170,7 @@ def refresh_from(self, values, api_key=None, partial=False, self._transient_values = self._transient_values - set(values) - for k, v in values.iteritems(): + for k, v in six.iteritems(values): super(StripeObject, self).__setitem__( k, util.convert_to_stripe_object(v, api_key, stripe_version, stripe_account)) @@ -195,16 +196,16 @@ def request(self, method, url, params=None, headers=None): def __repr__(self): ident_parts = [type(self).__name__] - if isinstance(self.get('object'), basestring): + if isinstance(self.get('object'), six.string_types): ident_parts.append(self.get('object')) - if isinstance(self.get('id'), basestring): + if isinstance(self.get('id'), six.string_types): ident_parts.append('id=%s' % (self.get('id'),)) unicode_repr = '<%s at %s> JSON: %s' % ( ' '.join(ident_parts), hex(id(self)), str(self)) - if sys.version_info[0] < 3: + if six.PY2: return unicode_repr.encode('utf-8') else: return unicode_repr @@ -230,7 +231,7 @@ def serialize(self, previous): unsaved_keys = self._unsaved_values or set() previous = previous or self._previous or {} - for k, v in self.items(): + for k, v in six.iteritems(self): if k == 'id' or (isinstance(k, str) and k.startswith('_')): continue elif isinstance(v, stripe.api_resources.abstract.APIResource): @@ -256,7 +257,7 @@ def __copy__(self): copied._retrieve_params = self._retrieve_params - for k, v in self.items(): + for k, v in six.iteritems(self): # Call parent's __setitem__ to avoid checks that we've added in the # overridden version that can throw exceptions. super(StripeObject, copied).__setitem__(k, v) @@ -272,7 +273,7 @@ def __deepcopy__(self, memo): copied = self.__copy__() memo[id(self)] = copied - for k, v in self.items(): + for k, v in six.iteritems(self): # Call parent's __setitem__ to avoid checks that we've added in the # overridden version that can throw exceptions. super(StripeObject, copied).__setitem__(k, deepcopy(v, memo)) diff --git a/stripe/test/__init__.py b/stripe/test/__init__.py index 45ac1b04a..b6a8eb259 100644 --- a/stripe/test/__init__.py +++ b/stripe/test/__init__.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import os import unittest2 diff --git a/stripe/test/api_resources/abstract/test_api_resource.py b/stripe/test/api_resources/abstract/test_api_resource.py index dbb82cabb..c5c7972cf 100644 --- a/stripe/test/api_resources/abstract/test_api_resource.py +++ b/stripe/test/api_resources/abstract/test_api_resource.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe.test.helper import StripeApiTestCase diff --git a/stripe/test/api_resources/abstract/test_createable_api_resource.py b/stripe/test/api_resources/abstract/test_createable_api_resource.py index f0ae65a4f..6f6745b12 100644 --- a/stripe/test/api_resources/abstract/test_createable_api_resource.py +++ b/stripe/test/api_resources/abstract/test_createable_api_resource.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe.test.helper import StripeApiTestCase diff --git a/stripe/test/api_resources/abstract/test_deletable_api_resource.py b/stripe/test/api_resources/abstract/test_deletable_api_resource.py index e259ed1bc..e46c3ae0e 100644 --- a/stripe/test/api_resources/abstract/test_deletable_api_resource.py +++ b/stripe/test/api_resources/abstract/test_deletable_api_resource.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe.test.helper import StripeApiTestCase diff --git a/stripe/test/api_resources/abstract/test_listable_api_resource.py b/stripe/test/api_resources/abstract/test_listable_api_resource.py index 4d282210f..ee5aa0d11 100644 --- a/stripe/test/api_resources/abstract/test_listable_api_resource.py +++ b/stripe/test/api_resources/abstract/test_listable_api_resource.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe.test.helper import StripeApiTestCase diff --git a/stripe/test/api_resources/abstract/test_nested_resource_class_methods.py b/stripe/test/api_resources/abstract/test_nested_resource_class_methods.py index 6c049adcb..1cfada700 100644 --- a/stripe/test/api_resources/abstract/test_nested_resource_class_methods.py +++ b/stripe/test/api_resources/abstract/test_nested_resource_class_methods.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe.test.helper import StripeApiTestCase diff --git a/stripe/test/api_resources/abstract/test_singleton_api_resource.py b/stripe/test/api_resources/abstract/test_singleton_api_resource.py index fbbfe2d9a..b1cafe21d 100644 --- a/stripe/test/api_resources/abstract/test_singleton_api_resource.py +++ b/stripe/test/api_resources/abstract/test_singleton_api_resource.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe.test.helper import StripeApiTestCase diff --git a/stripe/test/api_resources/abstract/test_updateable_api_resource.py b/stripe/test/api_resources/abstract/test_updateable_api_resource.py index 166f11ad8..940ee415b 100644 --- a/stripe/test/api_resources/abstract/test_updateable_api_resource.py +++ b/stripe/test/api_resources/abstract/test_updateable_api_resource.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe.test.helper import StripeApiTestCase diff --git a/stripe/test/api_resources/test_account.py b/stripe/test/api_resources/test_account.py index 0bc286d34..04ee23ada 100644 --- a/stripe/test/api_resources/test_account.py +++ b/stripe/test/api_resources/test_account.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe.test.helper import StripeResourceTest diff --git a/stripe/test/api_resources/test_apple_pay_domain.py b/stripe/test/api_resources/test_apple_pay_domain.py index ed0b0e6f5..ec1048430 100644 --- a/stripe/test/api_resources/test_apple_pay_domain.py +++ b/stripe/test/api_resources/test_apple_pay_domain.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe.test.helper import StripeResourceTest diff --git a/stripe/test/api_resources/test_application_fee.py b/stripe/test/api_resources/test_application_fee.py index 1aa0ed830..74c2de69f 100644 --- a/stripe/test/api_resources/test_application_fee.py +++ b/stripe/test/api_resources/test_application_fee.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe.test.helper import StripeResourceTest diff --git a/stripe/test/api_resources/test_application_fee_refund.py b/stripe/test/api_resources/test_application_fee_refund.py index d1a9e1dc7..56a64bed5 100644 --- a/stripe/test/api_resources/test_application_fee_refund.py +++ b/stripe/test/api_resources/test_application_fee_refund.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe.test.helper import StripeResourceTest diff --git a/stripe/test/api_resources/test_balance.py b/stripe/test/api_resources/test_balance.py index 618feaced..3aea9a4fe 100644 --- a/stripe/test/api_resources/test_balance.py +++ b/stripe/test/api_resources/test_balance.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe.test.helper import StripeResourceTest diff --git a/stripe/test/api_resources/test_balance_transaction.py b/stripe/test/api_resources/test_balance_transaction.py index 7d5dec47e..62811202b 100644 --- a/stripe/test/api_resources/test_balance_transaction.py +++ b/stripe/test/api_resources/test_balance_transaction.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe.test.helper import StripeResourceTest diff --git a/stripe/test/api_resources/test_bitcoin_receiver.py b/stripe/test/api_resources/test_bitcoin_receiver.py index 1160f8e9d..364b00495 100644 --- a/stripe/test/api_resources/test_bitcoin_receiver.py +++ b/stripe/test/api_resources/test_bitcoin_receiver.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe.test.helper import StripeResourceTest diff --git a/stripe/test/api_resources/test_charge.py b/stripe/test/api_resources/test_charge.py index 398449492..2a5780cb0 100644 --- a/stripe/test/api_resources/test_charge.py +++ b/stripe/test/api_resources/test_charge.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe.test.helper import ( StripeResourceTest, NOW, DUMMY_CHARGE diff --git a/stripe/test/api_resources/test_country_spec.py b/stripe/test/api_resources/test_country_spec.py index 8bbfbdf28..136a4b831 100644 --- a/stripe/test/api_resources/test_country_spec.py +++ b/stripe/test/api_resources/test_country_spec.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe.test.helper import StripeResourceTest diff --git a/stripe/test/api_resources/test_coupon.py b/stripe/test/api_resources/test_coupon.py index e9e9df32b..a86c24930 100644 --- a/stripe/test/api_resources/test_coupon.py +++ b/stripe/test/api_resources/test_coupon.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe.test.helper import StripeResourceTest diff --git a/stripe/test/api_resources/test_customer.py b/stripe/test/api_resources/test_customer.py index 910c8547e..c5565a262 100644 --- a/stripe/test/api_resources/test_customer.py +++ b/stripe/test/api_resources/test_customer.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import datetime import time import warnings diff --git a/stripe/test/api_resources/test_dispute.py b/stripe/test/api_resources/test_dispute.py index d22e3e73c..75f90f118 100644 --- a/stripe/test/api_resources/test_dispute.py +++ b/stripe/test/api_resources/test_dispute.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe.test.helper import StripeResourceTest, NOW diff --git a/stripe/test/api_resources/test_ephemeral_key.py b/stripe/test/api_resources/test_ephemeral_key.py index fb8a92f63..c1a1151c8 100644 --- a/stripe/test/api_resources/test_ephemeral_key.py +++ b/stripe/test/api_resources/test_ephemeral_key.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import warnings import stripe diff --git a/stripe/test/api_resources/test_exchange_rate.py b/stripe/test/api_resources/test_exchange_rate.py index 89e60fc8a..7e2ef727a 100644 --- a/stripe/test/api_resources/test_exchange_rate.py +++ b/stripe/test/api_resources/test_exchange_rate.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe.test.helper import StripeResourceTest diff --git a/stripe/test/api_resources/test_file_upload.py b/stripe/test/api_resources/test_file_upload.py index e9262cf9b..7a43a8fad 100644 --- a/stripe/test/api_resources/test_file_upload.py +++ b/stripe/test/api_resources/test_file_upload.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import tempfile import stripe diff --git a/stripe/test/api_resources/test_invoice.py b/stripe/test/api_resources/test_invoice.py index d3b9c1f1c..f9d812433 100644 --- a/stripe/test/api_resources/test_invoice.py +++ b/stripe/test/api_resources/test_invoice.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe.test.helper import StripeResourceTest diff --git a/stripe/test/api_resources/test_list_object.py b/stripe/test/api_resources/test_list_object.py index d5851c315..7dc2387e3 100644 --- a/stripe/test/api_resources/test_list_object.py +++ b/stripe/test/api_resources/test_list_object.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe.test.helper import StripeApiTestCase diff --git a/stripe/test/api_resources/test_metadata.py b/stripe/test/api_resources/test_metadata.py index c9e8f8971..6dc545a7f 100644 --- a/stripe/test/api_resources/test_metadata.py +++ b/stripe/test/api_resources/test_metadata.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe.test.helper import StripeResourceTest diff --git a/stripe/test/api_resources/test_order.py b/stripe/test/api_resources/test_order.py index 8a5b2389c..fd6d6cf85 100644 --- a/stripe/test/api_resources/test_order.py +++ b/stripe/test/api_resources/test_order.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe.test.helper import StripeResourceTest diff --git a/stripe/test/api_resources/test_order_return.py b/stripe/test/api_resources/test_order_return.py index fea428d2a..2c2bda08e 100644 --- a/stripe/test/api_resources/test_order_return.py +++ b/stripe/test/api_resources/test_order_return.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe.test.helper import StripeResourceTest diff --git a/stripe/test/api_resources/test_payout.py b/stripe/test/api_resources/test_payout.py index 5fce4f32c..ed5cbf91c 100644 --- a/stripe/test/api_resources/test_payout.py +++ b/stripe/test/api_resources/test_payout.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe.test.helper import StripeResourceTest diff --git a/stripe/test/api_resources/test_plans.py b/stripe/test/api_resources/test_plans.py index ebeb5ee36..ad7fc952d 100644 --- a/stripe/test/api_resources/test_plans.py +++ b/stripe/test/api_resources/test_plans.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe.test.helper import ( StripeResourceTest, DUMMY_PLAN diff --git a/stripe/test/api_resources/test_product.py b/stripe/test/api_resources/test_product.py index ff9302b1a..5d0ed46e1 100644 --- a/stripe/test/api_resources/test_product.py +++ b/stripe/test/api_resources/test_product.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe.test.helper import StripeResourceTest diff --git a/stripe/test/api_resources/test_recipient.py b/stripe/test/api_resources/test_recipient.py index 3d90e6eba..4dfb7be80 100644 --- a/stripe/test/api_resources/test_recipient.py +++ b/stripe/test/api_resources/test_recipient.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe.test.helper import (StripeResourceTest) diff --git a/stripe/test/api_resources/test_refund.py b/stripe/test/api_resources/test_refund.py index 770dbc2bd..93d769ff4 100644 --- a/stripe/test/api_resources/test_refund.py +++ b/stripe/test/api_resources/test_refund.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe.test.helper import StripeResourceTest diff --git a/stripe/test/api_resources/test_reversal.py b/stripe/test/api_resources/test_reversal.py index f8e28ff31..1d0b30985 100644 --- a/stripe/test/api_resources/test_reversal.py +++ b/stripe/test/api_resources/test_reversal.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe.test.helper import StripeResourceTest diff --git a/stripe/test/api_resources/test_sku.py b/stripe/test/api_resources/test_sku.py index 7cc09c1e7..86b9dc3d4 100644 --- a/stripe/test/api_resources/test_sku.py +++ b/stripe/test/api_resources/test_sku.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe.test.helper import StripeResourceTest diff --git a/stripe/test/api_resources/test_source.py b/stripe/test/api_resources/test_source.py index 5d41c104d..24ca86edd 100644 --- a/stripe/test/api_resources/test_source.py +++ b/stripe/test/api_resources/test_source.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import warnings import stripe diff --git a/stripe/test/api_resources/test_source_transaction.py b/stripe/test/api_resources/test_source_transaction.py index 7a56617a0..9dfaa24a1 100644 --- a/stripe/test/api_resources/test_source_transaction.py +++ b/stripe/test/api_resources/test_source_transaction.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe.test.helper import StripeResourceTest diff --git a/stripe/test/api_resources/test_subscription.py b/stripe/test/api_resources/test_subscription.py index 13e386f70..23dd74610 100644 --- a/stripe/test/api_resources/test_subscription.py +++ b/stripe/test/api_resources/test_subscription.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import datetime import time diff --git a/stripe/test/api_resources/test_subscription_item.py b/stripe/test/api_resources/test_subscription_item.py index b8d074808..fc694e8be 100644 --- a/stripe/test/api_resources/test_subscription_item.py +++ b/stripe/test/api_resources/test_subscription_item.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe.test.helper import ( StripeResourceTest, DUMMY_PLAN diff --git a/stripe/test/api_resources/test_three_d_secure.py b/stripe/test/api_resources/test_three_d_secure.py index e6c14a88d..2ed6fb81c 100644 --- a/stripe/test/api_resources/test_three_d_secure.py +++ b/stripe/test/api_resources/test_three_d_secure.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe.test.helper import StripeResourceTest diff --git a/stripe/test/api_resources/test_transfer.py b/stripe/test/api_resources/test_transfer.py index cc12485b4..e5c77899f 100644 --- a/stripe/test/api_resources/test_transfer.py +++ b/stripe/test/api_resources/test_transfer.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import, division, print_function + import stripe from stripe.test.helper import StripeResourceTest diff --git a/stripe/test/helper.py b/stripe/test/helper.py index c28495803..e948b6839 100644 --- a/stripe/test/helper.py +++ b/stripe/test/helper.py @@ -1,13 +1,15 @@ +from __future__ import absolute_import, division, print_function + import datetime import os import random import string -import sys import unittest2 from mock import patch, Mock import stripe +from stripe import six NOW = datetime.datetime.now() @@ -54,12 +56,7 @@ def tearDown(self): class StripeUnitTestCase(StripeTestCase): - REQUEST_LIBRARIES = ['urlfetch', 'requests', 'pycurl'] - - if sys.version_info >= (3, 0): - REQUEST_LIBRARIES.append('urllib.request') - else: - REQUEST_LIBRARIES.append('urllib2') + REQUEST_LIBRARIES = ['urlfetch', 'requests', 'pycurl', 'urllib.request'] def setUp(self): super(StripeUnitTestCase, self).setUp() @@ -75,7 +72,7 @@ def setUp(self): def tearDown(self): super(StripeUnitTestCase, self).tearDown() - for patcher in self.request_patchers.itervalues(): + for patcher in six.itervalues(self.request_patchers): patcher.stop() diff --git a/stripe/test/test_api_requestor.py b/stripe/test/test_api_requestor.py index b699b842d..13006abc9 100644 --- a/stripe/test/test_api_requestor.py +++ b/stripe/test/test_api_requestor.py @@ -1,13 +1,17 @@ +from __future__ import absolute_import, division, print_function + import datetime import unittest2 -import urlparse from mock import Mock, ANY import stripe +from stripe import six from stripe.test.helper import StripeUnitTestCase +from six.moves.urllib.parse import urlsplit + VALID_API_METHODS = ('get', 'post', 'delete') @@ -49,7 +53,7 @@ def __eq__(self, other): self._extra_match(other)) def _keys_match(self, other): - expected_keys = list(set(self.EXP_KEYS + self.extra.keys())) + expected_keys = list(set(self.EXP_KEYS + list(self.extra.keys()))) if self.request_method is not None and self.request_method in \ self.METHOD_EXTRA_KEYS: expected_keys.extend(self.METHOD_EXTRA_KEYS[self.request_method]) @@ -74,7 +78,7 @@ def _x_stripe_ua_contains_app_info(self, other): return True def _extra_match(self, other): - for k, v in self.extra.iteritems(): + for k, v in six.iteritems(self.extra): if other[k] != v: return False @@ -87,7 +91,7 @@ def __init__(self, expected): self.expected = sorted(expected) def __eq__(self, other): - query = urlparse.urlsplit(other).query or other + query = urlsplit(other).query or other parsed = stripe.util.parse_qsl(query) return self.expected == sorted(parsed) @@ -96,17 +100,17 @@ def __eq__(self, other): class UrlMatcher(object): def __init__(self, expected): - self.exp_parts = urlparse.urlsplit(expected) + self.exp_parts = urlsplit(expected) def __eq__(self, other): - other_parts = urlparse.urlsplit(other) + other_parts = urlsplit(other) for part in ('scheme', 'netloc', 'path', 'fragment'): expected = getattr(self.exp_parts, part) actual = getattr(other_parts, part) if expected != actual: - print 'Expected %s "%s" but got "%s"' % ( - part, expected, actual) + print('Expected %s "%s" but got "%s"' % ( + part, expected, actual)) return False q_matcher = QueryMatcher(stripe.util.parse_qsl(self.exp_parts.query)) @@ -222,7 +226,7 @@ def test_param_encoding(self): self.requestor.request('get', '', self.ENCODE_INPUTS) expectation = [] - for type_, values in self.ENCODE_EXPECTATIONS.iteritems(): + for type_, values in six.iteritems(self.ENCODE_EXPECTATIONS): expectation.extend([(k % (type_,), str(v)) for k, v in values]) self.check_call('get', QueryMatcher(expectation)) diff --git a/stripe/test/test_error.py b/stripe/test/test_error.py index 200bfe6a7..25606cdc3 100644 --- a/stripe/test/test_error.py +++ b/stripe/test/test_error.py @@ -1,9 +1,10 @@ # -*- coding: utf-8 -*- -import sys + +from __future__ import absolute_import, division, print_function import unittest2 -from stripe import StripeError +from stripe import six, StripeError from stripe.test.helper import StripeUnitTestCase @@ -11,7 +12,7 @@ class StripeErrorTests(StripeUnitTestCase): def test_formatting(self): err = StripeError(u'öre') - if sys.version_info > (3, 0): + if six.PY3: assert str(err) == u'öre' else: assert str(err) == '\xc3\xb6re' @@ -19,7 +20,7 @@ def test_formatting(self): def test_formatting_with_request_id(self): err = StripeError(u'öre', headers={'request-id': '123'}) - if sys.version_info > (3, 0): + if six.PY3: assert str(err) == u'Request 123: öre' else: assert str(err) == 'Request 123: \xc3\xb6re' @@ -27,7 +28,7 @@ def test_formatting_with_request_id(self): def test_formatting_with_none(self): err = StripeError(None, headers={'request-id': '123'}) - if sys.version_info > (3, 0): + if six.PY3: assert str(err) == u'Request 123: ' else: assert str(err) == 'Request 123: ' diff --git a/stripe/test/test_http_client.py b/stripe/test/test_http_client.py index 2cc5be4ca..06dabf417 100644 --- a/stripe/test/test_http_client.py +++ b/stripe/test/test_http_client.py @@ -1,9 +1,11 @@ -import sys +from __future__ import absolute_import, division, print_function + import unittest2 from mock import MagicMock, Mock, patch import stripe +from stripe import six from stripe.test.helper import StripeUnitTestCase @@ -219,7 +221,7 @@ def mock_error(self, mock): mock.build_opener.reset_mock() def check_call(self, mock, meth, url, post_data, headers): - if sys.version_info >= (3, 0) and isinstance(post_data, basestring): + if six.PY3 and isinstance(post_data, six.string_types): post_data = post_data.encode('utf-8') mock.Request.assert_called_with(url, post_data, headers) diff --git a/stripe/test/test_integration.py b/stripe/test/test_integration.py index ca1dc720f..2189996f5 100644 --- a/stripe/test/test_integration.py +++ b/stripe/test/test_integration.py @@ -1,10 +1,15 @@ # -*- coding: utf-8 -*- + +from __future__ import absolute_import, division, print_function + import os -import sys import unittest2 import stripe from mock import patch + +from stripe import six + from stripe.test.helper import (StripeTestCase, DUMMY_CHARGE) @@ -106,7 +111,7 @@ class PycurlFunctionalTests(FunctionalTests): def setUp(self): if not os.environ.get('STRIPE_TEST_PYCURL'): self.skipTest('Pycurl skipped as STRIPE_TEST_PYCURL is not set') - if sys.version_info >= (3, 0): + if six.PY3: self.skipTest('Pycurl is not supported in Python 3') else: super(PycurlFunctionalTests, self).setUp() @@ -123,7 +128,7 @@ def test_invalid_credentials(self): stripe.Customer.create() except stripe.error.AuthenticationError as e: self.assertEqual(401, e.http_status) - self.assertTrue(isinstance(e.http_body, basestring)) + self.assertTrue(isinstance(e.http_body, six.string_types)) self.assertTrue(isinstance(e.json_body, dict)) # Note that an invalid API key bypasses many of the standard # facilities in the API server so currently no Request ID is @@ -140,7 +145,7 @@ def test_declined_card_props(self): source='tok_chargeDeclinedExpiredCard') except stripe.error.CardError as e: self.assertEqual(402, e.http_status) - self.assertTrue(isinstance(e.http_body, basestring)) + self.assertTrue(isinstance(e.http_body, six.string_types)) self.assertTrue(isinstance(e.json_body, dict)) self.assertTrue(e.request_id.startswith('req_')) @@ -152,7 +157,7 @@ def test_nonexistent_object(self): stripe.Charge.retrieve('invalid') except stripe.error.InvalidRequestError as e: self.assertEqual(404, e.http_status) - self.assertTrue(isinstance(e.http_body, basestring)) + self.assertTrue(isinstance(e.http_body, six.string_types)) self.assertTrue(isinstance(e.json_body, dict)) self.assertTrue(e.request_id.startswith('req_')) @@ -161,7 +166,7 @@ def test_invalid_data(self): stripe.Charge.create() except stripe.error.InvalidRequestError as e: self.assertEqual(400, e.http_status) - self.assertTrue(isinstance(e.http_body, basestring)) + self.assertTrue(isinstance(e.http_body, six.string_types)) self.assertTrue(isinstance(e.json_body, dict)) self.assertTrue(e.request_id.startswith('req_')) diff --git a/stripe/test/test_multipart_data_generator.py b/stripe/test/test_multipart_data_generator.py index 94a909e2f..aced48de1 100644 --- a/stripe/test/test_multipart_data_generator.py +++ b/stripe/test/test_multipart_data_generator.py @@ -1,9 +1,10 @@ -# -*- encoding: utf-8 -*- +# -*- coding: utf-8 -*- + +from __future__ import absolute_import, division, print_function import re -import sys -import StringIO +from stripe import six from stripe.multipart_data_generator import MultipartDataGenerator from stripe.test.helper import StripeTestCase @@ -20,7 +21,7 @@ def run_test_multipart_data_with_file(self, test_file): generator.add_params(params) http_body = generator.get_post_data() - if sys.version_info >= (3,): + if six.PY3: http_body = http_body.decode('utf-8') self.assertTrue(re.search( @@ -39,7 +40,7 @@ def run_test_multipart_data_with_file(self, test_file): test_file.seek(0) file_contents = test_file.read() - if sys.version_info >= (3,) and isinstance(file_contents, bytes): + if six.PY3 and isinstance(file_contents, bytes): file_contents = file_contents.decode('utf-8') self.assertNotEqual(-1, http_body.find(file_contents)) @@ -53,5 +54,5 @@ def test_multipart_data_file_binary(self): self.run_test_multipart_data_with_file(test_file) def test_multipart_data_stringio(self): - string = StringIO.StringIO("foo") + string = six.StringIO("foo") self.run_test_multipart_data_with_file(string) diff --git a/stripe/test/test_oauth.py b/stripe/test/test_oauth.py index 6175118e9..c6562d349 100644 --- a/stripe/test/test_oauth.py +++ b/stripe/test/test_oauth.py @@ -1,4 +1,6 @@ -import urlparse +from __future__ import absolute_import, division, print_function + +from six.moves.urllib.parse import parse_qs, urlparse import stripe from stripe.test.helper import StripeApiTestCase @@ -26,8 +28,8 @@ def test_authorize_url(self): 'country': 'US', }) - o = urlparse.urlparse(url) - params = urlparse.parse_qs(o.query) + o = urlparse(url) + params = parse_qs(o.query) self.assertEqual('https', o.scheme) self.assertEqual('connect.stripe.com', o.netloc) diff --git a/stripe/test/test_stripe_object.py b/stripe/test/test_stripe_object.py index c60aca631..b70a652e2 100644 --- a/stripe/test/test_stripe_object.py +++ b/stripe/test/test_stripe_object.py @@ -1,9 +1,10 @@ +from __future__ import absolute_import, division, print_function + import pickle -import sys from copy import copy, deepcopy import stripe -from stripe import util +from stripe import util, six from stripe.test.helper import StripeUnitTestCase @@ -160,8 +161,8 @@ def test_to_json(self): def check_invoice_data(self, data): # Check rough structure - self.assertEqual(20, len(data.keys())) - self.assertEqual(3, len(data['lines'].keys())) + self.assertEqual(20, len(list(data.keys()))) + self.assertEqual(3, len(list(data['lines'].keys()))) self.assertEqual(0, len(data['lines']['invoiceitems'])) self.assertEqual(1, len(data['lines']['subscriptions'])) @@ -180,7 +181,7 @@ def test_repr(self): res = repr(obj) - if sys.version_info[0] < 3: + if six.PY2: res = unicode(repr(obj), 'utf-8') self.assertTrue(u'