braintree_python-3.38.0/ 0000755 0001750 0001750 00000000000 13150065776 013275 5 ustar hle hle braintree_python-3.38.0/setup.cfg 0000644 0001750 0001750 00000000034 13150065776 015113 0 ustar hle hle [bdist_wheel]
universal = 1
braintree_python-3.38.0/ACKNOWLEDGEMENTS.md 0000644 0001750 0001750 00000000262 13150065776 016151 0 ustar hle hle Acknowledgements
----------------
The Braintree SDK uses code from the following libraries:
* [requests](https://github.com/kennethreitz/requests), Apache License, Version 2.0
braintree_python-3.38.0/ci.sh 0000755 0001750 0001750 00000000301 13150065776 014221 0 ustar hle hle #!/bin/bash
if [[ "$1" == "http" ]]; then
python_tests="test:http"
fi
if [[ "$1" == "python3" ]]; then
/usr/local/lib/python3.3/bin/nosetests-3.3
else
env rake $python_tests --trace
fi
braintree_python-3.38.0/requirements.txt 0000644 0001750 0001750 00000000045 13150065776 016560 0 ustar hle hle requests>=0.11.1,<3.0
mock>=2.0,<3.0
braintree_python-3.38.0/tests/ 0000755 0001750 0001750 00000000000 13150065776 014437 5 ustar hle hle braintree_python-3.38.0/tests/__init__.py 0000644 0001750 0001750 00000000000 13150065776 016536 0 ustar hle hle braintree_python-3.38.0/tests/integration/ 0000755 0001750 0001750 00000000000 13150065776 016762 5 ustar hle hle braintree_python-3.38.0/tests/integration/test_us_bank_account.py 0000644 0001750 0001750 00000004366 13150065776 023542 0 ustar hle hle from tests.test_helper import *
class TestUsBankAccount(unittest.TestCase):
def test_find_returns_us_bank_account(self):
customer_id = Customer.create().customer.id
result = PaymentMethod.create({
"customer_id": customer_id,
"payment_method_nonce": TestHelper.generate_valid_us_bank_account_nonce()
})
self.assertTrue(result.is_success)
found_account = UsBankAccount.find(result.payment_method.token)
self.assertEqual(found_account.routing_number, "021000021")
self.assertEqual(found_account.last_4, "1234")
self.assertEqual(found_account.account_type, "checking")
self.assertEqual(found_account.account_holder_name, "Dan Schulman")
self.assertRegexpMatches(found_account.bank_name, r".*CHASE.*")
self.assertEqual(found_account.default, True)
self.assertEqual(found_account.ach_mandate.text, "cl mandate text")
self.assertIsNotNone(found_account.ach_mandate.accepted_at)
self.assertIsInstance(found_account.ach_mandate.accepted_at, datetime)
def test_find_does_not_return_invalid_us_bank_account(self):
self.assertRaises(NotFoundError, UsBankAccount.find, TestHelper.generate_invalid_us_bank_account_nonce())
def test_sale_transacts_us_bank_account(self):
customer_id = Customer.create().customer.id
result = PaymentMethod.create({
"customer_id": customer_id,
"payment_method_nonce": TestHelper.generate_valid_us_bank_account_nonce()
})
self.assertTrue(result.is_success)
params = {
"amount": TransactionAmounts.Authorize,
"merchant_account_id": "us_bank_merchant_account",
}
result = UsBankAccount.sale(result.payment_method.token, params)
self.assertTrue(result.is_success)
self.assertEqual(result.transaction.us_bank_account.routing_number, "021000021")
self.assertEqual(result.transaction.us_bank_account.last_4, "1234")
self.assertEqual(result.transaction.us_bank_account.account_type, "checking")
self.assertEqual(result.transaction.us_bank_account.account_holder_name, "Dan Schulman")
self.assertTrue(re.match(r".*CHASE.*", result.transaction.us_bank_account.bank_name))
braintree_python-3.38.0/tests/integration/test_disputes.py 0000644 0001750 0001750 00000016366 13150065776 022247 0 ustar hle hle import re
import time
import datetime
from tests.test_helper import *
from braintree.test.credit_card_numbers import CreditCardNumbers
class TestDisputes(unittest.TestCase):
def create_evidence_document(self):
file_path = os.path.join(os.path.dirname(__file__), "..", "fixtures/bt_logo.png")
png_file = open(file_path, "rb")
return DocumentUpload.create({
"kind": braintree.DocumentUpload.Kind.EvidenceDocument,
"file": png_file
}).document_upload
def create_sample_dispute(self):
return Transaction.sale({
"amount": "100.00",
"credit_card": {
"number": CreditCardNumbers.Disputes.Chargeback,
"expiration_date": "12/2019"
}
}).transaction.disputes[0]
def test_accept_changes_dispute_status_to_accepted(self):
dispute = self.create_sample_dispute()
result = Dispute.accept(dispute.id)
self.assertTrue(result.is_success)
updated_dispute = Dispute.find(dispute.id)
self.assertEqual(updated_dispute.status, Dispute.Status.Accepted)
def test_accept_errors_when_dispute_not_open(self):
result = Dispute.accept("wells_dispute")
self.assertFalse(result.is_success)
self.assertEqual(result.errors.for_object("dispute")[0].code, ErrorCodes.Dispute.CanOnlyAcceptOpenDispute)
self.assertEqual(result.errors.for_object("dispute")[0].message, "Disputes can only be accepted when they are in an Open state")
@raises_with_regexp(NotFoundError, "dispute with id 'invalid-id' not found")
def test_accept_raises_error_when_dispute_not_found(self):
dispute = Dispute.accept("invalid-id")
def test_add_file_evidence_adds_evidence(self):
dispute = self.create_sample_dispute()
document = self.create_evidence_document()
result = Dispute.add_file_evidence(dispute.id, document.id)
self.assertTrue(result.is_success)
updated_dispute = Dispute.find(dispute.id)
self.assertEqual(updated_dispute.evidence[0].id, result.evidence.id)
@raises_with_regexp(NotFoundError, "dispute with id 'unknown_dispute_id' not found")
def test_add_file_evidence_raises_error_when_dispute_not_found(self):
dispute = Dispute.add_file_evidence("unknown_dispute_id", "text evidence")
def test_add_file_evidence_raises_error_when_dispute_not_open(self):
dispute = self.create_sample_dispute()
document = self.create_evidence_document()
Dispute.accept(dispute.id)
result = Dispute.add_file_evidence(dispute.id, document.id)
self.assertFalse(result.is_success)
self.assertEqual(result.errors.for_object("dispute")[0].code, ErrorCodes.Dispute.CanOnlyAddEvidenceToOpenDispute)
self.assertEqual(result.errors.for_object("dispute")[0].message, "Evidence can only be attached to disputes that are in an Open state")
def test_add_text_evidence_adds_text_evidence(self):
dispute = self.create_sample_dispute()
result = Dispute.add_text_evidence(dispute.id, "text evidence")
evidence = result.evidence
self.assertTrue(result.is_success)
self.assertEqual(evidence.comment, "text evidence")
self.assertIsNotNone(evidence.created_at)
self.assertTrue(re.match("^\w{16,}$", evidence.id))
self.assertIsNone(evidence.sent_to_processor_at)
self.assertIsNone(evidence.url)
@raises_with_regexp(NotFoundError, "dispute with id 'unknown_dispute_id' not found")
def test_add_text_evidence_raises_error_when_dispute_not_found(self):
dispute = Dispute.add_text_evidence("unknown_dispute_id", "text evidence")
def test_add_text_evidence_raises_error_when_dispute_not_open(self):
dispute = self.create_sample_dispute()
Dispute.accept(dispute.id)
result = Dispute.add_text_evidence(dispute.id, "text evidence")
self.assertFalse(result.is_success)
self.assertEqual(result.errors.for_object("dispute")[0].code, ErrorCodes.Dispute.CanOnlyAddEvidenceToOpenDispute)
self.assertEqual(result.errors.for_object("dispute")[0].message, "Evidence can only be attached to disputes that are in an Open state")
def test_add_text_evidence_shows_new_record_in_find(self):
dispute = self.create_sample_dispute()
evidence = Dispute.add_text_evidence(dispute.id, "text evidence").evidence
refreshed_dispute = Dispute.find(dispute.id)
self.assertEqual(refreshed_dispute.evidence[0].id, evidence.id)
self.assertEqual(refreshed_dispute.evidence[0].comment, "text evidence")
def test_finalize_changes_dispute_status_to_disputed(self):
dispute = self.create_sample_dispute()
result = Dispute.finalize(dispute.id)
self.assertTrue(result.is_success)
updated_dispute = Dispute.find(dispute.id)
self.assertEqual(updated_dispute.status, Dispute.Status.Disputed)
def test_finalize_errors_when_dispute_not_open(self):
result = Dispute.finalize("wells_dispute")
self.assertFalse(result.is_success)
self.assertEqual(result.errors.for_object("dispute")[0].code, ErrorCodes.Dispute.CanOnlyFinalizeOpenDispute)
self.assertEqual(result.errors.for_object("dispute")[0].message, "Disputes can only be finalized when they are in an Open state")
@raises_with_regexp(NotFoundError, "dispute with id 'invalid-id' not found")
def test_finalize_raises_error_when_dispute_not_found(self):
dispute = Dispute.finalize("invalid-id")
def test_find_returns_dispute_with_given_id(self):
dispute = Dispute.find("open_dispute")
self.assertEqual(dispute.amount_disputed, 31.0)
self.assertEqual(dispute.amount_won, 0.0)
self.assertEqual(dispute.id, "open_dispute")
self.assertEqual(dispute.status, Dispute.Status.Open)
self.assertEqual(dispute.transaction.id, "open_disputed_transaction")
@raises_with_regexp(NotFoundError, "dispute with id 'invalid-id' not found")
def test_find_raises_error_when_dispute_not_found(self):
dispute = Dispute.find("invalid-id")
def test_remove_evidence_removes_evidence_from_the_dispute(self):
dispute = self.create_sample_dispute()
evidence = Dispute.add_text_evidence(dispute.id, "text evidence").evidence
result = Dispute.remove_evidence(dispute.id, evidence.id)
self.assertTrue(result.is_success)
@raises_with_regexp(NotFoundError, "evidence with id 'unknown_evidence_id' for dispute with id 'unknown_dispute_id' not found")
def test_remove_evidence_raises_error_when_dispute_or_evidence_not_found(self):
Dispute.remove_evidence("unknown_dispute_id", "unknown_evidence_id")
def test_remove_evidence_errors_when_dispute_not_open(self):
dispute = self.create_sample_dispute()
evidence = Dispute.add_text_evidence(dispute.id, "text evidence").evidence
Dispute.accept(dispute.id)
result = Dispute.remove_evidence(dispute.id, evidence.id)
self.assertFalse(result.is_success)
self.assertEqual(result.errors.for_object("dispute")[0].code, ErrorCodes.Dispute.CanOnlyRemoveEvidenceFromOpenDispute)
self.assertEqual(result.errors.for_object("dispute")[0].message, "Evidence can only be removed from disputes that are in an Open state")
braintree_python-3.38.0/tests/integration/test_transparent_redirect.py 0000644 0001750 0001750 00000017152 13150065776 024623 0 ustar hle hle from tests.test_helper import *
class TestTransparentRedirect(unittest.TestCase):
@raises(DownForMaintenanceError)
def test_parse_and_validate_query_string_checks_http_status_before_hash(self):
customer = Customer.create().customer
tr_data = {
"credit_card": {
"customer_id": customer.id
}
}
post_params = {
"tr_data": CreditCard.tr_data_for_create(tr_data, "http://example.com/path?foo=bar"),
"credit_card[cardholder_name]": "Card Holder",
"credit_card[number]": "4111111111111111",
"credit_card[expiration_date]": "05/2012",
}
query_string = TestHelper.simulate_tr_form_post(post_params, Configuration.instantiate().base_merchant_path() + "/test/maintenance")
CreditCard.confirm_transparent_redirect(query_string)
@raises(AuthenticationError)
def test_parse_and_validate_query_string_raises_authentication_error_with_bad_credentials(self):
customer = Customer.create().customer
tr_data = {
"credit_card": {
"customer_id": customer.id
}
}
old_private_key = Configuration.private_key
try:
Configuration.private_key = "bad"
post_params = {
"tr_data": CreditCard.tr_data_for_create(tr_data, "http://example.com/path?foo=bar"),
"credit_card[cardholder_name]": "Card Holder",
"credit_card[number]": "4111111111111111",
"credit_card[expiration_date]": "05/2012",
}
query_string = TestHelper.simulate_tr_form_post(post_params, CreditCard.transparent_redirect_create_url())
CreditCard.confirm_transparent_redirect(query_string)
finally:
Configuration.private_key = old_private_key
def test_transaction_sale_from_transparent_redirect_with_successful_result(self):
tr_data = {
"transaction": {
"amount": TransactionAmounts.Authorize,
}
}
post_params = {
"tr_data": Transaction.tr_data_for_sale(tr_data, "http://example.com/path"),
"transaction[credit_card][number]": "4111111111111111",
"transaction[credit_card][expiration_date]": "05/2010",
}
query_string = TestHelper.simulate_tr_form_post(post_params)
result = TransparentRedirect.confirm(query_string)
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(Decimal(TransactionAmounts.Authorize), transaction.amount)
self.assertEqual(Transaction.Type.Sale, transaction.type)
self.assertEqual("411111", transaction.credit_card_details.bin)
self.assertEqual("1111", transaction.credit_card_details.last_4)
self.assertEqual("05/2010", transaction.credit_card_details.expiration_date)
def test_transaction_credit_from_transparent_redirect_with_successful_result(self):
tr_data = {
"transaction": {
"amount": TransactionAmounts.Authorize,
}
}
post_params = {
"tr_data": Transaction.tr_data_for_credit(tr_data, "http://example.com/path"),
"transaction[credit_card][number]": "4111111111111111",
"transaction[credit_card][expiration_date]": "05/2010",
}
query_string = TestHelper.simulate_tr_form_post(post_params)
result = TransparentRedirect.confirm(query_string)
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(Decimal(TransactionAmounts.Authorize), transaction.amount)
self.assertEqual(Transaction.Type.Credit, transaction.type)
self.assertEqual("411111", transaction.credit_card_details.bin)
self.assertEqual("1111", transaction.credit_card_details.last_4)
self.assertEqual("05/2010", transaction.credit_card_details.expiration_date)
def test_customer_create_from_transparent_redirect(self):
tr_data = {
"customer": {
"first_name": "John",
"last_name": "Doe",
"company": "Doe Co",
}
}
post_params = {
"tr_data": Customer.tr_data_for_create(tr_data, "http://example.com/path"),
"customer[email]": "john@doe.com",
"customer[phone]": "312.555.2323",
"customer[fax]": "614.555.5656",
"customer[website]": "www.johndoe.com"
}
query_string = TestHelper.simulate_tr_form_post(post_params)
result = TransparentRedirect.confirm(query_string)
self.assertTrue(result.is_success)
customer = result.customer
self.assertEqual("John", customer.first_name)
self.assertEqual("Doe", customer.last_name)
self.assertEqual("Doe Co", customer.company)
self.assertEqual("john@doe.com", customer.email)
self.assertEqual("312.555.2323", customer.phone)
self.assertEqual("614.555.5656", customer.fax)
self.assertEqual("www.johndoe.com", customer.website)
def test_customer_update_from_transparent_redirect(self):
customer = Customer.create({"first_name": "Sarah", "last_name": "Humphrey"}).customer
tr_data = {
"customer_id": customer.id,
"customer": {
"first_name": "Stan",
}
}
post_params = {
"tr_data": Customer.tr_data_for_update(tr_data, "http://example.com/path"),
"customer[last_name]": "Humphrey",
}
query_string = TestHelper.simulate_tr_form_post(post_params)
result = TransparentRedirect.confirm(query_string)
self.assertTrue(result.is_success)
customer = Customer.find(customer.id)
self.assertEqual("Stan", customer.first_name)
self.assertEqual("Humphrey", customer.last_name)
def test_payment_method_create_from_transparent_redirect(self):
customer = Customer.create({"first_name": "Sarah", "last_name": "Humphrey"}).customer
tr_data = {
"credit_card": {
"customer_id": customer.id,
"number": "4111111111111111",
}
}
post_params = {
"tr_data": CreditCard.tr_data_for_create(tr_data, "http://example.com/path"),
"credit_card[expiration_month]": "01",
"credit_card[expiration_year]": "10"
}
query_string = TestHelper.simulate_tr_form_post(post_params)
result = TransparentRedirect.confirm(query_string)
self.assertTrue(result.is_success)
credit_card = result.credit_card
self.assertEqual("411111", credit_card.bin)
self.assertEqual("1111", credit_card.last_4)
self.assertEqual("01/2010", credit_card.expiration_date)
def test_payment_method_update_from_transparent_redirect(self):
customer = Customer.create({"first_name": "Sarah", "last_name": "Humphrey"}).customer
credit_card = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "10/10"
}).credit_card
tr_data = {
"payment_method_token": credit_card.token,
"credit_card": {
"expiration_date": "12/12"
}
}
post_params = {
"tr_data": CreditCard.tr_data_for_update(tr_data, "http://example.com/path"),
}
query_string = TestHelper.simulate_tr_form_post(post_params)
TransparentRedirect.confirm(query_string)
credit_card = CreditCard.find(credit_card.token)
self.assertEqual("12/2012", credit_card.expiration_date)
braintree_python-3.38.0/tests/integration/test_address.py 0000644 0001750 0001750 00000016244 13150065776 022027 0 ustar hle hle from tests.test_helper import *
class TestAddress(unittest.TestCase):
def test_create_returns_successful_result_if_valid(self):
customer = Customer.create().customer
result = Address.create({
"customer_id": customer.id,
"first_name": "Ben",
"last_name": "Moore",
"company": "Moore Co.",
"street_address": "1811 E Main St",
"extended_address": "Suite 200",
"locality": "Chicago",
"region": "Illinois",
"postal_code": "60622",
"country_name": "United States of America",
"country_code_alpha2": "US",
"country_code_alpha3": "USA",
"country_code_numeric": "840"
})
self.assertTrue(result.is_success)
address = result.address
self.assertEqual(customer.id, address.customer_id)
self.assertEqual("Ben", address.first_name)
self.assertEqual("Moore", address.last_name)
self.assertEqual("Moore Co.", address.company)
self.assertEqual("1811 E Main St", address.street_address)
self.assertEqual("Suite 200", address.extended_address)
self.assertEqual("Chicago", address.locality)
self.assertEqual("Illinois", address.region)
self.assertEqual("60622", address.postal_code)
self.assertEqual("US", address.country_code_alpha2)
self.assertEqual("USA", address.country_code_alpha3)
self.assertEqual("840", address.country_code_numeric)
self.assertEqual("United States of America", address.country_name)
def test_error_response_if_invalid(self):
customer = Customer.create().customer
result = Address.create({
"customer_id": customer.id,
"country_name": "zzzzzz",
"country_code_alpha2": "zz",
"country_code_alpha3": "zzz",
"country_code_numeric": "000"
})
self.assertFalse(result.is_success)
country_name_errors = result.errors.for_object("address").on("country_name")
self.assertEqual(1, len(country_name_errors))
self.assertEqual(ErrorCodes.Address.CountryNameIsNotAccepted, country_name_errors[0].code)
country_code_alpha2_errors = result.errors.for_object("address").on("country_code_alpha2")
self.assertEqual(1, len(country_code_alpha2_errors))
self.assertEqual(ErrorCodes.Address.CountryCodeAlpha2IsNotAccepted, country_code_alpha2_errors[0].code)
country_code_alpha3_errors = result.errors.for_object("address").on("country_code_alpha3")
self.assertEqual(1, len(country_code_alpha3_errors))
self.assertEqual(ErrorCodes.Address.CountryCodeAlpha3IsNotAccepted, country_code_alpha3_errors[0].code)
country_code_numeric_errors = result.errors.for_object("address").on("country_code_numeric")
self.assertEqual(1, len(country_code_numeric_errors))
self.assertEqual(ErrorCodes.Address.CountryCodeNumericIsNotAccepted, country_code_numeric_errors[0].code)
def test_error_response_if_inconsistent_country(self):
customer = Customer.create().customer
result = Address.create({
"customer_id": customer.id,
"country_code_alpha2": "US",
"country_code_alpha3": "MEX"
})
self.assertFalse(result.is_success)
address_errors = result.errors.for_object("address").on("base")
self.assertEqual(1, len(address_errors))
self.assertEqual(ErrorCodes.Address.InconsistentCountry, address_errors[0].code)
def test_delete_with_valid_customer_id_and_address_id(self):
customer = Customer.create().customer
address = Address.create({"customer_id": customer.id, "street_address": "123 Main St."}).address
result = Address.delete(customer.id, address.id)
self.assertTrue(result.is_success)
@raises(NotFoundError)
def test_delete_with_valid_customer_id_and_non_existing_address(self):
customer = Customer.create().customer
Address.delete(customer.id, "notreal")
def test_find_with_valid_customer_id_and_address_id(self):
customer = Customer.create().customer
address = Address.create({"customer_id": customer.id, "street_address": "123 Main St."}).address
found_address = Address.find(customer.id, address.id)
self.assertEqual(address.street_address, found_address.street_address)
@raises_with_regexp(NotFoundError,
"address for customer 'notreal' with id 'badaddress' not found")
def test_find_with_invalid_customer_id_and_address_id(self):
Address.find("notreal", "badaddress")
def test_update_with_valid_values(self):
customer = Customer.create().customer
address = Address.create({
"customer_id": customer.id,
"street_address": "1811 E Main St",
"extended_address": "Suite 200",
"locality": "Chicago",
"region": "Illinois",
"postal_code": "60622",
"country_name": "United States of America"
}).address
result = Address.update(customer.id, address.id, {
"street_address": "123 E New St",
"extended_address": "New Suite 3",
"locality": "Chicago",
"region": "Illinois",
"postal_code": "60621",
"country_code_alpha2": "MX",
"country_code_alpha3": "MEX",
"country_code_numeric": "484",
"country_name": "Mexico"
})
self.assertTrue(result.is_success)
address = result.address
self.assertEqual(customer.id, address.customer_id)
self.assertEqual("123 E New St", address.street_address)
self.assertEqual("New Suite 3", address.extended_address)
self.assertEqual("Chicago", address.locality)
self.assertEqual("Illinois", address.region)
self.assertEqual("60621", address.postal_code)
self.assertEqual("MX", address.country_code_alpha2)
self.assertEqual("MEX", address.country_code_alpha3)
self.assertEqual("484", address.country_code_numeric)
self.assertEqual("Mexico", address.country_name)
def test_update_with_invalid_values(self):
customer = Customer.create().customer
address = Address.create({
"customer_id": customer.id,
"street_address": "1811 E Main St",
"extended_address": "Suite 200",
"locality": "Chicago",
"region": "Illinois",
"postal_code": "60622",
"country_name": "United States of America"
}).address
result = Address.update(customer.id, address.id, {
"street_address": "123 E New St",
"country_name": "United States of Invalid"
})
self.assertFalse(result.is_success)
country_name_errors = result.errors.for_object("address").on("country_name")
self.assertEqual(1, len(country_name_errors))
self.assertEqual(ErrorCodes.Address.CountryNameIsNotAccepted, country_name_errors[0].code)
@raises(NotFoundError)
def test_update_raises_not_found_error_if_given_bad_address(self):
customer = Customer.create().customer
Address.update(customer.id, "notfound", {"street_address": "123 Main St."})
braintree_python-3.38.0/tests/integration/test_credit_card_verification.py 0000644 0001750 0001750 00000007016 13150065776 025404 0 ustar hle hle from tests.test_helper import *
from braintree.test.credit_card_numbers import CreditCardNumbers
class TestCreditCardVerfication(unittest.TestCase):
def test_create_success(self):
result = CreditCardVerification.create({
"credit_card": {
"number": CreditCardNumbers.Visa,
"cardholder_name": "John Smith",
"expiration_date": "05/2012"
}})
self.assertTrue(result.is_success)
def test_create_failure(self):
result = CreditCardVerification.create({
"credit_card": {
"number": CreditCardNumbers.FailsSandboxVerification.MasterCard,
"expiration_date": "05/2012"
}})
self.assertFalse(result.is_success)
def test_create_returns_validation_errors(self):
result = CreditCardVerification.create({
"credit_card": {
"number": CreditCardNumbers.FailsSandboxVerification.MasterCard,
"expiration_date": "05/2012"
},
"options": {"amount": "-10.00"}
})
self.assertFalse(result.is_success)
amount_errors = result.errors.for_object("verification").for_object("options").on("amount")
self.assertEqual(1, len(amount_errors))
self.assertEqual(ErrorCodes.Verification.Options.AmountCannotBeNegative, amount_errors[0].code)
def test_find_with_verification_id(self):
customer = Customer.create({
"credit_card": {
"number": CreditCardNumbers.FailsSandboxVerification.MasterCard,
"expiration_date": "05/2012",
"cardholder_name": "Tom Smith",
"options": {"verify_card": True}
}})
created_verification = customer.credit_card_verification
found_verification = CreditCardVerification.find(created_verification.id)
self.assertEqual(created_verification, found_verification)
def test_verification_not_found(self):
self.assertRaises(NotFoundError, CreditCardVerification.find,
"invalid-id")
def test_card_type_indicators(self):
cardholder_name = "Tom %s" % random.randint(1, 10000)
Customer.create({"credit_card": {
"cardholder_name": cardholder_name,
"expiration_date": "10/2012",
"number": CreditCardNumbers.CardTypeIndicators.Unknown,
"options": {"verify_card": True}
}})
found_verifications = CreditCardVerification.search(
CreditCardVerificationSearch.credit_card_cardholder_name == cardholder_name
)
self.assertEqual(CreditCard.Prepaid.Unknown, found_verifications.first.credit_card['prepaid'])
self.assertEqual(CreditCard.Debit.Unknown, found_verifications.first.credit_card['debit'])
self.assertEqual(CreditCard.Commercial.Unknown, found_verifications.first.credit_card['commercial'])
self.assertEqual(CreditCard.Healthcare.Unknown, found_verifications.first.credit_card['healthcare'])
self.assertEqual(CreditCard.Payroll.Unknown, found_verifications.first.credit_card['payroll'])
self.assertEqual(CreditCard.DurbinRegulated.Unknown, found_verifications.first.credit_card['durbin_regulated'])
self.assertEqual(CreditCard.IssuingBank.Unknown, found_verifications.first.credit_card['issuing_bank'])
self.assertEqual(CreditCard.CountryOfIssuance.Unknown, found_verifications.first.credit_card['country_of_issuance'])
self.assertEqual(CreditCard.ProductId.Unknown, found_verifications.first.credit_card['product_id'])
braintree_python-3.38.0/tests/integration/test_payment_method.py 0000644 0001750 0001750 00000143742 13150065776 023423 0 ustar hle hle import time
from datetime import datetime
from tests.test_helper import *
from braintree.test.credit_card_numbers import CreditCardNumbers
from braintree.test.nonces import Nonces
class TestPaymentMethod(unittest.TestCase):
def test_create_with_paypal_future_payments_nonce(self):
customer_id = Customer.create().customer.id
result = PaymentMethod.create({
"customer_id": customer_id,
"payment_method_nonce": Nonces.PayPalFuturePayment
})
self.assertTrue(result.is_success)
created_account = result.payment_method
self.assertEqual(PayPalAccount, created_account.__class__)
self.assertEqual("jane.doe@example.com", created_account.email)
self.assertNotEqual(created_account.image_url, None)
found_account = PaymentMethod.find(result.payment_method.token)
self.assertNotEqual(None, found_account)
self.assertEqual(created_account.token, found_account.token)
self.assertEqual(created_account.customer_id, found_account.customer_id)
def test_create_with_paypal_order_payment_nonce_and_paypal_options(self):
customer_id = Customer.create().customer.id
http = ClientApiHttp.create()
status_code, payment_method_nonce = http.get_paypal_nonce({
"intent": "order",
"payment-token": "fake-paypal-payment-token",
"payer-id": "fake-paypal-payer-id"
})
result = PaymentMethod.create({
"customer_id": customer_id,
"payment_method_nonce": payment_method_nonce,
"options": {
"paypal": {
"payee_email": "payee@example.com",
"order_id": "merchant-order-id",
"custom_field": "custom merchant field",
"description": "merchant description",
"amount": "1.23",
},
},
})
self.assertTrue(result.is_success)
created_account = result.payment_method
self.assertEqual(PayPalAccount, created_account.__class__)
self.assertEqual("bt_buyer_us@paypal.com", created_account.email)
self.assertNotEqual(created_account.image_url, None)
found_account = PaymentMethod.find(result.payment_method.token)
self.assertNotEqual(None, found_account)
self.assertEqual(created_account.token, found_account.token)
self.assertEqual(created_account.customer_id, found_account.customer_id)
def test_create_returns_validation_failures(self):
http = ClientApiHttp.create()
status_code, nonce = http.get_paypal_nonce({
"options": {"validate": False}
})
self.assertEqual(202, status_code)
result = PaymentMethod.create({
"payment_method_nonce": nonce
})
self.assertFalse(result.is_success)
paypal_error_codes = [
error.code for error in result.errors.for_object("paypal_account").on("base")
]
self.assertTrue(ErrorCodes.PayPalAccount.ConsentCodeOrAccessTokenIsRequired in paypal_error_codes)
customer_error_codes = [
error.code for error in result.errors.for_object("paypal_account").on("customer_id")
]
self.assertTrue(ErrorCodes.PayPalAccount.CustomerIdIsRequiredForVaulting in customer_error_codes)
def test_create_and_make_default(self):
customer_id = Customer.create().customer.id
credit_card_result = CreditCard.create({
"customer_id": customer_id,
"number": "4111111111111111",
"expiration_date": "05/2014",
})
self.assertTrue(credit_card_result.is_success)
result = PaymentMethod.create({
"customer_id": customer_id,
"payment_method_nonce": Nonces.PayPalFuturePayment,
"options": {"make_default": True},
})
self.assertTrue(result.is_success)
self.assertTrue(result.payment_method.default)
def test_create_and_set_token(self):
customer_id = Customer.create().customer.id
token = str(random.randint(1, 1000000))
result = PaymentMethod.create({
"customer_id": customer_id,
"payment_method_nonce": Nonces.PayPalFuturePayment,
"token": token
})
self.assertTrue(result.is_success)
self.assertEqual(token, result.payment_method.token)
def test_create_with_paypal_one_time_nonce_fails(self):
customer_id = Customer.create().customer.id
result = PaymentMethod.create({
"customer_id": customer_id,
"payment_method_nonce": Nonces.PayPalOneTimePayment
})
self.assertFalse(result.is_success)
base_errors = result.errors.for_object("paypal_account").on("base")
self.assertEqual(1, len(base_errors))
self.assertEqual(ErrorCodes.PayPalAccount.CannotVaultOneTimeUsePayPalAccount, base_errors[0].code)
def test_create_with_credit_card_nonce(self):
http = ClientApiHttp.create()
status_code, nonce = http.get_credit_card_nonce({
"number": "4111111111111111",
"expirationMonth": "12",
"expirationYear": "2020",
"options": {"validate": False}
})
self.assertEqual(202, status_code)
customer_id = Customer.create().customer.id
result = PaymentMethod.create({
"customer_id": customer_id,
"payment_method_nonce": nonce
})
self.assertTrue(result.is_success)
created_credit_card = result.payment_method
self.assertEqual(CreditCard, created_credit_card.__class__)
self.assertEqual("411111", created_credit_card.bin)
found_credit_card = PaymentMethod.find(result.payment_method.token)
self.assertNotEqual(None, found_credit_card)
self.assertEqual(found_credit_card.token, created_credit_card.token)
self.assertEqual(found_credit_card.customer_id, created_credit_card.customer_id)
def test_create_with_europe_bank_account_nonce(self):
config = Configuration.instantiate()
customer_id = Customer.create().customer.id
token = TestHelper.generate_decoded_client_token({"customer_id": customer_id, "sepa_mandate_type": EuropeBankAccount.MandateType.Business})
authorization_fingerprint = json.loads(token)["authorizationFingerprint"]
client_api = ClientApiHttp(config, {
"authorization_fingerprint": authorization_fingerprint,
"shared_customer_identifier": "fake_identifier",
"shared_customer_identifier_type": "testing"
})
nonce = client_api.get_europe_bank_account_nonce({
"locale": "de-DE",
"bic": "DEUTDEFF",
"iban": "DE89370400440532013000",
"accountHolderName": "Baron Von Holder",
"billingAddress": {"region": "Hesse", "country_name": "Germany"}
})
self.assertNotEqual(nonce, None)
result = PaymentMethod.create({
"customer_id": customer_id,
"payment_method_nonce": nonce
})
self.assertTrue(result.is_success)
self.assertNotEqual(result.payment_method.image_url, None)
self.assertEqual(customer_id, result.payment_method.customer_id)
found_bank_account = PaymentMethod.find(result.payment_method.token)
self.assertNotEqual(found_bank_account, None)
self.assertEqual("DEUTDEFF", found_bank_account.bic)
self.assertEqual(EuropeBankAccount, found_bank_account.__class__)
def test_create_with_fake_apple_pay_nonce(self):
customer_id = Customer.create().customer.id
result = PaymentMethod.create({
"customer_id": customer_id,
"payment_method_nonce": Nonces.ApplePayMasterCard
})
self.assertTrue(result.is_success)
apple_pay_card = result.payment_method
self.assertIsInstance(apple_pay_card, ApplePayCard)
self.assertNotEqual(apple_pay_card.bin, None)
self.assertNotEqual(apple_pay_card.token, None)
self.assertEqual(apple_pay_card.customer_id, customer_id)
self.assertEqual(ApplePayCard.CardType.MasterCard, apple_pay_card.card_type)
self.assertEqual("MasterCard 0017", apple_pay_card.payment_instrument_name)
self.assertEqual("MasterCard 0017", apple_pay_card.source_description)
self.assertTrue(apple_pay_card.default)
self.assertIn("apple_pay", apple_pay_card.image_url)
self.assertTrue(int(apple_pay_card.expiration_month) > 0)
self.assertTrue(int(apple_pay_card.expiration_year) > 0)
def test_create_with_fake_android_pay_proxy_card_nonce(self):
customer_id = Customer.create().customer.id
result = PaymentMethod.create({
"customer_id": customer_id,
"payment_method_nonce": Nonces.AndroidPayCardDiscover
})
self.assertTrue(result.is_success)
android_pay_card = result.payment_method
self.assertIsInstance(android_pay_card, AndroidPayCard)
self.assertNotEqual(android_pay_card.token, None)
self.assertEqual(customer_id, android_pay_card.customer_id)
self.assertEqual(CreditCard.CardType.Discover, android_pay_card.virtual_card_type)
self.assertEqual("1117", android_pay_card.virtual_card_last_4)
self.assertEqual("Visa 1111", android_pay_card.source_description)
self.assertEqual(CreditCard.CardType.Visa, android_pay_card.source_card_type)
self.assertEqual("1111", android_pay_card.source_card_last_4)
self.assertEqual("1117", android_pay_card.last_4)
self.assertEqual(CreditCard.CardType.Discover, android_pay_card.card_type)
self.assertTrue(android_pay_card.default)
self.assertIn("android_pay", android_pay_card.image_url)
self.assertTrue(int(android_pay_card.expiration_month) > 0)
self.assertTrue(int(android_pay_card.expiration_year) > 0)
self.assertIsInstance(android_pay_card.created_at, datetime)
self.assertIsInstance(android_pay_card.updated_at, datetime)
self.assertEqual("601111", android_pay_card.bin)
self.assertEqual("google_transaction_id", android_pay_card.google_transaction_id)
def test_create_with_fake_android_pay_network_token_nonce(self):
customer_id = Customer.create().customer.id
result = PaymentMethod.create({
"customer_id": customer_id,
"payment_method_nonce": Nonces.AndroidPayCardMasterCard
})
self.assertTrue(result.is_success)
android_pay_card = result.payment_method
self.assertIsInstance(android_pay_card, AndroidPayCard)
self.assertNotEqual(android_pay_card.token, None)
self.assertEqual(customer_id, android_pay_card.customer_id)
self.assertEqual(CreditCard.CardType.MasterCard, android_pay_card.virtual_card_type)
self.assertEqual("4444", android_pay_card.virtual_card_last_4)
self.assertEqual("MasterCard 4444", android_pay_card.source_description)
self.assertEqual(CreditCard.CardType.MasterCard, android_pay_card.source_card_type)
self.assertEqual("4444", android_pay_card.source_card_last_4)
self.assertEqual("4444", android_pay_card.last_4)
self.assertEqual(CreditCard.CardType.MasterCard, android_pay_card.card_type)
self.assertTrue(android_pay_card.default)
self.assertIn("android_pay", android_pay_card.image_url)
self.assertTrue(int(android_pay_card.expiration_month) > 0)
self.assertTrue(int(android_pay_card.expiration_year) > 0)
self.assertIsInstance(android_pay_card.created_at, datetime)
self.assertIsInstance(android_pay_card.updated_at, datetime)
self.assertEqual("555555", android_pay_card.bin)
self.assertEqual("google_transaction_id", android_pay_card.google_transaction_id)
def test_create_with_fake_amex_express_checkout_card_nonce(self):
customer_id = Customer.create().customer.id
result = PaymentMethod.create({
"customer_id": customer_id,
"payment_method_nonce": Nonces.AmexExpressCheckoutCard
})
self.assertTrue(result.is_success)
amex_express_checkout_card = result.payment_method
self.assertIsInstance(amex_express_checkout_card, AmexExpressCheckoutCard)
self.assertNotEqual(amex_express_checkout_card.token, None)
self.assertTrue(amex_express_checkout_card.default)
self.assertEqual("American Express", amex_express_checkout_card.card_type)
self.assertRegexpMatches(amex_express_checkout_card.bin, r"\A\d{6}\Z")
self.assertRegexpMatches(amex_express_checkout_card.expiration_month, r"\A\d{2}\Z")
self.assertRegexpMatches(amex_express_checkout_card.expiration_year, r"\A\d{4}\Z")
self.assertRegexpMatches(amex_express_checkout_card.card_member_number, r"\A\d{4}\Z")
self.assertRegexpMatches(amex_express_checkout_card.card_member_expiry_date, r"\A\d{2}/\d{2}\Z")
self.assertRegexpMatches(amex_express_checkout_card.source_description, r"\AAmEx \d{4}\Z")
self.assertRegexpMatches(amex_express_checkout_card.image_url, r"\.png")
self.assertEqual(customer_id, amex_express_checkout_card.customer_id)
def test_create_with_venmo_account_nonce(self):
customer_id = Customer.create().customer.id
result = PaymentMethod.create({
"customer_id": customer_id,
"payment_method_nonce": Nonces.VenmoAccount,
})
self.assertTrue(result.is_success)
venmo_account = result.payment_method
self.assertIsInstance(venmo_account, VenmoAccount)
self.assertTrue(venmo_account.default)
self.assertIsNotNone(venmo_account.token)
self.assertEqual("venmojoe", venmo_account.username)
self.assertEqual("Venmo-Joe-1", venmo_account.venmo_user_id)
self.assertEqual("Venmo Account: venmojoe", venmo_account.source_description)
self.assertRegexpMatches(venmo_account.image_url, r"\.png")
self.assertEqual(customer_id, venmo_account.customer_id)
def test_create_with_us_bank_account_nonce(self):
customer_id = Customer.create().customer.id
result = PaymentMethod.create({
"customer_id": customer_id,
"payment_method_nonce": TestHelper.generate_valid_us_bank_account_nonce()
})
self.assertTrue(result.is_success)
us_bank_account = result.payment_method
self.assertIsInstance(us_bank_account, UsBankAccount)
self.assertEqual(us_bank_account.routing_number, "021000021")
self.assertEqual(us_bank_account.last_4, "1234")
self.assertEqual(us_bank_account.account_type, "checking")
self.assertEqual(us_bank_account.account_holder_name, "Dan Schulman")
self.assertTrue(re.match(r".*CHASE.*", us_bank_account.bank_name))
self.assertEqual(us_bank_account.default, True)
self.assertEqual(us_bank_account.ach_mandate.text, "cl mandate text")
self.assertIsInstance(us_bank_account.ach_mandate.accepted_at, datetime)
def test_create_fails_with_invalid_us_bank_account_nonce(self):
customer_id = Customer.create().customer.id
result = PaymentMethod.create({
"customer_id": customer_id,
"payment_method_nonce": TestHelper.generate_invalid_us_bank_account_nonce()
})
self.assertFalse(result.is_success)
error_code = result.errors.for_object("payment_method").on("payment_method_nonce")[0].code
self.assertEqual(ErrorCodes.PaymentMethod.PaymentMethodNonceUnknown, error_code)
def test_create_with_abstract_payment_method_nonce(self):
customer_id = Customer.create().customer.id
result = PaymentMethod.create({
"customer_id": customer_id,
"payment_method_nonce": Nonces.AbstractTransactable
})
self.assertTrue(result.is_success)
payment_method = result.payment_method
self.assertNotEqual(None, payment_method)
self.assertNotEqual(None, payment_method.token)
self.assertEqual(customer_id, payment_method.customer_id)
def test_create_with_custom_card_verification_amount(self):
config = Configuration.instantiate()
customer_id = Customer.create().customer.id
client_token = json.loads(TestHelper.generate_decoded_client_token())
authorization_fingerprint = client_token["authorizationFingerprint"]
http = ClientApiHttp(config, {
"authorization_fingerprint": authorization_fingerprint,
"shared_customer_identifier": "fake_identifier",
"shared_customer_identifier_type": "testing"
})
status_code, nonce = http.get_credit_card_nonce({
"number": "4000111111111115",
"expirationMonth": "11",
"expirationYear": "2099"
})
self.assertTrue(status_code == 201)
result = PaymentMethod.create({
"customer_id": customer_id,
"payment_method_nonce": nonce,
"options": {
"verify_card": "true",
"verification_amount": "1.02"
}
})
self.assertFalse(result.is_success)
verification = result.credit_card_verification
self.assertEqual(CreditCardVerification.Status.ProcessorDeclined, verification.status)
def test_create_respects_verify_card_and_verification_merchant_account_id_when_outside_nonce(self):
config = Configuration.instantiate()
customer_id = Customer.create().customer.id
client_token = json.loads(TestHelper.generate_decoded_client_token())
authorization_fingerprint = client_token["authorizationFingerprint"]
http = ClientApiHttp(config, {
"authorization_fingerprint": authorization_fingerprint,
"shared_customer_identifier": "fake_identifier",
"shared_customer_identifier_type": "testing"
})
status_code, nonce = http.get_credit_card_nonce({
"number": "4000111111111115",
"expirationMonth": "11",
"expirationYear": "2099"
})
self.assertTrue(status_code == 201)
result = PaymentMethod.create({
"payment_method_nonce": nonce,
"customer_id": customer_id,
"options": {
"verify_card": "true",
"verification_merchant_account_id": TestHelper.non_default_merchant_account_id
}
})
self.assertFalse(result.is_success)
self.assertTrue(result.credit_card_verification.status == Transaction.Status.ProcessorDeclined)
self.assertTrue(result.credit_card_verification.processor_response_code == "2000")
self.assertTrue(result.credit_card_verification.processor_response_text == "Do Not Honor")
self.assertTrue(result.credit_card_verification.merchant_account_id == TestHelper.non_default_merchant_account_id)
def test_create_respects_fail_one_duplicate_payment_method_when_included_outside_of_the_nonce(self):
customer_id = Customer.create().customer.id
credit_card_result = CreditCard.create({
"customer_id": customer_id,
"number": CreditCardNumbers.Visa,
"expiration_date": "05/2012"
})
self.assertTrue(credit_card_result.is_success)
config = Configuration.instantiate()
customer_id = Customer.create().customer.id
client_token = json.loads(TestHelper.generate_decoded_client_token())
authorization_fingerprint = client_token["authorizationFingerprint"]
http = ClientApiHttp(config, {
"authorization_fingerprint": authorization_fingerprint,
"shared_customer_identifier": "fake_identifier",
"shared_customer_identifier_type": "testing"
})
status_code, nonce = http.get_credit_card_nonce({
"number": CreditCardNumbers.Visa,
"expiration_date": "05/2012"
})
self.assertTrue(status_code == 201)
result = PaymentMethod.create({
"payment_method_nonce": nonce,
"customer_id": customer_id,
"options": {
"fail_on_duplicate_payment_method": "true"
}
})
self.assertFalse(result.is_success)
self.assertTrue(result.errors.deep_errors[0].code == "81724")
def test_create_allows_passing_billing_address_id_outside_the_nonce(self):
customer_id = Customer.create().customer.id
http = ClientApiHttp.create()
status_code, nonce = http.get_credit_card_nonce({
"number": "4111111111111111",
"expirationMonth": "12",
"expirationYear": "2020",
"options": {"validate": "false"}
})
self.assertTrue(status_code == 202)
address_result = Address.create({
"customer_id": customer_id,
"first_name": "Bobby",
"last_name": "Tables"
})
self.assertTrue(address_result.is_success)
payment_method_result = PaymentMethod.create({
"payment_method_nonce": nonce,
"customer_id": customer_id,
"billing_address_id": address_result.address.id
})
self.assertTrue(payment_method_result.is_success)
self.assertTrue(isinstance(payment_method_result.payment_method, CreditCard))
token = payment_method_result.payment_method.token
found_credit_card = CreditCard.find(token)
self.assertFalse(found_credit_card is None)
self.assertTrue(found_credit_card.billing_address.first_name == "Bobby")
self.assertTrue(found_credit_card.billing_address.last_name == "Tables")
def test_create_allows_passing_billing_address_outside_the_nonce(self):
customer_id = Customer.create().customer.id
http = ClientApiHttp.create()
status_code, nonce = http.get_credit_card_nonce({
"number": "4111111111111111",
"expirationMonth": "12",
"expirationYear": "2020",
"options": {"validate": "false"}
})
self.assertTrue(status_code == 202)
result = PaymentMethod.create({
"payment_method_nonce": nonce,
"customer_id": customer_id,
"billing_address": {
"street_address": "123 Abc Way"
}
})
self.assertTrue(result.is_success)
self.assertTrue(isinstance(result.payment_method, CreditCard))
token = result.payment_method.token
found_credit_card = CreditCard.find(token)
self.assertFalse(found_credit_card is None)
self.assertTrue(found_credit_card.billing_address.street_address == "123 Abc Way")
def test_create_overrides_the_billing_address_in_the_nonce(self):
customer_id = Customer.create().customer.id
http = ClientApiHttp.create()
status_code, nonce = http.get_credit_card_nonce({
"number": "4111111111111111",
"expirationMonth": "12",
"expirationYear": "2020",
"options": {"validate": "false"},
"billing_address": {
"street_address": "456 Xyz Way"
}
})
self.assertTrue(status_code == 202)
result = PaymentMethod.create({
"payment_method_nonce": nonce,
"customer_id": customer_id,
"billing_address": {
"street_address": "123 Abc Way"
}
})
self.assertTrue(result.is_success)
self.assertTrue(isinstance(result.payment_method, CreditCard))
token = result.payment_method.token
found_credit_card = CreditCard.find(token)
self.assertFalse(found_credit_card is None)
self.assertTrue(found_credit_card.billing_address.street_address == "123 Abc Way")
def test_create_does_not_override_the_billing_address_for_a_valuted_credit_card(self):
config = Configuration.instantiate()
customer_id = Customer.create().customer.id
client_token = json.loads(TestHelper.generate_decoded_client_token({"customer_id": customer_id}))
authorization_fingerprint = client_token["authorizationFingerprint"]
http = ClientApiHttp(config, {"authorization_fingerprint": authorization_fingerprint})
status_code, nonce = http.get_credit_card_nonce({
"number": "4111111111111111",
"expirationMonth": "12",
"expirationYear": "2020",
"billing_address": {
"street_address": "456 Xyz Way"
}
})
self.assertTrue(status_code == 201)
result = PaymentMethod.create({
"payment_method_nonce": nonce,
"customer_id": customer_id,
"billing_address": {
"street_address": "123 Abc Way"
}
})
self.assertTrue(result.is_success)
self.assertTrue(isinstance(result.payment_method, CreditCard))
token = result.payment_method.token
found_credit_card = CreditCard.find(token)
self.assertFalse(found_credit_card is None)
self.assertTrue(found_credit_card.billing_address.street_address == "456 Xyz Way")
def test_create_does_not_return_an_error_if_credit_card_options_are_present_for_paypal_nonce(self):
customer_id = Customer.create().customer.id
original_token = "paypal-account-" + str(int(time.time()))
nonce = TestHelper.nonce_for_paypal_account({
"consent_code": "consent-code",
"token": original_token
})
result = PaymentMethod.create({
"payment_method_nonce": nonce,
"customer_id": customer_id,
"options": {
"verify_card": "true",
"fail_on_duplicate_payment_method": "true",
"verification_merchant_account_id": "not_a_real_merchant_account_id"
}
})
self.assertTrue(result.is_success)
def test_create_for_paypal_ignores_passed_billing_address_id(self):
nonce = TestHelper.nonce_for_paypal_account({
"consent_code": "consent-code"
})
customer_id = Customer.create().customer.id
result = PaymentMethod.create({
"payment_method_nonce": nonce,
"customer_id": customer_id,
"billing_address_id": "address_id"
})
self.assertTrue(result.is_success)
self.assertTrue(isinstance(result.payment_method, PayPalAccount))
self.assertFalse(result.payment_method.image_url is None)
token = result.payment_method.token
found_paypal_account = PayPalAccount.find(token)
self.assertFalse(found_paypal_account is None)
def test_create_for_paypal_ignores_passed_billing_address_params(self):
nonce = TestHelper.nonce_for_paypal_account({
"consent_code": "PAYPAL_CONSENT_CODE"
})
customer_id = Customer.create().customer.id
result = PaymentMethod.create({
"payment_method_nonce": nonce,
"customer_id": customer_id,
"billing_address": {
"street_address": "123 Abc Way"
}
})
self.assertTrue(result.is_success)
self.assertTrue(isinstance(result.payment_method, PayPalAccount))
self.assertFalse(result.payment_method.image_url is None)
token = result.payment_method.token
found_paypal_account = PayPalAccount.find(token)
self.assertFalse(found_paypal_account is None)
def test_find_returns_an_abstract_payment_method(self):
customer_id = Customer.create().customer.id
result = PaymentMethod.create({
"customer_id": customer_id,
"payment_method_nonce": Nonces.AbstractTransactable
})
self.assertTrue(result.is_success)
found_payment_method = PaymentMethod.find(result.payment_method.token)
self.assertNotEqual(None, found_payment_method)
self.assertEqual(found_payment_method.token, result.payment_method.token)
def test_find_returns_a_paypal_account(self):
customer_id = Customer.create().customer.id
result = PaymentMethod.create({
"customer_id": customer_id,
"payment_method_nonce": Nonces.PayPalFuturePayment
})
self.assertTrue(result.is_success)
found_account = PaymentMethod.find(result.payment_method.token)
self.assertNotEqual(None, found_account)
self.assertEqual(PayPalAccount, found_account.__class__)
self.assertEqual("jane.doe@example.com", found_account.email)
def test_find_returns_a_credit_card(self):
customer = Customer.create().customer
result = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "05/2009",
"cvv": "100",
"cardholder_name": "John Doe"
})
self.assertTrue(result.is_success)
found_credit_card = PaymentMethod.find(result.credit_card.token)
self.assertNotEqual(None, found_credit_card)
self.assertEqual(CreditCard, found_credit_card.__class__)
self.assertEqual("411111", found_credit_card.bin)
def test_find_returns_an_android_pay_card(self):
customer = Customer.create().customer
result = PaymentMethod.create({
"customer_id": customer.id,
"payment_method_nonce": Nonces.AndroidPayCard
})
self.assertTrue(result.is_success)
android_pay_card = result.payment_method
found_android_pay_card = PaymentMethod.find(android_pay_card.token)
self.assertNotEqual(None, found_android_pay_card)
self.assertEqual(AndroidPayCard, found_android_pay_card.__class__)
self.assertEqual(found_android_pay_card.token, android_pay_card.token)
def test_delete_deletes_a_credit_card(self):
customer = Customer.create().customer
result = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "05/2009",
"cvv": "100",
"cardholder_name": "John Doe"
})
self.assertTrue(result.is_success)
delete_result = PaymentMethod.delete(result.credit_card.token)
self.assertTrue(delete_result.is_success)
self.assertRaises(NotFoundError, PaymentMethod.find, result.credit_card.token)
def test_delete_deletes_a_paypal_account(self):
customer_id = Customer.create().customer.id
result = PaymentMethod.create({
"customer_id": customer_id,
"payment_method_nonce": Nonces.PayPalFuturePayment
})
self.assertTrue(result.is_success)
delete_result = PaymentMethod.delete(result.payment_method.token, {"revoke_all_grants": False})
self.assertTrue(delete_result.is_success)
self.assertRaises(NotFoundError, PaymentMethod.find, result.payment_method.token)
def test_update_credit_cards_updates_the_credit_card(self):
customer_id = Customer.create().customer.id
credit_card_result = CreditCard.create({
"cardholder_name": "Original Holder",
"customer_id": customer_id,
"cvv": "123",
"number": CreditCardNumbers.Visa,
"expiration_date": "05/2012"
})
update_result = PaymentMethod.update(credit_card_result.credit_card.token, {
"cardholder_name": "New Holder",
"cvv": "456",
"number": CreditCardNumbers.MasterCard,
"expiration_date": "06/2013"
})
self.assertTrue(update_result.is_success)
self.assertTrue(update_result.payment_method.token == credit_card_result.credit_card.token)
updated_credit_card = update_result.payment_method
self.assertTrue(updated_credit_card.bin == CreditCardNumbers.MasterCard[:6])
self.assertTrue(updated_credit_card.last_4 == CreditCardNumbers.MasterCard[-4:])
self.assertTrue(updated_credit_card.expiration_date == "06/2013")
def test_update_creates_a_new_billing_address_by_default(self):
customer_id = Customer.create().customer.id
credit_card_result = CreditCard.create({
"customer_id": customer_id,
"number": CreditCardNumbers.Visa,
"expiration_date": "05/2012",
"billing_address": {
"street_address": "123 Nigeria Ave"
}
})
update_result = PaymentMethod.update(credit_card_result.credit_card.token, {
"billing_address": {
"region": "IL"
}
})
self.assertTrue(update_result.is_success)
updated_credit_card = update_result.payment_method
self.assertTrue(updated_credit_card.billing_address.region == "IL")
self.assertTrue(updated_credit_card.billing_address.street_address is None)
self.assertFalse(updated_credit_card.billing_address.id == credit_card_result.credit_card.billing_address.id)
def test_update_updates_the_billing_address_if_option_is_specified(self):
customer_id = Customer.create().customer.id
credit_card_result = CreditCard.create({
"customer_id": customer_id,
"number": CreditCardNumbers.Visa,
"expiration_date": "05/2012",
"billing_address": {
"street_address": "123 Nigeria Ave"
}
})
update_result = PaymentMethod.update(credit_card_result.credit_card.token, {
"billing_address": {
"region": "IL",
"options": {
"update_existing": "true"
}
}
})
self.assertTrue(update_result.is_success)
updated_credit_card = update_result.payment_method
self.assertTrue(updated_credit_card.billing_address.region == "IL")
self.assertTrue(updated_credit_card.billing_address.street_address == "123 Nigeria Ave")
self.assertTrue(updated_credit_card.billing_address.id == credit_card_result.credit_card.billing_address.id)
def test_update_updates_the_country_via_codes(self):
customer_id = Customer.create().customer.id
credit_card_result = CreditCard.create({
"customer_id": customer_id,
"number": CreditCardNumbers.Visa,
"expiration_date": "05/2012",
"billing_address": {
"street_address": "123 Nigeria Ave"
}
})
update_result = PaymentMethod.update(credit_card_result.credit_card.token, {
"billing_address": {
"country_name": "American Samoa",
"country_code_alpha2": "AS",
"country_code_alpha3": "ASM",
"country_code_numeric": "016",
"options": {
"update_existing": "true"
}
}
})
self.assertTrue(update_result.is_success)
updated_credit_card = update_result.payment_method
self.assertTrue(updated_credit_card.billing_address.country_name == "American Samoa")
self.assertTrue(updated_credit_card.billing_address.country_code_alpha2 == "AS")
self.assertTrue(updated_credit_card.billing_address.country_code_alpha3 == "ASM")
self.assertTrue(updated_credit_card.billing_address.country_code_numeric == "016")
def test_update_can_pass_expiration_month_and_expiration_year(self):
customer_id = Customer.create().customer.id
credit_card_result = CreditCard.create({
"customer_id": customer_id,
"number": CreditCardNumbers.Visa,
"expiration_date": "05/2012"
})
update_result = PaymentMethod.update(credit_card_result.credit_card.token, {
"number": CreditCardNumbers.MasterCard,
"expiration_month": "07",
"expiration_year": "2011"
})
self.assertTrue(update_result.is_success)
self.assertTrue(update_result.payment_method.token == credit_card_result.credit_card.token)
updated_credit_card = update_result.payment_method
self.assertTrue(updated_credit_card.expiration_month == "07")
self.assertTrue(updated_credit_card.expiration_year == "2011")
self.assertTrue(updated_credit_card.expiration_date == "07/2011")
def test_update_verifies_the_update_if_options_verify_card_is_true(self):
customer_id = Customer.create().customer.id
credit_card_result = CreditCard.create({
"cardholder_name": "Original Holder",
"customer_id": customer_id,
"cvv": "123",
"number": CreditCardNumbers.Visa,
"expiration_date": "05/2012"
})
update_result = PaymentMethod.update(credit_card_result.credit_card.token, {
"cardholder_name": "New Holder",
"cvv": "456",
"number": CreditCardNumbers.FailsSandboxVerification.MasterCard,
"expiration_date": "06/2013",
"options": {
"verify_card": "true"
}
})
self.assertFalse(update_result.is_success)
self.assertTrue(update_result.credit_card_verification.status == CreditCardVerification.Status.ProcessorDeclined)
self.assertTrue(update_result.credit_card_verification.gateway_rejection_reason is None)
def test_update_can_pass_custom_verification_amount(self):
customer_id = Customer.create().customer.id
credit_card_result = CreditCard.create({
"cardholder_name": "Card Holder",
"customer_id": customer_id,
"cvv": "123",
"number": CreditCardNumbers.Visa,
"expiration_date": "05/2020"
})
update_result = PaymentMethod.update(credit_card_result.credit_card.token, {
"payment_method_nonce": Nonces.ProcessorDeclinedMasterCard,
"options": {
"verify_card": "true",
"verification_amount": "2.34"
}
})
self.assertFalse(update_result.is_success)
self.assertTrue(update_result.credit_card_verification.status == CreditCardVerification.Status.ProcessorDeclined)
self.assertTrue(update_result.credit_card_verification.gateway_rejection_reason is None)
def test_update_can_update_the_billing_address(self):
customer_id = Customer.create().customer.id
credit_card_result = CreditCard.create({
"cardholder_name": "Original Holder",
"customer_id": customer_id,
"cvv": "123",
"number": CreditCardNumbers.Visa,
"expiration_date": "05/2012",
"billing_address": {
"first_name": "Old First Name",
"last_name": "Old Last Name",
"company": "Old Company",
"street_address": "123 Old St",
"extended_address": "Apt Old",
"locality": "Old City",
"region": "Old State",
"postal_code": "12345",
"country_name": "Canada"
}
})
update_result = PaymentMethod.update(credit_card_result.credit_card.token, {
"options": {"verify_card": "false"},
"billing_address": {
"first_name": "New First Name",
"last_name": "New Last Name",
"company": "New Company",
"street_address": "123 New St",
"extended_address": "Apt New",
"locality": "New City",
"region": "New State",
"postal_code": "56789",
"country_name": "United States of America"
}
})
self.assertTrue(update_result.is_success)
address = update_result.payment_method.billing_address
self.assertTrue(address.first_name == "New First Name")
self.assertTrue(address.last_name == "New Last Name")
self.assertTrue(address.company == "New Company")
self.assertTrue(address.street_address == "123 New St")
self.assertTrue(address.extended_address == "Apt New")
self.assertTrue(address.locality == "New City")
self.assertTrue(address.region == "New State")
self.assertTrue(address.postal_code == "56789")
self.assertTrue(address.country_name == "United States of America")
def test_update_returns_an_error_response_if_invalid(self):
customer_id = Customer.create().customer.id
credit_card_result = CreditCard.create({
"cardholder_name": "Original Holder",
"customer_id": customer_id,
"number": CreditCardNumbers.Visa,
"expiration_date": "05/2012"
})
update_result = PaymentMethod.update(credit_card_result.credit_card.token, {
"cardholder_name": "New Holder",
"number": "invalid",
"expiration_date": "05/2014",
})
self.assertFalse(update_result.is_success)
number_errors = update_result.errors.for_object("credit_card").on("number")
self.assertEqual(1, len(number_errors))
self.assertEqual("Credit card number must be 12-19 digits.", number_errors[0].message)
def test_update_can_update_the_default(self):
customer_id = Customer.create().customer.id
card1 = CreditCard.create({
"customer_id": customer_id,
"number": CreditCardNumbers.Visa,
"expiration_date": "05/2009"
}).credit_card
card2 = CreditCard.create({
"customer_id": customer_id,
"number": CreditCardNumbers.Visa,
"expiration_date": "05/2009"
}).credit_card
self.assertTrue(card1.default)
self.assertFalse(card2.default)
PaymentMethod.update(card2.token, {
"options": {"make_default": True}
})
self.assertFalse(CreditCard.find(card1.token).default)
self.assertTrue(CreditCard.find(card2.token).default)
def test_update_updates_a_paypal_accounts_token(self):
customer_id = Customer.create().customer.id
original_token = "paypal-account-" + str(int(time.time()))
nonce = TestHelper.nonce_for_paypal_account({
"consent_code": "consent-code",
"token": original_token
})
original_result = PaymentMethod.create({
"payment_method_nonce": nonce,
"customer_id": customer_id
})
updated_token = "UPDATED_TOKEN-" + str(random.randint(0, 100000000))
PaymentMethod.update(
original_token,
{"token": updated_token}
)
updated_paypal_account = PayPalAccount.find(updated_token)
self.assertTrue(updated_paypal_account.email == original_result.payment_method.email)
self.assertRaises(NotFoundError, PaymentMethod.find, original_token)
def test_update_can_make_a_paypal_account_the_default_payment_method(self):
customer_id = Customer.create().customer.id
credit_card_result = CreditCard.create({
"customer_id": customer_id,
"number": CreditCardNumbers.Visa,
"expiration_date": "05/2009",
"options": {"make_default": "true"}
})
self.assertTrue(credit_card_result.is_success)
nonce = TestHelper.nonce_for_paypal_account({
"consent_code": "consent-code"
})
original_token = PaymentMethod.create({
"payment_method_nonce": nonce,
"customer_id": customer_id
}).payment_method.token
PaymentMethod.update(
original_token,
{"options": {"make_default": "true"}}
)
updated_paypal_account = PayPalAccount.find(original_token)
self.assertTrue(updated_paypal_account.default)
def test_update_fails_to_updates_a_paypal_accounts_token_with(self):
customer_id = Customer.create().customer.id
first_token = "paypal-account-" + str(random.randint(0, 100000000))
second_token = "paypal-account-" + str(random.randint(0, 100000000))
first_nonce = TestHelper.nonce_for_paypal_account({
"consent_code": "consent-code",
"token": first_token
})
PaymentMethod.create({
"payment_method_nonce": first_nonce,
"customer_id": customer_id
})
second_nonce = TestHelper.nonce_for_paypal_account({
"consent_code": "consent-code",
"token": second_token
})
PaymentMethod.create({
"payment_method_nonce": second_nonce,
"customer_id": customer_id
})
updated_result = PaymentMethod.update(
first_token,
{"token": second_token}
)
self.assertFalse(updated_result.is_success)
errors = updated_result.errors.deep_errors
self.assertEqual(1, len(errors))
self.assertEqual("92906", errors[0].code)
def test_payment_method_grant_raises_on_non_existent_tokens(self):
granting_gateway, _ = TestHelper.create_payment_method_grant_fixtures()
self.assertRaises(NotFoundError, granting_gateway.payment_method.grant, "non-existant-token", False)
def test_payment_method_grant_returns_one_time_nonce(self):
"""
Payment method grant returns a nonce that is transactable by a partner merchant exactly once
"""
granting_gateway, credit_card = TestHelper.create_payment_method_grant_fixtures()
grant_result = granting_gateway.payment_method.grant(credit_card.token, { "allow_vaulting": False });
self.assertTrue(grant_result.is_success)
result = Transaction.sale({
"payment_method_nonce": grant_result.payment_method_nonce.nonce,
"amount": TransactionAmounts.Authorize
})
self.assertTrue(result.is_success)
result = Transaction.sale({
"payment_method_nonce": grant_result.payment_method_nonce.nonce,
"amount": TransactionAmounts.Authorize
})
self.assertFalse(result.is_success)
def test_payment_method_grant_returns_a_nonce_that_is_not_vaultable(self):
granting_gateway, credit_card = TestHelper.create_payment_method_grant_fixtures()
grant_result = granting_gateway.payment_method.grant(credit_card.token, False)
customer_id = Customer.create().customer.id
result = PaymentMethod.create({
"customer_id": customer_id,
"payment_method_nonce": grant_result.payment_method_nonce.nonce
})
self.assertFalse(result.is_success)
def test_payment_method_grant_returns_a_nonce_that_is_vaultable(self):
granting_gateway, credit_card = TestHelper.create_payment_method_grant_fixtures()
grant_result = granting_gateway.payment_method.grant(credit_card.token, { "allow_vaulting": True })
customer_id = Customer.create().customer.id
result = PaymentMethod.create({
"customer_id": customer_id,
"payment_method_nonce": grant_result.payment_method_nonce.nonce
})
self.assertTrue(result.is_success)
def test_payment_method_revoke_renders_a_granted_nonce_unusable(self):
granting_gateway, credit_card = TestHelper.create_payment_method_grant_fixtures()
grant_result = granting_gateway.payment_method.grant(credit_card.token)
revoke_result = granting_gateway.payment_method.revoke(credit_card.token)
self.assertTrue(revoke_result.is_success)
result = Transaction.sale({
"payment_method_nonce": grant_result.payment_method_nonce.nonce,
"amount": TransactionAmounts.Authorize
})
self.assertFalse(result.is_success)
def test_payment_method_revoke_raises_on_non_existent_tokens(self):
granting_gateway, _ = TestHelper.create_payment_method_grant_fixtures()
self.assertRaises(NotFoundError, granting_gateway.payment_method.revoke, "non-existant-token")
class CreditCardForwardingTest(unittest.TestCase):
def setUp(self):
braintree.Configuration.configure(
braintree.Environment.Development,
"forward_payment_method_merchant_id",
"forward_payment_method_public_key",
"forward_payment_method_private_key"
)
def tearDown(self):
braintree.Configuration.configure(
braintree.Environment.Development,
"integration_merchant_id",
"integration_public_key",
"integration_private_key"
)
def test_forward(self):
customer = Customer.create().customer
credit_card_result = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "05/2025"
})
self.assertTrue(credit_card_result.is_success)
source_merchant_card = credit_card_result.credit_card
forward_result = CreditCard.forward(
source_merchant_card.token,
"integration_merchant_id"
)
self.assertTrue(forward_result.is_success)
braintree.Configuration.configure(
braintree.Environment.Development,
"integration_merchant_id",
"integration_public_key",
"integration_private_key"
)
customer = Customer.create().customer
credit_card_result = CreditCard.create({
"customer_id": customer.id,
"payment_method_nonce": forward_result.nonce
})
self.assertTrue(credit_card_result.is_success)
receiving_merchant_card = credit_card_result.credit_card
self.assertEqual(source_merchant_card.bin, receiving_merchant_card.bin)
self.assertEqual(source_merchant_card.last_4, receiving_merchant_card.last_4)
self.assertEqual(source_merchant_card.expiration_month, receiving_merchant_card.expiration_month)
self.assertEqual(source_merchant_card.expiration_year, receiving_merchant_card.expiration_year)
def test_forward_invalid_token_raises_exception(self):
self.assertRaises(NotFoundError, CreditCard.forward, "invalid", "integration_merchant_id")
def test_forward_invalid_receiving_merchant_raises_exception(self):
customer = Customer.create().customer
credit_card_result = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "05/2025"
})
self.assertTrue(credit_card_result.is_success)
source_merchant_card = credit_card_result.credit_card
self.assertRaises(NotFoundError, CreditCard.forward, source_merchant_card.token, "invalid_merchant_id")
braintree_python-3.38.0/tests/integration/test_client_token.py 0000644 0001750 0001750 00000015132 13150065776 023053 0 ustar hle hle from tests.test_helper import *
import json
import urllib
import datetime
import braintree
from braintree.util import Http
from base64 import b64decode
class TestClientTokenGenerate(unittest.TestCase):
def test_allows_client_token_version_to_be_specified(self):
client_token = ClientToken.generate({"version": 1})
version = json.loads(client_token)["version"]
self.assertEqual(1, version)
def test_error_in_generate_raises_value_error(self):
self.assertRaises(ValueError, ClientToken.generate, {
"customer_id": "i_am_not_a_real_customer"
})
class TestClientToken(unittest.TestCase):
def test_is_authorized_with_authorization_fingerprint(self):
config = Configuration.instantiate()
client_token = TestHelper.generate_decoded_client_token()
authorization_fingerprint = json.loads(client_token)["authorizationFingerprint"]
http = ClientApiHttp(config, {
"authorization_fingerprint": authorization_fingerprint,
"shared_customer_identifier": "fake_identifier",
"shared_customer_identifier_type": "testing"
})
status_code, _ = http.get_cards()
self.assertEqual(200, status_code)
def test_client_token_version_defaults_to_two(self):
client_token = TestHelper.generate_decoded_client_token()
version = json.loads(client_token)["version"]
self.assertEqual(2, version)
def test_can_pass_verify_card(self):
config = Configuration.instantiate()
result = braintree.Customer.create()
customer_id = result.customer.id
client_token = TestHelper.generate_decoded_client_token({
"customer_id": customer_id,
"options": {
"verify_card": True
}
})
authorization_fingerprint = json.loads(client_token)["authorizationFingerprint"]
http = ClientApiHttp(config, {
"authorization_fingerprint": authorization_fingerprint,
"shared_customer_identifier": "fake_identifier",
"shared_customer_identifier_type": "testing"
})
status_code, _ = http.add_card({
"credit_card": {
"number": "4000111111111115",
"expiration_month": "11",
"expiration_year": "2099",
}
})
self.assertEqual(422, status_code)
def test_can_pass_make_default(self):
config = Configuration.instantiate()
result = braintree.Customer.create()
customer_id = result.customer.id
client_token = TestHelper.generate_decoded_client_token({
"customer_id": customer_id,
"options": {
"make_default": True
}
})
authorization_fingerprint = json.loads(client_token)["authorizationFingerprint"]
http = ClientApiHttp(config, {
"authorization_fingerprint": authorization_fingerprint,
"shared_customer_identifier": "fake_identifier",
"shared_customer_identifier_type": "testing"
})
status_code, _ = http.add_card({
"credit_card": {
"number": "4111111111111111",
"expiration_month": "11",
"expiration_year": "2099",
}
})
self.assertEqual(201, status_code)
status_code, _ = http.add_card({
"credit_card": {
"number": "4005519200000004",
"expiration_month": "11",
"expiration_year": "2099",
}
})
self.assertEqual(201, status_code)
customer = braintree.Customer.find(customer_id)
self.assertEqual(2, len(customer.credit_cards))
for credit_card in customer.credit_cards:
if credit_card.bin == "400551":
self.assertTrue(credit_card.default)
def test_can_pass_fail_on_duplicate_payment_method(self):
config = Configuration.instantiate()
result = braintree.Customer.create()
customer_id = result.customer.id
client_token = TestHelper.generate_decoded_client_token({
"customer_id": customer_id,
})
authorization_fingerprint = json.loads(client_token)["authorizationFingerprint"]
http = ClientApiHttp(config, {
"authorization_fingerprint": authorization_fingerprint,
"shared_customer_identifier": "fake_identifier",
"shared_customer_identifier_type": "testing"
})
status_code, _ = http.add_card({
"credit_card": {
"number": "4111111111111111",
"expiration_month": "11",
"expiration_year": "2099",
}
})
self.assertEqual(201, status_code)
client_token = TestHelper.generate_decoded_client_token({
"customer_id": customer_id,
"options": {
"fail_on_duplicate_payment_method": True
}
})
authorization_fingerprint = json.loads(client_token)["authorizationFingerprint"]
http.set_authorization_fingerprint(authorization_fingerprint)
status_code, _ = http.add_card({
"credit_card": {
"number": "4111111111111111",
"expiration_month": "11",
"expiration_year": "2099",
}
})
self.assertEqual(422, status_code)
customer = braintree.Customer.find(customer_id)
self.assertEqual(1, len(customer.credit_cards))
def test_can_pass_sepa_params(self):
result = braintree.Customer.create()
customer_id = result.customer.id
client_token = TestHelper.generate_decoded_client_token({
"customer_id": customer_id,
"sepa_mandate_acceptance_location": "Hamburg, Germany",
"sepa_mandate_type": EuropeBankAccount.MandateType.Business
})
authorization_fingerprint = json.loads(client_token)["authorizationFingerprint"]
self.assertNotEqual(authorization_fingerprint, None)
def test_can_pass_merchant_account_id(self):
expected_merchant_account_id = TestHelper.non_default_merchant_account_id
client_token = TestHelper.generate_decoded_client_token({
"merchant_account_id": expected_merchant_account_id
})
merchant_account_id = json.loads(client_token)["merchantAccountId"]
self.assertEqual(expected_merchant_account_id, merchant_account_id)
@raises_with_regexp(Exception, "'Invalid keys: merchant_id'")
def test_required_data_cannot_be_overridden(self):
TestHelper.generate_decoded_client_token({
"merchant_id": "1234"
})
braintree_python-3.38.0/tests/integration/test_search.py 0000644 0001750 0001750 00000031466 13150065776 021652 0 ustar hle hle from tests.test_helper import *
class TestSearch(unittest.TestCase):
def test_text_node_is(self):
credit_card = Customer.create({
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2010",
}
}).customer.credit_cards[0]
trial_subscription = Subscription.create({
"payment_method_token": credit_card.token,
"plan_id": TestHelper.trial_plan["id"]
}).subscription
trialless_subscription = Subscription.create({
"payment_method_token": credit_card.token,
"plan_id": TestHelper.trialless_plan["id"]
}).subscription
collection = Subscription.search([
SubscriptionSearch.plan_id == "integration_trial_plan"
])
self.assertTrue(TestHelper.includes(collection, trial_subscription))
self.assertFalse(TestHelper.includes(collection, trialless_subscription))
def test_text_node_is_not(self):
credit_card = Customer.create({
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2010",
}
}).customer.credit_cards[0]
trial_subscription = Subscription.create({
"payment_method_token": credit_card.token,
"plan_id": TestHelper.trial_plan["id"]
}).subscription
trialless_subscription = Subscription.create({
"payment_method_token": credit_card.token,
"plan_id": TestHelper.trialless_plan["id"]
}).subscription
collection = Subscription.search([
SubscriptionSearch.plan_id != "integration_trialless_plan"
])
self.assertTrue(TestHelper.includes(collection, trial_subscription))
self.assertFalse(TestHelper.includes(collection, trialless_subscription))
def test_text_node_starts_with(self):
credit_card = Customer.create({
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2010",
}
}).customer.credit_cards[0]
trial_subscription = Subscription.create({
"payment_method_token": credit_card.token,
"plan_id": TestHelper.trial_plan["id"]
}).subscription
trialless_subscription = Subscription.create({
"payment_method_token": credit_card.token,
"plan_id": TestHelper.trialless_plan["id"]
}).subscription
collection = Subscription.search([
SubscriptionSearch.plan_id.starts_with("integration_trial_p")
])
self.assertTrue(TestHelper.includes(collection, trial_subscription))
self.assertFalse(TestHelper.includes(collection, trialless_subscription))
def test_text_node_ends_with(self):
credit_card = Customer.create({
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2010",
}
}).customer.credit_cards[0]
trial_subscription = Subscription.create({
"payment_method_token": credit_card.token,
"plan_id": TestHelper.trial_plan["id"]
}).subscription
trialless_subscription = Subscription.create({
"payment_method_token": credit_card.token,
"plan_id": TestHelper.trialless_plan["id"]
}).subscription
collection = Subscription.search([
SubscriptionSearch.plan_id.ends_with("trial_plan")
])
self.assertTrue(TestHelper.includes(collection, trial_subscription))
self.assertFalse(TestHelper.includes(collection, trialless_subscription))
def test_text_node_contains(self):
credit_card = Customer.create({
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2010",
}
}).customer.credit_cards[0]
trial_subscription = Subscription.create({
"payment_method_token": credit_card.token,
"plan_id": TestHelper.trial_plan["id"]
}).subscription
trialless_subscription = Subscription.create({
"payment_method_token": credit_card.token,
"plan_id": TestHelper.trialless_plan["id"]
}).subscription
collection = Subscription.search([
SubscriptionSearch.plan_id.contains("rial_pl")
])
self.assertTrue(TestHelper.includes(collection, trial_subscription))
self.assertFalse(TestHelper.includes(collection, trialless_subscription))
def test_multiple_value_node_in_list(self):
credit_card = Customer.create({
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2010",
}
}).customer.credit_cards[0]
active_subscription = Subscription.create({
"payment_method_token": credit_card.token,
"plan_id": TestHelper.trialless_plan["id"]
}).subscription
canceled_subscription = Subscription.create({
"payment_method_token": credit_card.token,
"plan_id": TestHelper.trialless_plan["id"]
}).subscription
Subscription.cancel(canceled_subscription.id)
collection = Subscription.search([
SubscriptionSearch.status.in_list([Subscription.Status.Active, Subscription.Status.Canceled])
])
self.assertTrue(TestHelper.includes(collection, active_subscription))
self.assertTrue(TestHelper.includes(collection, canceled_subscription))
def test_multiple_value_node_in_list_as_arg_list(self):
credit_card = Customer.create({
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2010",
}
}).customer.credit_cards[0]
active_subscription = Subscription.create({
"payment_method_token": credit_card.token,
"plan_id": TestHelper.trialless_plan["id"]
}).subscription
canceled_subscription = Subscription.create({
"payment_method_token": credit_card.token,
"plan_id": TestHelper.trialless_plan["id"]
}).subscription
Subscription.cancel(canceled_subscription.id)
collection = Subscription.search([
SubscriptionSearch.status.in_list(Subscription.Status.Active, Subscription.Status.Canceled)
])
self.assertTrue(TestHelper.includes(collection, active_subscription))
self.assertTrue(TestHelper.includes(collection, canceled_subscription))
def test_multiple_value_node_is(self):
credit_card = Customer.create({
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2010",
}
}).customer.credit_cards[0]
active_subscription = Subscription.create({
"payment_method_token": credit_card.token,
"plan_id": TestHelper.trialless_plan["id"]
}).subscription
canceled_subscription = Subscription.create({
"payment_method_token": credit_card.token,
"plan_id": TestHelper.trialless_plan["id"]
}).subscription
Subscription.cancel(canceled_subscription.id)
collection = Subscription.search([
SubscriptionSearch.status == Subscription.Status.Active
])
self.assertTrue(TestHelper.includes(collection, active_subscription))
self.assertFalse(TestHelper.includes(collection, canceled_subscription))
def test_range_node_min(self):
name = "Henrietta Livingston%s" % random.randint(1, 100000)
Transaction.sale({
"amount": "1500.00",
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012",
"cardholder_name": name
}
})
t_1800 = Transaction.sale({
"amount": "1800.00",
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012",
"cardholder_name": name
}
}).transaction
collection = Transaction.search([
TransactionSearch.credit_card_cardholder_name == name,
TransactionSearch.amount >= "1700"
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(t_1800.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.credit_card_cardholder_name == name,
TransactionSearch.amount.greater_than_or_equal_to("1700")
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(t_1800.id, collection.first.id)
def test_range_node_max(self):
name = "Henrietta Livingston%s" % random.randint(1, 100000)
t_1500 = Transaction.sale({
"amount": "1500.00",
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012",
"cardholder_name": name
}
}).transaction
Transaction.sale({
"amount": "1800.00",
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012",
"cardholder_name": name
}
})
collection = Transaction.search([
TransactionSearch.credit_card_cardholder_name == name,
TransactionSearch.amount <= "1700"
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(t_1500.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.credit_card_cardholder_name == name,
TransactionSearch.amount.less_than_or_equal_to("1700")
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(t_1500.id, collection.first.id)
def test_range_node_is(self):
name = "Henrietta Livingston%s" % random.randint(1, 100000)
Transaction.sale({
"amount": "1500.00",
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012",
"cardholder_name": name
}
})
t_1800 = Transaction.sale({
"amount": "1800.00",
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012",
"cardholder_name": name
}
}).transaction
collection = Transaction.search([
TransactionSearch.credit_card_cardholder_name == name,
TransactionSearch.amount == "1800"
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(t_1800.id, collection.first.id)
def test_range_node_between(self):
name = "Henrietta Livingston%s" % random.randint(1, 100000)
Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012",
"cardholder_name": name
}
})
t_1500 = Transaction.sale({
"amount": "1500.00",
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012",
"cardholder_name": name
}
}).transaction
Transaction.sale({
"amount": "1800.00",
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012",
"cardholder_name": name
}
})
collection = Transaction.search([
TransactionSearch.credit_card_cardholder_name == name,
TransactionSearch.amount.between("1100", "1600")
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(t_1500.id, collection.first.id)
def test_search_on_multiple_values(self):
credit_card = Customer.create({
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2010",
}
}).customer.credit_cards[0]
active_subscription = Subscription.create({
"payment_method_token": credit_card.token,
"plan_id": TestHelper.trialless_plan["id"]
}).subscription
canceled_subscription = Subscription.create({
"payment_method_token": credit_card.token,
"plan_id": TestHelper.trialless_plan["id"]
}).subscription
Subscription.cancel(canceled_subscription.id)
collection = Subscription.search([
SubscriptionSearch.plan_id == "integration_trialless_plan",
SubscriptionSearch.status.in_list([Subscription.Status.Active])
])
self.assertTrue(TestHelper.includes(collection, active_subscription))
self.assertFalse(TestHelper.includes(collection, canceled_subscription))
braintree_python-3.38.0/tests/integration/test_masterpass.py 0000644 0001750 0001750 00000010571 13150065776 022561 0 ustar hle hle from tests.test_helper import *
class TestMasterpass(unittest.TestCase):
def test_create_from_nonce(self):
customer = Customer.create().customer
result = PaymentMethod.create({
"customer_id": customer.id,
"payment_method_nonce": Nonces.MasterpassVisa
})
self.assertTrue(result.is_success)
masterpass_card = result.payment_method
self.assertIsNotNone(masterpass_card.billing_address)
self.assertIsNotNone(masterpass_card.bin)
self.assertIsNotNone(masterpass_card.card_type)
self.assertIsNotNone(masterpass_card.cardholder_name)
self.assertIsNotNone(masterpass_card.commercial)
self.assertIsNotNone(masterpass_card.country_of_issuance)
self.assertIsNotNone(masterpass_card.created_at)
self.assertIsNotNone(masterpass_card.customer_id)
self.assertIsNotNone(masterpass_card.customer_location)
self.assertIsNotNone(masterpass_card.debit)
self.assertIsNotNone(masterpass_card.default)
self.assertIsNotNone(masterpass_card.durbin_regulated)
self.assertIsNotNone(masterpass_card.expiration_date)
self.assertIsNotNone(masterpass_card.expiration_month)
self.assertIsNotNone(masterpass_card.expiration_year)
self.assertIsNotNone(masterpass_card.expired)
self.assertIsNotNone(masterpass_card.healthcare)
self.assertIsNotNone(masterpass_card.image_url)
self.assertIsNotNone(masterpass_card.issuing_bank)
self.assertIsNotNone(masterpass_card.last_4)
self.assertIsNotNone(masterpass_card.masked_number)
self.assertIsNotNone(masterpass_card.payroll)
self.assertIsNotNone(masterpass_card.prepaid)
self.assertIsNotNone(masterpass_card.product_id)
self.assertIsNotNone(masterpass_card.subscriptions)
self.assertIsNotNone(masterpass_card.token)
self.assertIsNotNone(masterpass_card.unique_number_identifier)
self.assertIsNotNone(masterpass_card.updated_at)
customer = Customer.find(customer.id)
self.assertEqual(len(customer.masterpass_cards), 1)
self.assertEqual(result.payment_method.token, customer.masterpass_cards[0].token)
def test_search_for_transaction(self):
result = Transaction.sale({
"payment_method_nonce": Nonces.MasterpassVisa,
"amount": "1.23"
})
self.assertTrue(result.is_success)
transaction = result.transaction
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.payment_instrument_type == PaymentInstrumentType.MasterpassCard
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
def test_create_transaction_from_nonce_and_vault(self):
customer = Customer.create().customer
result = Transaction.sale({
"payment_method_nonce": Nonces.MasterpassVisa,
"customer_id": customer.id,
"amount": "1.23",
"options": {
"store_in_vault": "true"
}
})
self.assertTrue(result.is_success)
masterpass_card_details = result.transaction.masterpass_card_details
self.assertIsNotNone(masterpass_card_details.bin)
self.assertIsNotNone(masterpass_card_details.card_type)
self.assertIsNotNone(masterpass_card_details.cardholder_name)
self.assertIsNotNone(masterpass_card_details.commercial)
self.assertIsNotNone(masterpass_card_details.country_of_issuance)
self.assertIsNotNone(masterpass_card_details.debit)
self.assertIsNotNone(masterpass_card_details.durbin_regulated)
self.assertIsNotNone(masterpass_card_details.expiration_date)
self.assertIsNotNone(masterpass_card_details.expiration_year)
self.assertIsNotNone(masterpass_card_details.expiration_month)
self.assertIsNotNone(masterpass_card_details.healthcare)
self.assertIsNotNone(masterpass_card_details.image_url)
self.assertIsNotNone(masterpass_card_details.issuing_bank)
self.assertIsNotNone(masterpass_card_details.last_4)
self.assertIsNotNone(masterpass_card_details.payroll)
self.assertIsNotNone(masterpass_card_details.prepaid)
self.assertIsNotNone(masterpass_card_details.product_id)
self.assertIsNotNone(masterpass_card_details.token)
braintree_python-3.38.0/tests/integration/__init__.py 0000644 0001750 0001750 00000000000 13150065776 021061 0 ustar hle hle braintree_python-3.38.0/tests/integration/test_customer.py 0000644 0001750 0001750 00000110735 13150065776 022243 0 ustar hle hle # -*- coding: latin-1 -*-
from tests.test_helper import *
import braintree.test.venmo_sdk as venmo_sdk
from braintree.test.nonces import Nonces
class TestCustomer(unittest.TestCase):
def test_all(self):
collection = Customer.all()
self.assertTrue(collection.maximum_size > 100)
customer_ids = [c.id for c in collection.items]
self.assertEqual(collection.maximum_size, len(TestHelper.unique(customer_ids)))
self.assertEqual(Customer, type(collection.first))
def test_create(self):
result = Customer.create({
"first_name": "Joe",
"last_name": "Brown",
"company": "Fake Company",
"email": "joe@email.com",
"phone": "312.555.1234",
"fax": "614.555.5678",
"website": "www.email.com"
})
self.assertTrue(result.is_success)
customer = result.customer
self.assertEqual("Joe", customer.first_name)
self.assertEqual("Brown", customer.last_name)
self.assertEqual("Fake Company", customer.company)
self.assertEqual("joe@email.com", customer.email)
self.assertEqual("312.555.1234", customer.phone)
self.assertEqual("614.555.5678", customer.fax)
self.assertEqual("www.email.com", customer.website)
self.assertNotEqual(None, customer.id)
self.assertNotEqual(None, re.search(r"\A\d{6,}\Z", customer.id))
def test_create_unicode(self):
result = Customer.create({
"first_name": "Kimi",
"last_name": u"Räikkönen",
"company": "Fake Company",
"email": "joe@email.com",
"phone": "312.555.1234",
"fax": "614.555.5678",
"website": "www.email.com"
})
self.assertTrue(result.is_success)
customer = result.customer
self.assertEqual("Kimi", customer.first_name)
self.assertEqual(u"Räikkönen", customer.last_name)
self.assertEqual("Fake Company", customer.company)
self.assertEqual("joe@email.com", customer.email)
self.assertEqual("312.555.1234", customer.phone)
self.assertEqual("614.555.5678", customer.fax)
self.assertEqual("www.email.com", customer.website)
self.assertNotEqual(None, customer.id)
def test_create_with_device_session_id_and_fraud_merchant_id(self):
result = Customer.create({
"first_name": "Joe",
"last_name": "Brown",
"company": "Fake Company",
"email": "joe@email.com",
"phone": "312.555.1234",
"fax": "614.555.5678",
"website": "www.email.com",
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2010",
"cvv": "100",
"device_session_id": "abc123",
"fraud_merchant_id": "456"
}
})
self.assertTrue(result.is_success)
def test_create_with_risk_data_security_parameters(self):
result = Customer.create({
"first_name": "Joe",
"last_name": "Brown",
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2010",
"options": {
"verify_card": True,
}
},
"risk_data": {
"customer_browser": "IE7",
"customer_ip": "192.168.0.1"
}
})
self.assertTrue(result.is_success)
def test_create_using_access_token(self):
gateway = BraintreeGateway(
client_id="client_id$development$integration_client_id",
client_secret="client_secret$development$integration_client_secret",
environment=Environment.Development
)
code = TestHelper.create_grant(gateway, {
"merchant_public_id": "integration_merchant_id",
"scope": "read_write"
})
result = gateway.oauth.create_token_from_code({
"code": code
})
gateway = BraintreeGateway(
access_token=result.credentials.access_token,
environment=Environment.Development
)
result = gateway.customer.create({
"first_name": "Joe",
"last_name": "Brown"
})
self.assertTrue(result.is_success)
customer = result.customer
self.assertEqual("Joe", customer.first_name)
def test_create_with_unicode(self):
result = Customer.create({
"first_name": u"Joe<&>",
"last_name": u"G\u1F00t\u1F18s",
"company": "Fake Company",
"email": "joe@email.com",
"phone": "312.555.1234",
"fax": "614.555.5678",
"website": "www.email.com"
})
self.assertTrue(result.is_success)
customer = result.customer
self.assertEqual(u"Joe<&>", customer.first_name)
self.assertEqual(u"G\u1f00t\u1F18s", customer.last_name)
self.assertEqual("Fake Company", customer.company)
self.assertEqual("joe@email.com", customer.email)
self.assertEqual("312.555.1234", customer.phone)
self.assertEqual("614.555.5678", customer.fax)
self.assertEqual("www.email.com", customer.website)
self.assertNotEqual(None, customer.id)
self.assertNotEqual(None, re.search(r"\A\d{6,}\Z", customer.id))
found_customer = Customer.find(customer.id)
self.assertEqual(u"G\u1f00t\u1F18s", found_customer.last_name)
def test_create_with_apple_pay_nonce(self):
result = Customer.create({"payment_method_nonce": Nonces.ApplePayVisa})
self.assertTrue(result.is_success)
customer = result.customer
self.assertEqual(1, len(customer.apple_pay_cards))
self.assertIsInstance(customer.apple_pay_cards[0], ApplePayCard)
def test_create_with_android_pay_proxy_card_nonce(self):
result = Customer.create({"payment_method_nonce": Nonces.AndroidPayCardDiscover})
self.assertTrue(result.is_success)
customer = result.customer
self.assertEqual(1, len(customer.android_pay_cards))
self.assertIsInstance(customer.android_pay_cards[0], AndroidPayCard)
def test_create_with_android_pay_network_token_nonce(self):
result = Customer.create({"payment_method_nonce": Nonces.AndroidPayCardMasterCard})
self.assertTrue(result.is_success)
customer = result.customer
self.assertEqual(1, len(customer.android_pay_cards))
self.assertIsInstance(customer.android_pay_cards[0], AndroidPayCard)
def test_create_with_amex_express_checkout_card_nonce(self):
result = Customer.create({"payment_method_nonce": Nonces.AmexExpressCheckoutCard})
self.assertTrue(result.is_success)
customer = result.customer
self.assertEqual(1, len(customer.amex_express_checkout_cards))
self.assertIsInstance(customer.amex_express_checkout_cards[0], AmexExpressCheckoutCard)
def test_create_with_venmo_account_nonce(self):
result = Customer.create({"payment_method_nonce": Nonces.VenmoAccount})
self.assertTrue(result.is_success)
customer = result.customer
self.assertEqual(1, len(customer.venmo_accounts))
self.assertIsInstance(customer.venmo_accounts[0], VenmoAccount)
def test_create_with_us_bank_account_nonce(self):
result = Customer.create({"payment_method_nonce": TestHelper.generate_valid_us_bank_account_nonce()})
self.assertTrue(result.is_success)
customer = result.customer
self.assertEqual(1, len(customer.us_bank_accounts))
self.assertIsInstance(customer.us_bank_accounts[0], UsBankAccount)
def test_create_with_paypal_future_payments_nonce(self):
result = Customer.create({"payment_method_nonce": Nonces.PayPalFuturePayment})
self.assertTrue(result.is_success)
customer = result.customer
self.assertEqual(1, len(customer.paypal_accounts))
self.assertIsInstance(customer.paypal_accounts[0], PayPalAccount)
def test_create_with_paypal_order_payment_nonce(self):
http = ClientApiHttp.create()
status_code, payment_method_nonce = http.get_paypal_nonce({
"intent": "order",
"payment-token": "fake-paypal-payment-token",
"payer-id": "fake-paypal-payer-id"
})
result = Customer.create({"payment_method_nonce": payment_method_nonce})
self.assertTrue(result.is_success)
customer = result.customer
self.assertEqual(1, len(customer.paypal_accounts))
self.assertIsInstance(customer.paypal_accounts[0], PayPalAccount)
def test_create_with_paypal_order_payment_nonce_and_paypal_options(self):
http = ClientApiHttp.create()
status_code, payment_method_nonce = http.get_paypal_nonce({
"intent": "order",
"payment-token": "fake-paypal-payment-token",
"payer-id": "fake-paypal-payer-id"
})
result = Customer.create({
"payment_method_nonce": payment_method_nonce,
"options": {
"paypal": {
"payee_email": "payee@example.com",
"order_id": "merchant-order-id",
"custom_field": "custom merchant field",
"description": "merchant description",
"amount": "1.23",
},
},
})
self.assertTrue(result.is_success)
customer = result.customer
self.assertEqual(1, len(customer.paypal_accounts))
self.assertIsInstance(customer.paypal_accounts[0], PayPalAccount)
def test_create_with_paypal_one_time_nonce_fails(self):
result = Customer.create({"payment_method_nonce": Nonces.PayPalOneTimePayment})
self.assertFalse(result.is_success)
paypal_account_errors = result.errors.for_object("customer").for_object("paypal_account").on("base")
self.assertEqual(1, len(paypal_account_errors))
self.assertEqual(ErrorCodes.PayPalAccount.CannotVaultOneTimeUsePayPalAccount, paypal_account_errors[0].code)
def test_create_with_no_attributes(self):
result = Customer.create()
self.assertTrue(result.is_success)
self.assertNotEqual(None, result.customer.id)
def test_create_with_special_chars(self):
result = Customer.create({"first_name": "XML Chars <>&'\""})
self.assertTrue(result.is_success)
self.assertEqual("XML Chars <>&'\"", result.customer.first_name)
def test_create_returns_an_error_response_if_invalid(self):
result = Customer.create({
"email": "@invalid.com",
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2010",
"billing_address": {
"country_code_alpha2": "MX",
"country_code_alpha3": "USA"
}
}
})
self.assertFalse(result.is_success)
customer_email_errors = result.errors.for_object("customer").on("email")
self.assertEqual(1, len(customer_email_errors))
self.assertEqual(ErrorCodes.Customer.EmailIsInvalid, customer_email_errors[0].code)
billing_address_errors = result.errors.for_object("customer").for_object("credit_card").for_object("billing_address").on("base")
self.assertEqual(1, len(billing_address_errors))
self.assertEqual(ErrorCodes.Address.InconsistentCountry, billing_address_errors[0].code)
def test_create_customer_and_payment_method_at_the_same_time(self):
result = Customer.create({
"first_name": "Mike",
"last_name": "Jones",
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2010",
"cvv": "100"
}
})
self.assertTrue(result.is_success)
customer = result.customer
self.assertEqual("Mike", customer.first_name)
self.assertEqual("Jones", customer.last_name)
credit_card = customer.credit_cards[0]
self.assertEqual("411111", credit_card.bin)
self.assertEqual("1111", credit_card.last_4)
self.assertEqual("05/2010", credit_card.expiration_date)
def test_create_customer_and_verify_payment_method(self):
result = Customer.create({
"first_name": "Mike",
"last_name": "Jones",
"credit_card": {
"number": "4000111111111115",
"expiration_date": "05/2010",
"cvv": "100",
"options": {"verify_card": True}
}
})
self.assertFalse(result.is_success)
self.assertEqual(CreditCardVerification.Status.ProcessorDeclined, result.credit_card_verification.status)
def test_create_customer_and_verify_payment_method_with_verification_amount(self):
result = Customer.create({
"first_name": "Mike",
"last_name": "Jones",
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2010",
"cvv": "100",
"options": {"verify_card": True, "verification_amount": "6.00"}
}
})
self.assertTrue(result.is_success)
def test_create_customer_with_check_duplicate_payment_method(self):
attributes = {
"first_name": "Mike",
"last_name": "Jones",
"credit_card": {
"number": "4000111111111115",
"expiration_date": "05/2010",
"cvv": "100",
"options": {"fail_on_duplicate_payment_method": True}
}
}
Customer.create(attributes)
result = Customer.create(attributes)
self.assertFalse(result.is_success)
self.assertEqual("Duplicate card exists in the vault.", result.message)
card_number_errors = result.errors.for_object("customer").for_object("credit_card").on("number")
self.assertEqual(1, len(card_number_errors))
self.assertEqual(ErrorCodes.CreditCard.DuplicateCardExists, card_number_errors[0].code)
def test_create_customer_with_payment_method_and_billing_address(self):
result = Customer.create({
"first_name": "Mike",
"last_name": "Jones",
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2010",
"cvv": "100",
"billing_address": {
"street_address": "123 Abc Way",
"locality": "Chicago",
"region": "Illinois",
"postal_code": "60622",
"country_code_alpha2": "US",
"country_code_alpha3": "USA",
"country_code_numeric": "840",
"country_name": "United States of America"
}
}
})
self.assertTrue(result.is_success)
customer = result.customer
self.assertEqual("Mike", customer.first_name)
self.assertEqual("Jones", customer.last_name)
address = customer.credit_cards[0].billing_address
self.assertEqual("123 Abc Way", address.street_address)
self.assertEqual("Chicago", address.locality)
self.assertEqual("Illinois", address.region)
self.assertEqual("60622", address.postal_code)
self.assertEqual("US", address.country_code_alpha2)
self.assertEqual("USA", address.country_code_alpha3)
self.assertEqual("840", address.country_code_numeric)
self.assertEqual("United States of America", address.country_name)
def test_create_with_customer_fields(self):
result = Customer.create({
"first_name": "Mike",
"last_name": "Jones",
"custom_fields": {
"store_me": "custom value"
}
})
self.assertTrue(result.is_success)
self.assertEqual("custom value", result.customer.custom_fields["store_me"])
def test_create_returns_nested_errors(self):
result = Customer.create({
"email": "invalid",
"credit_card": {
"number": "invalid",
"billing_address": {
"country_name": "invalid"
}
}
})
self.assertFalse(result.is_success)
email_errors = result.errors.for_object("customer").on("email")
self.assertEqual(1, len(email_errors))
self.assertEqual(ErrorCodes.Customer.EmailIsInvalid, email_errors[0].code)
card_number_errors = result.errors.for_object("customer").for_object("credit_card").on("number")
self.assertEqual(1, len(card_number_errors))
self.assertEqual(ErrorCodes.CreditCard.NumberHasInvalidLength, card_number_errors[0].code)
country_name_errors = result.errors.for_object("customer").for_object("credit_card").for_object("billing_address").on("country_name")
self.assertEqual(1, len(country_name_errors))
self.assertEqual(ErrorCodes.Address.CountryNameIsNotAccepted, country_name_errors[0].code)
def test_create_returns_errors_if_custom_fields_are_not_registered(self):
result = Customer.create({
"first_name": "Jack",
"last_name": "Kennedy",
"custom_fields": {
"spouse_name": "Jacqueline"
}
})
self.assertFalse(result.is_success)
custom_fields_errors = result.errors.for_object("customer").on("custom_fields")
self.assertEqual(1, len(custom_fields_errors))
self.assertEqual(ErrorCodes.Customer.CustomFieldIsInvalid, custom_fields_errors[0].code)
def test_create_with_venmo_sdk_session(self):
result = Customer.create({
"first_name": "Jack",
"last_name": "Kennedy",
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2010",
"options": {
"venmo_sdk_session": venmo_sdk.Session
}
}
})
self.assertTrue(result.is_success)
self.assertTrue(result.customer.credit_cards[0].venmo_sdk)
def test_create_with_venmo_sdk_payment_method_code(self):
result = Customer.create({
"first_name": "Jack",
"last_name": "Kennedy",
"credit_card": {
"venmo_sdk_payment_method_code": venmo_sdk.generate_test_payment_method_code("4111111111111111")
}
})
self.assertTrue(result.is_success)
self.assertEqual("411111", result.customer.credit_cards[0].bin)
def test_create_with_payment_method_nonce(self):
config = Configuration.instantiate()
authorization_fingerprint = json.loads(TestHelper.generate_decoded_client_token())["authorizationFingerprint"]
http = ClientApiHttp(config, {
"authorization_fingerprint": authorization_fingerprint,
"shared_customer_identifier": "fake_identifier",
"shared_customer_identifier_type": "testing"
})
_, response = http.add_card({
"credit_card": {
"number": "4111111111111111",
"expiration_month": "11",
"expiration_year": "2099",
},
"share": True
})
nonce = json.loads(response)["creditCards"][0]["nonce"]
result = Customer.create({
"credit_card": {
"payment_method_nonce": nonce
}
})
self.assertTrue(result.is_success)
self.assertEqual("411111", result.customer.credit_cards[0].bin)
def test_delete_with_valid_customer(self):
customer = Customer.create().customer
result = Customer.delete(customer.id)
self.assertTrue(result.is_success)
@raises(NotFoundError)
def test_delete_with_invalid_customer(self):
customer = Customer.create().customer
Customer.delete(customer.id)
Customer.delete(customer.id)
def test_find_with_valid_customer(self):
customer = Customer.create({
"first_name": "Joe",
"last_name": "Cool"
}).customer
found_customer = Customer.find(customer.id)
self.assertEqual(customer.id, found_customer.id)
self.assertEqual(customer.first_name, found_customer.first_name)
self.assertEqual(customer.last_name, found_customer.last_name)
def test_find_customer_with_us_bank_account(self):
customer = Customer.create({
"payment_method_nonce": TestHelper.generate_valid_us_bank_account_nonce()
}).customer
found_customer = Customer.find(customer.id)
self.assertEqual(customer.id, found_customer.id)
self.assertEqual(customer.first_name, found_customer.first_name)
self.assertEqual(customer.last_name, found_customer.last_name)
self.assertEqual(1, len(found_customer.us_bank_accounts))
self.assertIsInstance(found_customer.us_bank_accounts[0], UsBankAccount)
@raises_with_regexp(NotFoundError, "customer with id 'badid' not found")
def test_find_with_invalid_customer(self):
Customer.find("badid")
def test_update_with_valid_options(self):
customer = Customer.create({
"first_name": "Joe",
"last_name": "Brown",
"company": "Fake Company",
"email": "joe@email.com",
"phone": "312.555.5555",
"fax": "614.555.5555",
"website": "www.email.com"
}).customer
result = Customer.update(customer.id, {
"first_name": "Joe",
"last_name": "Brown",
"company": "Fake Company",
"email": "joe@email.com",
"phone": "312.555.1234",
"fax": "614.555.5678",
"website": "www.email.com"
})
self.assertTrue(result.is_success)
customer = result.customer
self.assertEqual("Joe", customer.first_name)
self.assertEqual("Brown", customer.last_name)
self.assertEqual("Fake Company", customer.company)
self.assertEqual("joe@email.com", customer.email)
self.assertEqual("312.555.1234", customer.phone)
self.assertEqual("614.555.5678", customer.fax)
self.assertEqual("www.email.com", customer.website)
self.assertNotEqual(None, customer.id)
self.assertNotEqual(None, re.search(r"\A\d{6,}\Z", customer.id))
def test_update_with_default_payment_method(self):
customer = Customer.create({
"first_name": "Joe",
"last_name": "Brown",
}).customer
token1 = str(random.randint(1, 1000000))
payment_method1 = PaymentMethod.create({
"customer_id": customer.id,
"payment_method_nonce": Nonces.TransactableVisa,
"token": token1
}).payment_method
payment_method1 = PaymentMethod.find(payment_method1.token)
self.assertTrue(payment_method1.default)
token2 = str(random.randint(1, 1000000))
payment_method2 = PaymentMethod.create({
"customer_id": customer.id,
"payment_method_nonce": Nonces.TransactableMasterCard,
"token": token2
}).payment_method
Customer.update(customer.id, {
"default_payment_method_token": payment_method2.token
})
payment_method2 = PaymentMethod.find(payment_method2.token)
self.assertTrue(payment_method2.default)
def test_update_with_default_payment_method_in_options(self):
customer = Customer.create({
"first_name": "Joe",
"last_name": "Brown",
}).customer
token1 = str(random.randint(1, 1000000))
payment_method1 = PaymentMethod.create({
"customer_id": customer.id,
"payment_method_nonce": Nonces.TransactableVisa,
"token": token1
}).payment_method
payment_method1 = PaymentMethod.find(payment_method1.token)
self.assertTrue(payment_method1.default)
token2 = str(random.randint(1, 1000000))
payment_method2 = PaymentMethod.create({
"customer_id": customer.id,
"payment_method_nonce": Nonces.TransactableMasterCard,
"token": token2
}).payment_method
Customer.update(customer.id, {
"credit_card": {
"options": {
"update_existing_token": token2,
"make_default": True
}
}
})
payment_method2 = PaymentMethod.find(payment_method2.token)
self.assertTrue(payment_method2.default)
def test_update_with_nested_values(self):
customer = Customer.create({
"first_name": "Joe",
"last_name": "Brown",
"credit_card": {
"number": "4111111111111111",
"expiration_date": "10/10",
"billing_address": {
"postal_code": "11111"
}
}
}).customer
credit_card = customer.credit_cards[0]
address = credit_card.billing_address
updated_customer = Customer.update(customer.id, {
"first_name": "Joe",
"last_name": "Brown",
"credit_card": {
"expiration_date": "12/12",
"options": {
"update_existing_token": credit_card.token
},
"billing_address": {
"postal_code": "44444",
"country_code_alpha2": "US",
"country_code_alpha3": "USA",
"country_code_numeric": "840",
"country_name": "United States of America",
"options": {
"update_existing": True
}
}
}
}).customer
updated_credit_card = CreditCard.find(credit_card.token)
updated_address = Address.find(customer.id, address.id)
self.assertEqual("Joe", updated_customer.first_name)
self.assertEqual("Brown", updated_customer.last_name)
self.assertEqual("12/2012", updated_credit_card.expiration_date)
self.assertEqual("44444", updated_address.postal_code)
self.assertEqual("US", updated_address.country_code_alpha2)
self.assertEqual("USA", updated_address.country_code_alpha3)
self.assertEqual("840", updated_address.country_code_numeric)
self.assertEqual("United States of America", updated_address.country_name)
def test_update_with_nested_billing_address_id(self):
customer = Customer.create().customer
address = Address.create({
"customer_id": customer.id,
"postal_code": "11111"
}).address
updated_customer = Customer.update(customer.id, {
"credit_card": {
"number": "4111111111111111",
"expiration_date": "12/12",
"billing_address_id": address.id
}
}).customer
credit_card = updated_customer.credit_cards[0]
self.assertEqual(address.id, credit_card.billing_address.id)
self.assertEqual("11111", credit_card.billing_address.postal_code)
def test_update_with_invalid_options(self):
customer = Customer.create({
"first_name": "Joe",
"last_name": "Brown",
"company": "Fake Company",
"email": "joe@email.com",
"phone": "312.555.5555",
"fax": "614.555.5555",
"website": "www.email.com"
}).customer
result = Customer.update(customer.id, {
"email": "@email.com",
})
self.assertFalse(result.is_success)
email_errors = result.errors.for_object("customer").on("email")
self.assertEqual(1, len(email_errors))
self.assertEqual(ErrorCodes.Customer.EmailIsInvalid, email_errors[0].code)
def test_update_with_paypal_future_payments_nonce(self):
customer = Customer.create().customer
result = Customer.update(customer.id, {
"payment_method_nonce": Nonces.PayPalFuturePayment
})
self.assertTrue(result.is_success)
customer = result.customer
self.assertNotEqual(None, customer.paypal_accounts[0])
def test_update_with_paypal_one_time_nonce_fails(self):
customer = Customer.create().customer
result = Customer.update(customer.id, {
"payment_method_nonce": Nonces.PayPalOneTimePayment
})
self.assertFalse(result.is_success)
paypal_account_errors = result.errors.for_object("customer").for_object("paypal_account").on("base")
self.assertEqual(1, len(paypal_account_errors))
self.assertEqual(ErrorCodes.PayPalAccount.CannotVaultOneTimeUsePayPalAccount, paypal_account_errors[0].code)
def test_update_with_nested_verification_amount(self):
customer = Customer.create({
"first_name": "Joe",
"last_name": "Brown",
"credit_card": {
"number": "4111111111111111",
"expiration_date": "10/10",
"billing_address": {
"postal_code": "11111"
}
}
}).customer
result = Customer.update(customer.id, {
"credit_card": {
"number": "4111111111111111",
"expiration_date": "10/10",
"options": {
"verify_card": True,
"verification_amount": "2.00"
},
}
})
self.assertTrue(result.is_success)
def test_create_from_transparent_redirect_with_successful_result(self):
tr_data = {
"customer": {
"first_name": "John",
"last_name": "Doe",
"company": "Doe Co",
}
}
post_params = {
"tr_data": Customer.tr_data_for_create(tr_data, "http://example.com/path"),
"customer[email]": "john@doe.com",
"customer[phone]": "312.555.2323",
"customer[fax]": "614.555.5656",
"customer[website]": "www.johndoe.com",
"customer[credit_card][number]": "4111111111111111",
"customer[credit_card][expiration_date]": "05/2012",
"customer[credit_card][billing_address][country_code_alpha2]": "MX",
"customer[credit_card][billing_address][country_code_alpha3]": "MEX",
"customer[credit_card][billing_address][country_code_numeric]": "484",
"customer[credit_card][billing_address][country_name]": "Mexico",
}
query_string = TestHelper.simulate_tr_form_post(post_params, Customer.transparent_redirect_create_url())
result = Customer.confirm_transparent_redirect(query_string)
self.assertTrue(result.is_success)
customer = result.customer
self.assertEqual("John", customer.first_name)
self.assertEqual("Doe", customer.last_name)
self.assertEqual("Doe Co", customer.company)
self.assertEqual("john@doe.com", customer.email)
self.assertEqual("312.555.2323", customer.phone)
self.assertEqual("614.555.5656", customer.fax)
self.assertEqual("www.johndoe.com", customer.website)
self.assertEqual("05/2012", customer.credit_cards[0].expiration_date)
self.assertEqual("MX", customer.credit_cards[0].billing_address.country_code_alpha2)
self.assertEqual("MEX", customer.credit_cards[0].billing_address.country_code_alpha3)
self.assertEqual("484", customer.credit_cards[0].billing_address.country_code_numeric)
self.assertEqual("Mexico", customer.credit_cards[0].billing_address.country_name)
def test_create_from_transparent_redirect_with_error_result(self):
tr_data = {
"customer": {
"company": "Doe Co",
}
}
post_params = {
"tr_data": Customer.tr_data_for_create(tr_data, "http://example.com/path"),
"customer[email]": "john#doe.com",
}
query_string = TestHelper.simulate_tr_form_post(post_params, Customer.transparent_redirect_create_url())
result = Customer.confirm_transparent_redirect(query_string)
self.assertFalse(result.is_success)
email_errors = result.errors.for_object("customer").on("email")
self.assertEqual(1, len(email_errors))
self.assertEqual(ErrorCodes.Customer.EmailIsInvalid, email_errors[0].code)
def test_update_from_transparent_redirect_with_successful_result(self):
customer = Customer.create({
"first_name": "Jane",
}).customer
tr_data = {
"customer_id": customer.id,
"customer": {
"first_name": "John",
}
}
post_params = {
"tr_data": Customer.tr_data_for_update(tr_data, "http://example.com/path"),
"customer[email]": "john@doe.com",
}
query_string = TestHelper.simulate_tr_form_post(post_params, Customer.transparent_redirect_update_url())
result = Customer.confirm_transparent_redirect(query_string)
self.assertTrue(result.is_success)
customer = result.customer
self.assertEqual("John", customer.first_name)
self.assertEqual("john@doe.com", customer.email)
def test_update_with_nested_values_via_transparent_redirect(self):
customer = Customer.create({
"first_name": "Joe",
"last_name": "Brown",
"credit_card": {
"number": "4111111111111111",
"expiration_date": "10/10",
"billing_address": {
"postal_code": "11111"
}
}
}).customer
credit_card = customer.credit_cards[0]
address = credit_card.billing_address
tr_data = {
"customer_id": customer.id,
"customer": {
"first_name": "Joe",
"last_name": "Brown",
"credit_card": {
"expiration_date": "12/12",
"options": {
"update_existing_token": credit_card.token
},
"billing_address": {
"postal_code": "44444",
"options": {
"update_existing": True
}
}
}
}
}
post_params = {
"tr_data": Customer.tr_data_for_update(tr_data, "http://example.com/path"),
}
query_string = TestHelper.simulate_tr_form_post(post_params, Customer.transparent_redirect_update_url())
updated_customer = Customer.confirm_transparent_redirect(query_string).customer
updated_credit_card = CreditCard.find(credit_card.token)
updated_address = Address.find(customer.id, address.id)
self.assertEqual("Joe", updated_customer.first_name)
self.assertEqual("Brown", updated_customer.last_name)
self.assertEqual("12/2012", updated_credit_card.expiration_date)
self.assertEqual("44444", updated_address.postal_code)
def test_update_from_transparent_redirect_with_error_result(self):
customer = Customer.create({
"first_name": "Jane",
}).customer
tr_data = {
"customer_id": customer.id,
"customer": {
"first_name": "John",
}
}
post_params = {
"tr_data": Customer.tr_data_for_update(tr_data, "http://example.com/path"),
"customer[email]": "john#doe.com",
}
query_string = TestHelper.simulate_tr_form_post(post_params, Customer.transparent_redirect_update_url())
result = Customer.confirm_transparent_redirect(query_string)
self.assertFalse(result.is_success)
customer_email_errors = result.errors.for_object("customer").on("email")
self.assertEqual(1, len(customer_email_errors))
self.assertEqual(ErrorCodes.Customer.EmailIsInvalid, customer_email_errors[0].code)
def test_customer_payment_methods(self):
customer = Customer("gateway", {
"credit_cards": [{"token": "credit_card"}],
"paypal_accounts": [{"token": "paypal_account"}],
"apple_pay_cards": [{"token": "apple_pay_card"}],
"android_pay_cards": [{"token": "android_pay_card"}],
"europe_bank_accounts": [{"token": "europe_bank_account"}],
"us_bank_accounts": [{"token": "us_bank_account"}]
})
payment_method_tokens = [ pm.token for pm in customer.payment_methods ]
self.assertEqual(sorted(payment_method_tokens), ["android_pay_card", "apple_pay_card", "credit_card", "europe_bank_account", "paypal_account", "us_bank_account"])
braintree_python-3.38.0/tests/integration/test_ideal_payment.py 0000644 0001750 0001750 00000005674 13150065776 023222 0 ustar hle hle from braintree.transaction_amounts import TransactionAmounts
from braintree.ideal_payment import IdealPayment
from decimal import Decimal
from tests.test_helper import *
class TestIdealPayment(unittest.TestCase):
def test_creates_transaction_using_ideal_payment_token_and_returns_result_object(self):
ideal_payment_id = TestHelper.generate_valid_ideal_payment_id(amount=TransactionAmounts.Authorize)
result = IdealPayment.sale(ideal_payment_id, {
'order_id': 'ABC123',
'merchant_account_id': 'ideal_merchant_account',
'amount': TransactionAmounts.Authorize,
})
self.assertTrue(result.is_success)
self.assertEqual(result.transaction.amount, Decimal(TransactionAmounts.Authorize))
self.assertEqual(result.transaction.type, 'sale')
ideal_payment_details = result.transaction.ideal_payment_details
self.assertRegexpMatches(ideal_payment_details.ideal_payment_id, r'^idealpayment_\w{6,}$')
self.assertRegexpMatches(ideal_payment_details.ideal_transaction_id, r'^\d{16,}$')
self.assertEqual(ideal_payment_details.image_url[:8], 'https://')
self.assertNotEqual(ideal_payment_details.masked_iban, None)
self.assertNotEqual(ideal_payment_details.bic, None)
def test_doesnt_create_transaction_with_ideal_payment(self):
result = IdealPayment.sale('invalid_id', {
'merchant_account_id': 'ideal_merchant_account',
'amount': TransactionAmounts.Authorize,
})
self.assertFalse(result.is_success)
def test_find_ideal_payment_by_id(self):
ideal_payment_id = TestHelper.generate_valid_ideal_payment_id(amount=TransactionAmounts.Authorize)
ideal_payment = IdealPayment.find(ideal_payment_id)
self.assertRegexpMatches(ideal_payment.id, r'^idealpayment_\w{6,}$')
self.assertRegexpMatches(ideal_payment.ideal_transaction_id, r'^\d{16,}$')
self.assertNotEqual(ideal_payment.currency, None)
self.assertNotEqual(ideal_payment.amount, None)
self.assertNotEqual(ideal_payment.status, None)
self.assertNotEqual(ideal_payment.order_id, None)
self.assertNotEqual(ideal_payment.issuer, None)
self.assertEqual(ideal_payment.approval_url[:8], 'https://')
self.assertNotEqual(ideal_payment.iban_bank_account.account_holder_name, None)
self.assertNotEqual(ideal_payment.iban_bank_account.bic, None)
self.assertNotEqual(ideal_payment.iban_bank_account.masked_iban, None)
self.assertRegexpMatches(ideal_payment.iban_bank_account.iban_account_number_last_4, r'^\d{4}$')
self.assertNotEqual(ideal_payment.iban_bank_account.iban_country, None)
self.assertNotEqual(ideal_payment.iban_bank_account.description, None)
def test_errors_if_ideal_payment_is_not_found(self):
def find():
IdealPayment.find('idealpayment_nxyqkq_s654wq_92jr64_mnr4kr_yjz')
self.assertRaises(NotFoundError, find)
braintree_python-3.38.0/tests/integration/test_visa_checkout.py 0000644 0001750 0001750 00000012240 13150065776 023221 0 ustar hle hle from tests.test_helper import *
class TestVisaCheckout(unittest.TestCase):
def test_create_from_nonce(self):
customer = Customer.create().customer
result = PaymentMethod.create({
"customer_id": customer.id,
"payment_method_nonce": Nonces.VisaCheckoutVisa
})
self.assertTrue(result.is_success)
visa_checkout_card = result.payment_method
self.assertEqual("abc123", visa_checkout_card.call_id)
self.assertIsNotNone(visa_checkout_card.billing_address)
self.assertIsNotNone(visa_checkout_card.bin)
self.assertIsNotNone(visa_checkout_card.card_type)
self.assertIsNotNone(visa_checkout_card.cardholder_name)
self.assertIsNotNone(visa_checkout_card.commercial)
self.assertIsNotNone(visa_checkout_card.country_of_issuance)
self.assertIsNotNone(visa_checkout_card.created_at)
self.assertIsNotNone(visa_checkout_card.customer_id)
self.assertIsNotNone(visa_checkout_card.customer_location)
self.assertIsNotNone(visa_checkout_card.debit)
self.assertIsNotNone(visa_checkout_card.default)
self.assertIsNotNone(visa_checkout_card.durbin_regulated)
self.assertIsNotNone(visa_checkout_card.expiration_date)
self.assertIsNotNone(visa_checkout_card.expiration_month)
self.assertIsNotNone(visa_checkout_card.expiration_year)
self.assertIsNotNone(visa_checkout_card.expired)
self.assertIsNotNone(visa_checkout_card.healthcare)
self.assertIsNotNone(visa_checkout_card.image_url)
self.assertIsNotNone(visa_checkout_card.issuing_bank)
self.assertIsNotNone(visa_checkout_card.last_4)
self.assertIsNotNone(visa_checkout_card.masked_number)
self.assertIsNotNone(visa_checkout_card.payroll)
self.assertIsNotNone(visa_checkout_card.prepaid)
self.assertIsNotNone(visa_checkout_card.product_id)
self.assertIsNotNone(visa_checkout_card.subscriptions)
self.assertIsNotNone(visa_checkout_card.token)
self.assertIsNotNone(visa_checkout_card.unique_number_identifier)
self.assertIsNotNone(visa_checkout_card.updated_at)
customer = Customer.find(customer.id)
self.assertEqual(len(customer.visa_checkout_cards), 1)
self.assertEqual(result.payment_method.token, customer.visa_checkout_cards[0].token)
def test_create_with_verification(self):
customer = Customer.create().customer
result = PaymentMethod.create({
"customer_id": customer.id,
"payment_method_nonce": Nonces.VisaCheckoutVisa,
"options": {
"verify_card": "true"
}
})
self.assertTrue(result.is_success)
verification = result.payment_method.verification
self.assertEqual(CreditCardVerification.Status.Verified, verification.status)
def test_search_for_transaction(self):
result = Transaction.sale({
"payment_method_nonce": Nonces.VisaCheckoutVisa,
"amount": "1.23"
})
self.assertTrue(result.is_success)
transaction = result.transaction
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.payment_instrument_type == PaymentInstrumentType.VisaCheckoutCard
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
def test_create_transaction_from_nonce_and_vault(self):
customer = Customer.create().customer
result = Transaction.sale({
"payment_method_nonce": Nonces.VisaCheckoutVisa,
"customer_id": customer.id,
"amount": "1.23",
"options": {
"store_in_vault": "true"
}
})
self.assertTrue(result.is_success)
visa_checkout_card_details = result.transaction.visa_checkout_card_details
self.assertEqual("abc123", visa_checkout_card_details.call_id)
self.assertIsNotNone(visa_checkout_card_details.bin)
self.assertIsNotNone(visa_checkout_card_details.card_type)
self.assertIsNotNone(visa_checkout_card_details.cardholder_name)
self.assertIsNotNone(visa_checkout_card_details.commercial)
self.assertIsNotNone(visa_checkout_card_details.country_of_issuance)
self.assertIsNotNone(visa_checkout_card_details.debit)
self.assertIsNotNone(visa_checkout_card_details.durbin_regulated)
self.assertIsNotNone(visa_checkout_card_details.expiration_date)
self.assertIsNotNone(visa_checkout_card_details.expiration_year)
self.assertIsNotNone(visa_checkout_card_details.expiration_month)
self.assertIsNotNone(visa_checkout_card_details.healthcare)
self.assertIsNotNone(visa_checkout_card_details.image_url)
self.assertIsNotNone(visa_checkout_card_details.issuing_bank)
self.assertIsNotNone(visa_checkout_card_details.last_4)
self.assertIsNotNone(visa_checkout_card_details.payroll)
self.assertIsNotNone(visa_checkout_card_details.prepaid)
self.assertIsNotNone(visa_checkout_card_details.product_id)
self.assertIsNotNone(visa_checkout_card_details.token)
braintree_python-3.38.0/tests/integration/test_transaction_search.py 0000644 0001750 0001750 00000170403 13150065776 024252 0 ustar hle hle from tests.test_helper import *
class TestTransactionSearch(unittest.TestCase):
def test_advanced_search_no_results(self):
collection = Transaction.search([
TransactionSearch.billing_first_name == "no_such_person"
])
self.assertEqual(0, collection.maximum_size)
def test_advanced_search_searches_all_text_fields_at_once(self):
first_name = "Tim%s" % random.randint(1, 100000)
token = "creditcard%s" % random.randint(1, 100000)
customer_id = "customer%s" % random.randint(1, 100000)
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012",
"cardholder_name": "Tom Smith",
"token": token,
},
"billing": {
"company": "Braintree",
"country_name": "United States of America",
"extended_address": "Suite 123",
"first_name": first_name,
"last_name": "Smith",
"locality": "Chicago",
"postal_code": "12345",
"region": "IL",
"street_address": "123 Main St"
},
"customer": {
"company": "Braintree",
"email": "smith@example.com",
"fax": "5551231234",
"first_name": "Tom",
"id": customer_id,
"last_name": "Smith",
"phone": "5551231234",
"website": "http://example.com",
},
"options": {
"store_in_vault": True,
"submit_for_settlement": True
},
"order_id": "myorder",
"shipping": {
"company": "Braintree P.S.",
"country_name": "Mexico",
"extended_address": "Apt 456",
"first_name": "Thomas",
"last_name": "Smithy",
"locality": "Braintree",
"postal_code": "54321",
"region": "MA",
"street_address": "456 Road"
}
}).transaction
TestHelper.settle_transaction(transaction.id)
transaction = Transaction.find(transaction.id)
collection = Transaction.search([
TransactionSearch.billing_company == "Braintree",
TransactionSearch.billing_country_name == "United States of America",
TransactionSearch.billing_extended_address == "Suite 123",
TransactionSearch.billing_first_name == first_name,
TransactionSearch.billing_last_name == "Smith",
TransactionSearch.billing_locality == "Chicago",
TransactionSearch.billing_postal_code == "12345",
TransactionSearch.billing_region == "IL",
TransactionSearch.billing_street_address == "123 Main St",
TransactionSearch.credit_card_cardholder_name == "Tom Smith",
TransactionSearch.credit_card_expiration_date == "05/2012",
TransactionSearch.credit_card_number == "4111111111111111",
TransactionSearch.customer_company == "Braintree",
TransactionSearch.customer_email == "smith@example.com",
TransactionSearch.customer_fax == "5551231234",
TransactionSearch.customer_first_name == "Tom",
TransactionSearch.customer_id == customer_id,
TransactionSearch.customer_last_name == "Smith",
TransactionSearch.customer_phone == "5551231234",
TransactionSearch.customer_website == "http://example.com",
TransactionSearch.order_id == "myorder",
TransactionSearch.payment_method_token == token,
TransactionSearch.processor_authorization_code == transaction.processor_authorization_code,
TransactionSearch.settlement_batch_id == transaction.settlement_batch_id,
TransactionSearch.shipping_company == "Braintree P.S.",
TransactionSearch.shipping_country_name == "Mexico",
TransactionSearch.shipping_extended_address == "Apt 456",
TransactionSearch.shipping_first_name == "Thomas",
TransactionSearch.shipping_last_name == "Smithy",
TransactionSearch.shipping_locality == "Braintree",
TransactionSearch.shipping_postal_code == "54321",
TransactionSearch.shipping_region == "MA",
TransactionSearch.shipping_street_address == "456 Road",
TransactionSearch.id == transaction.id
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
def test_advanced_search_search_each_text_field(self):
first_name = "Tim%s" % random.randint(1, 100000)
token = "creditcard%s" % random.randint(1, 100000)
customer_id = "customer%s" % random.randint(1, 100000)
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012",
"cardholder_name": "Tom Smith",
"token": token,
},
"billing": {
"company": "Braintree",
"country_name": "United States of America",
"extended_address": "Suite 123",
"first_name": first_name,
"last_name": "Smith",
"locality": "Chicago",
"postal_code": "12345",
"region": "IL",
"street_address": "123 Main St"
},
"customer": {
"company": "Braintree",
"email": "smith@example.com",
"fax": "5551231234",
"first_name": "Tom",
"id": customer_id,
"last_name": "Smith",
"phone": "5551231234",
"website": "http://example.com",
},
"options": {
"store_in_vault": True
},
"order_id": "myorder",
"shipping": {
"company": "Braintree P.S.",
"country_name": "Mexico",
"extended_address": "Apt 456",
"first_name": "Thomas",
"last_name": "Smithy",
"locality": "Braintree",
"postal_code": "54321",
"region": "MA",
"street_address": "456 Road"
}
}).transaction
search_criteria = {
"billing_company": "Braintree",
"billing_country_name": "United States of America",
"billing_extended_address": "Suite 123",
"billing_first_name": first_name,
"billing_last_name": "Smith",
"billing_locality": "Chicago",
"billing_postal_code": "12345",
"billing_region": "IL",
"billing_street_address": "123 Main St",
"credit_card_cardholder_name": "Tom Smith",
"credit_card_expiration_date": "05/2012",
"credit_card_number": "4111111111111111",
"customer_company": "Braintree",
"customer_email": "smith@example.com",
"customer_fax": "5551231234",
"customer_first_name": "Tom",
"customer_id": customer_id,
"customer_last_name": "Smith",
"customer_phone": "5551231234",
"customer_website": "http://example.com",
"order_id": "myorder",
"payment_method_token": token,
"processor_authorization_code": transaction.processor_authorization_code,
"shipping_company": "Braintree P.S.",
"shipping_country_name": "Mexico",
"shipping_extended_address": "Apt 456",
"shipping_first_name": "Thomas",
"shipping_last_name": "Smithy",
"shipping_locality": "Braintree",
"shipping_postal_code": "54321",
"shipping_region": "MA",
"shipping_street_address": "456 Road",
"user": "integration_user_public_id",
"credit_card_unique_identifier": transaction.credit_card["unique_number_identifier"]
}
for criterion, value in search_criteria.items():
text_node = getattr(TransactionSearch, criterion)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
text_node == value
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
text_node == "invalid"
])
self.assertEqual(0, collection.maximum_size)
def test_advanced_search_with_argument_list_rather_than_literal_list(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012",
"cardholder_name": "Tom Smith",
},
}).transaction
collection = Transaction.search(
TransactionSearch.id == transaction.id,
TransactionSearch.credit_card_cardholder_name == "Tom Smith"
)
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
def test_advanced_search_with_payment_instrument_type_is_credit_card(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012",
"cardholder_name": "Tom Smith",
},
}).transaction
collection = Transaction.search(
TransactionSearch.id == transaction.id,
TransactionSearch.payment_instrument_type == "CreditCardDetail"
)
self.assertEqual(transaction.payment_instrument_type, PaymentInstrumentType.CreditCard)
self.assertEqual(transaction.id, collection.first.id)
def test_advanced_search_with_payment_instrument_type_is_paypal(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"payment_method_nonce": Nonces.PayPalOneTimePayment
}).transaction
collection = Transaction.search(
TransactionSearch.id == transaction.id,
TransactionSearch.payment_instrument_type == "PayPalDetail"
)
self.assertEqual(transaction.payment_instrument_type, PaymentInstrumentType.PayPalAccount)
self.assertEqual(transaction.id, collection.first.id)
def test_advanced_search_with_payment_instrument_type_is_apple_pay(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"payment_method_nonce": Nonces.ApplePayVisa
}).transaction
collection = Transaction.search(
TransactionSearch.id == transaction.id,
TransactionSearch.payment_instrument_type == "ApplePayDetail"
)
self.assertEqual(transaction.payment_instrument_type, PaymentInstrumentType.ApplePayCard)
self.assertEqual(transaction.id, collection.first.id)
def test_advanced_search_with_payment_instrument_type_is_europe(self):
old_merchant_id = Configuration.merchant_id
old_public_key = Configuration.public_key
old_private_key = Configuration.private_key
try:
Configuration.merchant_id = "altpay_merchant"
Configuration.public_key = "altpay_merchant_public_key"
Configuration.private_key = "altpay_merchant_private_key"
customer_id = Customer.create().customer.id
token = TestHelper.generate_decoded_client_token({"customer_id": customer_id, "sepa_mandate_type": EuropeBankAccount.MandateType.Business})
authorization_fingerprint = json.loads(token)["authorizationFingerprint"]
config = Configuration.instantiate()
client_api = ClientApiHttp(config, {
"authorization_fingerprint": authorization_fingerprint,
"shared_customer_identifier": "fake_identifier",
"shared_customer_identifier_type": "testing"
})
nonce = client_api.get_europe_bank_account_nonce({
"locale": "de-DE",
"bic": "DEUTDEFF",
"iban": "DE89370400440532013000",
"accountHolderName": "Baron Von Holder",
"billingAddress": {"region": "Hesse", "country_name": "Germany"}
})
transaction = Transaction.sale({
"merchant_account_id": "fake_sepa_ma",
"amount": "10.00",
"payment_method_nonce": nonce
}).transaction
collection = Transaction.search(
TransactionSearch.id == transaction.id,
TransactionSearch.payment_instrument_type == "EuropeBankAccountDetail"
)
self.assertEqual(transaction.payment_instrument_type, PaymentInstrumentType.EuropeBankAccount)
self.assertEqual(transaction.id, collection.first.id)
finally:
Configuration.merchant_id = old_merchant_id
Configuration.public_key = old_public_key
Configuration.private_key = old_private_key
def test_advanced_search_text_node_contains(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012",
"cardholder_name": "Jane Shea"
}
}).transaction
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.credit_card_cardholder_name.contains("ane She")
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.credit_card_cardholder_name.contains("invalid")
])
self.assertEqual(0, collection.maximum_size)
def test_advanced_search_text_node_starts_with(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012",
"cardholder_name": "Jane Shea"
}
}).transaction
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.credit_card_cardholder_name.starts_with("Jane S")
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.credit_card_cardholder_name.starts_with("invalid")
])
self.assertEqual(0, collection.maximum_size)
def test_advanced_search_text_node_ends_with(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012",
"cardholder_name": "Jane Shea"
}
}).transaction
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.credit_card_cardholder_name.ends_with("e Shea")
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.credit_card_cardholder_name.ends_with("invalid")
])
self.assertEqual(0, collection.maximum_size)
def test_advanced_search_text_node_is_not(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012",
"cardholder_name": "Jane Shea"
}
}).transaction
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.credit_card_cardholder_name != "invalid"
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.credit_card_cardholder_name != "Jane Shea"
])
self.assertEqual(0, collection.maximum_size)
def test_advanced_search_multiple_value_node_created_using(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012"
}
}).transaction
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.created_using == Transaction.CreatedUsing.FullInformation
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.created_using.in_list([Transaction.CreatedUsing.FullInformation, Transaction.CreatedUsing.Token])
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.created_using == Transaction.CreatedUsing.Token
])
self.assertEqual(0, collection.maximum_size)
@raises_with_regexp(AttributeError, "Invalid argument\(s\) for created_using: noSuchCreatedUsing")
def test_advanced_search_multiple_value_node_allowed_values_created_using(self):
Transaction.search([TransactionSearch.created_using == "noSuchCreatedUsing"])
def test_advanced_search_multiple_value_node_credit_card_customer_location(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012"
}
}).transaction
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.credit_card_customer_location == CreditCard.CustomerLocation.US
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.credit_card_customer_location.in_list([CreditCard.CustomerLocation.US, CreditCard.CustomerLocation.International])
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.credit_card_customer_location == CreditCard.CustomerLocation.International
])
self.assertEqual(0, collection.maximum_size)
@raises_with_regexp(AttributeError,
"Invalid argument\(s\) for credit_card_customer_location: noSuchCreditCardCustomerLocation")
def test_advanced_search_multiple_value_node_allowed_values_credit_card_customer_location(self):
Transaction.search([
TransactionSearch.credit_card_customer_location == "noSuchCreditCardCustomerLocation"
])
def test_advanced_search_multiple_value_node_merchant_account_id(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012"
}
}).transaction
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.merchant_account_id == transaction.merchant_account_id
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.merchant_account_id.in_list([transaction.merchant_account_id, "bogus_merchant_account_id"])
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.merchant_account_id == "bogus_merchant_account_id"
])
self.assertEqual(0, collection.maximum_size)
def test_advanced_search_multiple_value_node_credit_card_card_type(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012"
}
}).transaction
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.credit_card_card_type == transaction.credit_card_details.card_type
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.credit_card_card_type.in_list([transaction.credit_card_details.card_type, CreditCard.CardType.AmEx])
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.credit_card_card_type == CreditCard.CardType.AmEx
])
self.assertEqual(0, collection.maximum_size)
@raises_with_regexp(AttributeError,
"Invalid argument\(s\) for credit_card_card_type: noSuchCreditCardCardType")
def test_advanced_search_multiple_value_node_allowed_values_credit_card_card_type(self):
Transaction.search([
TransactionSearch.credit_card_card_type == "noSuchCreditCardCardType"
])
def test_advanced_search_multiple_value_node_status(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012"
}
}).transaction
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.status == Transaction.Status.Authorized
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.status.in_list([Transaction.Status.Authorized, Transaction.Status.Settled])
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.status == Transaction.Status.Settled
])
self.assertEqual(0, collection.maximum_size)
def test_advanced_search_authorization_expired_status(self):
collection = Transaction.search(
TransactionSearch.status == Transaction.Status.AuthorizationExpired
)
self.assertTrue(collection.maximum_size > 0)
self.assertEqual(Transaction.Status.AuthorizationExpired, collection.first.status)
def test_advanced_search_allows_new_settlement_statuses(self):
collection = Transaction.search([
TransactionSearch.status.in_list(["settlement_confirmed", "settlement_declined"])
])
print(collection)
@raises_with_regexp(AttributeError, "Invalid argument\(s\) for status: noSuchStatus")
def test_advanced_search_multiple_value_node_allowed_values_status(self):
Transaction.search([TransactionSearch.status == "noSuchStatus"])
def test_advanced_search_multiple_value_node_source(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012"
}
}).transaction
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.source == Transaction.Source.Api
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.source.in_list([Transaction.Source.Api, Transaction.Source.ControlPanel])
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.source == Transaction.Source.ControlPanel
])
self.assertEqual(0, collection.maximum_size)
def test_advanced_search_multiple_value_node_type(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012"
}
}).transaction
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.type == Transaction.Type.Sale
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.type.in_list([Transaction.Type.Sale, Transaction.Type.Credit])
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.type == Transaction.Type.Credit
])
self.assertEqual(0, collection.maximum_size)
@raises_with_regexp(AttributeError, "Invalid argument\(s\) for type: noSuchType")
def test_advanced_search_multiple_value_node_allowed_values_type(self):
Transaction.search([
TransactionSearch.type == "noSuchType"
])
def test_advanced_search_multiple_value_node_type_with_refund(self):
name = "Anabel Atkins%s" % random.randint(1, 100000)
sale = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012",
"cardholder_name": name
},
'options': {
'submit_for_settlement': True
}
}).transaction
TestHelper.settle_transaction(sale.id)
refund = Transaction.refund(sale.id).transaction
credit = Transaction.credit({
"amount": Decimal(TransactionAmounts.Authorize),
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009",
"cardholder_name": name
}
}).transaction
collection = Transaction.search([
TransactionSearch.credit_card_cardholder_name == name,
TransactionSearch.type == Transaction.Type.Credit
])
self.assertEqual(2, collection.maximum_size)
collection = Transaction.search([
TransactionSearch.credit_card_cardholder_name == name,
TransactionSearch.type == Transaction.Type.Credit,
TransactionSearch.refund == True
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(refund.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.credit_card_cardholder_name == name,
TransactionSearch.type == Transaction.Type.Credit,
TransactionSearch.refund == False
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(credit.id, collection.first.id)
def test_advanced_search_range_node_amount(self):
name = "Henrietta Livingston%s" % random.randint(1, 100000)
t_1000 = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012",
"cardholder_name": name
}
}).transaction
t_1500 = Transaction.sale({
"amount": "1500.00",
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012",
"cardholder_name": name
}
}).transaction
t_1800 = Transaction.sale({
"amount": "1800.00",
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012",
"cardholder_name": name
}
}).transaction
collection = Transaction.search([
TransactionSearch.credit_card_cardholder_name == name,
TransactionSearch.amount >= "1700"
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(t_1800.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.credit_card_cardholder_name == name,
TransactionSearch.amount <= "1250"
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(t_1000.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.credit_card_cardholder_name == name,
TransactionSearch.amount.between("1100", "1600")
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(t_1500.id, collection.first.id)
def test_advanced_search_range_node_created_at_less_than_or_equal_to(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012"
}
}).transaction
past = transaction.created_at - timedelta(minutes=10)
now = transaction.created_at
future = transaction.created_at + timedelta(minutes=10)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.created_at <= past
])
self.assertEqual(0, collection.maximum_size)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.created_at <= now
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.created_at <= future
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
def test_advanced_search_range_node_created_at_greater_than_or_equal_to(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012"
}
}).transaction
past = transaction.created_at - timedelta(minutes=10)
now = transaction.created_at
future = transaction.created_at + timedelta(minutes=10)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.created_at >= past
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.created_at >= now
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.created_at >= future
])
self.assertEqual(0, collection.maximum_size)
def test_advanced_search_range_node_created_at_between(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012"
}
}).transaction
past = transaction.created_at - timedelta(minutes=10)
now = transaction.created_at
future = transaction.created_at + timedelta(minutes=10)
future2 = transaction.created_at + timedelta(minutes=20)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.created_at.between(past, now)
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.created_at.between(now, future)
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.created_at.between(past, future)
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.created_at.between(future, future2)
])
self.assertEqual(0, collection.maximum_size)
def test_advanced_search_range_node_created_at_is(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012"
}
}).transaction
past = transaction.created_at - timedelta(minutes=10)
now = transaction.created_at
future = transaction.created_at + timedelta(minutes=10)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.created_at == past
])
self.assertEqual(0, collection.maximum_size)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.created_at == now
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.created_at == future
])
self.assertEqual(0, collection.maximum_size)
def test_advanced_search_range_node_created_with_dates(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012"
}
}).transaction
past = datetime.today() - timedelta(days=1)
future = datetime.today() + timedelta(days=1)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.created_at.between(past, future)
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
def test_advanced_search_range_node_disbursement_date_less_than_or_equal_to(self):
transaction_id = "deposittransaction"
disbursement_time = datetime(2013, 4, 10, 0, 0, 0)
past = disbursement_time - timedelta(minutes=10)
future = disbursement_time + timedelta(minutes=10)
collection = Transaction.search([
TransactionSearch.id == transaction_id,
TransactionSearch.disbursement_date <= past
])
self.assertEqual(0, collection.maximum_size)
collection = Transaction.search([
TransactionSearch.id == transaction_id,
TransactionSearch.disbursement_date <= disbursement_time
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction_id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction_id,
TransactionSearch.disbursement_date <= future
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction_id, collection.first.id)
def test_advanced_search_range_node_disbursement_date_greater_than_or_equal_to(self):
transaction_id = "deposittransaction"
disbursement_time = datetime(2013, 4, 10, 0, 0, 0)
past = disbursement_time - timedelta(minutes=10)
future = disbursement_time + timedelta(days=1)
collection = Transaction.search([
TransactionSearch.id == transaction_id,
TransactionSearch.disbursement_date >= past
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction_id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction_id,
TransactionSearch.disbursement_date >= disbursement_time
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction_id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction_id,
TransactionSearch.disbursement_date >= future
])
self.assertEqual(0, collection.maximum_size)
def test_advanced_search_range_node_disbursement_date_between(self):
transaction_id = "deposittransaction"
disbursement_time = datetime(2013, 4, 10, 0, 0, 0)
past = disbursement_time - timedelta(days=1)
future = disbursement_time + timedelta(days=1)
future2 = disbursement_time + timedelta(days=2)
collection = Transaction.search([
TransactionSearch.id == transaction_id,
TransactionSearch.disbursement_date.between(past, disbursement_time)
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction_id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction_id,
TransactionSearch.disbursement_date.between(disbursement_time, future)
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction_id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction_id,
TransactionSearch.disbursement_date.between(past, future)
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction_id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction_id,
TransactionSearch.disbursement_date.between(future, future2)
])
self.assertEqual(0, collection.maximum_size)
def test_advanced_search_range_node_disbursement_date_is(self):
transaction_id = "deposittransaction"
disbursement_time = datetime(2013, 4, 10, 0, 0, 0)
past = disbursement_time - timedelta(days=10)
now = disbursement_time
future = disbursement_time + timedelta(days=10)
collection = Transaction.search([
TransactionSearch.id == transaction_id,
TransactionSearch.disbursement_date == past
])
self.assertEqual(0, collection.maximum_size)
collection = Transaction.search([
TransactionSearch.id == transaction_id,
TransactionSearch.disbursement_date == now
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction_id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction_id,
TransactionSearch.disbursement_date == future
])
self.assertEqual(0, collection.maximum_size)
def test_advanced_search_range_node_disbursement_date_with_dates(self):
transaction_id = "deposittransaction"
disbursement_date = date(2013, 4, 10)
past = disbursement_date - timedelta(days=1)
future = disbursement_date + timedelta(days=1)
collection = Transaction.search([
TransactionSearch.id == transaction_id,
TransactionSearch.disbursement_date.between(past, future)
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction_id, collection.first.id)
def test_advanced_search_range_node_disputed_date_less_than_or_equal_to(self):
transaction_id = "disputedtransaction"
disputed_time = datetime(2014, 3, 1, 0, 0, 0)
past = disputed_time - timedelta(minutes=10)
future = disputed_time + timedelta(minutes=10)
collection = Transaction.search([
TransactionSearch.id == transaction_id,
TransactionSearch.dispute_date <= past
])
self.assertEqual(0, collection.maximum_size)
collection = Transaction.search([
TransactionSearch.id == transaction_id,
TransactionSearch.dispute_date <= disputed_time
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction_id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction_id,
TransactionSearch.dispute_date <= future
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction_id, collection.first.id)
def test_advanced_search_range_node_disputed_date_greater_than_or_equal_to(self):
transaction_id = "2disputetransaction"
disputed_time = datetime(2014, 3, 1, 0, 0, 0)
past = disputed_time - timedelta(minutes=10)
future = disputed_time + timedelta(days=1)
collection = Transaction.search([
TransactionSearch.id == transaction_id,
TransactionSearch.dispute_date >= past
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction_id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction_id,
TransactionSearch.dispute_date >= disputed_time
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction_id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction_id,
TransactionSearch.dispute_date >= future
])
self.assertEqual(1, collection.maximum_size)
def test_advanced_search_range_node_disputed_date_between(self):
transaction_id = "disputedtransaction"
disputed_time = datetime(2014, 3, 1, 0, 0, 0)
past = disputed_time - timedelta(days=1)
future = disputed_time + timedelta(days=1)
future2 = disputed_time + timedelta(days=2)
collection = Transaction.search([
TransactionSearch.id == transaction_id,
TransactionSearch.dispute_date.between(past, disputed_time)
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction_id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction_id,
TransactionSearch.dispute_date.between(disputed_time, future)
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction_id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction_id,
TransactionSearch.dispute_date.between(past, future)
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction_id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction_id,
TransactionSearch.dispute_date.between(future, future2)
])
self.assertEqual(0, collection.maximum_size)
def test_advanced_search_range_node_disputed_date_is(self):
transaction_id = "disputedtransaction"
disputed_time = datetime(2014, 3, 1, 0, 0, 0)
past = disputed_time - timedelta(days=10)
now = disputed_time
future = disputed_time + timedelta(days=10)
collection = Transaction.search([
TransactionSearch.id == transaction_id,
TransactionSearch.dispute_date == past
])
self.assertEqual(0, collection.maximum_size)
collection = Transaction.search([
TransactionSearch.id == transaction_id,
TransactionSearch.dispute_date == now
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction_id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction_id,
TransactionSearch.dispute_date == future
])
self.assertEqual(0, collection.maximum_size)
def test_advanced_search_range_node_disputed_date_with_dates(self):
transaction_id = "disputedtransaction"
disputed_date = date(2014, 3, 1)
past = disputed_date - timedelta(days=1)
future = disputed_date + timedelta(days=1)
collection = Transaction.search([
TransactionSearch.id == transaction_id,
TransactionSearch.dispute_date.between(past, future)
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction_id, collection.first.id)
def test_advanced_search_range_node_authorization_expired_at(self):
two_days_ago = datetime.today() - timedelta(days=2)
yesterday = datetime.today() - timedelta(days=1)
tomorrow = datetime.today() + timedelta(days=1)
collection = Transaction.search(
TransactionSearch.authorization_expired_at.between(two_days_ago, yesterday)
)
self.assertEqual(0, collection.maximum_size)
collection = Transaction.search(
TransactionSearch.authorization_expired_at.between(yesterday, tomorrow)
)
self.assertTrue(collection.maximum_size > 0)
self.assertEqual(Transaction.Status.AuthorizationExpired, collection.first.status)
def test_advanced_search_range_node_authorized_at(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012"
}
}).transaction
past = datetime.today() - timedelta(days=1)
future = datetime.today() + timedelta(days=1)
future2 = datetime.today() + timedelta(days=2)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.authorized_at.between(past, future)
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.authorized_at.between(future, future2)
])
self.assertEqual(0, collection.maximum_size)
def test_advanced_search_range_node_failed_at(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Fail,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012"
}
}).transaction
past = datetime.today() - timedelta(days=1)
future = datetime.today() + timedelta(days=1)
future2 = datetime.today() + timedelta(days=2)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.failed_at.between(past, future)
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.failed_at.between(future, future2)
])
self.assertEqual(0, collection.maximum_size)
def test_advanced_search_range_node_gateway_rejected_at(self):
old_merchant_id = Configuration.merchant_id
old_public_key = Configuration.public_key
old_private_key = Configuration.private_key
try:
Configuration.merchant_id = "processing_rules_merchant_id"
Configuration.public_key = "processing_rules_public_key"
Configuration.private_key = "processing_rules_private_key"
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012",
"cvv": "200"
}
}).transaction
past = datetime.today() - timedelta(days=1)
future = datetime.today() + timedelta(days=1)
future2 = datetime.today() + timedelta(days=2)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.gateway_rejected_at.between(past, future)
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.gateway_rejected_at.between(future, future2)
])
self.assertEqual(0, collection.maximum_size)
finally:
Configuration.merchant_id = old_merchant_id
Configuration.public_key = old_public_key
Configuration.private_key = old_private_key
def test_advanced_search_range_node_processor_declined_at(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Decline,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012"
}
}).transaction
past = datetime.today() - timedelta(days=1)
future = datetime.today() + timedelta(days=1)
future2 = datetime.today() + timedelta(days=2)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.processor_declined_at.between(past, future)
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.processor_declined_at.between(future, future2)
])
self.assertEqual(0, collection.maximum_size)
def test_advanced_search_range_node_settled_at(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012"
},
"options": {
"submit_for_settlement": True
}
}).transaction
TestHelper.settle_transaction(transaction.id)
transaction = Transaction.find(transaction.id)
past = datetime.today() - timedelta(days=1)
future = datetime.today() + timedelta(days=1)
future2 = datetime.today() + timedelta(days=2)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.settled_at.between(past, future)
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.settled_at.between(future, future2)
])
self.assertEqual(0, collection.maximum_size)
def test_advanced_search_range_node_submitted_for_settlement_at(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012"
},
"options": {
"submit_for_settlement": True
}
}).transaction
past = datetime.today() - timedelta(days=1)
future = datetime.today() + timedelta(days=1)
future2 = datetime.today() + timedelta(days=2)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.submitted_for_settlement_at.between(past, future)
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.submitted_for_settlement_at.between(future, future2)
])
self.assertEqual(0, collection.maximum_size)
def test_advanced_search_range_node_voided_at(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012"
}
}).transaction
transaction = Transaction.void(transaction.id).transaction
past = datetime.today() - timedelta(days=1)
future = datetime.today() + timedelta(days=1)
future2 = datetime.today() + timedelta(days=2)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.voided_at.between(past, future)
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.voided_at.between(future, future2)
])
self.assertEqual(0, collection.maximum_size)
def test_advanced_search_range_node_can_search_on_multiple_statuses(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012"
},
"options": {
"submit_for_settlement": True
}
}).transaction
past = datetime.today() - timedelta(days=1)
future = datetime.today() + timedelta(days=1)
future2 = datetime.today() + timedelta(days=2)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.authorized_at.between(past, future),
TransactionSearch.submitted_for_settlement_at.between(past, future)
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.authorized_at.between(future, future2),
TransactionSearch.submitted_for_settlement_at.between(future, future2)
])
self.assertEqual(0, collection.maximum_size)
collection = Transaction.search([
TransactionSearch.id == transaction.id,
TransactionSearch.authorized_at.between(past, future),
TransactionSearch.voided_at.between(past, future)
])
self.assertEqual(0, collection.maximum_size)
def test_advanced_search_returns_iteratable_results(self):
collection = Transaction.search([
TransactionSearch.credit_card_number.starts_with("411")
])
self.assertTrue(collection.maximum_size > 100)
transaction_ids = [transaction.id for transaction in collection.items]
self.assertEqual(collection.maximum_size, len(TestHelper.unique(transaction_ids)))
def test_advanced_search_can_search_on_paypal_fields(self):
http = ClientApiHttp.create()
status_code, nonce = http.get_paypal_nonce({
"access_token": "PAYPAL-ACCESS-TOKEN",
"options": {"validate": False}
})
self.assertEqual(202, status_code)
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"payment_method_nonce": nonce
}).transaction
collection = Transaction.search([
TransactionSearch.paypal_payer_email == transaction.paypal_details.payer_email,
TransactionSearch.paypal_authorization_id == transaction.paypal_details.authorization_id,
TransactionSearch.paypal_payment_id == transaction.paypal_details.payment_id,
])
self.assertEqual(1, collection.maximum_size)
self.assertEqual(transaction.id, collection.first.id)
def test_advanced_search_can_search_on_sepa_iban(self):
old_merchant_id = Configuration.merchant_id
old_public_key = Configuration.public_key
old_private_key = Configuration.private_key
try:
Configuration.merchant_id = "altpay_merchant"
Configuration.public_key = "altpay_merchant_public_key"
Configuration.private_key = "altpay_merchant_private_key"
customer_id = Customer.create().customer.id
token = TestHelper.generate_decoded_client_token({"customer_id": customer_id, "sepa_mandate_type": EuropeBankAccount.MandateType.Business})
authorization_fingerprint = json.loads(token)["authorizationFingerprint"]
config = Configuration.instantiate()
client_api = ClientApiHttp(config, {
"authorization_fingerprint": authorization_fingerprint,
"shared_customer_identifier": "fake_identifier",
"shared_customer_identifier_type": "testing"
})
nonce = client_api.get_europe_bank_account_nonce({
"locale": "de-DE",
"bic": "DEUTDEFF",
"iban": "DE89370400440532013000",
"accountHolderName": "Baron Von Holder",
"billingAddress": {"region": "Hesse", "country_name": "Germany"}
})
result = Transaction.sale({
"merchant_account_id": "fake_sepa_ma",
"amount": "10.00",
"payment_method_nonce": nonce
})
collection = Transaction.search([
TransactionSearch.europe_bank_account_iban == "DE89370400440532013000"
])
self.assertTrue(collection.maximum_size >= 1)
ids = [transaction.id for transaction in collection.items]
self.assertIn(result.transaction.id, ids)
finally:
Configuration.merchant_id = old_merchant_id
Configuration.public_key = old_public_key
Configuration.private_key = old_private_key
@raises(DownForMaintenanceError)
def test_search_handles_a_search_timeout(self):
Transaction.search([
TransactionSearch.amount.between("-1100", "1600")
])
braintree_python-3.38.0/tests/integration/test_plan.py 0000644 0001750 0001750 00000005711 13150065776 021331 0 ustar hle hle from tests.test_helper import *
class TestPlan(unittest.TestCase):
def test_all_returns_empty_list(self):
Configuration.configure(
Environment.Development,
"test_merchant_id",
"test_public_key",
"test_private_key"
)
plans = Plan.all()
self.assertEqual([], plans)
Configuration.configure(
Environment.Development,
"integration_merchant_id",
"integration_public_key",
"integration_private_key"
)
def test_all_returns_all_the_plans(self):
plan_token = str(random.randint(1, 1000000))
attributes = {
"id": plan_token,
"billing_day_of_month": 1,
"billing_frequency": 1,
"currency_iso_code": "USD",
"description": "some description",
"name": "python test plan",
"number_of_billing_cycles": 1,
"price": "1.00",
}
Configuration.instantiate().http().post(Configuration.instantiate().base_merchant_path() + "/plans/create_plan_for_tests", {"plan": attributes})
add_on_attributes = {
"amount": "100.00",
"description": "some description",
"plan_id": plan_token,
"kind": "add_on",
"name": "python_add_on",
"never_expires": False,
"number_of_billing_cycles": 1
}
Configuration.instantiate().http().post(Configuration.instantiate().base_merchant_path() + "/modifications/create_modification_for_tests", {"modification": add_on_attributes})
discount_attributes = {
"amount": "100.00",
"description": "some description",
"plan_id": plan_token,
"kind": "discount",
"name": "python_discount",
"never_expires": False,
"number_of_billing_cycles": 1
}
Configuration.instantiate().http().post(Configuration.instantiate().base_merchant_path() + "/modifications/create_modification_for_tests", {"modification": discount_attributes})
plans = Plan.all()
for plan in plans:
if plan.id == plan_token:
actual_plan = plan
self.assertNotEqual(None, actual_plan)
self.assertEqual(1, attributes["billing_day_of_month"])
self.assertEqual(1, attributes["billing_frequency"])
self.assertEqual("USD", attributes["currency_iso_code"])
self.assertEqual("some description", attributes["description"])
self.assertEqual("python test plan", attributes["name"])
self.assertEqual(1, attributes["number_of_billing_cycles"])
self.assertEqual("1.00", attributes["price"])
self.assertEqual(1, len(actual_plan.add_ons))
self.assertEqual(add_on_attributes["name"], actual_plan.add_ons[0].name)
self.assertEqual(1, len(actual_plan.discounts))
self.assertEqual(discount_attributes["name"], actual_plan.discounts[0].name)
braintree_python-3.38.0/tests/integration/test_oauth.py 0000644 0001750 0001750 00000016041 13150065776 021515 0 ustar hle hle from tests.test_helper import *
from braintree.test.nonces import Nonces
import sys
if sys.version_info[0] == 2:
import urlparse
else:
import urllib.parse as urlparse
class TestOAuthGateway(unittest.TestCase):
def setUp(self):
self.gateway = BraintreeGateway(
client_id="client_id$development$integration_client_id",
client_secret="client_secret$development$integration_client_secret"
)
def test_create_token_from_code(self):
code = TestHelper.create_grant(self.gateway, {
"merchant_public_id": "integration_merchant_id",
"scope": "read_write"
})
result = self.gateway.oauth.create_token_from_code({
"code": code
})
self.assertTrue(result.is_success)
credentials = result.credentials
self.assertIsNotNone(credentials.access_token)
self.assertIsNotNone(credentials.refresh_token)
self.assertIsNotNone(credentials.expires_at)
self.assertEqual("bearer", credentials.token_type)
def test_create_token_from_code_with_bad_parameters(self):
result = self.gateway.oauth.create_token_from_code({
"code": "bad_code",
"scope": "read_write"
})
self.assertFalse(result.is_success)
self.assertIn(result.message, "Invalid grant: code not found")
credentials_code_errors = result.errors.for_object("credentials").on("code")
self.assertEqual(1, len(credentials_code_errors))
self.assertEqual(ErrorCodes.OAuth.InvalidGrant, credentials_code_errors[0].code)
def test_create_token_from_code_returns_helpful_error_with_bad_credentials(self):
gateway = BraintreeGateway(
access_token="access_token$development$integration_merchant_id$fb27c79dd",
)
with self.assertRaises(ConfigurationError) as error:
gateway.oauth.create_token_from_code({
"code": "some_code",
"scope": "read_write"
})
config_error = error.exception
self.assertIn("client_id and client_secret are required", str(config_error))
def test_create_token_from_refresh_token(self):
code = TestHelper.create_grant(self.gateway, {
"merchant_public_id": "integration_merchant_id",
"scope": "read_write"
})
refresh_token = self.gateway.oauth.create_token_from_code({
"code": code,
"scope": "read_write"
}).credentials.refresh_token
result = self.gateway.oauth.create_token_from_refresh_token({
"refresh_token": refresh_token
})
self.assertTrue(result.is_success)
credentials = result.credentials
self.assertIsNotNone(credentials.access_token)
self.assertIsNotNone(credentials.refresh_token)
self.assertIsNotNone(credentials.expires_at)
self.assertEqual("bearer", credentials.token_type)
def test_revoke_access_token(self):
code = TestHelper.create_grant(self.gateway, {
"merchant_public_id": "integration_merchant_id",
"scope": "read_write"
})
access_token = self.gateway.oauth.create_token_from_code({
"code": code,
"scope": "read_write"
}).credentials.access_token
result = self.gateway.oauth.revoke_access_token(access_token)
self.assertTrue(result.is_success)
with self.assertRaises(AuthenticationError):
gateway = BraintreeGateway(access_token=access_token)
gateway.customer.create()
def test_connect_url(self):
connect_url = self.gateway.oauth.connect_url({
"merchant_id": "integration_merchant_id",
"redirect_uri": "http://bar.example.com",
"scope": "read_write",
"state": "baz_state",
"landing_page": "login",
"user": {
"country": "USA",
"email": "foo@example.com",
"first_name": "Bob",
"last_name": "Jones",
"phone": "555-555-5555",
"dob_year": "1970",
"dob_month": "01",
"dob_day": "01",
"street_address": "222 W Merchandise Mart",
"locality": "Chicago",
"region": "IL",
"postal_code": "60606"
},
"business": {
"name": "14 Ladders",
"registered_as": "14.0 Ladders",
"industry": "Ladders",
"description": "We sell the best ladders",
"street_address": "111 N Canal",
"locality": "Chicago",
"region": "IL",
"postal_code": "60606",
"country": "USA",
"annual_volume_amount": "1000000",
"average_transaction_amount": "100",
"maximum_transaction_amount": "10000",
"ship_physical_goods": "true",
"fulfillment_completed_in": 7,
"currency": "USD",
"website": "http://example.com"
},
"payment_methods": ["credit_card", "paypal"]
})
query_string = urlparse.urlparse(connect_url)[4]
params = urlparse.parse_qs(query_string)
self.assertEqual(params["merchant_id"], ["integration_merchant_id"])
self.assertEqual(params["client_id"], ["client_id$development$integration_client_id"])
self.assertEqual(params["redirect_uri"], ["http://bar.example.com"])
self.assertEqual(params["scope"], ["read_write"])
self.assertEqual(params["state"], ["baz_state"])
self.assertEqual(params["landing_page"], ["login"])
self.assertEqual(params["user[country]"], ["USA"])
self.assertEqual(params["business[name]"], ["14 Ladders"])
self.assertEqual(params["payment_methods[]"], ["credit_card", "paypal"])
self.assertEqual(64, len(params["signature"][0]))
self.assertEqual(["SHA256"], params["algorithm"])
def test_connect_url_limits_payment_methods(self):
connect_url = self.gateway.oauth.connect_url({
"merchant_id": "integration_merchant_id",
"redirect_uri": "http://bar.example.com",
"scope": "read_write",
"state": "baz_state",
"payment_methods": ["credit_card"]
})
query_string = urlparse.urlparse(connect_url)[4]
params = urlparse.parse_qs(query_string)
self.assertEqual(params["merchant_id"], ["integration_merchant_id"])
self.assertEqual(params["client_id"], ["client_id$development$integration_client_id"])
self.assertEqual(params["redirect_uri"], ["http://bar.example.com"])
self.assertEqual(params["payment_methods[]"], ["credit_card"])
def test_compute_signature(self):
url = "http://localhost:3000/oauth/connect?business%5Bname%5D=We+Like+Spaces&client_id=client_id%24development%24integration_client_id"
signature = self.gateway.oauth._compute_signature(url)
self.assertEqual("a36bcf10dd982e2e47e0d6a2cb930aea47ade73f954b7d59c58dae6167894d41", signature)
braintree_python-3.38.0/tests/integration/test_settlement_batch_summary.py 0000644 0001750 0001750 00000005217 13150065776 025502 0 ustar hle hle from tests.test_helper import *
class TestSettlementBatchSummary(unittest.TestCase):
possible_gateway_time_zone_offsets = (5, 4)
def test_generate_returns_empty_collection_if_there_is_no_data(self):
result = SettlementBatchSummary.generate('2011-01-01')
self.assertTrue(result.is_success)
self.assertEqual([], result.settlement_batch_summary.records)
def test_generate_returns_error_if_date_can_not_be_parsed(self):
result = SettlementBatchSummary.generate('THIS AINT NO DATE')
self.assertFalse(result.is_success)
settlement_date_errors = result.errors.for_object('settlement_batch_summary').on('settlement_date')
self.assertEqual(1, len(settlement_date_errors))
self.assertEqual(ErrorCodes.SettlementBatchSummary.SettlementDateIsInvalid, settlement_date_errors[0].code)
def test_generate_returns_transactions_settled_on_a_given_day(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012",
"cardholder_name": "Sergio Ramos"
},
"merchant_account_id": "sandbox_credit_card",
"options": {"submit_for_settlement": True}
})
result = TestHelper.settle_transaction(result.transaction.id)
settlement_date = result.transaction.settlement_batch_id.split('_')[0]
result = SettlementBatchSummary.generate(settlement_date)
self.assertTrue(result.is_success)
visa_records = [row for row in result.settlement_batch_summary.records
if row['card_type'] == 'Visa'
and row['merchant_account_id'] == 'sandbox_credit_card'][0]
count = int(visa_records['count'])
self.assertGreaterEqual(count, 1)
def test_generate_can_be_grouped_by_a_custom_field(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012",
"cardholder_name": "Sergio Ramos"
},
"options": {"submit_for_settlement": True},
"custom_fields": {
"store_me": 1
}
})
result = TestHelper.settle_transaction(result.transaction.id)
settlement_date = result.transaction.settlement_batch_id.split('_')[0]
result = SettlementBatchSummary.generate(settlement_date, 'store_me')
self.assertTrue(result.is_success)
self.assertTrue('store_me' in result.settlement_batch_summary.records[0])
braintree_python-3.38.0/tests/integration/test_credit_card.py 0000644 0001750 0001750 00000146014 13150065776 022644 0 ustar hle hle from tests.test_helper import *
from braintree.test.credit_card_defaults import CreditCardDefaults
from braintree.test.credit_card_numbers import CreditCardNumbers
import braintree.test.venmo_sdk as venmo_sdk
class TestCreditCard(unittest.TestCase):
def test_create_adds_credit_card_to_existing_customer(self):
customer = Customer.create().customer
result = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "05/2014",
"cvv": "100",
"cardholder_name": "John Doe"
})
self.assertTrue(result.is_success)
credit_card = result.credit_card
self.assertTrue(re.search(r"\A\w{4,}\Z", credit_card.token) is not None)
self.assertEqual("411111", credit_card.bin)
self.assertEqual("1111", credit_card.last_4)
self.assertEqual("05", credit_card.expiration_month)
self.assertEqual("2014", credit_card.expiration_year)
self.assertEqual("05/2014", credit_card.expiration_date)
self.assertEqual("John Doe", credit_card.cardholder_name)
self.assertNotEqual(re.search(r"\A\w{32}\Z", credit_card.unique_number_identifier), None)
self.assertFalse(credit_card.venmo_sdk)
self.assertNotEqual(re.search("png", credit_card.image_url), None)
def test_create_and_make_default(self):
customer = Customer.create().customer
card1 = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "05/2014",
"cvv": "100",
"cardholder_name": "John Doe"
}).credit_card
self.assertTrue(card1.default)
card2 = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "05/2014",
"cvv": "100",
"cardholder_name": "John Doe",
"options":
{"make_default": True}
}).credit_card
card1 = CreditCard.find(card1.token)
self.assertFalse(card1.default)
self.assertTrue(card2.default)
def test_create_with_expiration_month_and_year(self):
customer = Customer.create().customer
result = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_month": "05",
"expiration_year": "2014",
"cvv": "100",
"cardholder_name": "John Doe"
})
self.assertTrue(result.is_success)
credit_card = result.credit_card
self.assertEqual("05/2014", credit_card.expiration_date)
def test_create_with_security_params(self):
customer = Customer.create().customer
result = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_month": "05",
"expiration_year": "2014",
"cvv": "100",
"cardholder_name": "John Doe",
"device_session_id": "abc123",
"fraud_merchant_id": "456"
})
self.assertTrue(result.is_success)
def test_create_can_specify_the_desired_token(self):
token = str(random.randint(1, 1000000))
customer = Customer.create().customer
result = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "05/2014",
"token": token
})
self.assertTrue(result.is_success)
credit_card = result.credit_card
self.assertEqual(token, credit_card.token)
def test_create_with_billing_address(self):
customer = Customer.create().customer
result = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "05/2014",
"billing_address": {
"street_address": "123 Abc Way",
"locality": "Chicago",
"region": "Illinois",
"postal_code": "60622",
"country_code_alpha2": "MX",
"country_code_alpha3": "MEX",
"country_code_numeric": "484",
"country_name": "Mexico"
}
})
self.assertTrue(result.is_success)
address = result.credit_card.billing_address
self.assertEqual("123 Abc Way", address.street_address)
self.assertEqual("Chicago", address.locality)
self.assertEqual("Illinois", address.region)
self.assertEqual("60622", address.postal_code)
self.assertEqual("MX", address.country_code_alpha2)
self.assertEqual("MEX", address.country_code_alpha3)
self.assertEqual("484", address.country_code_numeric)
self.assertEqual("Mexico", address.country_name)
def test_create_with_billing_address_id(self):
customer = Customer.create().customer
address = Address.create({
"customer_id": customer.id,
"street_address": "123 Abc Way"
}).address
result = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "05/2014",
"billing_address_id": address.id
})
self.assertTrue(result.is_success)
billing_address = result.credit_card.billing_address
self.assertEqual(address.id, billing_address.id)
self.assertEqual("123 Abc Way", billing_address.street_address)
def test_create_without_billing_address_still_has_billing_address_method(self):
customer = Customer.create().customer
result = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "05/2014",
})
self.assertTrue(result.is_success)
self.assertEqual(None, result.credit_card.billing_address)
def test_create_with_card_verification_returns_risk_data(self):
customer = Customer.create().customer
result = CreditCard.create({
"customer_id": customer.id,
"number": "4000111111111115",
"expiration_date": "05/2014",
"options": {"verify_card": True}
})
self.assertFalse(result.is_success)
verification = result.credit_card_verification
self.assertIsInstance(verification.risk_data, RiskData)
self.assertEqual(None, verification.risk_data.id)
self.assertEqual("Not Evaluated", verification.risk_data.decision)
def test_successful_create_with_card_verification_returns_risk_data(self):
customer = Customer.create().customer
result = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "05/2014",
"options": {"verify_card": True}
})
self.assertTrue(result.is_success)
verification = result.credit_card.verification
self.assertIsInstance(verification.risk_data, RiskData)
self.assertEqual(None, verification.risk_data.id)
self.assertEqual("Not Evaluated", verification.risk_data.decision)
def test_create_with_card_verification(self):
customer = Customer.create().customer
result = CreditCard.create({
"customer_id": customer.id,
"number": "4000111111111115",
"expiration_date": "05/2014",
"options": {"verify_card": True}
})
self.assertFalse(result.is_success)
verification = result.credit_card_verification
self.assertEqual(CreditCardVerification.Status.ProcessorDeclined, verification.status)
self.assertEqual("2000", verification.processor_response_code)
self.assertEqual("Do Not Honor", verification.processor_response_text)
self.assertEqual("I", verification.cvv_response_code)
self.assertEqual(None, verification.avs_error_response_code)
self.assertEqual("I", verification.avs_postal_code_response_code)
self.assertEqual("I", verification.avs_street_address_response_code)
self.assertEqual(Decimal("0.00"), verification.amount)
self.assertEqual("USD", verification.currency_iso_code)
self.assertEqual(TestHelper.default_merchant_account_id, verification.merchant_account_id)
def test_create_with_card_verification_with_overridden_amount(self):
customer = Customer.create().customer
result = CreditCard.create({
"customer_id": customer.id,
"number": "4000111111111115",
"expiration_date": "05/2014",
"options": {"verify_card": True, "verification_amount": "1.02"}
})
self.assertFalse(result.is_success)
verification = result.credit_card_verification
self.assertEqual(CreditCardVerification.Status.ProcessorDeclined, verification.status)
self.assertEqual("2000", verification.processor_response_code)
self.assertEqual("Do Not Honor", verification.processor_response_text)
self.assertEqual("I", verification.cvv_response_code)
self.assertEqual(None, verification.avs_error_response_code)
self.assertEqual("I", verification.avs_postal_code_response_code)
self.assertEqual("I", verification.avs_street_address_response_code)
self.assertEqual(Decimal("1.02"), verification.amount)
self.assertEqual("USD", verification.currency_iso_code)
self.assertEqual(TestHelper.default_merchant_account_id, verification.merchant_account_id)
def test_create_with_card_verification_and_non_default_merchant_account(self):
customer = Customer.create().customer
result = CreditCard.create({
"customer_id": customer.id,
"number": "4000111111111115",
"expiration_date": "05/2014",
"options": {
"verification_merchant_account_id": TestHelper.non_default_merchant_account_id,
"verify_card": True
}
})
self.assertFalse(result.is_success)
verification = result.credit_card_verification
self.assertEqual(CreditCardVerification.Status.ProcessorDeclined, verification.status)
self.assertEqual(None, verification.gateway_rejection_reason)
self.assertEqual(TestHelper.non_default_merchant_account_id, verification.merchant_account_id)
def test_verify_gateway_rejected_responds_to_processor_response_code(self):
old_merchant_id = Configuration.merchant_id
old_public_key = Configuration.public_key
old_private_key = Configuration.private_key
try:
Configuration.merchant_id = "processing_rules_merchant_id"
Configuration.public_key = "processing_rules_public_key"
Configuration.private_key = "processing_rules_private_key"
customer = Customer.create().customer
result = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "05/2014",
"billing_address": {
"postal_code": "20000"
},
"options": {
"verify_card": True
}
})
self.assertFalse(result.is_success)
self.assertEqual('1000', result.credit_card_verification.processor_response_code)
self.assertEqual('Approved', result.credit_card_verification.processor_response_text)
finally:
Configuration.merchant_id = old_merchant_id
Configuration.public_key = old_public_key
Configuration.private_key = old_private_key
def test_expose_gateway_rejection_reason_on_verification(self):
old_merchant_id = Configuration.merchant_id
old_public_key = Configuration.public_key
old_private_key = Configuration.private_key
try:
Configuration.merchant_id = "processing_rules_merchant_id"
Configuration.public_key = "processing_rules_public_key"
Configuration.private_key = "processing_rules_private_key"
customer = Customer.create().customer
result = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "05/2014",
"cvv": "200",
"options": {
"verify_card": True
}
})
self.assertFalse(result.is_success)
verification = result.credit_card_verification
self.assertEqual(Transaction.GatewayRejectionReason.Cvv, verification.gateway_rejection_reason)
finally:
Configuration.merchant_id = old_merchant_id
Configuration.public_key = old_public_key
Configuration.private_key = old_private_key
def test_create_with_card_verification_set_to_false(self):
customer = Customer.create().customer
result = CreditCard.create({
"customer_id": customer.id,
"number": "4000111111111115",
"expiration_date": "05/2014",
"options": {"verify_card": False}
})
self.assertTrue(result.is_success)
def test_create_with_fail_on_duplicate_payment_method_set_to_true(self):
customer = Customer.create().customer
CreditCard.create({
"customer_id": customer.id,
"number": "4000111111111115",
"expiration_date": "05/2014"
})
result = CreditCard.create({
"customer_id": customer.id,
"number": "4000111111111115",
"expiration_date": "05/2014",
"options": {"fail_on_duplicate_payment_method": True}
})
self.assertFalse(result.is_success)
self.assertEqual("Duplicate card exists in the vault.", result.message)
credit_card_number_errors = result.errors.for_object("credit_card").on("number")
self.assertEqual(1, len(credit_card_number_errors))
self.assertEqual(ErrorCodes.CreditCard.DuplicateCardExists, credit_card_number_errors[0].code)
def test_create_with_invalid_invalid_options(self):
customer = Customer.create().customer
result = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "invalid_date",
})
self.assertFalse(result.is_success)
self.assertEqual("Expiration date is invalid.", result.message)
expiration_date_errors = result.errors.for_object("credit_card").on("expiration_date")
self.assertEqual(1, len(expiration_date_errors))
self.assertEqual(ErrorCodes.CreditCard.ExpirationDateIsInvalid, expiration_date_errors[0].code)
def test_create_with_invalid_country_codes(self):
customer = Customer.create().customer
result = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "05/2012",
"billing_address": {
"country_code_alpha2": "ZZ",
"country_code_alpha3": "ZZZ",
"country_code_numeric": "000",
"country_name": "zzzzzzz"
}
})
self.assertFalse(result.is_success)
country_code_alpha2_errors = result.errors.for_object("credit_card").for_object("billing_address").on("country_code_alpha2")
self.assertEqual(1, len(country_code_alpha2_errors))
self.assertEqual(ErrorCodes.Address.CountryCodeAlpha2IsNotAccepted, country_code_alpha2_errors[0].code)
country_code_alpha3_errors = result.errors.for_object("credit_card").for_object("billing_address").on("country_code_alpha3")
self.assertEqual(1, len(country_code_alpha3_errors))
self.assertEqual(ErrorCodes.Address.CountryCodeAlpha3IsNotAccepted, country_code_alpha3_errors[0].code)
country_code_numeric_errors = result.errors.for_object("credit_card").for_object("billing_address").on("country_code_numeric")
self.assertEqual(1, len(country_code_numeric_errors))
self.assertEqual(ErrorCodes.Address.CountryCodeNumericIsNotAccepted, country_code_numeric_errors[0].code)
country_name_errors = result.errors.for_object("credit_card").for_object("billing_address").on("country_name")
self.assertEqual(1, len(country_name_errors))
self.assertEqual(ErrorCodes.Address.CountryNameIsNotAccepted, country_name_errors[0].code)
def test_create_with_venmo_sdk_payment_method_code(self):
customer = Customer.create().customer
result = CreditCard.create({
"customer_id": customer.id,
"venmo_sdk_payment_method_code": venmo_sdk.VisaPaymentMethodCode
})
self.assertTrue(result.is_success)
self.assertEqual("411111", result.credit_card.bin)
self.assertTrue(result.credit_card.venmo_sdk)
def test_create_with_invalid_venmo_sdk_payment_method_code(self):
customer = Customer.create().customer
result = CreditCard.create({
"customer_id": customer.id,
"venmo_sdk_payment_method_code": venmo_sdk.InvalidPaymentMethodCode
})
self.assertFalse(result.is_success)
self.assertEqual("Invalid VenmoSDK payment method code", result.message)
venmo_sdk_payment_method_code_errors = result.errors.for_object("credit_card").on("venmo_sdk_payment_method_code")
self.assertEqual(1, len(venmo_sdk_payment_method_code_errors))
self.assertEqual(ErrorCodes.CreditCard.InvalidVenmoSDKPaymentMethodCode, venmo_sdk_payment_method_code_errors[0].code)
def test_create_with_payment_method_nonce(self):
config = Configuration.instantiate()
authorization_fingerprint = json.loads(TestHelper.generate_decoded_client_token())["authorizationFingerprint"]
http = ClientApiHttp(config, {
"authorization_fingerprint": authorization_fingerprint,
"shared_customer_identifier": "fake_identifier",
"shared_customer_identifier_type": "testing"
})
_, response = http.add_card({
"credit_card": {
"number": "4111111111111111",
"expiration_month": "11",
"expiration_year": "2099",
},
"share": True
})
nonce = json.loads(response)["creditCards"][0]["nonce"]
customer = Customer.create().customer
result = CreditCard.create({
"customer_id": customer.id,
"payment_method_nonce": nonce
})
self.assertTrue(result.is_success)
self.assertEqual("411111", result.credit_card.bin)
def test_create_with_venmo_sdk_session(self):
customer = Customer.create().customer
result = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "05/2014",
"cvv": "100",
"cardholder_name": "John Doe",
"options": {
"venmo_sdk_session": venmo_sdk.Session
}
})
self.assertTrue(result.is_success)
self.assertTrue(result.credit_card.venmo_sdk)
def test_create_with_invalid_venmo_sdk_session(self):
customer = Customer.create().customer
result = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "05/2014",
"cvv": "100",
"cardholder_name": "John Doe",
"options": {
"venmo_sdk_session": venmo_sdk.InvalidSession
}
})
self.assertTrue(result.is_success)
self.assertFalse(result.credit_card.venmo_sdk)
def test_update_with_valid_options(self):
customer = Customer.create().customer
credit_card = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "05/2014",
"cvv": "100",
"cardholder_name": "John Doe"
}).credit_card
result = CreditCard.update(credit_card.token, {
"number": "5105105105105100",
"expiration_date": "06/2010",
"cvv": "123",
"cardholder_name": "Jane Jones"
})
self.assertTrue(result.is_success)
credit_card = result.credit_card
self.assertTrue(re.search(r"\A\w{4,}\Z", credit_card.token) is not None)
self.assertEqual("510510", credit_card.bin)
self.assertEqual("5100", credit_card.last_4)
self.assertEqual("06", credit_card.expiration_month)
self.assertEqual("2010", credit_card.expiration_year)
self.assertEqual("06/2010", credit_card.expiration_date)
self.assertEqual("Jane Jones", credit_card.cardholder_name)
def test_update_billing_address_creates_new_by_default(self):
customer = Customer.create().customer
initial_credit_card = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "05/2014",
"billing_address": {
"street_address": "123 Nigeria Ave",
}
}).credit_card
updated_credit_card = CreditCard.update(initial_credit_card.token, {
"billing_address": {
"region": "IL",
"country_code_alpha2": "NG",
"country_code_alpha3": "NGA",
"country_code_numeric": "566",
"country_name": "Nigeria"
}
}).credit_card
self.assertEqual("IL", updated_credit_card.billing_address.region)
self.assertEqual("NG", updated_credit_card.billing_address.country_code_alpha2)
self.assertEqual("NGA", updated_credit_card.billing_address.country_code_alpha3)
self.assertEqual("566", updated_credit_card.billing_address.country_code_numeric)
self.assertEqual("Nigeria", updated_credit_card.billing_address.country_name)
self.assertEqual(None, updated_credit_card.billing_address.street_address)
self.assertNotEqual(initial_credit_card.billing_address.id, updated_credit_card.billing_address.id)
def test_update_billing_address_when_update_existing_is_True(self):
customer = Customer.create().customer
initial_credit_card = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "05/2014",
"billing_address": {
"street_address": "123 Nigeria Ave",
}
}).credit_card
updated_credit_card = CreditCard.update(initial_credit_card.token, {
"billing_address": {
"region": "IL",
"options": {
"update_existing": True
}
}
}).credit_card
self.assertEqual("IL", updated_credit_card.billing_address.region)
self.assertEqual("123 Nigeria Ave", updated_credit_card.billing_address.street_address)
self.assertEqual(initial_credit_card.billing_address.id, updated_credit_card.billing_address.id)
def test_update_and_make_default(self):
customer = Customer.create().customer
card1 = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "05/2014",
"cvv": "100",
"cardholder_name": "John Doe"
}).credit_card
card2 = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "05/2014",
"cvv": "100",
"cardholder_name": "John Doe"
}).credit_card
self.assertTrue(card1.default)
self.assertFalse(card2.default)
CreditCard.update(card2.token, {
"options": {
"make_default": True
}
})
self.assertFalse(CreditCard.find(card1.token).default)
self.assertTrue(CreditCard.find(card2.token).default)
def test_update_verifies_card_if_option_is_provided(self):
customer = Customer.create().customer
credit_card = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "05/2014",
"cvv": "100",
"cardholder_name": "John Doe"
}).credit_card
result = CreditCard.update(credit_card.token, {
"number": "4000111111111115",
"expiration_date": "06/2010",
"cvv": "123",
"cardholder_name": "Jane Jones",
"options": {"verify_card": True}
})
self.assertFalse(result.is_success)
self.assertEqual(CreditCardVerification.Status.ProcessorDeclined, result.credit_card_verification.status)
def test_update_verifies_card_with_non_default_merchant_account(self):
customer = Customer.create().customer
credit_card = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "05/2014",
"cvv": "100",
"cardholder_name": "John Doe"
}).credit_card
result = CreditCard.update(credit_card.token, {
"number": "4000111111111115",
"expiration_date": "06/2010",
"cvv": "123",
"cardholder_name": "Jane Jones",
"options": {
"verification_merchant_account_id": TestHelper.non_default_merchant_account_id,
"verify_card": True
}
})
self.assertFalse(result.is_success)
self.assertEqual(CreditCardVerification.Status.ProcessorDeclined, result.credit_card_verification.status)
def test_update_billing_address(self):
customer = Customer.create().customer
credit_card = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "05/2014",
"billing_address": {
"street_address": "321 Xyz Way",
"locality": "Chicago",
"region": "Illinois",
"postal_code": "60621"
}
}).credit_card
result = CreditCard.update(credit_card.token, {
"billing_address": {
"street_address": "123 Abc Way",
"locality": "Chicago",
"region": "Illinois",
"postal_code": "60622"
}
})
self.assertTrue(result.is_success)
address = result.credit_card.billing_address
self.assertEqual("123 Abc Way", address.street_address)
self.assertEqual("Chicago", address.locality)
self.assertEqual("Illinois", address.region)
self.assertEqual("60622", address.postal_code)
def test_update_returns_error_if_invalid(self):
customer = Customer.create().customer
credit_card = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "05/2014"
}).credit_card
result = CreditCard.update(credit_card.token, {
"expiration_date": "invalid_date"
})
self.assertFalse(result.is_success)
expiration_date_errors = result.errors.for_object("credit_card").on("expiration_date")
self.assertEqual(1, len(expiration_date_errors))
self.assertEqual(ErrorCodes.CreditCard.ExpirationDateIsInvalid, expiration_date_errors[0].code)
def test_update_returns_error_with_duplicate_payment_method_if_fail_on_duplicate_payment_method_is_set(self):
create_result = Customer.create({
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2021",
}
})
self.assertTrue(create_result.is_success)
update_result = Customer.update(create_result.customer.id, {
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2021",
"options": {
"fail_on_duplicate_payment_method": True,
},
}
})
self.assertFalse(update_result.is_success)
number_errors = update_result.errors.for_object("customer").for_object("credit_card").on("number")
self.assertEqual(1, len(number_errors))
self.assertEqual(ErrorCodes.CreditCard.DuplicateCardExists, number_errors[0].code)
def test_delete_with_valid_token(self):
customer = Customer.create().customer
credit_card = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "05/2014"
}).credit_card
result = CreditCard.delete(credit_card.token)
self.assertTrue(result.is_success)
@raises(NotFoundError)
def test_delete_raises_error_when_deleting_twice(self):
customer = Customer.create().customer
credit_card = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "05/2014"
}).credit_card
CreditCard.delete(credit_card.token)
CreditCard.delete(credit_card.token)
@raises(NotFoundError)
def test_delete_with_invalid_token(self):
CreditCard.delete("notreal")
def test_find_with_valid_token(self):
customer = Customer.create().customer
credit_card = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "05/2014"
}).credit_card
found_credit_card = CreditCard.find(credit_card.token)
self.assertTrue(re.search(r"\A\w{4,}\Z", found_credit_card.token) is not None)
self.assertEqual("411111", found_credit_card.bin)
self.assertEqual("1111", found_credit_card.last_4)
self.assertEqual("05", found_credit_card.expiration_month)
self.assertEqual("2014", found_credit_card.expiration_year)
self.assertEqual("05/2014", found_credit_card.expiration_date)
def test_find_returns_associated_subsriptions(self):
customer = Customer.create().customer
credit_card = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "05/2014"
}).credit_card
subscription_id = "id_" + str(random.randint(1, 1000000))
subscription = Subscription.create({
"id": subscription_id,
"plan_id": "integration_trialless_plan",
"payment_method_token": credit_card.token,
"price": Decimal("1.00")
}).subscription
found_credit_card = CreditCard.find(credit_card.token)
subscriptions = found_credit_card.subscriptions
self.assertEqual(1, len(subscriptions))
subscription = subscriptions[0]
self.assertEqual(subscription_id, subscription.id)
self.assertEqual(Decimal("1.00"), subscription.price)
self.assertEqual(credit_card.token, subscription.payment_method_token)
@raises_with_regexp(NotFoundError, "payment method with token 'bad_token' not found")
def test_find_with_invalid_token(self):
CreditCard.find("bad_token")
def test_from_nonce_with_unlocked_nonce(self):
config = Configuration.instantiate()
customer = Customer.create().customer
client_token = TestHelper.generate_decoded_client_token({
"customer_id": customer.id,
})
authorization_fingerprint = json.loads(client_token)["authorizationFingerprint"]
http = ClientApiHttp(config, {
"authorization_fingerprint": authorization_fingerprint,
"shared_customer_identifier": "fake_identifier",
"shared_customer_identifier_type": "testing"
})
status_code, response = http.add_card({
"credit_card": {
"number": "4111111111111111",
"expiration_month": "11",
"expiration_year": "2099",
}
})
self.assertEqual(201, status_code)
nonce = json.loads(response)["creditCards"][0]["nonce"]
card = CreditCard.from_nonce(nonce)
customer = Customer.find(customer.id)
self.assertEqual(1, len(customer.credit_cards))
self.assertEqual(customer.credit_cards[0].token, card.token)
@raises_with_regexp(NotFoundError, "payment method with nonce .* or not found")
def test_from_nonce_with_unlocked_nonce_pointing_to_shared_card(self):
config = Configuration.instantiate()
client_token = TestHelper.generate_decoded_client_token()
authorization_fingerprint = json.loads(client_token)["authorizationFingerprint"]
http = ClientApiHttp(config, {
"authorization_fingerprint": authorization_fingerprint,
"shared_customer_identifier": "fake_identifier",
"shared_customer_identifier_type": "testing"
})
status_code, response = http.add_card({
"credit_card": {
"number": "4111111111111111",
"expiration_month": "11",
"expiration_year": "2099",
},
"share": True
})
self.assertEqual(201, status_code)
nonce = json.loads(response)["creditCards"][0]["nonce"]
CreditCard.from_nonce(nonce)
@raises_with_regexp(NotFoundError, ".* consumed .*")
def test_from_nonce_with_consumed_nonce(self):
config = Configuration.instantiate()
customer = Customer.create().customer
client_token = TestHelper.generate_decoded_client_token({
"customer_id": customer.id,
})
authorization_fingerprint = json.loads(client_token)["authorizationFingerprint"]
http = ClientApiHttp(config, {
"authorization_fingerprint": authorization_fingerprint,
"shared_customer_identifier": "fake_identifier",
"shared_customer_identifier_type": "testing"
})
status_code, response = http.add_card({
"credit_card": {
"number": "4111111111111111",
"expiration_month": "11",
"expiration_year": "2099",
}
})
self.assertEqual(201, status_code)
nonce = json.loads(response)["creditCards"][0]["nonce"]
CreditCard.from_nonce(nonce)
CreditCard.from_nonce(nonce)
def test_create_from_transparent_redirect(self):
customer = Customer.create().customer
tr_data = {
"credit_card": {
"customer_id": customer.id
}
}
post_params = {
"tr_data": CreditCard.tr_data_for_create(tr_data, "http://example.com/path?foo=bar"),
"credit_card[cardholder_name]": "Card Holder",
"credit_card[number]": "4111111111111111",
"credit_card[expiration_date]": "05/2012",
"credit_card[billing_address][country_code_alpha2]": "MX",
"credit_card[billing_address][country_code_alpha3]": "MEX",
"credit_card[billing_address][country_code_numeric]": "484",
"credit_card[billing_address][country_name]": "Mexico",
}
query_string = TestHelper.simulate_tr_form_post(post_params, CreditCard.transparent_redirect_create_url())
result = CreditCard.confirm_transparent_redirect(query_string)
self.assertTrue(result.is_success)
credit_card = result.credit_card
self.assertEqual("411111", credit_card.bin)
self.assertEqual("1111", credit_card.last_4)
self.assertEqual("05", credit_card.expiration_month)
self.assertEqual("2012", credit_card.expiration_year)
self.assertEqual(customer.id, credit_card.customer_id)
self.assertEqual("MX", credit_card.billing_address.country_code_alpha2)
self.assertEqual("MEX", credit_card.billing_address.country_code_alpha3)
self.assertEqual("484", credit_card.billing_address.country_code_numeric)
self.assertEqual("Mexico", credit_card.billing_address.country_name)
def test_create_from_transparent_redirect_and_make_default(self):
customer = Customer.create().customer
card1 = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "05/2014",
"cvv": "100",
"cardholder_name": "John Doe"
}).credit_card
self.assertTrue(card1.default)
tr_data = {
"credit_card": {
"customer_id": customer.id,
"options": {
"make_default": True
}
}
}
post_params = {
"tr_data": CreditCard.tr_data_for_create(tr_data, "http://example.com/path?foo=bar"),
"credit_card[cardholder_name]": "Card Holder",
"credit_card[number]": "4111111111111111",
"credit_card[expiration_date]": "05/2012",
}
query_string = TestHelper.simulate_tr_form_post(post_params, CreditCard.transparent_redirect_create_url())
card2 = CreditCard.confirm_transparent_redirect(query_string).credit_card
self.assertFalse(CreditCard.find(card1.token).default)
self.assertTrue(card2.default)
def test_create_from_transparent_redirect_with_error_result(self):
customer = Customer.create().customer
tr_data = {
"credit_card": {
"customer_id": customer.id
}
}
post_params = {
"tr_data": CreditCard.tr_data_for_create(tr_data, "http://example.com/path"),
"credit_card[cardholder_name]": "Card Holder",
"credit_card[number]": "eleventy",
"credit_card[expiration_date]": "y2k"
}
query_string = TestHelper.simulate_tr_form_post(post_params, CreditCard.transparent_redirect_create_url())
result = CreditCard.confirm_transparent_redirect(query_string)
self.assertFalse(result.is_success)
credit_card_number_errors = result.errors.for_object("credit_card").on("number")
self.assertEqual(1, len(credit_card_number_errors))
self.assertEqual(ErrorCodes.CreditCard.NumberHasInvalidLength, credit_card_number_errors[0].code)
expiration_date_errors = result.errors.for_object("credit_card").on("expiration_date")
self.assertEqual(1, len(expiration_date_errors))
self.assertEqual(ErrorCodes.CreditCard.ExpirationDateIsInvalid, expiration_date_errors[0].code)
def test_update_from_transparent_redirect_with_successful_result(self):
old_token = str(random.randint(1, 1000000))
new_token = str(random.randint(1, 1000000))
credit_card = Customer.create({
"credit_card": {
"cardholder_name": "Old Cardholder Name",
"number": "4111111111111111",
"expiration_date": "05/2012",
"token": old_token
}
}).customer.credit_cards[0]
tr_data = {
"payment_method_token": old_token,
"credit_card": {
"token": new_token
}
}
post_params = {
"tr_data": CreditCard.tr_data_for_update(tr_data, "http://example.com/path"),
"credit_card[cardholder_name]": "New Cardholder Name",
"credit_card[expiration_date]": "05/2014"
}
query_string = TestHelper.simulate_tr_form_post(post_params, CreditCard.transparent_redirect_update_url())
result = CreditCard.confirm_transparent_redirect(query_string)
self.assertTrue(result.is_success)
credit_card = result.credit_card
self.assertEqual(new_token, credit_card.token)
self.assertEqual("411111", credit_card.bin)
self.assertEqual("1111", credit_card.last_4)
self.assertEqual("05", credit_card.expiration_month)
self.assertEqual("2014", credit_card.expiration_year)
def test_update_from_transparent_redirect_and_make_default(self):
customer = Customer.create({
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012"
}
}).customer
card1 = customer.credit_cards[0]
card2 = CreditCard.create({
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "05/2014",
}).credit_card
self.assertTrue(card1.default)
self.assertFalse(card2.default)
tr_data = {
"payment_method_token": card2.token,
"credit_card": {
"options": {
"make_default": True
}
}
}
post_params = {
"tr_data": CreditCard.tr_data_for_update(tr_data, "http://example.com/path"),
"credit_card[cardholder_name]": "New Cardholder Name",
"credit_card[expiration_date]": "05/2014"
}
query_string = TestHelper.simulate_tr_form_post(post_params, CreditCard.transparent_redirect_update_url())
CreditCard.confirm_transparent_redirect(query_string)
self.assertFalse(CreditCard.find(card1.token).default)
self.assertTrue(CreditCard.find(card2.token).default)
def test_update_from_transparent_redirect_and_update_existing_billing_address(self):
customer = Customer.create({
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012",
"billing_address": {
"street_address": "123 Old St",
"locality": "Chicago",
"region": "Illinois",
"postal_code": "60621"
}
}
}).customer
card = customer.credit_cards[0]
tr_data = {
"payment_method_token": card.token,
"credit_card": {
"billing_address": {
"street_address": "123 New St",
"locality": "Columbus",
"region": "Ohio",
"postal_code": "43215",
"options": {
"update_existing": True
}
}
}
}
post_params = {
"tr_data": CreditCard.tr_data_for_update(tr_data, "http://example.com/path")
}
query_string = TestHelper.simulate_tr_form_post(post_params, CreditCard.transparent_redirect_update_url())
CreditCard.confirm_transparent_redirect(query_string)
self.assertEqual(1, len(Customer.find(customer.id).addresses))
updated_card = CreditCard.find(card.token)
self.assertEqual("123 New St", updated_card.billing_address.street_address)
self.assertEqual("Columbus", updated_card.billing_address.locality)
self.assertEqual("Ohio", updated_card.billing_address.region)
self.assertEqual("43215", updated_card.billing_address.postal_code)
def test_update_from_transparent_redirect_with_error_result(self):
old_token = str(random.randint(1, 1000000))
Customer.create({
"credit_card": {
"cardholder_name": "Old Cardholder Name",
"number": "4111111111111111",
"expiration_date": "05/2012",
"token": old_token
}
})
tr_data = {
"payment_method_token": old_token,
"credit_card": {
"token": "bad token"
}
}
post_params = {
"tr_data": CreditCard.tr_data_for_update(tr_data, "http://example.com/path"),
"credit_card[cardholder_name]": "New Cardholder Name",
"credit_card[expiration_date]": "05/2014"
}
query_string = TestHelper.simulate_tr_form_post(post_params, CreditCard.transparent_redirect_update_url())
result = CreditCard.confirm_transparent_redirect(query_string)
self.assertFalse(result.is_success)
credit_card_token_errors = result.errors.for_object("credit_card").on("token")
self.assertEqual(1, len(credit_card_token_errors))
self.assertEqual(ErrorCodes.CreditCard.TokenInvalid, credit_card_token_errors[0].code)
def test_expired_can_iterate_over_all_items(self):
customer_id = Customer.all().first.id
for _ in range(110 - CreditCard.expired().maximum_size):
CreditCard.create({
"customer_id": customer_id,
"number": "4111111111111111",
"expiration_date": "05/2014",
"cvv": "100",
"cardholder_name": "John Doe"
})
collection = CreditCard.expired()
self.assertTrue(collection.maximum_size > 100)
credit_card_tokens = [credit_card.token for credit_card in collection.items]
self.assertEqual(collection.maximum_size, len(TestHelper.unique(credit_card_tokens)))
self.assertEqual(set([True]), TestHelper.unique([credit_card.is_expired for credit_card in collection.items]))
def test_expiring_between(self):
customer_id = Customer.all().first.id
for _ in range(110 - CreditCard.expiring_between(date(2010, 1, 1), date(2010, 12, 31)).maximum_size):
CreditCard.create({
"customer_id": customer_id,
"number": "4111111111111111",
"expiration_date": "05/2010",
"cvv": "100",
"cardholder_name": "John Doe"
})
collection = CreditCard.expiring_between(date(2010, 1, 1), date(2010, 12, 31))
self.assertTrue(collection.maximum_size > 100)
credit_card_tokens = [credit_card.token for credit_card in collection.items]
self.assertEqual(collection.maximum_size, len(TestHelper.unique(credit_card_tokens)))
self.assertEqual(set(['2010']), TestHelper.unique([credit_card.expiration_year for credit_card in collection.items]))
def test_commercial_card(self):
customer = Customer.create().customer
result = CreditCard.create({
"customer_id": customer.id,
"number": CreditCardNumbers.CardTypeIndicators.Commercial,
"expiration_date": "05/2014",
"options": {"verify_card": True}
})
credit_card = result.credit_card
self.assertEqual(CreditCard.Commercial.Yes, credit_card.commercial)
def test_issuing_bank(self):
customer = Customer.create().customer
result = CreditCard.create({
"customer_id": customer.id,
"number": CreditCardNumbers.CardTypeIndicators.IssuingBank,
"expiration_date": "05/2014"
})
credit_card = result.credit_card
self.assertEqual(CreditCardDefaults.IssuingBank, credit_card.issuing_bank)
def test_country_of_issuance(self):
customer = Customer.create().customer
result = CreditCard.create({
"customer_id": customer.id,
"number": CreditCardNumbers.CardTypeIndicators.CountryOfIssuance,
"expiration_date": "05/2014",
"options": {"verify_card": True}
})
credit_card = result.credit_card
self.assertEqual(CreditCardDefaults.CountryOfIssuance, credit_card.country_of_issuance)
def test_durbin_regulated_card(self):
customer = Customer.create().customer
result = CreditCard.create({
"customer_id": customer.id,
"number": CreditCardNumbers.CardTypeIndicators.DurbinRegulated,
"expiration_date": "05/2014",
"options": {"verify_card": True}
})
credit_card = result.credit_card
self.assertEqual(CreditCard.DurbinRegulated.Yes, credit_card.durbin_regulated)
def test_debit_card(self):
customer = Customer.create().customer
result = CreditCard.create({
"customer_id": customer.id,
"number": CreditCardNumbers.CardTypeIndicators.Debit,
"expiration_date": "05/2014",
"options": {"verify_card": True}
})
credit_card = result.credit_card
self.assertEqual(CreditCard.Debit.Yes, credit_card.debit)
def test_healthcare_card(self):
customer = Customer.create().customer
result = CreditCard.create({
"customer_id": customer.id,
"number": CreditCardNumbers.CardTypeIndicators.Healthcare,
"expiration_date": "05/2014",
"options": {"verify_card": True}
})
credit_card = result.credit_card
self.assertEqual(CreditCard.Healthcare.Yes, credit_card.healthcare)
self.assertEqual("J3", credit_card.product_id)
def test_payroll_card(self):
customer = Customer.create().customer
result = CreditCard.create({
"customer_id": customer.id,
"number": CreditCardNumbers.CardTypeIndicators.Payroll,
"expiration_date": "05/2014",
"options": {"verify_card": True}
})
credit_card = result.credit_card
self.assertEqual(CreditCard.Payroll.Yes, credit_card.payroll)
self.assertEqual("MSA", credit_card.product_id)
def test_prepaid_card(self):
customer = Customer.create().customer
result = CreditCard.create({
"customer_id": customer.id,
"number": CreditCardNumbers.CardTypeIndicators.Prepaid,
"expiration_date": "05/2014",
"options": {"verify_card": True}
})
credit_card = result.credit_card
self.assertEqual(CreditCard.Prepaid.Yes, credit_card.prepaid)
def test_all_negative_card_type_indicators(self):
customer = Customer.create().customer
result = CreditCard.create({
"customer_id": customer.id,
"number": CreditCardNumbers.CardTypeIndicators.No,
"expiration_date": "05/2014",
"options": {"verify_card": True}
})
credit_card = result.credit_card
self.assertEqual(CreditCard.Debit.No, credit_card.debit)
self.assertEqual(CreditCard.DurbinRegulated.No, credit_card.durbin_regulated)
self.assertEqual(CreditCard.Prepaid.No, credit_card.prepaid)
self.assertEqual(CreditCard.Payroll.No, credit_card.payroll)
self.assertEqual(CreditCard.Commercial.No, credit_card.commercial)
self.assertEqual(CreditCard.Healthcare.No, credit_card.healthcare)
self.assertEqual("MSB", credit_card.product_id)
def test_card_without_card_type_indicators(self):
customer = Customer.create().customer
result = CreditCard.create({
"customer_id": customer.id,
"number": CreditCardNumbers.CardTypeIndicators.Unknown,
"expiration_date": "05/2014",
"options": {"verify_card": True}
})
credit_card = result.credit_card
self.assertEqual(CreditCard.Debit.Unknown, credit_card.debit)
self.assertEqual(CreditCard.DurbinRegulated.Unknown, credit_card.durbin_regulated)
self.assertEqual(CreditCard.Prepaid.Unknown, credit_card.prepaid)
self.assertEqual(CreditCard.Payroll.Unknown, credit_card.payroll)
self.assertEqual(CreditCard.Commercial.Unknown, credit_card.commercial)
self.assertEqual(CreditCard.Healthcare.Unknown, credit_card.healthcare)
self.assertEqual(CreditCard.IssuingBank.Unknown, credit_card.issuing_bank)
self.assertEqual(CreditCard.CountryOfIssuance.Unknown, credit_card.country_of_issuance)
self.assertEquals(CreditCard.ProductId.Unknown, credit_card.product_id)
braintree_python-3.38.0/tests/integration/test_discounts.py 0000644 0001750 0001750 00000002352 13150065776 022410 0 ustar hle hle from tests.test_helper import *
class TestDiscounts(unittest.TestCase):
def test_all_returns_all_discounts(self):
new_id = str(random.randint(1, 1000000))
attributes = {
"amount": "100.00",
"description": "some description",
"id": new_id,
"kind": "discount",
"name": "python_discount",
"never_expires": False,
"number_of_billing_cycles": 1
}
Configuration.instantiate().http().post(Configuration.instantiate().base_merchant_path() + "/modifications/create_modification_for_tests", {"modification": attributes})
discounts = Discount.all()
for discount in discounts:
if discount.id == new_id:
break
else:
discount = None
self.assertNotEqual(None, discount)
self.assertEqual(Decimal("100.00"), discount.amount)
self.assertEqual("some description", discount.description)
self.assertEqual(new_id, discount.id)
self.assertEqual("discount", discount.kind)
self.assertEqual("python_discount", discount.name)
self.assertEqual(False, discount.never_expires)
self.assertEqual(1, discount.number_of_billing_cycles)
braintree_python-3.38.0/tests/integration/test_testing_gateway.py 0000644 0001750 0001750 00000003260 13150065776 023572 0 ustar hle hle from tests.test_helper import *
from braintree.configuration import Configuration
from braintree.exceptions.test_operation_performed_in_production_error import TestOperationPerformedInProductionError
class TestTestingGateway(unittest.TestCase):
def setUp(self):
config = Configuration(braintree.Environment.Production, "merchant_id", "public_key", "private_key")
braintree_gateway = BraintreeGateway(config)
self.gateway = TestingGateway(braintree_gateway)
@raises(TestOperationPerformedInProductionError)
def test_error_is_raised_in_production_for_settle_transaction(self):
self.gateway.settle_transaction("")
@raises(TestOperationPerformedInProductionError)
def test_error_is_raised_in_production_for_make_past_due(self):
self.gateway.make_past_due("")
@raises(TestOperationPerformedInProductionError)
def test_error_is_raised_in_production_for_escrow_transaction(self):
self.gateway.escrow_transaction("")
@raises(TestOperationPerformedInProductionError)
def test_error_is_raised_in_production_for_settlement_confirm_transaction(self):
self.gateway.settlement_confirm_transaction("")
@raises(TestOperationPerformedInProductionError)
def test_error_is_raised_in_production_for_settlement_decline_transaction(self):
self.gateway.settlement_decline_transaction("")
@raises(TestOperationPerformedInProductionError)
def test_error_is_raised_in_production_for_create_3ds_verification(self):
self.gateway.create_3ds_verification("", "")
@raises(TestOperationPerformedInProductionError)
def test_error_is_raised_in_production(self):
self.gateway.settle_transaction("")
braintree_python-3.38.0/tests/integration/test_paypal_account.py 0000644 0001750 0001750 00000014144 13150065776 023401 0 ustar hle hle from tests.test_helper import *
import time
from braintree.test.nonces import Nonces
class TestPayPalAccount(unittest.TestCase):
def test_find_returns_paypal_account(self):
customer_id = Customer.create().customer.id
result = PaymentMethod.create({
"customer_id": customer_id,
"payment_method_nonce": Nonces.PayPalFuturePayment
})
self.assertTrue(result.is_success)
found_account = PayPalAccount.find(result.payment_method.token)
self.assertNotEqual(None, found_account)
self.assertEqual(found_account.__class__, PayPalAccount)
self.assertEqual(found_account.token, result.payment_method.token)
self.assertNotEqual(None, found_account.image_url)
self.assertNotEqual(None, found_account.created_at)
self.assertNotEqual(None, found_account.updated_at)
def test_find_raises_on_not_found_token(self):
self.assertRaises(NotFoundError, PayPalAccount.find, "non-existant-token")
def test_find_will_not_return_credit_card(self):
credit_card = CreditCard.create({
"customer_id": Customer.create().customer.id,
"number": "4111111111111111",
"expiration_date": "12/2099"
}).credit_card
self.assertRaises(NotFoundError, PayPalAccount.find, credit_card.token)
def test_find_returns_subscriptions_associated_with_a_paypal_account(self):
customer_id = Customer.create().customer.id
payment_method_token = "paypal-account-" + str(int(time.time()))
nonce = TestHelper.nonce_for_paypal_account({
"consent_code": "consent-code",
"token": payment_method_token
})
result = PaymentMethod.create({
"payment_method_nonce": nonce,
"customer_id": customer_id
})
self.assertTrue(result.is_success)
token = result.payment_method.token
subscription1 = Subscription.create({
"payment_method_token": token,
"plan_id": TestHelper.trialless_plan["id"]
}).subscription
subscription2 = Subscription.create({
"payment_method_token": token,
"plan_id": TestHelper.trialless_plan["id"]
}).subscription
paypal_account = PayPalAccount.find(result.payment_method.token)
self.assertTrue(subscription1.id in [s.id for s in paypal_account.subscriptions])
self.assertTrue(subscription2.id in [s.id for s in paypal_account.subscriptions])
def test_find_retuns_billing_agreement_id_with_a_paypal_account(self):
customer_id = Customer.create().customer.id
result = PaymentMethod.create({
"payment_method_nonce": Nonces.PayPalBillingAgreement,
"customer_id": customer_id
})
self.assertTrue(result.is_success)
paypal_account = PayPalAccount.find(result.payment_method.token)
self.assertNotEqual(None, paypal_account.billing_agreement_id)
def test_delete_deletes_paypal_account(self):
result = PaymentMethod.create({
"customer_id": Customer.create().customer.id,
"payment_method_nonce": Nonces.PayPalFuturePayment
})
self.assertTrue(result.is_success)
paypal_account_token = result.payment_method.token
delete_result = PayPalAccount.delete(paypal_account_token)
self.assertTrue(delete_result.is_success)
self.assertRaises(NotFoundError, PayPalAccount.find, paypal_account_token)
def test_delete_raises_on_not_found(self):
self.assertRaises(NotFoundError, PayPalAccount.delete, "non-existant-token")
def test_delete_delete_wont_delete_credit_card(self):
credit_card = CreditCard.create({
"customer_id": Customer.create().customer.id,
"number": "4111111111111111",
"expiration_date": "12/2099"
}).credit_card
self.assertRaises(NotFoundError, PayPalAccount.delete, credit_card.token)
def test_update_can_update_token_and_default(self):
customer_id = Customer.create().customer.id
CreditCard.create({
"customer_id": customer_id,
"number": "4111111111111111",
"expiration_date": "12/2099"
})
result = PaymentMethod.create({
"customer_id": customer_id,
"payment_method_nonce": Nonces.PayPalFuturePayment
})
self.assertTrue(result.is_success)
old_token = result.payment_method.token
new_token = "new-token-%s" % int(round(time.time() * 1000))
result = PayPalAccount.update(old_token, {
"token": new_token,
"options": {"make_default": True}
})
self.assertTrue(result.is_success)
updated_account = PayPalAccount.find(new_token)
self.assertEqual(updated_account.default, True)
def test_update_returns_validation_errors(self):
payment_method_token = "payment-token-%s" % int(round(time.time() * 1000))
customer_id = Customer.create().customer.id
CreditCard.create({
"token": payment_method_token,
"customer_id": customer_id,
"number": "4111111111111111",
"expiration_date": "12/2099"
})
result = PaymentMethod.create({
"customer_id": customer_id,
"payment_method_nonce": Nonces.PayPalFuturePayment
})
self.assertTrue(result.is_success)
old_token = result.payment_method.token
result = PayPalAccount.update(old_token, {
"token": payment_method_token,
})
self.assertFalse(result.is_success)
token_errors = result.errors.for_object("paypal_account").on("token")
self.assertEqual(1, len(token_errors))
self.assertEqual(ErrorCodes.PayPalAccount.TokenIsInUse, token_errors[0].code)
result = PayPalAccount.update(old_token, {
"token": payment_method_token,
})
self.assertFalse(result.is_success)
token_errors = result.errors.for_object("paypal_account").on("token")
self.assertEqual(1, len(token_errors))
self.assertEqual(ErrorCodes.PayPalAccount.TokenIsInUse, token_errors[0].code)
braintree_python-3.38.0/tests/integration/test_transaction.py 0000644 0001750 0001750 00000441750 13150065776 022733 0 ustar hle hle import json
from tests.test_helper import *
from braintree.test.credit_card_numbers import CreditCardNumbers
from braintree.test.nonces import Nonces
from braintree.dispute import Dispute
import braintree.test.venmo_sdk as venmo_sdk
class TestTransaction(unittest.TestCase):
def test_sale_returns_risk_data(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertIsInstance(transaction.risk_data, RiskData)
self.assertEqual(transaction.risk_data.id, None)
self.assertEqual(transaction.risk_data.decision, "Not Evaluated")
def test_sale_returns_a_successful_result_with_type_of_sale(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertNotEqual(None, re.search(r"\A\w{6,}\Z", transaction.id))
self.assertEqual(Transaction.Type.Sale, transaction.type)
self.assertEqual(Decimal(TransactionAmounts.Authorize), transaction.amount)
self.assertEqual("411111", transaction.credit_card_details.bin)
self.assertEqual("1111", transaction.credit_card_details.last_4)
self.assertEqual("05/2009", transaction.credit_card_details.expiration_date)
self.assertEqual(None, transaction.voice_referral_number)
def test_sale_allows_amount_as_a_decimal(self):
result = Transaction.sale({
"amount": Decimal(TransactionAmounts.Authorize),
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertNotEqual(None, re.search(r"\A\w{6,}\Z", transaction.id))
self.assertEqual(Transaction.Type.Sale, transaction.type)
self.assertEqual(Decimal(TransactionAmounts.Authorize), transaction.amount)
self.assertEqual("411111", transaction.credit_card_details.bin)
self.assertEqual("1111", transaction.credit_card_details.last_4)
self.assertEqual("05/2009", transaction.credit_card_details.expiration_date)
def test_sale_with_expiration_month_and_year_separately(self):
result = Transaction.sale({
"amount": Decimal(TransactionAmounts.Authorize),
"credit_card": {
"number": "4111111111111111",
"expiration_month": "05",
"expiration_year": "2012"
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(Transaction.Type.Sale, transaction.type)
self.assertEqual("05", transaction.credit_card_details.expiration_month)
self.assertEqual("2012", transaction.credit_card_details.expiration_year)
def test_sale_works_with_all_attributes(self):
result = Transaction.sale({
"amount": "100.00",
"order_id": "123",
"channel": "MyShoppingCartProvider",
"credit_card": {
"cardholder_name": "The Cardholder",
"number": "5105105105105100",
"expiration_date": "05/2011",
"cvv": "123"
},
"customer": {
"first_name": "Dan",
"last_name": "Smith",
"company": "Braintree",
"email": "dan@example.com",
"phone": "419-555-1234",
"fax": "419-555-1235",
"website": "http://braintreepayments.com"
},
"billing": {
"first_name": "Carl",
"last_name": "Jones",
"company": "Braintree",
"street_address": "123 E Main St",
"extended_address": "Suite 403",
"locality": "Chicago",
"region": "IL",
"postal_code": "60622",
"country_name": "United States of America",
"country_code_alpha2": "US",
"country_code_alpha3": "USA",
"country_code_numeric": "840"
},
"shipping": {
"first_name": "Andrew",
"last_name": "Mason",
"company": "Braintree",
"street_address": "456 W Main St",
"extended_address": "Apt 2F",
"locality": "Bartlett",
"region": "IL",
"postal_code": "60103",
"country_name": "Mexico",
"country_code_alpha2": "MX",
"country_code_alpha3": "MEX",
"country_code_numeric": "484"
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertNotEqual(None, re.search(r"\A\w{6,}\Z", transaction.id))
self.assertEqual(Transaction.Type.Sale, transaction.type)
self.assertEqual(Transaction.Status.Authorized, transaction.status)
self.assertEqual(Decimal("100.00"), transaction.amount)
self.assertEqual("123", transaction.order_id)
self.assertEqual("MyShoppingCartProvider", transaction.channel)
self.assertEqual("1000", transaction.processor_response_code)
self.assertEqual(datetime, type(transaction.created_at))
self.assertEqual(datetime, type(transaction.updated_at))
self.assertEqual("510510", transaction.credit_card_details.bin)
self.assertEqual("5100", transaction.credit_card_details.last_4)
self.assertEqual("510510******5100", transaction.credit_card_details.masked_number)
self.assertEqual("MasterCard", transaction.credit_card_details.card_type)
self.assertEqual("The Cardholder", transaction.credit_card_details.cardholder_name)
self.assertEqual(None, transaction.avs_error_response_code)
self.assertEqual("M", transaction.avs_postal_code_response_code)
self.assertEqual("M", transaction.avs_street_address_response_code)
self.assertEqual("Dan", transaction.customer_details.first_name)
self.assertEqual("Smith", transaction.customer_details.last_name)
self.assertEqual("Braintree", transaction.customer_details.company)
self.assertEqual("dan@example.com", transaction.customer_details.email)
self.assertEqual("419-555-1234", transaction.customer_details.phone)
self.assertEqual("419-555-1235", transaction.customer_details.fax)
self.assertEqual("http://braintreepayments.com", transaction.customer_details.website)
self.assertEqual("Carl", transaction.billing_details.first_name)
self.assertEqual("Jones", transaction.billing_details.last_name)
self.assertEqual("Braintree", transaction.billing_details.company)
self.assertEqual("123 E Main St", transaction.billing_details.street_address)
self.assertEqual("Suite 403", transaction.billing_details.extended_address)
self.assertEqual("Chicago", transaction.billing_details.locality)
self.assertEqual("IL", transaction.billing_details.region)
self.assertEqual("60622", transaction.billing_details.postal_code)
self.assertEqual("United States of America", transaction.billing_details.country_name)
self.assertEqual("US", transaction.billing_details.country_code_alpha2)
self.assertEqual("USA", transaction.billing_details.country_code_alpha3)
self.assertEqual("840", transaction.billing_details.country_code_numeric)
self.assertEqual("Andrew", transaction.shipping_details.first_name)
self.assertEqual("Mason", transaction.shipping_details.last_name)
self.assertEqual("Braintree", transaction.shipping_details.company)
self.assertEqual("456 W Main St", transaction.shipping_details.street_address)
self.assertEqual("Apt 2F", transaction.shipping_details.extended_address)
self.assertEqual("Bartlett", transaction.shipping_details.locality)
self.assertEqual("IL", transaction.shipping_details.region)
self.assertEqual("60103", transaction.shipping_details.postal_code)
self.assertEqual("Mexico", transaction.shipping_details.country_name)
self.assertEqual("MX", transaction.shipping_details.country_code_alpha2)
self.assertEqual("MEX", transaction.shipping_details.country_code_alpha3)
self.assertEqual("484", transaction.shipping_details.country_code_numeric)
self.assertEqual(None, transaction.additional_processor_response)
def test_sale_with_vault_customer_and_credit_card_data(self):
customer = Customer.create({
"first_name": "Pingu",
"last_name": "Penguin",
}).customer
result = Transaction.sale({
"amount": Decimal(TransactionAmounts.Authorize),
"customer_id": customer.id,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(transaction.credit_card_details.masked_number, "411111******1111")
self.assertEqual(None, transaction.vault_credit_card)
def test_sale_with_vault_customer_and_credit_card_data_and_store_in_vault(self):
customer = Customer.create({
"first_name": "Pingu",
"last_name": "Penguin",
}).customer
result = Transaction.sale({
"amount": Decimal(TransactionAmounts.Authorize),
"customer_id": customer.id,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"options": {
"store_in_vault": True
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual("411111******1111", transaction.credit_card_details.masked_number)
self.assertEqual("411111******1111", transaction.vault_credit_card.masked_number)
def test_sale_with_venmo_merchant_data(self):
result = Transaction.sale({
"amount": Decimal(TransactionAmounts.Authorize),
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"options": {
"venmo_merchant_data": {
"venmo_merchant_public_id": "12345",
"originating_transaction_id": "abc123",
"originating_merchant_id": "xyz123",
"originating_merchant_kind": "braintree",
}
}
})
self.assertTrue(result.is_success)
def test_sale_with_custom_fields(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"custom_fields": {
"store_me": "some extra stuff"
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual("some extra stuff", transaction.custom_fields["store_me"])
def test_sale_with_merchant_account_id(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"merchant_account_id": TestHelper.non_default_merchant_account_id,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(TestHelper.non_default_merchant_account_id, transaction.merchant_account_id)
def test_sale_without_merchant_account_id_falls_back_to_default(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(TestHelper.default_merchant_account_id, transaction.merchant_account_id)
def test_sale_with_shipping_address_id(self):
result = Customer.create({
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2010"
}
})
self.assertTrue(result.is_success)
customer = result.customer
result = Address.create({
"customer_id": customer.id,
"street_address": "123 Fake St."
})
self.assertTrue(result.is_success)
address = result.address
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"customer_id": customer.id,
"shipping_address_id": address.id,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual("123 Fake St.", transaction.shipping_details.street_address)
self.assertEqual(address.id, transaction.shipping_details.id)
def test_sale_with_risk_data_security_parameters(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"risk_data": {
"customer_browser": "IE7",
"customer_ip": "192.168.0.1"
}
})
self.assertTrue(result.is_success)
def test_sale_with_billing_address_id(self):
result = Customer.create({
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2010"
}
})
self.assertTrue(result.is_success)
customer = result.customer
result = Address.create({
"customer_id": customer.id,
"street_address": "123 Fake St."
})
self.assertTrue(result.is_success)
address = result.address
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"customer_id": customer.id,
"billing_address_id": address.id,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual("123 Fake St.", transaction.billing_details.street_address)
self.assertEqual(address.id, transaction.billing_details.id)
def test_sale_with_device_session_id_and_fraud_merchant_id(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2010"
},
"device_session_id": "abc123",
"fraud_merchant_id": "456"
})
self.assertTrue(result.is_success)
def test_sale_with_level_2(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"purchase_order_number": "12345",
"tax_amount": Decimal("10.00"),
"tax_exempt": True,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual("12345", transaction.purchase_order_number)
self.assertEqual(Decimal("10.00"), transaction.tax_amount)
self.assertEqual(True, transaction.tax_exempt)
def test_create_with_invalid_tax_amount(self):
result = Transaction.sale({
"amount": Decimal("100"),
"tax_amount": "asdf",
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
})
self.assertFalse(result.is_success)
tax_amount_errors = result.errors.for_object("transaction").on("tax_amount")
self.assertEqual(1, len(tax_amount_errors))
self.assertEqual(ErrorCodes.Transaction.TaxAmountFormatIsInvalid, tax_amount_errors[0].code)
def test_create_with_too_long_purchase_order_number(self):
result = Transaction.sale({
"amount": Decimal("100"),
"purchase_order_number": "aaaaaaaaaaaaaaaaaa",
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
})
self.assertFalse(result.is_success)
purchase_order_number_errors = result.errors.for_object("transaction").on("purchase_order_number")
self.assertEqual(1, len(purchase_order_number_errors))
self.assertEqual(ErrorCodes.Transaction.PurchaseOrderNumberIsTooLong, purchase_order_number_errors[0].code)
def test_create_with_invalid_purchase_order_number(self):
result = Transaction.sale({
"amount": Decimal("100"),
"purchase_order_number": "\xc3\x9f\xc3\xa5\xe2\x88\x82",
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
})
self.assertFalse(result.is_success)
purchase_order_number_errors = result.errors.for_object("transaction").on("purchase_order_number")
self.assertEqual(1, len(purchase_order_number_errors))
self.assertEqual(ErrorCodes.Transaction.PurchaseOrderNumberIsInvalid, purchase_order_number_errors[0].code)
def test_sale_with_processor_declined(self):
result = Transaction.sale({
"amount": TransactionAmounts.Decline,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
})
self.assertFalse(result.is_success)
transaction = result.transaction
self.assertEqual(Transaction.Status.ProcessorDeclined, transaction.status)
self.assertEqual("2000 : Do Not Honor", transaction.additional_processor_response)
def test_sale_with_gateway_rejected_with_incomplete_application(self):
gateway = BraintreeGateway(
client_id="client_id$development$integration_client_id",
client_secret="client_secret$development$integration_client_secret",
environment=Environment.Development
)
result = gateway.merchant.create({
"email": "name@email.com",
"country_code_alpha3": "USA",
"payment_methods": ["credit_card", "paypal"]
})
gateway = BraintreeGateway(
access_token=result.credentials.access_token,
environment=Environment.Development
)
result = gateway.transaction.sale({
"amount": "4000.00",
"billing": {
"street_address": "200 Fake Street"
},
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
})
self.assertFalse(result.is_success)
transaction = result.transaction
self.assertEqual(Transaction.GatewayRejectionReason.ApplicationIncomplete, transaction.gateway_rejection_reason)
def test_sale_with_gateway_rejected_with_avs(self):
old_merchant_id = Configuration.merchant_id
old_public_key = Configuration.public_key
old_private_key = Configuration.private_key
try:
Configuration.merchant_id = "processing_rules_merchant_id"
Configuration.public_key = "processing_rules_public_key"
Configuration.private_key = "processing_rules_private_key"
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"billing": {
"street_address": "200 Fake Street"
},
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
})
self.assertFalse(result.is_success)
transaction = result.transaction
self.assertEqual(Transaction.GatewayRejectionReason.Avs, transaction.gateway_rejection_reason)
finally:
Configuration.merchant_id = old_merchant_id
Configuration.public_key = old_public_key
Configuration.private_key = old_private_key
def test_sale_with_gateway_rejected_with_avs_and_cvv(self):
old_merchant_id = Configuration.merchant_id
old_public_key = Configuration.public_key
old_private_key = Configuration.private_key
try:
Configuration.merchant_id = "processing_rules_merchant_id"
Configuration.public_key = "processing_rules_public_key"
Configuration.private_key = "processing_rules_private_key"
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"billing": {
"postal_code": "20000"
},
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009",
"cvv": "200"
}
})
self.assertFalse(result.is_success)
transaction = result.transaction
self.assertEqual(Transaction.GatewayRejectionReason.AvsAndCvv, transaction.gateway_rejection_reason)
finally:
Configuration.merchant_id = old_merchant_id
Configuration.public_key = old_public_key
Configuration.private_key = old_private_key
def test_sale_with_gateway_rejected_with_cvv(self):
old_merchant_id = Configuration.merchant_id
old_public_key = Configuration.public_key
old_private_key = Configuration.private_key
try:
Configuration.merchant_id = "processing_rules_merchant_id"
Configuration.public_key = "processing_rules_public_key"
Configuration.private_key = "processing_rules_private_key"
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009",
"cvv": "200"
}
})
self.assertFalse(result.is_success)
transaction = result.transaction
self.assertEqual(Transaction.GatewayRejectionReason.Cvv, transaction.gateway_rejection_reason)
finally:
Configuration.merchant_id = old_merchant_id
Configuration.public_key = old_public_key
Configuration.private_key = old_private_key
def test_sale_with_gateway_rejected_with_fraud(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4000111111111511",
"expiration_date": "05/2017",
"cvv": "333"
}
})
self.assertFalse(result.is_success)
self.assertEqual(Transaction.GatewayRejectionReason.Fraud, result.transaction.gateway_rejection_reason)
def test_sale_with_service_fee(self):
result = Transaction.sale({
"amount": "10.00",
"merchant_account_id": TestHelper.non_default_sub_merchant_account_id,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"service_fee_amount": "1.00"
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(transaction.service_fee_amount, "1.00")
def test_sale_on_master_merchant_accoount_is_invalid_with_service_fee(self):
result = Transaction.sale({
"amount": "10.00",
"merchant_account_id": TestHelper.non_default_merchant_account_id,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"service_fee_amount": "1.00"
})
self.assertFalse(result.is_success)
amount_errors = result.errors.for_object("transaction").on("service_fee_amount")
self.assertEqual(1, len(amount_errors))
self.assertEqual(ErrorCodes.Transaction.ServiceFeeAmountNotAllowedOnMasterMerchantAccount, amount_errors[0].code)
def test_sale_on_submerchant_is_invalid_without_with_service_fee(self):
result = Transaction.sale({
"amount": "10.00",
"merchant_account_id": TestHelper.non_default_sub_merchant_account_id,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
})
self.assertFalse(result.is_success)
self.assertEqual(
ErrorCodes.Transaction.SubMerchantAccountRequiresServiceFeeAmount,
result.errors.for_object("transaction").on("merchant_account_id")[0].code
)
def test_sale_with_hold_in_escrow_option(self):
result = Transaction.sale({
"amount": "10.00",
"merchant_account_id": TestHelper.non_default_sub_merchant_account_id,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"options": {
"hold_in_escrow": True
},
"service_fee_amount": "1.00"
})
self.assertTrue(result.is_success)
self.assertEqual(
Transaction.EscrowStatus.HoldPending,
result.transaction.escrow_status
)
def test_sale_with_hold_in_escrow_option_fails_for_master_merchant_account(self):
result = Transaction.sale({
"amount": "10.00",
"merchant_account_id": TestHelper.non_default_merchant_account_id,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"options": {
"hold_in_escrow": True
}
})
self.assertFalse(result.is_success)
self.assertEqual(
ErrorCodes.Transaction.CannotHoldInEscrow,
result.errors.for_object("transaction").on("base")[0].code
)
def test_hold_in_escrow_after_sale(self):
result = Transaction.sale({
"amount": "10.00",
"merchant_account_id": TestHelper.non_default_sub_merchant_account_id,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"service_fee_amount": "1.00"
})
self.assertTrue(result.is_success)
result = Transaction.hold_in_escrow(result.transaction.id)
self.assertTrue(result.is_success)
self.assertEqual(
Transaction.EscrowStatus.HoldPending,
result.transaction.escrow_status
)
def test_hold_in_escrow_after_sale_fails_for_master_merchant_account(self):
result = Transaction.sale({
"amount": "10.00",
"merchant_account_id": TestHelper.non_default_merchant_account_id,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
})
self.assertTrue(result.is_success)
result = Transaction.hold_in_escrow(result.transaction.id)
self.assertFalse(result.is_success)
self.assertEqual(
ErrorCodes.Transaction.CannotHoldInEscrow,
result.errors.for_object("transaction").on("base")[0].code
)
def test_release_from_escrow_from_escrow(self):
transaction = self.__create_escrowed_transaction()
result = Transaction.release_from_escrow(transaction.id)
self.assertTrue(result.is_success)
self.assertEqual(
Transaction.EscrowStatus.ReleasePending,
result.transaction.escrow_status
)
def test_release_from_escrow_from_escrow_fails_when_transaction_not_in_escrow(self):
result = Transaction.sale({
"amount": "10.00",
"merchant_account_id": TestHelper.non_default_merchant_account_id,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
})
self.assertTrue(result.is_success)
result = Transaction.release_from_escrow(result.transaction.id)
self.assertFalse(result.is_success)
self.assertEqual(
ErrorCodes.Transaction.CannotReleaseFromEscrow,
result.errors.for_object("transaction").on("base")[0].code
)
def test_cancel_release_from_escrow(self):
transaction = self.__create_escrowed_transaction()
submit_result = Transaction.release_from_escrow(transaction.id)
result = Transaction.cancel_release(submit_result.transaction.id)
self.assertTrue(result.is_success)
self.assertEqual(
Transaction.EscrowStatus.Held,
result.transaction.escrow_status
)
def test_cancel_release_from_escrow_fails_if_transaction_is_not_pending_release(self):
transaction = self.__create_escrowed_transaction()
result = Transaction.cancel_release(transaction.id)
self.assertFalse(result.is_success)
self.assertEqual(
ErrorCodes.Transaction.CannotCancelRelease,
result.errors.for_object("transaction").on("base")[0].code
)
def test_sale_with_venmo_sdk_session(self):
result = Transaction.sale({
"amount": "10.00",
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"options": {
"venmo_sdk_session": venmo_sdk.Session
}
})
self.assertTrue(result.is_success)
self.assertTrue(result.transaction.credit_card_details.venmo_sdk)
def test_sale_with_venmo_sdk_payment_method_code(self):
result = Transaction.sale({
"amount": "10.00",
"venmo_sdk_payment_method_code": venmo_sdk.VisaPaymentMethodCode
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual("411111", transaction.credit_card_details.bin)
def test_sale_with_payment_method_nonce(self):
config = Configuration.instantiate()
parsed_client_token = TestHelper.generate_decoded_client_token()
authorization_fingerprint = json.loads(parsed_client_token)["authorizationFingerprint"]
http = ClientApiHttp(config, {
"authorization_fingerprint": authorization_fingerprint,
"shared_customer_identifier": "fake_identifier",
"shared_customer_identifier_type": "testing"
})
_, response = http.add_card({
"credit_card": {
"number": "4111111111111111",
"expiration_month": "11",
"expiration_year": "2099",
},
"share": True
})
nonce = json.loads(response)["creditCards"][0]["nonce"]
result = Transaction.sale({
"amount": "10.00",
"payment_method_nonce": nonce
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual("411111", transaction.credit_card_details.bin)
def test_sale_with_fake_apple_pay_nonce(self):
result = Transaction.sale({
"amount": "10.00",
"payment_method_nonce": Nonces.ApplePayAmEx
})
self.assertTrue(result.is_success)
self.assertEqual(result.transaction.amount, 10.00)
self.assertEqual(result.transaction.payment_instrument_type, PaymentInstrumentType.ApplePayCard)
apple_pay_details = result.transaction.apple_pay_details
self.assertNotEqual(None, apple_pay_details)
self.assertEqual(ApplePayCard.CardType.AmEx, apple_pay_details.card_type)
self.assertEqual("AmEx 41002", apple_pay_details.payment_instrument_name)
self.assertTrue(int(apple_pay_details.expiration_month) > 0)
self.assertTrue(int(apple_pay_details.expiration_year) > 0)
self.assertNotEqual(None, apple_pay_details.cardholder_name)
def test_sale_with_fake_android_pay_proxy_card_nonce(self):
result = Transaction.sale({
"amount": "10.00",
"payment_method_nonce": Nonces.AndroidPayCardDiscover
})
self.assertTrue(result.is_success)
self.assertEqual(result.transaction.amount, 10.00)
self.assertEqual(result.transaction.payment_instrument_type, PaymentInstrumentType.AndroidPayCard)
android_pay_card_details = result.transaction.android_pay_card_details
self.assertNotEqual(None, android_pay_card_details)
self.assertEqual(CreditCard.CardType.Discover, android_pay_card_details.card_type)
self.assertTrue(int(android_pay_card_details.expiration_month) > 0)
self.assertTrue(int(android_pay_card_details.expiration_year) > 0)
def test_sale_with_fake_android_pay_network_token_nonce(self):
result = Transaction.sale({
"amount": "10.00",
"payment_method_nonce": Nonces.AndroidPayCardMasterCard
})
self.assertTrue(result.is_success)
self.assertEqual(result.transaction.amount, 10.00)
self.assertEqual(result.transaction.payment_instrument_type, PaymentInstrumentType.AndroidPayCard)
android_pay_card_details = result.transaction.android_pay_card_details
self.assertNotEqual(None, android_pay_card_details)
self.assertEqual(CreditCard.CardType.MasterCard, android_pay_card_details.card_type)
self.assertTrue(int(android_pay_card_details.expiration_month) > 0)
self.assertTrue(int(android_pay_card_details.expiration_year) > 0)
def test_sale_with_fake_amex_express_checkout_card_nonce(self):
result = Transaction.sale({
"amount": "10.00",
"payment_method_nonce": Nonces.AmexExpressCheckoutCard,
"merchant_account_id": TestHelper.fake_amex_direct_merchant_account_id,
})
self.assertTrue(result.is_success)
self.assertEqual(result.transaction.amount, 10.00)
self.assertEqual(result.transaction.payment_instrument_type, PaymentInstrumentType.AmexExpressCheckoutCard)
amex_express_checkout_card_details = result.transaction.amex_express_checkout_card_details
self.assertNotEqual(None, amex_express_checkout_card_details)
self.assertEqual(CreditCard.CardType.AmEx, amex_express_checkout_card_details.card_type)
self.assertTrue(int(amex_express_checkout_card_details.expiration_month) > 0)
self.assertTrue(int(amex_express_checkout_card_details.expiration_year) > 0)
def test_sale_with_fake_venmo_account_nonce(self):
result = Transaction.sale({
"amount": "10.00",
"payment_method_nonce": Nonces.VenmoAccount,
"merchant_account_id": TestHelper.fake_venmo_account_merchant_account_id,
})
self.assertTrue(result.is_success)
self.assertEqual(result.transaction.amount, 10.00)
self.assertEqual(result.transaction.payment_instrument_type, PaymentInstrumentType.VenmoAccount)
venmo_account_details = result.transaction.venmo_account_details
self.assertIsNotNone(venmo_account_details)
self.assertEqual(venmo_account_details.username, "venmojoe")
self.assertEqual(venmo_account_details.venmo_user_id, "Venmo-Joe-1")
def test_sale_with_advanced_fraud_checking_skipped(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": CreditCardNumbers.Visa,
"expiration_date": "05/2009"
},
"options": {
"skip_advanced_fraud_checking": True
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertIsInstance(transaction.risk_data, RiskData)
self.assertEqual(transaction.risk_data.id, None)
def test_sale_with_skip_cvv_option_set(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": CreditCardNumbers.Visa,
"expiration_date": "05/2009"
},
"options": {
"skip_cvv": True
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(transaction.cvv_response_code, "B")
def test_sale_with_skip_avs_option_set(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": CreditCardNumbers.Visa,
"expiration_date": "05/2009"
},
"options": {
"skip_avs": True
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(transaction.avs_error_response_code, None)
self.assertEqual(transaction.avs_street_address_response_code, "B")
def test_validation_error_on_invalid_custom_fields(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"custom_fields": {
"invalid_key": "some extra stuff"
}
})
self.assertFalse(result.is_success)
self.assertEqual(
ErrorCodes.Transaction.CustomFieldIsInvalid,
result.errors.for_object("transaction").on("custom_fields")[0].code
)
def test_card_type_indicators(self):
result = Transaction.sale({
"amount": Decimal(TransactionAmounts.Authorize),
"credit_card": {
"number": CreditCardNumbers.CardTypeIndicators.Unknown,
"expiration_month": "05",
"expiration_year": "2012"
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(CreditCard.Prepaid.Unknown, transaction.credit_card_details.prepaid)
self.assertEqual(CreditCard.Debit.Unknown, transaction.credit_card_details.debit)
self.assertEqual(CreditCard.Commercial.Unknown, transaction.credit_card_details.commercial)
self.assertEqual(CreditCard.Healthcare.Unknown, transaction.credit_card_details.healthcare)
self.assertEqual(CreditCard.Payroll.Unknown, transaction.credit_card_details.payroll)
self.assertEqual(CreditCard.DurbinRegulated.Unknown, transaction.credit_card_details.durbin_regulated)
self.assertEqual(CreditCard.CardTypeIndicator.Unknown, transaction.credit_card_details.issuing_bank)
self.assertEqual(CreditCard.CardTypeIndicator.Unknown, transaction.credit_card_details.country_of_issuance)
self.assertEqual(CreditCard.ProductId.Unknown, transaction.credit_card_details.product_id)
def test_create_can_set_recurring_flag(self):
result = Transaction.sale({
"amount": "100",
"customer": {
"first_name": "Adam",
"last_name": "Williams"
},
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"recurring": True
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(True, transaction.recurring)
def test_create_can_set_transaction_source_flag_recurring(self):
result = Transaction.sale({
"amount": "100",
"customer": {
"first_name": "Adam",
"last_name": "Williams"
},
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"transaction_source": "recurring"
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(True, transaction.recurring)
def test_create_can_set_transaction_source_flag_moto(self):
result = Transaction.sale({
"amount": "100",
"customer": {
"first_name": "Adam",
"last_name": "Williams"
},
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"transaction_source": "moto"
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(False, transaction.recurring)
def test_create_can_store_customer_and_credit_card_in_the_vault(self):
result = Transaction.sale({
"amount": "100",
"customer": {
"first_name": "Adam",
"last_name": "Williams"
},
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"options": {
"store_in_vault": True
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertNotEqual(None, re.search(r"\A\d{6,}\Z", transaction.customer_details.id))
self.assertEqual(transaction.customer_details.id, transaction.vault_customer.id)
self.assertNotEqual(None, re.search(r"\A\w{4,}\Z", transaction.credit_card_details.token))
self.assertEqual(transaction.credit_card_details.token, transaction.vault_credit_card.token)
def test_create_can_store_customer_and_credit_card_in_the_vault_on_success(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"customer": {
"first_name": "Adam",
"last_name": "Williams"
},
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"options": {
"store_in_vault_on_success": True
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertNotEqual(None, re.search(r"\A\d{6,}\Z", transaction.customer_details.id))
self.assertEqual(transaction.customer_details.id, transaction.vault_customer.id)
self.assertNotEqual(None, re.search(r"\A\w{4,}\Z", transaction.credit_card_details.token))
self.assertEqual(transaction.credit_card_details.token, transaction.vault_credit_card.token)
def test_create_does_not_store_customer_and_credit_card_in_the_vault_on_failure(self):
result = Transaction.sale({
"amount": TransactionAmounts.Decline,
"customer": {
"first_name": "Adam",
"last_name": "Williams"
},
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"options": {
"store_in_vault_on_success": True
}
})
self.assertFalse(result.is_success)
transaction = result.transaction
self.assertEqual(None, transaction.customer_details.id)
self.assertEqual(None, transaction.credit_card_details.token)
self.assertEqual(None, transaction.vault_customer)
self.assertEqual(None, transaction.vault_credit_card)
def test_create_associated_a_billing_address_with_credit_card_in_vault(self):
result = Transaction.sale({
"amount": "100",
"customer": {
"first_name": "Adam",
"last_name": "Williams"
},
"credit_card": {
"number": "5105105105105100",
"expiration_date": "05/2012"
},
"billing": {
"first_name": "Carl",
"last_name": "Jones",
"company": "Braintree",
"street_address": "123 E Main St",
"extended_address": "Suite 403",
"locality": "Chicago",
"region": "IL",
"postal_code": "60622",
"country_name": "United States of America"
},
"options": {
"store_in_vault": True,
"add_billing_address_to_payment_method": True,
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertNotEqual(None, re.search(r"\A\d{6,}\Z", transaction.customer_details.id))
self.assertEqual(transaction.customer_details.id, transaction.vault_customer.id)
credit_card = CreditCard.find(transaction.vault_credit_card.token)
self.assertEqual(credit_card.billing_address.id, transaction.billing_details.id)
self.assertEqual(credit_card.billing_address.id, transaction.vault_billing_address.id)
self.assertEqual("Carl", credit_card.billing_address.first_name)
self.assertEqual("Jones", credit_card.billing_address.last_name)
self.assertEqual("Braintree", credit_card.billing_address.company)
self.assertEqual("123 E Main St", credit_card.billing_address.street_address)
self.assertEqual("Suite 403", credit_card.billing_address.extended_address)
self.assertEqual("Chicago", credit_card.billing_address.locality)
self.assertEqual("IL", credit_card.billing_address.region)
self.assertEqual("60622", credit_card.billing_address.postal_code)
self.assertEqual("United States of America", credit_card.billing_address.country_name)
def test_create_and_store_the_shipping_address_in_the_vault(self):
result = Transaction.sale({
"amount": "100",
"customer": {
"first_name": "Adam",
"last_name": "Williams"
},
"credit_card": {
"number": "5105105105105100",
"expiration_date": "05/2012"
},
"shipping": {
"first_name": "Carl",
"last_name": "Jones",
"company": "Braintree",
"street_address": "123 E Main St",
"extended_address": "Suite 403",
"locality": "Chicago",
"region": "IL",
"postal_code": "60622",
"country_name": "United States of America"
},
"options": {
"store_in_vault": True,
"store_shipping_address_in_vault": True,
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertNotEqual(None, re.search(r"\A\d{6,}\Z", transaction.customer_details.id))
self.assertEqual(transaction.customer_details.id, transaction.vault_customer.id)
shipping_address = transaction.vault_customer.addresses[0]
self.assertEqual("Carl", shipping_address.first_name)
self.assertEqual("Jones", shipping_address.last_name)
self.assertEqual("Braintree", shipping_address.company)
self.assertEqual("123 E Main St", shipping_address.street_address)
self.assertEqual("Suite 403", shipping_address.extended_address)
self.assertEqual("Chicago", shipping_address.locality)
self.assertEqual("IL", shipping_address.region)
self.assertEqual("60622", shipping_address.postal_code)
self.assertEqual("United States of America", shipping_address.country_name)
def test_create_submits_for_settlement_if_given_submit_for_settlement_option(self):
result = Transaction.sale({
"amount": "100",
"credit_card": {
"number": "5105105105105100",
"expiration_date": "05/2012"
},
"options": {
"submit_for_settlement": True
}
})
self.assertTrue(result.is_success)
self.assertEqual(Transaction.Status.SubmittedForSettlement, result.transaction.status)
def test_create_does_not_submit_for_settlement_if_submit_for_settlement_is_false(self):
result = Transaction.sale({
"amount": "100",
"credit_card": {
"number": "5105105105105100",
"expiration_date": "05/2012"
},
"options": {
"submit_for_settlement": False
}
})
self.assertTrue(result.is_success)
self.assertEqual(Transaction.Status.Authorized, result.transaction.status)
def test_create_can_specify_the_customer_id_and_payment_method_token(self):
customer_id = "customer_" + str(random.randint(1, 1000000))
payment_method_token = "credit_card_" + str(random.randint(1, 1000000))
result = Transaction.sale({
"amount": "100",
"customer": {
"id": customer_id,
"first_name": "Adam",
"last_name": "Williams"
},
"credit_card": {
"token": payment_method_token,
"number": "5105105105105100",
"expiration_date": "05/2012"
},
"options": {
"store_in_vault": True
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(customer_id, transaction.customer_details.id)
self.assertEqual(customer_id, transaction.vault_customer.id)
self.assertEqual(payment_method_token, transaction.credit_card_details.token)
self.assertEqual(payment_method_token, transaction.vault_credit_card.token)
def test_create_using_customer_id(self):
result = Customer.create({
"first_name": "Mike",
"last_name": "Jones",
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2010",
"cvv": "100"
}
})
self.assertTrue(result.is_success)
customer = result.customer
credit_card = customer.credit_cards[0]
result = Transaction.sale({
"amount": "100",
"customer_id": customer.id
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(customer.id, transaction.customer_details.id)
self.assertEqual(customer.id, transaction.vault_customer.id)
self.assertEqual(credit_card.token, transaction.credit_card_details.token)
self.assertEqual(credit_card.token, transaction.vault_credit_card.token)
def test_create_using_payment_method_token(self):
result = Customer.create({
"first_name": "Mike",
"last_name": "Jones",
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2010",
"cvv": "100"
}
})
self.assertTrue(result.is_success)
customer = result.customer
credit_card = customer.credit_cards[0]
result = Transaction.sale({
"amount": "100",
"payment_method_token": credit_card.token
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(customer.id, transaction.customer_details.id)
self.assertEqual(customer.id, transaction.vault_customer.id)
self.assertEqual(credit_card.token, transaction.credit_card_details.token)
self.assertEqual(credit_card.token, transaction.vault_credit_card.token)
def test_create_using_payment_method_token_with_cvv(self):
result = Customer.create({
"first_name": "Mike",
"last_name": "Jones",
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2010",
"cvv": "100"
}
})
self.assertTrue(result.is_success)
customer = result.customer
credit_card = customer.credit_cards[0]
result = Transaction.sale({
"amount": "100",
"payment_method_token": credit_card.token,
"credit_card": {
"cvv": "301"
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(customer.id, transaction.customer_details.id)
self.assertEqual(customer.id, transaction.vault_customer.id)
self.assertEqual(credit_card.token, transaction.credit_card_details.token)
self.assertEqual(credit_card.token, transaction.vault_credit_card.token)
self.assertEqual("S", transaction.cvv_response_code)
def test_create_with_failing_validations(self):
params = {
"transaction": {
"amount": None,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
}
}
result = Transaction.sale(params["transaction"])
params["transaction"]["credit_card"].pop("number")
self.assertFalse(result.is_success)
self.assertEqual(params, result.params)
self.assertEqual(
ErrorCodes.Transaction.AmountIsRequired,
result.errors.for_object("transaction").on("amount")[0].code
)
def test_credit_with_a_successful_result(self):
result = Transaction.credit({
"amount": Decimal(TransactionAmounts.Authorize),
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertNotEqual(None, re.search(r"\A\w{6,}\Z", transaction.id))
self.assertEqual(Transaction.Type.Credit, transaction.type)
self.assertEqual(Decimal(TransactionAmounts.Authorize), transaction.amount)
cc_details = transaction.credit_card_details
self.assertEqual("411111", cc_details.bin)
self.assertEqual("1111", cc_details.last_4)
self.assertEqual("05/2009", cc_details.expiration_date)
def test_credit_with_unsuccessful_result(self):
result = Transaction.credit({
"amount": None,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
})
params = {
"transaction": {
"type": Transaction.Type.Credit,
"amount": None,
"credit_card": {
"expiration_date": "05/2009"
}
}
}
self.assertFalse(result.is_success)
self.assertEqual(params, result.params)
self.assertEqual(
ErrorCodes.Transaction.AmountIsRequired,
result.errors.for_object("transaction").on("amount")[0].code
)
def test_credit_card_payment_instrument_type_is_credit_card(self):
result = Transaction.credit({
"amount": Decimal(TransactionAmounts.Authorize),
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(
PaymentInstrumentType.CreditCard,
transaction.payment_instrument_type
)
def test_service_fee_not_allowed_with_credits(self):
result = Transaction.credit({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"service_fee_amount": "1.00"
})
self.assertFalse(result.is_success)
self.assertTrue(
ErrorCodes.Transaction.ServiceFeeIsNotAllowedOnCredits in [error.code for error in result.errors.for_object("transaction").on("base")]
)
def test_credit_with_merchant_account_id(self):
result = Transaction.credit({
"amount": TransactionAmounts.Authorize,
"merchant_account_id": TestHelper.non_default_merchant_account_id,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(TestHelper.non_default_merchant_account_id, transaction.merchant_account_id)
def test_credit_without_merchant_account_id_falls_back_to_default(self):
result = Transaction.credit({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(TestHelper.default_merchant_account_id, transaction.merchant_account_id)
def test_find_returns_a_found_transaction(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Fail,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
}).transaction
TestHelper.settle_transaction(transaction.id)
found_transaction = Transaction.find(transaction.id)
self.assertEqual(transaction.id, found_transaction.id)
@raises_with_regexp(NotFoundError, "transaction with id 'notreal' not found")
def test_find_for_bad_transaction_raises_not_found_error(self):
Transaction.find("notreal")
def test_void_with_successful_result(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
}).transaction
result = Transaction.void(transaction.id)
self.assertTrue(result.is_success)
self.assertEqual(transaction.id, result.transaction.id)
self.assertEqual(Transaction.Status.Voided, result.transaction.status)
def test_void_with_unsuccessful_result(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Decline,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
}).transaction
result = Transaction.void(transaction.id)
self.assertFalse(result.is_success)
self.assertEqual(
ErrorCodes.Transaction.CannotBeVoided,
result.errors.for_object("transaction").on("base")[0].code
)
def test_create_with_successful_result(self):
result = Transaction.create({
"type": Transaction.Type.Sale,
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(Transaction.Type.Sale, transaction.type)
def test_create_with_error_result(self):
result = Transaction.create({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"billing": {
"country_code_alpha2": "ZZ",
"country_code_alpha3": "ZZZ",
"country_code_numeric": "000",
"country_name": "zzzzzz"
}
})
self.assertFalse(result.is_success)
self.assertEqual(ErrorCodes.Transaction.TypeIsRequired, result.errors.for_object("transaction").on("type")[0].code)
self.assertEqual(
ErrorCodes.Address.CountryCodeAlpha2IsNotAccepted,
result.errors.for_object("transaction").for_object("billing").on("country_code_alpha2")[0].code
)
self.assertEqual(
ErrorCodes.Address.CountryCodeAlpha3IsNotAccepted,
result.errors.for_object("transaction").for_object("billing").on("country_code_alpha3")[0].code
)
self.assertEqual(
ErrorCodes.Address.CountryCodeNumericIsNotAccepted,
result.errors.for_object("transaction").for_object("billing").on("country_code_numeric")[0].code
)
self.assertEqual(
ErrorCodes.Address.CountryNameIsNotAccepted,
result.errors.for_object("transaction").for_object("billing").on("country_name")[0].code
)
def test_sale_from_transparent_redirect_with_successful_result(self):
tr_data = {
"transaction": {
"amount": TransactionAmounts.Authorize,
}
}
post_params = {
"tr_data": Transaction.tr_data_for_sale(tr_data, "http://example.com/path"),
"transaction[credit_card][number]": "4111111111111111",
"transaction[credit_card][expiration_date]": "05/2010",
}
query_string = TestHelper.simulate_tr_form_post(post_params, Transaction.transparent_redirect_create_url())
result = Transaction.confirm_transparent_redirect(query_string)
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(Decimal(TransactionAmounts.Authorize), transaction.amount)
self.assertEqual(Transaction.Type.Sale, transaction.type)
self.assertEqual("411111", transaction.credit_card_details.bin)
self.assertEqual("1111", transaction.credit_card_details.last_4)
self.assertEqual("05/2010", transaction.credit_card_details.expiration_date)
def test_sale_from_transparent_redirect_with_error_result(self):
tr_data = {
"transaction": {
"amount": TransactionAmounts.Authorize,
}
}
post_params = {
"tr_data": Transaction.tr_data_for_sale(tr_data, "http://example.com/path"),
"transaction[credit_card][number]": "booya",
"transaction[credit_card][expiration_date]": "05/2010",
}
query_string = TestHelper.simulate_tr_form_post(post_params, Transaction.transparent_redirect_create_url())
result = Transaction.confirm_transparent_redirect(query_string)
self.assertFalse(result.is_success)
self.assertTrue(len(result.errors.for_object("transaction").for_object("credit_card").on("number")) > 0)
def test_sale_from_transparent_redirect_with_403_and_message(self):
tr_data = {
"transaction": {
"amount": TransactionAmounts.Authorize
}
}
post_params = {
"tr_data": Transaction.tr_data_for_sale(tr_data, "http://example.com/path"),
"transaction[credit_card][number]": "booya",
"transaction[credit_card][expiration_date]": "05/2010",
"transaction[bad]": "value"
}
query_string = TestHelper.simulate_tr_form_post(post_params, Transaction.transparent_redirect_create_url())
try:
Transaction.confirm_transparent_redirect(query_string)
self.fail()
except AuthorizationError as e:
self.assertEqual("Invalid params: transaction[bad]", str(e))
def test_credit_from_transparent_redirect_with_successful_result(self):
tr_data = {
"transaction": {
"amount": TransactionAmounts.Authorize,
}
}
post_params = {
"tr_data": Transaction.tr_data_for_credit(tr_data, "http://example.com/path"),
"transaction[credit_card][number]": "4111111111111111",
"transaction[credit_card][expiration_date]": "05/2010",
"transaction[billing][country_code_alpha2]": "US",
"transaction[billing][country_code_alpha3]": "USA",
"transaction[billing][country_code_numeric]": "840",
"transaction[billing][country_name]": "United States of America"
}
query_string = TestHelper.simulate_tr_form_post(post_params, Transaction.transparent_redirect_create_url())
result = Transaction.confirm_transparent_redirect(query_string)
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(Decimal(TransactionAmounts.Authorize), transaction.amount)
self.assertEqual(Transaction.Type.Credit, transaction.type)
self.assertEqual("411111", transaction.credit_card_details.bin)
self.assertEqual("1111", transaction.credit_card_details.last_4)
self.assertEqual("05/2010", transaction.credit_card_details.expiration_date)
self.assertEqual("US", transaction.billing_details.country_code_alpha2)
self.assertEqual("USA", transaction.billing_details.country_code_alpha3)
self.assertEqual("840", transaction.billing_details.country_code_numeric)
self.assertEqual("United States of America", transaction.billing_details.country_name)
def test_credit_from_transparent_redirect_with_error_result(self):
tr_data = {
"transaction": {
"amount": TransactionAmounts.Authorize,
}
}
post_params = {
"tr_data": Transaction.tr_data_for_credit(tr_data, "http://example.com/path"),
"transaction[credit_card][number]": "booya",
"transaction[credit_card][expiration_date]": "05/2010",
}
query_string = TestHelper.simulate_tr_form_post(post_params, Transaction.transparent_redirect_create_url())
result = Transaction.confirm_transparent_redirect(query_string)
self.assertFalse(result.is_success)
self.assertTrue(len(result.errors.for_object("transaction").for_object("credit_card").on("number")) > 0)
def test_submit_for_settlement_without_amount(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
}).transaction
submitted_transaction = Transaction.submit_for_settlement(transaction.id).transaction
self.assertEqual(Transaction.Status.SubmittedForSettlement, submitted_transaction.status)
self.assertEqual(Decimal(TransactionAmounts.Authorize), submitted_transaction.amount)
def test_submit_for_settlement_with_amount(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
}).transaction
submitted_transaction = Transaction.submit_for_settlement(transaction.id, Decimal("900")).transaction
self.assertEqual(Transaction.Status.SubmittedForSettlement, submitted_transaction.status)
self.assertEqual(Decimal("900.00"), submitted_transaction.amount)
def test_submit_for_settlement_with_order_id(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
}).transaction
params = {"order_id": "ABC123"}
submitted_transaction = Transaction.submit_for_settlement(transaction.id, Decimal("900"), params).transaction
self.assertEqual(Transaction.Status.SubmittedForSettlement, submitted_transaction.status)
self.assertEqual("ABC123", submitted_transaction.order_id)
def test_submit_for_settlement_with_descriptor(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
}).transaction
params = {
"descriptor": {
"name": "123*123456789012345678",
"phone": "3334445555",
"url": "ebay.com"
}
}
submitted_transaction = Transaction.submit_for_settlement(transaction.id, Decimal("900"), params).transaction
self.assertEqual(Transaction.Status.SubmittedForSettlement, submitted_transaction.status)
self.assertEqual("123*123456789012345678", submitted_transaction.descriptor.name)
self.assertEqual("3334445555", submitted_transaction.descriptor.phone)
self.assertEqual("ebay.com", submitted_transaction.descriptor.url)
@raises_with_regexp(KeyError, "'Invalid keys: invalid_param'")
def test_submit_for_settlement_with_invalid_params(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
}).transaction
params = {
"descriptor": {
"name": "123*123456789012345678",
"phone": "3334445555",
"url": "ebay.com"
},
"invalid_param": "foo",
}
Transaction.submit_for_settlement(transaction.id, Decimal("900"), params)
def test_submit_for_settlement_with_validation_error(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
}).transaction
result = Transaction.submit_for_settlement(transaction.id, Decimal("1200"))
self.assertFalse(result.is_success)
self.assertEqual(
ErrorCodes.Transaction.SettlementAmountIsTooLarge,
result.errors.for_object("transaction").on("amount")[0].code
)
def test_submit_for_settlement_with_validation_error_on_service_fee(self):
transaction = Transaction.sale({
"amount": "10.00",
"merchant_account_id": TestHelper.non_default_sub_merchant_account_id,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"service_fee_amount": "5.00"
}).transaction
result = Transaction.submit_for_settlement(transaction.id, "1.00")
self.assertFalse(result.is_success)
self.assertEqual(
ErrorCodes.Transaction.SettlementAmountIsLessThanServiceFeeAmount,
result.errors.for_object("transaction").on("amount")[0].code
)
def test_update_details_with_valid_params(self):
transaction = Transaction.sale({
"amount": "10.00",
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"options": {
"submit_for_settlement": True
}
}).transaction
params = {
"amount" : "9.00",
"order_id": "123",
"descriptor": {
"name": "456*123456789012345678",
"phone": "3334445555",
"url": "ebay.com"
}
}
result = Transaction.update_details(transaction.id, params)
self.assertTrue(result.is_success)
self.assertEqual(Decimal("9.00"), result.transaction.amount)
self.assertEqual(Transaction.Status.SubmittedForSettlement, result.transaction.status)
self.assertEqual("123", result.transaction.order_id)
self.assertEqual("456*123456789012345678", result.transaction.descriptor.name)
self.assertEqual("3334445555", result.transaction.descriptor.phone)
self.assertEqual("ebay.com", result.transaction.descriptor.url)
@raises_with_regexp(KeyError, "'Invalid keys: invalid_key'")
def test_update_details_with_invalid_params(self):
transaction = Transaction.sale({
"amount": "10.00",
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"options": {
"submit_for_settlement": True
},
}).transaction
params = {
"amount" : "9.00",
"invalid_key": "invalid_value",
"order_id": "123",
"descriptor": {
"name": "456*123456789012345678",
"phone": "3334445555",
"url": "ebay.com"
}
}
Transaction.update_details(transaction.id, params)
def test_update_details_with_invalid_order_id(self):
transaction = Transaction.sale({
"amount": "10.00",
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"options": {
"submit_for_settlement": True
},
}).transaction
params = {
"amount" : "9.00",
"order_id": "A" * 256,
"descriptor": {
"name": "456*123456789012345678",
"phone": "3334445555",
"url": "ebay.com"
}
}
result = Transaction.update_details(transaction.id, params)
self.assertFalse(result.is_success)
self.assertEqual(
ErrorCodes.Transaction.OrderIdIsTooLong,
result.errors.for_object("transaction").on("order_id")[0].code
)
def test_update_details_with_invalid_descriptor(self):
transaction = Transaction.sale({
"amount": "10.00",
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"options": {
"submit_for_settlement": True
},
}).transaction
params = {
"amount" : "9.00",
"order_id": "123",
"descriptor": {
"name": "invalid name",
"phone": "invalid phone",
"url": "12345678901234567890"
}
}
result = Transaction.update_details(transaction.id, params)
self.assertFalse(result.is_success)
self.assertEqual(
ErrorCodes.Descriptor.NameFormatIsInvalid,
result.errors.for_object("transaction").for_object("descriptor").on("name")[0].code
)
self.assertEqual(
ErrorCodes.Descriptor.PhoneFormatIsInvalid,
result.errors.for_object("transaction").for_object("descriptor").on("phone")[0].code
)
self.assertEqual(
ErrorCodes.Descriptor.UrlFormatIsInvalid,
result.errors.for_object("transaction").for_object("descriptor").on("url")[0].code
)
def test_update_details_with_invalid_amount(self):
transaction = Transaction.sale({
"amount": "10.00",
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"options": {
"submit_for_settlement": True
},
}).transaction
params = {
"amount" : "999.00",
"order_id": "123",
}
result = Transaction.update_details(transaction.id, params)
self.assertFalse(result.is_success)
self.assertEqual(
ErrorCodes.Transaction.SettlementAmountIsTooLarge,
result.errors.for_object("transaction").on("amount")[0].code
)
def test_update_details_with_invalid_status(self):
transaction = Transaction.sale({
"amount": "10.00",
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
}).transaction
params = {
"amount" : "9.00",
"order_id": "123",
}
result = Transaction.update_details(transaction.id, params)
self.assertFalse(result.is_success)
self.assertEqual(
ErrorCodes.Transaction.CannotUpdateTransactionDetailsNotSubmittedForSettlement,
result.errors.for_object("transaction").on("base")[0].code
)
def test_update_details_with_invalid_processor(self):
transaction = Transaction.sale({
"amount": "10.00",
"merchant_account_id": TestHelper.fake_amex_direct_merchant_account_id,
"credit_card": {
"number": CreditCardNumbers.AmexPayWithPoints.Success,
"expiration_date": "05/2020"
},
"options": {
"submit_for_settlement": True
},
}).transaction
params = {
"amount" : "9.00",
"order_id": "123",
}
result = Transaction.update_details(transaction.id, params)
self.assertFalse(result.is_success)
self.assertEqual(
ErrorCodes.Transaction.ProcessorDoesNotSupportUpdatingTransactionDetails,
result.errors.for_object("transaction").on("base")[0].code
)
def test_status_history(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
}).transaction
submitted_transaction = Transaction.submit_for_settlement(transaction.id).transaction
self.assertEqual(2, len(submitted_transaction.status_history))
self.assertEqual(Transaction.Status.Authorized, submitted_transaction.status_history[0].status)
self.assertEqual(Decimal(TransactionAmounts.Authorize), submitted_transaction.status_history[0].amount)
self.assertEqual(Transaction.Status.SubmittedForSettlement, submitted_transaction.status_history[1].status)
self.assertEqual(Decimal(TransactionAmounts.Authorize), submitted_transaction.status_history[1].amount)
def test_successful_refund(self):
transaction = self.__create_transaction_to_refund()
result = Transaction.refund(transaction.id)
self.assertTrue(result.is_success)
refund = result.transaction
self.assertEqual(Transaction.Type.Credit, refund.type)
self.assertEqual(Decimal(TransactionAmounts.Authorize), refund.amount)
self.assertEqual(transaction.id, refund.refunded_transaction_id)
self.assertEqual(refund.id, Transaction.find(transaction.id).refund_id)
def test_successful_partial_refund(self):
transaction = self.__create_transaction_to_refund()
result = Transaction.refund(transaction.id, Decimal("500.00"))
self.assertTrue(result.is_success)
self.assertEqual(Transaction.Type.Credit, result.transaction.type)
self.assertEqual(Decimal("500.00"), result.transaction.amount)
def test_multiple_successful_partial_refunds(self):
transaction = self.__create_transaction_to_refund()
refund1 = Transaction.refund(transaction.id, Decimal("500.00")).transaction
self.assertEqual(Transaction.Type.Credit, refund1.type)
self.assertEqual(Decimal("500.00"), refund1.amount)
refund2 = Transaction.refund(transaction.id, Decimal("500.00")).transaction
self.assertEqual(Transaction.Type.Credit, refund2.type)
self.assertEqual(Decimal("500.00"), refund2.amount)
transaction = Transaction.find(transaction.id)
self.assertEqual(2, len(transaction.refund_ids))
self.assertTrue(TestHelper.in_list(transaction.refund_ids, refund1.id))
self.assertTrue(TestHelper.in_list(transaction.refund_ids, refund2.id))
def test_refund_already_refunded_transation_fails(self):
transaction = self.__create_transaction_to_refund()
Transaction.refund(transaction.id)
result = Transaction.refund(transaction.id)
self.assertFalse(result.is_success)
self.assertEqual(
ErrorCodes.Transaction.HasAlreadyBeenRefunded,
result.errors.for_object("transaction").on("base")[0].code
)
def test_refund_with_options_params(self):
transaction = self.__create_transaction_to_refund()
options = {
"amount": Decimal("1.00"),
"order_id": "abcd"
}
result = Transaction.refund(transaction.id, options)
self.assertTrue(result.is_success)
self.assertEqual(
"abcd",
result.transaction.order_id
)
self.assertEqual(
Decimal("1.00"),
result.transaction.amount
)
def test_refund_returns_an_error_if_unsettled(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"options": {
"submit_for_settlement": True
}
}).transaction
result = Transaction.refund(transaction.id)
self.assertFalse(result.is_success)
self.assertEqual(
ErrorCodes.Transaction.CannotRefundUnlessSettled,
result.errors.for_object("transaction").on("base")[0].code
)
@staticmethod
def __create_transaction_to_refund():
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"options": {
"submit_for_settlement": True
}
}).transaction
TestHelper.settle_transaction(transaction.id)
return transaction
@staticmethod
def __create_paypal_transaction():
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"payment_method_nonce": Nonces.PayPalOneTimePayment,
"options": {
"submit_for_settlement": True
}
}).transaction
return transaction
@staticmethod
def __create_escrowed_transaction():
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2012"
},
"service_fee_amount": "10.00",
"merchant_account_id": TestHelper.non_default_sub_merchant_account_id,
"options": {
"hold_in_escrow": True
}
}).transaction
TestHelper.escrow_transaction(transaction.id)
return transaction
def test_snapshot_plan_id_add_ons_and_discounts_from_subscription(self):
credit_card = Customer.create({
"first_name": "Mike",
"last_name": "Jones",
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2010",
"cvv": "100"
}
}).customer.credit_cards[0]
result = Subscription.create({
"payment_method_token": credit_card.token,
"plan_id": TestHelper.trialless_plan["id"],
"add_ons": {
"add": [
{
"amount": Decimal("11.00"),
"inherited_from_id": "increase_10",
"quantity": 2,
"number_of_billing_cycles": 5
},
{
"amount": Decimal("21.00"),
"inherited_from_id": "increase_20",
"quantity": 3,
"number_of_billing_cycles": 6
}
]
},
"discounts": {
"add": [
{
"amount": Decimal("7.50"),
"inherited_from_id": "discount_7",
"quantity": 2,
"never_expires": True
}
]
}
})
transaction = result.subscription.transactions[0]
self.assertEqual(TestHelper.trialless_plan["id"], transaction.plan_id)
self.assertEqual(2, len(transaction.add_ons))
add_ons = sorted(transaction.add_ons, key=lambda add_on: add_on.id)
self.assertEqual("increase_10", add_ons[0].id)
self.assertEqual(Decimal("11.00"), add_ons[0].amount)
self.assertEqual(2, add_ons[0].quantity)
self.assertEqual(5, add_ons[0].number_of_billing_cycles)
self.assertFalse(add_ons[0].never_expires)
self.assertEqual("increase_20", add_ons[1].id)
self.assertEqual(Decimal("21.00"), add_ons[1].amount)
self.assertEqual(3, add_ons[1].quantity)
self.assertEqual(6, add_ons[1].number_of_billing_cycles)
self.assertFalse(add_ons[1].never_expires)
self.assertEqual(1, len(transaction.discounts))
discounts = transaction.discounts
self.assertEqual("discount_7", discounts[0].id)
self.assertEqual(Decimal("7.50"), discounts[0].amount)
self.assertEqual(2, discounts[0].quantity)
self.assertEqual(None, discounts[0].number_of_billing_cycles)
self.assertTrue(discounts[0].never_expires)
def test_transactions_accept_lodging_industry_data(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"industry": {
"industry_type": Transaction.IndustryType.Lodging,
"data": {
"folio_number": "aaa",
"check_in_date": "2014-07-07",
"check_out_date": "2014-08-08",
"room_rate": "239.00",
}
}
})
self.assertTrue(result.is_success)
def test_transactions_return_validation_errors_on_lodging_industry_data(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"industry": {
"industry_type": Transaction.IndustryType.Lodging,
"data": {
"folio_number": "aaa",
"check_in_date": "2014-07-07",
"check_out_date": "2014-06-06",
"room_rate": "asdfsdf",
}
}
})
self.assertFalse(result.is_success)
self.assertEqual(
ErrorCodes.Transaction.Industry.Lodging.CheckOutDateMustFollowCheckInDate,
result.errors.for_object("transaction").for_object("industry").on("check_out_date")[0].code
)
def test_transactions_accept_travel_cruise_industry_data(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"industry": {
"industry_type": Transaction.IndustryType.TravelAndCruise,
"data": {
"travel_package": "flight",
"departure_date": "2014-07-07",
"lodging_check_in_date": "2014-07-07",
"lodging_check_out_date": "2014-09-07",
"lodging_name": "Royal Caribbean"
}
}
})
self.assertTrue(result.is_success)
def test_transactions_return_validation_errors_on_travel_cruise_industry_data(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"industry": {
"industry_type": Transaction.IndustryType.TravelAndCruise,
"data": {
"travel_package": "roadtrip",
"departure_date": "2014-07-07",
"lodging_check_in_date": "2014-07-07",
"lodging_check_out_date": "2014-09-07",
"lodging_name": "Royal Caribbean"
}
}
})
self.assertFalse(result.is_success)
self.assertEqual(
ErrorCodes.Transaction.Industry.TravelCruise.TravelPackageIsInvalid,
result.errors.for_object("transaction").for_object("industry").on("travel_package")[0].code
)
def test_descriptors_accepts_name_phone_and_url(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"descriptor": {
"name": "123*123456789012345678",
"phone": "3334445555",
"url": "ebay.com"
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual("123*123456789012345678", transaction.descriptor.name)
self.assertEqual("3334445555", transaction.descriptor.phone)
self.assertEqual("ebay.com", transaction.descriptor.url)
def test_descriptors_has_validation_errors_if_format_is_invalid(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"descriptor": {
"name": "badcompanyname12*badproduct12",
"phone": "%bad4445555",
"url": "12345678901234"
}
})
self.assertFalse(result.is_success)
self.assertEqual(
ErrorCodes.Descriptor.NameFormatIsInvalid,
result.errors.for_object("transaction").for_object("descriptor").on("name")[0].code
)
self.assertEqual(
ErrorCodes.Descriptor.PhoneFormatIsInvalid,
result.errors.for_object("transaction").for_object("descriptor").on("phone")[0].code
)
self.assertEqual(
ErrorCodes.Descriptor.UrlFormatIsInvalid,
result.errors.for_object("transaction").for_object("descriptor").on("url")[0].code
)
def test_clone_transaction(self):
result = Transaction.sale({
"amount": "100.00",
"order_id": "123",
"credit_card": {
"number": "5105105105105100",
"expiration_date": "05/2011",
},
"customer": {
"first_name": "Dan",
},
"billing": {
"first_name": "Carl",
},
"shipping": {
"first_name": "Andrew",
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
clone_result = Transaction.clone_transaction(
transaction.id,
{
"amount": "123.45",
"channel": "MyShoppingCartProvider",
"options": {"submit_for_settlement": "false"}
})
self.assertTrue(clone_result.is_success)
clone_transaction = clone_result.transaction
self.assertNotEqual(transaction.id, clone_transaction.id)
self.assertEqual(Transaction.Type.Sale, clone_transaction.type)
self.assertEqual(Transaction.Status.Authorized, clone_transaction.status)
self.assertEqual(Decimal("123.45"), clone_transaction.amount)
self.assertEqual("MyShoppingCartProvider", clone_transaction.channel)
self.assertEqual("123", clone_transaction.order_id)
self.assertEqual("510510******5100", clone_transaction.credit_card_details.masked_number)
self.assertEqual("Dan", clone_transaction.customer_details.first_name)
self.assertEqual("Carl", clone_transaction.billing_details.first_name)
self.assertEqual("Andrew", clone_transaction.shipping_details.first_name)
def test_clone_transaction_submits_for_settlement(self):
result = Transaction.sale({
"amount": "100.00",
"credit_card": {
"number": "5105105105105100",
"expiration_date": "05/2011",
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
clone_result = Transaction.clone_transaction(transaction.id, {"amount": "123.45", "options": {"submit_for_settlement": "true"}})
self.assertTrue(clone_result.is_success)
clone_transaction = clone_result.transaction
self.assertEqual(Transaction.Type.Sale, clone_transaction.type)
self.assertEqual(Transaction.Status.SubmittedForSettlement, clone_transaction.status)
def test_clone_transaction_with_validations(self):
result = Transaction.credit({
"amount": "100.00",
"credit_card": {
"number": "5105105105105100",
"expiration_date": "05/2011",
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
clone_result = Transaction.clone_transaction(transaction.id, {"amount": "123.45"})
self.assertFalse(clone_result.is_success)
self.assertEqual(
ErrorCodes.Transaction.CannotCloneCredit,
clone_result.errors.for_object("transaction").on("base")[0].code
)
def test_find_exposes_disbursement_details(self):
transaction = Transaction.find("deposittransaction")
disbursement_details = transaction.disbursement_details
self.assertEqual(date(2013, 4, 10), disbursement_details.disbursement_date)
self.assertEqual("USD", disbursement_details.settlement_currency_iso_code)
self.assertEqual(Decimal("1"), disbursement_details.settlement_currency_exchange_rate)
self.assertEqual(False, disbursement_details.funds_held)
self.assertEqual(True, disbursement_details.success)
self.assertEqual(Decimal("100.00"), disbursement_details.settlement_amount)
def test_sale_with_three_d_secure_option(self):
result = Transaction.sale({
"merchant_account_id": TestHelper.three_d_secure_merchant_account_id,
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"options": {
"three_d_secure": {
"required": True
}
}
})
self.assertFalse(result.is_success)
self.assertEqual(Transaction.Status.GatewayRejected, result.transaction.status)
self.assertEqual(Transaction.GatewayRejectionReason.ThreeDSecure, result.transaction.gateway_rejection_reason)
def test_sale_with_three_d_secure_token(self):
three_d_secure_token = TestHelper.create_3ds_verification(TestHelper.three_d_secure_merchant_account_id, {
"number": "4111111111111111",
"expiration_month": "05",
"expiration_year": "2009",
})
result = Transaction.sale({
"merchant_account_id": TestHelper.three_d_secure_merchant_account_id,
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"three_d_secure_token": three_d_secure_token
})
self.assertTrue(result.is_success)
def test_sale_without_three_d_secure_token(self):
result = Transaction.sale({
"merchant_account_id": TestHelper.three_d_secure_merchant_account_id,
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
})
self.assertTrue(result.is_success)
def test_sale_returns_error_with_none_three_d_secure_token(self):
result = Transaction.sale({
"merchant_account_id": TestHelper.three_d_secure_merchant_account_id,
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"three_d_secure_token": None
})
self.assertFalse(result.is_success)
self.assertEqual(
ErrorCodes.Transaction.ThreeDSecureTokenIsInvalid,
result.errors.for_object("transaction").on("three_d_secure_token")[0].code
)
def test_sale_returns_error_with_mismatched_3ds_verification_data(self):
three_d_secure_token = TestHelper.create_3ds_verification(TestHelper.three_d_secure_merchant_account_id, {
"number": "4111111111111111",
"expiration_month": "05",
"expiration_year": "2009",
})
result = Transaction.sale({
"merchant_account_id": TestHelper.three_d_secure_merchant_account_id,
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "5105105105105100",
"expiration_date": "05/2009"
},
"three_d_secure_token": three_d_secure_token
})
self.assertFalse(result.is_success)
self.assertEqual(
ErrorCodes.Transaction.ThreeDSecureTransactionDataDoesntMatchVerify,
result.errors.for_object("transaction").on("three_d_secure_token")[0].code
)
def test_transaction_with_three_d_secure_pass_thru(self):
result = Transaction.sale({
"merchant_account_id": TestHelper.three_d_secure_merchant_account_id,
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"three_d_secure_pass_thru": {
"eci_flag": "02",
"cavv": "some-cavv",
"xid": "some-xid"
}
})
self.assertTrue(result.is_success)
self.assertEqual(Transaction.Status.Authorized, result.transaction.status)
def test_transaction_with_three_d_secure_pass_thru_with_invalid_processor_settings(self):
result = Transaction.sale({
"merchant_account_id": "adyen_ma",
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"three_d_secure_pass_thru": {
"eci_flag": "02",
"cavv": "some-cavv",
"xid": "some-xid"
}
})
self.assertFalse(result.is_success)
self.assertEqual(
ErrorCodes.Transaction.ThreeDSecureMerchantAccountDoesNotSupportCardType,
result.errors.for_object("transaction").on("merchant_account_id")[0].code
)
def test_transaction_with_three_d_secure_pass_thru_with_missing_eci_flag(self):
result = Transaction.sale({
"merchant_account_id": TestHelper.three_d_secure_merchant_account_id,
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"three_d_secure_pass_thru": {
"eci_flag": "",
"cavv": "some-cavv",
"xid": "some-xid"
}
})
self.assertFalse(result.is_success)
self.assertEqual(
ErrorCodes.Transaction.ThreeDSecureEciFlagIsRequired,
result.errors.for_object("transaction").for_object("three_d_secure_pass_thru").on("eci_flag")[0].code
)
def test_transaction_with_three_d_secure_pass_thru_with_missing_cavv_and_xid(self):
result = Transaction.sale({
"merchant_account_id": TestHelper.three_d_secure_merchant_account_id,
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"three_d_secure_pass_thru": {
"eci_flag": "05",
"cavv": "",
"xid": ""
}
})
self.assertFalse(result.is_success)
self.assertEqual(
ErrorCodes.Transaction.ThreeDSecureCavvIsRequired,
result.errors.for_object("transaction").for_object("three_d_secure_pass_thru").on("cavv")[0].code
)
def test_transaction_with_three_d_secure_pass_thru_with_invalid_eci_flag(self):
result = Transaction.sale({
"merchant_account_id": TestHelper.three_d_secure_merchant_account_id,
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"three_d_secure_pass_thru": {
"eci_flag": "bad_eci_flag",
"cavv": "some-cavv",
"xid": "some-xid"
}
})
self.assertFalse(result.is_success)
self.assertEqual(
ErrorCodes.Transaction.ThreeDSecureEciFlagIsInvalid,
result.errors.for_object("transaction").for_object("three_d_secure_pass_thru").on("eci_flag")[0].code
)
def test_sale_with_amex_rewards_succeeds(self):
result = Transaction.sale({
"merchant_account_id": TestHelper.fake_amex_direct_merchant_account_id,
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": CreditCardNumbers.AmexPayWithPoints.Success,
"expiration_date": "05/2020"
},
"options" : {
"submit_for_settlement" : True,
"amex_rewards" : {
"request_id" : "ABC123",
"points" : "100",
"currency_amount" : "1.00",
"currency_iso_code" : "USD"
}
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(Transaction.Type.Sale, transaction.type)
self.assertEqual(Transaction.Status.SubmittedForSettlement, transaction.status)
def test_sale_with_amex_rewards_succeeds_even_if_card_is_ineligible(self):
result = Transaction.sale({
"merchant_account_id": TestHelper.fake_amex_direct_merchant_account_id,
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": CreditCardNumbers.AmexPayWithPoints.IneligibleCard,
"expiration_date": "05/2009"
},
"options" : {
"submit_for_settlement" : True,
"amex_rewards" : {
"request_id" : "ABC123",
"points" : "100",
"currency_amount" : "1.00",
"currency_iso_code" : "USD"
}
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(Transaction.Type.Sale, transaction.type)
self.assertEqual(Transaction.Status.SubmittedForSettlement, transaction.status)
def test_sale_with_amex_rewards_succeeds_even_if_card_balance_is_insufficient(self):
result = Transaction.sale({
"merchant_account_id": TestHelper.fake_amex_direct_merchant_account_id,
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": CreditCardNumbers.AmexPayWithPoints.InsufficientPoints,
"expiration_date": "05/2009"
},
"options" : {
"submit_for_settlement" : True,
"amex_rewards" : {
"request_id" : "ABC123",
"points" : "100",
"currency_amount" : "1.00",
"currency_iso_code" : "USD"
}
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(Transaction.Type.Sale, transaction.type)
self.assertEqual(Transaction.Status.SubmittedForSettlement, transaction.status)
def test_submit_for_settlement_with_amex_rewards_succeeds(self):
result = Transaction.sale({
"merchant_account_id": TestHelper.fake_amex_direct_merchant_account_id,
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": CreditCardNumbers.AmexPayWithPoints.Success,
"expiration_date": "05/2009"
},
"options" : {
"amex_rewards" : {
"request_id" : "ABC123",
"points" : "100",
"currency_amount" : "1.00",
"currency_iso_code" : "USD"
}
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(Transaction.Type.Sale, transaction.type)
self.assertEqual(Transaction.Status.Authorized, transaction.status)
submitted_transaction = Transaction.submit_for_settlement(transaction.id).transaction
self.assertEqual(Transaction.Status.SubmittedForSettlement, submitted_transaction.status)
def test_submit_for_settlement_with_amex_rewards_succeeds_even_if_card_is_ineligible(self):
result = Transaction.sale({
"merchant_account_id": TestHelper.fake_amex_direct_merchant_account_id,
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": CreditCardNumbers.AmexPayWithPoints.IneligibleCard,
"expiration_date": "05/2009"
},
"options" : {
"amex_rewards" : {
"request_id" : "ABC123",
"points" : "100",
"currency_amount" : "1.00",
"currency_iso_code" : "USD"
}
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(Transaction.Type.Sale, transaction.type)
self.assertEqual(Transaction.Status.Authorized, transaction.status)
submitted_transaction = Transaction.submit_for_settlement(transaction.id).transaction
self.assertEqual(Transaction.Status.SubmittedForSettlement, submitted_transaction.status)
def test_submit_for_settlement_with_amex_rewards_succeeds_even_if_card_balance_is_insufficient(self):
result = Transaction.sale({
"merchant_account_id": TestHelper.fake_amex_direct_merchant_account_id,
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": CreditCardNumbers.AmexPayWithPoints.InsufficientPoints,
"expiration_date": "05/2009"
},
"options" : {
"amex_rewards" : {
"request_id" : "ABC123",
"points" : "100",
"currency_amount" : "1.00",
"currency_iso_code" : "USD"
}
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(Transaction.Type.Sale, transaction.type)
self.assertEqual(Transaction.Status.Authorized, transaction.status)
submitted_transaction = Transaction.submit_for_settlement(transaction.id).transaction
self.assertEqual(Transaction.Status.SubmittedForSettlement, submitted_transaction.status)
def test_find_exposes_authorization_adjustments(self):
transaction = Transaction.find("authadjustmenttransaction")
authorization_adjustment = transaction.authorization_adjustments[0]
self.assertEqual(datetime, type(authorization_adjustment.timestamp))
self.assertEqual(Decimal("-20.00"), authorization_adjustment.amount)
self.assertEqual(True, authorization_adjustment.success)
def test_find_exposes_disputes(self):
transaction = Transaction.find("disputedtransaction")
dispute = transaction.disputes[0]
self.assertEqual(date(2014, 3, 1), dispute.received_date)
self.assertEqual(date(2014, 3, 21), dispute.reply_by_date)
self.assertEqual("USD", dispute.currency_iso_code)
self.assertEqual(Decimal("250.00"), dispute.amount)
self.assertEqual(Dispute.Status.Won, dispute.status)
self.assertEqual(Dispute.Reason.Fraud, dispute.reason)
self.assertEqual("disputedtransaction", dispute.transaction_details.id)
self.assertEqual(Decimal("1000.00"), dispute.transaction_details.amount)
self.assertEqual(Dispute.Kind.Chargeback, dispute.kind)
self.assertEqual(date(2014, 3, 1), dispute.date_opened)
self.assertEqual(date(2014, 3, 7), dispute.date_won)
def test_find_exposes_three_d_secure_info(self):
transaction = Transaction.find("threedsecuredtransaction")
three_d_secure_info = transaction.three_d_secure_info
self.assertEqual("Y", three_d_secure_info.enrolled)
self.assertEqual("authenticate_successful", three_d_secure_info.status)
self.assertEqual(True, three_d_secure_info.liability_shifted)
self.assertEqual(True, three_d_secure_info.liability_shift_possible)
def test_find_exposes_none_for_null_three_d_secure_info(self):
transaction = Transaction.find("settledtransaction")
three_d_secure_info = transaction.three_d_secure_info
self.assertEqual(None, three_d_secure_info)
def test_find_exposes_retrievals(self):
transaction = Transaction.find("retrievaltransaction")
dispute = transaction.disputes[0]
self.assertEqual("USD", dispute.currency_iso_code)
self.assertEqual(Decimal("1000.00"), dispute.amount)
self.assertEqual(Dispute.Status.Open, dispute.status)
self.assertEqual(Dispute.Reason.Retrieval, dispute.reason)
self.assertEqual("retrievaltransaction", dispute.transaction_details.id)
self.assertEqual(Decimal("1000.00"), dispute.transaction_details.amount)
def test_creating_paypal_transaction_with_one_time_use_nonce(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"payment_method_nonce": Nonces.PayPalOneTimePayment,
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(transaction.paypal_details.payer_email, "payer@example.com")
self.assertNotEqual(None, re.search(r'PAY-\w+', transaction.paypal_details.payment_id))
self.assertNotEqual(None, re.search(r'AUTH-\w+', transaction.paypal_details.authorization_id))
self.assertNotEqual(None, transaction.paypal_details.image_url)
self.assertNotEqual(None, transaction.paypal_details.debug_id)
def test_creating_paypal_transaction_with_payee_email(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"payment_method_nonce": Nonces.PayPalOneTimePayment,
"paypal_account": {
"payee_email": "payee@example.com"
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(transaction.paypal_details.payer_email, "payer@example.com")
self.assertNotEqual(None, re.search(r'PAY-\w+', transaction.paypal_details.payment_id))
self.assertNotEqual(None, re.search(r'AUTH-\w+', transaction.paypal_details.authorization_id))
self.assertNotEqual(None, transaction.paypal_details.image_url)
self.assertNotEqual(None, transaction.paypal_details.debug_id)
self.assertEqual(transaction.paypal_details.payee_email, "payee@example.com")
def test_creating_paypal_transaction_with_payee_email_in_options_params(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"payment_method_nonce": Nonces.PayPalOneTimePayment,
"paypal_account": {},
"options": {
"payee_email": "payee@example.com"
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(transaction.paypal_details.payer_email, "payer@example.com")
self.assertNotEqual(None, re.search(r'PAY-\w+', transaction.paypal_details.payment_id))
self.assertNotEqual(None, re.search(r'AUTH-\w+', transaction.paypal_details.authorization_id))
self.assertNotEqual(None, transaction.paypal_details.image_url)
self.assertNotEqual(None, transaction.paypal_details.debug_id)
self.assertEqual(transaction.paypal_details.payee_email, "payee@example.com")
def test_creating_paypal_transaction_with_payee_email_in_options_paypal_params(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"payment_method_nonce": Nonces.PayPalOneTimePayment,
"paypal_account": {},
"options": {
"paypal": {
"payee_email": "foo@paypal.com"
}
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(transaction.paypal_details.payer_email, "payer@example.com")
self.assertNotEqual(None, re.search(r'PAY-\w+', transaction.paypal_details.payment_id))
self.assertNotEqual(None, re.search(r'AUTH-\w+', transaction.paypal_details.authorization_id))
self.assertNotEqual(None, transaction.paypal_details.image_url)
self.assertNotEqual(None, transaction.paypal_details.debug_id)
self.assertEqual(transaction.paypal_details.payee_email, "foo@paypal.com")
def test_creating_paypal_transaction_with_custom_field_in_options_paypal_params(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"payment_method_nonce": Nonces.PayPalOneTimePayment,
"paypal_account": {},
"options": {
"paypal": {
"custom_field": "custom field stuff"
}
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(transaction.paypal_details.payer_email, "payer@example.com")
self.assertNotEqual(None, re.search(r'PAY-\w+', transaction.paypal_details.payment_id))
self.assertNotEqual(None, re.search(r'AUTH-\w+', transaction.paypal_details.authorization_id))
self.assertNotEqual(None, transaction.paypal_details.image_url)
self.assertNotEqual(None, transaction.paypal_details.debug_id)
self.assertEqual(transaction.paypal_details.custom_field, "custom field stuff")
def test_creating_paypal_transaction_with_supplementary_data_in_options_paypal_params(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"payment_method_nonce": Nonces.PayPalOneTimePayment,
"paypal_account": {},
"options": {
"paypal": {
"supplementary_data": {
"key1": "value1",
"key2": "value2"
}
}
}
})
# note - supplementary data is not returned in response
self.assertTrue(result.is_success)
def test_creating_paypal_transaction_with_description_in_options_paypal_params(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"payment_method_nonce": Nonces.PayPalOneTimePayment,
"paypal_account": {},
"options": {
"paypal": {
"description": "Product description"
}
}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(transaction.paypal_details.payer_email, "payer@example.com")
self.assertNotEqual(None, re.search(r'PAY-\w+', transaction.paypal_details.payment_id))
self.assertNotEqual(None, re.search(r'AUTH-\w+', transaction.paypal_details.authorization_id))
self.assertNotEqual(None, transaction.paypal_details.image_url)
self.assertNotEqual(None, transaction.paypal_details.debug_id)
self.assertEqual(transaction.paypal_details.description, "Product description")
def test_paypal_transaction_payment_instrument_type(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"payment_method_nonce": Nonces.PayPalOneTimePayment,
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(PaymentInstrumentType.PayPalAccount, transaction.payment_instrument_type)
def test_creating_paypal_transaction_with_one_time_use_nonce_and_store_in_vault(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"payment_method_nonce": Nonces.PayPalOneTimePayment,
"options": {"store_in_vault": True}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(transaction.paypal_details.payer_email, "payer@example.com")
self.assertEqual(transaction.paypal_details.token, None)
self.assertNotEqual(None, transaction.paypal_details.debug_id)
def test_creating_paypal_transaction_with_future_payment_nonce(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"payment_method_nonce": Nonces.PayPalFuturePayment
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(transaction.paypal_details.payer_email, "payer@example.com")
self.assertNotEqual(None, re.search(r'PAY-\w+', transaction.paypal_details.payment_id))
self.assertNotEqual(None, re.search(r'AUTH-\w+', transaction.paypal_details.authorization_id))
self.assertNotEqual(None, transaction.paypal_details.debug_id)
def test_validation_failure_on_invalid_paypal_nonce(self):
http = ClientApiHttp.create()
status_code, nonce = http.get_paypal_nonce({
"consent-code": "consent-code",
"access-token": "access-token",
"options": {"validate": False}
})
self.assertEqual(202, status_code)
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"payment_method_nonce": nonce
})
self.assertFalse(result.is_success)
error_code = result.errors.for_object("transaction").for_object("paypal_account").on("base")[0].code
self.assertEqual(error_code, ErrorCodes.PayPalAccount.CannotHaveBothAccessTokenAndConsentCode)
def test_validation_failure_on_non_existent_nonce(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"payment_method_nonce": "doesnt-exist"
})
self.assertFalse(result.is_success)
error_code = result.errors.for_object("transaction").on("payment_method_nonce")[0].code
self.assertEqual(error_code, ErrorCodes.Transaction.PaymentMethodNonceUnknown)
def test_creating_paypal_transaction_with_vaulted_token(self):
customer_id = Customer.create().customer.id
result = PaymentMethod.create({
"customer_id": customer_id,
"payment_method_nonce": Nonces.PayPalFuturePayment
})
self.assertTrue(result.is_success)
transaction_result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"payment_method_token": result.payment_method.token
})
self.assertTrue(transaction_result.is_success)
transaction = transaction_result.transaction
self.assertEqual(transaction.paypal_details.payer_email, "payer@example.com")
self.assertNotEqual(None, transaction.paypal_details.debug_id)
def test_creating_paypal_transaction_with_one_time_nonce_and_store_in_vault_fails_gracefully(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"payment_method_nonce": Nonces.PayPalOneTimePayment,
"options": {"store_in_vault": True}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(None, transaction.paypal_details.token)
def test_creating_paypal_transaction_with_future_payment_nonce_and_store_in_vault(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"payment_method_nonce": Nonces.PayPalFuturePayment,
"options": {"store_in_vault": True}
})
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertNotEqual(None, transaction.paypal_details.token)
paypal_account = PaymentMethod.find(transaction.paypal_details.token)
self.assertEqual(paypal_account.email, transaction.paypal_details.payer_email)
def test_creating_paypal_transaction_and_submitting_for_settlement(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"payment_method_nonce": Nonces.PayPalOneTimePayment,
"options": {"submit_for_settlement": True}
})
self.assertTrue(result.is_success)
self.assertEqual(result.transaction.status, Transaction.Status.Settling)
def test_voiding_a_paypal_transaction(self):
sale_result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"payment_method_nonce": Nonces.PayPalOneTimePayment,
})
self.assertTrue(sale_result.is_success)
sale_transaction = sale_result.transaction
void_result = Transaction.void(sale_transaction.id)
self.assertTrue(void_result.is_success)
void_transaction = void_result.transaction
self.assertEqual(void_transaction.id, sale_transaction.id)
self.assertEqual(void_transaction.status, Transaction.Status.Voided)
def test_paypal_transaction_successful_refund(self):
transaction = self.__create_paypal_transaction()
result = Transaction.refund(transaction.id)
self.assertTrue(result.is_success)
refund = result.transaction
self.assertEqual(Transaction.Type.Credit, refund.type)
self.assertEqual(Decimal(TransactionAmounts.Authorize), refund.amount)
self.assertEqual(transaction.id, refund.refunded_transaction_id)
self.assertEqual(refund.id, Transaction.find(transaction.id).refund_id)
def test_paypal_transaction_successful_partial_refund(self):
transaction = self.__create_paypal_transaction()
result = Transaction.refund(transaction.id, Decimal("500.00"))
self.assertTrue(result.is_success)
self.assertEqual(Transaction.Type.Credit, result.transaction.type)
self.assertEqual(Decimal("500.00"), result.transaction.amount)
def test_paypal_transaction_multiple_successful_partial_refunds(self):
transaction = self.__create_paypal_transaction()
refund1 = Transaction.refund(transaction.id, Decimal("500.00")).transaction
self.assertEqual(Transaction.Type.Credit, refund1.type)
self.assertEqual(Decimal("500.00"), refund1.amount)
refund2 = Transaction.refund(transaction.id, Decimal("500.00")).transaction
self.assertEqual(Transaction.Type.Credit, refund2.type)
self.assertEqual(Decimal("500.00"), refund2.amount)
transaction = Transaction.find(transaction.id)
self.assertEqual(2, len(transaction.refund_ids))
self.assertTrue(TestHelper.in_list(transaction.refund_ids, refund1.id))
self.assertTrue(TestHelper.in_list(transaction.refund_ids, refund2.id))
def test_paypal_transaction_returns_required_fields(self):
transaction = self.__create_paypal_transaction()
self.assertNotEqual(None, transaction.paypal_details.debug_id)
self.assertNotEqual(None, transaction.paypal_details.payer_email)
self.assertNotEqual(None, transaction.paypal_details.authorization_id)
self.assertNotEqual(None, transaction.paypal_details.payer_id)
self.assertNotEqual(None, transaction.paypal_details.payer_first_name)
self.assertNotEqual(None, transaction.paypal_details.payer_last_name)
self.assertNotEqual(None, transaction.paypal_details.payer_status)
self.assertNotEqual(None, transaction.paypal_details.seller_protection_status)
self.assertNotEqual(None, transaction.paypal_details.capture_id)
#self.assertNotEqual(None, transaction.paypal_details.refund_id)
self.assertNotEqual(None, transaction.paypal_details.transaction_fee_amount)
self.assertNotEqual(None, transaction.paypal_details.transaction_fee_currency_iso_code)
def test_paypal_transaction_refund_already_refunded_transation_fails(self):
transaction = self.__create_paypal_transaction()
Transaction.refund(transaction.id)
result = Transaction.refund(transaction.id)
self.assertFalse(result.is_success)
self.assertEqual(
ErrorCodes.Transaction.HasAlreadyBeenRefunded,
result.errors.for_object("transaction").on("base")[0].code
)
def test_paypal_transaction_refund_returns_an_error_if_unsettled(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"options": {
"submit_for_settlement": True
}
}).transaction
result = Transaction.refund(transaction.id)
self.assertFalse(result.is_success)
self.assertEqual(
ErrorCodes.Transaction.CannotRefundUnlessSettled,
result.errors.for_object("transaction").on("base")[0].code
)
def test_europe_bank_account_details(self):
old_merchant_id = Configuration.merchant_id
old_public_key = Configuration.public_key
old_private_key = Configuration.private_key
try:
Configuration.merchant_id = "altpay_merchant"
Configuration.public_key = "altpay_merchant_public_key"
Configuration.private_key = "altpay_merchant_private_key"
customer_id = Customer.create().customer.id
token = TestHelper.generate_decoded_client_token({"customer_id": customer_id, "sepa_mandate_type": EuropeBankAccount.MandateType.Business})
authorization_fingerprint = json.loads(token)["authorizationFingerprint"]
config = Configuration.instantiate()
client_api = ClientApiHttp(config, {
"authorization_fingerprint": authorization_fingerprint,
"shared_customer_identifier": "fake_identifier",
"shared_customer_identifier_type": "testing"
})
nonce = client_api.get_europe_bank_account_nonce({
"locale": "de-DE",
"bic": "DEUTDEFF",
"iban": "DE89370400440532013000",
"accountHolderName": "Baron Von Holder",
"billingAddress": {"region": "Hesse", "country_name": "Germany"}
})
result = Transaction.sale({
"merchant_account_id": "fake_sepa_ma",
"amount": "10.00",
"payment_method_nonce": nonce
})
self.assertTrue(result.is_success)
europe_bank_account_details = result.transaction.europe_bank_account_details
self.assertEqual(europe_bank_account_details.bic, "DEUTDEFF")
self.assertEqual(europe_bank_account_details.account_holder_name, "Baron Von Holder")
self.assertEqual(europe_bank_account_details.masked_iban[-4:], "3000")
self.assertNotEqual(europe_bank_account_details.image_url, None)
self.assertEqual(PaymentInstrumentType.EuropeBankAccount, result.transaction.payment_instrument_type)
finally:
Configuration.merchant_id = old_merchant_id
Configuration.public_key = old_public_key
Configuration.private_key = old_private_key
def test_us_bank_account_nonce_transactions(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"merchant_account_id": "us_bank_merchant_account",
"payment_method_nonce": TestHelper.generate_valid_us_bank_account_nonce(),
"options": {
"submit_for_settlement": True,
"store_in_vault": True
}
})
self.assertTrue(result.is_success)
self.assertEqual(result.transaction.us_bank_account.routing_number, "021000021")
self.assertEqual(result.transaction.us_bank_account.last_4, "1234")
self.assertEqual(result.transaction.us_bank_account.account_type, "checking")
self.assertEqual(result.transaction.us_bank_account.account_holder_name, "Dan Schulman")
self.assertTrue(re.match(r".*CHASE.*", result.transaction.us_bank_account.bank_name))
self.assertEqual(result.transaction.us_bank_account.ach_mandate.text, "cl mandate text")
self.assertIsInstance(result.transaction.us_bank_account.ach_mandate.accepted_at, datetime)
def test_us_bank_account_nonce_transactions_with_vaulted_token(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"merchant_account_id": "us_bank_merchant_account",
"payment_method_nonce": TestHelper.generate_valid_us_bank_account_nonce(),
"options": {
"submit_for_settlement": True,
"store_in_vault": True
}
})
self.assertTrue(result.is_success)
self.assertEqual(result.transaction.us_bank_account.routing_number, "021000021")
self.assertEqual(result.transaction.us_bank_account.last_4, "1234")
self.assertEqual(result.transaction.us_bank_account.account_type, "checking")
self.assertEqual(result.transaction.us_bank_account.account_holder_name, "Dan Schulman")
self.assertTrue(re.match(r".*CHASE.*", result.transaction.us_bank_account.bank_name))
self.assertEqual(result.transaction.us_bank_account.ach_mandate.text, "cl mandate text")
self.assertIsInstance(result.transaction.us_bank_account.ach_mandate.accepted_at, datetime)
token = result.transaction.us_bank_account.token
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"merchant_account_id": "us_bank_merchant_account",
"payment_method_token": token,
"options": {
"submit_for_settlement": True,
}
})
self.assertTrue(result.is_success)
self.assertEqual(result.transaction.us_bank_account.routing_number, "021000021")
self.assertEqual(result.transaction.us_bank_account.last_4, "1234")
self.assertEqual(result.transaction.us_bank_account.account_type, "checking")
self.assertEqual(result.transaction.us_bank_account.account_holder_name, "Dan Schulman")
self.assertTrue(re.match(r".*CHASE.*", result.transaction.us_bank_account.bank_name))
self.assertEqual(result.transaction.us_bank_account.ach_mandate.text, "cl mandate text")
self.assertIsInstance(result.transaction.us_bank_account.ach_mandate.accepted_at, datetime)
def test_us_bank_account_token_transactions_not_found(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"merchant_account_id": "us_bank_merchant_account",
"payment_method_nonce": TestHelper.generate_invalid_us_bank_account_nonce(),
"options": {
"submit_for_settlement": True,
"store_in_vault": True
}
})
self.assertFalse(result.is_success)
error_code = result.errors.for_object("transaction").on("payment_method_nonce")[0].code
self.assertEqual(error_code, ErrorCodes.Transaction.PaymentMethodNonceUnknown)
def test_transaction_settlement_errors(self):
sale_result = Transaction.sale({
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2010",
"cvv": "100"
},
"amount": "100.00",
})
transaction = sale_result.transaction
settle_result = TestHelper.settle_transaction(transaction.id)
self.assertFalse(settle_result.is_success)
error_codes = [
error.code for error in settle_result.errors.for_object("transaction").on("base")
]
self.assertTrue(ErrorCodes.Transaction.CannotSimulateTransactionSettlement in error_codes)
def test_transaction_returns_settlement_declined_response(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"payment_method_nonce": Nonces.PayPalOneTimePayment,
"options": {"submit_for_settlement": True}
})
self.assertTrue(result.is_success)
TestHelper.settlement_decline_transaction(result.transaction.id)
transaction = Transaction.find(result.transaction.id)
self.assertTrue("4001", transaction.processor_settlement_response_code)
self.assertTrue("Settlement Declined", transaction.processor_settlement_response_text)
self.assertTrue(Transaction.Status.SettlementDeclined, transaction.status)
def test_transaction_returns_settlement_pending_response(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"payment_method_nonce": Nonces.PayPalOneTimePayment,
"options": {"submit_for_settlement": True}
})
self.assertTrue(result.is_success)
TestHelper.settlement_pending_transaction(result.transaction.id)
transaction = Transaction.find(result.transaction.id)
self.assertTrue("4002", transaction.processor_settlement_response_code)
self.assertTrue("Settlement Pending", transaction.processor_settlement_response_text)
self.assertTrue(Transaction.Status.SettlementPending, transaction.status)
def test_transaction_submit_for_partial_settlement(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
})
self.assertTrue(result.is_success)
authorized_transaction = result.transaction
partial_settlement_result = Transaction.submit_for_partial_settlement(authorized_transaction.id, Decimal("500.00"))
partial_settlement_transaction = partial_settlement_result.transaction
self.assertTrue(partial_settlement_result.is_success)
self.assertEqual(partial_settlement_transaction.amount, Decimal("500.00"))
self.assertEqual(Transaction.Type.Sale, partial_settlement_transaction.type)
self.assertEqual(Transaction.Status.SubmittedForSettlement, partial_settlement_transaction.status)
self.assertEqual(authorized_transaction.id, partial_settlement_transaction.authorized_transaction_id)
partial_settlement_result_2 = Transaction.submit_for_partial_settlement(authorized_transaction.id, Decimal("500.00"))
partial_settlement_transaction_2 = partial_settlement_result_2.transaction
self.assertTrue(partial_settlement_result_2.is_success)
self.assertEqual(partial_settlement_transaction_2.amount, Decimal("500.00"))
self.assertEqual(Transaction.Type.Sale, partial_settlement_transaction_2.type)
self.assertEqual(Transaction.Status.SubmittedForSettlement, partial_settlement_transaction_2.status)
self.assertEqual(authorized_transaction.id, partial_settlement_transaction_2.authorized_transaction_id)
refreshed_authorized_transaction = Transaction.find(authorized_transaction.id)
self.assertEqual(2, len(refreshed_authorized_transaction.partial_settlement_transaction_ids))
def test_transaction_submit_for_partial_settlement_unsuccessful(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
})
self.assertTrue(result.is_success)
authorized_transaction = result.transaction
partial_settlement_result = Transaction.submit_for_partial_settlement(authorized_transaction.id, Decimal("500.00"))
partial_settlement_transaction = partial_settlement_result.transaction
partial_settlement_result_2 = Transaction.submit_for_partial_settlement(partial_settlement_transaction.id, Decimal("250.00"))
self.assertFalse(partial_settlement_result_2.is_success)
error_code = partial_settlement_result_2.errors.for_object("transaction").on("base")[0].code
self.assertEqual(ErrorCodes.Transaction.CannotSubmitForPartialSettlement, error_code)
def test_submit_for_partial_settlement_with_order_id(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
}).transaction
params = {"order_id": "ABC123"}
submitted_transaction = Transaction.submit_for_partial_settlement(transaction.id, Decimal("900"), params).transaction
self.assertEqual(Transaction.Status.SubmittedForSettlement, submitted_transaction.status)
self.assertEqual("ABC123", submitted_transaction.order_id)
def test_submit_for_partial_settlement_with_descriptor(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
}).transaction
params = {
"descriptor": {
"name": "123*123456789012345678",
"phone": "3334445555",
"url": "ebay.com"
}
}
submitted_transaction = Transaction.submit_for_partial_settlement(transaction.id, Decimal("900"), params).transaction
self.assertEqual(Transaction.Status.SubmittedForSettlement, submitted_transaction.status)
self.assertEqual("123*123456789012345678", submitted_transaction.descriptor.name)
self.assertEqual("3334445555", submitted_transaction.descriptor.phone)
self.assertEqual("ebay.com", submitted_transaction.descriptor.url)
@raises_with_regexp(KeyError, "'Invalid keys: invalid_param'")
def test_submit_for_partial_settlement_with_invalid_params(self):
transaction = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
}
}).transaction
params = {
"descriptor": {
"name": "123*123456789012345678",
"phone": "3334445555",
"url": "ebay.com"
},
"invalid_param": "foo",
}
Transaction.submit_for_partial_settlement(transaction.id, Decimal("900"), params)
def test_facilitated_transaction(self):
granting_gateway, credit_card = TestHelper.create_payment_method_grant_fixtures()
grant_result = granting_gateway.payment_method.grant(credit_card.token, False)
nonce = grant_result.payment_method_nonce.nonce
result = Transaction.sale({
"payment_method_nonce": nonce,
"amount": TransactionAmounts.Authorize,
})
self.assertNotEqual(result.transaction.facilitated_details, None)
self.assertEqual(result.transaction.facilitated_details.merchant_id, "integration_merchant_id")
self.assertEqual(result.transaction.facilitated_details.merchant_name, "14ladders")
self.assertEqual(result.transaction.facilitated_details.payment_method_nonce, nonce)
self.assertTrue(result.transaction.facilitator_details is not None)
self.assertEqual(result.transaction.facilitator_details.oauth_application_client_id, "client_id$development$integration_client_id")
self.assertEqual(result.transaction.facilitator_details.oauth_application_name, "PseudoShop")
self.assertTrue(result.transaction.billing["postal_code"] is None)
def test_include_billing_postal_code(self):
granting_gateway, credit_card = TestHelper.create_payment_method_grant_fixtures()
grant_result = granting_gateway.payment_method.grant(credit_card.token, { "allow_vaulting": False, "include_billing_postal_code": True })
result = Transaction.sale({
"payment_method_nonce": grant_result.payment_method_nonce.nonce,
"amount": TransactionAmounts.Authorize,
})
self.assertTrue(result.transaction.billing["postal_code"], "95131")
def test_shared_vault_transaction(self):
config = Configuration(
merchant_id="integration_merchant_public_id",
public_key="oauth_app_partner_user_public_key",
private_key="oauth_app_partner_user_private_key",
environment=Environment.Development
)
gateway = BraintreeGateway(config)
customer = gateway.customer.create({"first_name": "Bob"}).customer
address = gateway.address.create({
"customer_id": customer.id,
"first_name": "Joe",
}).address
credit_card = gateway.credit_card.create(
params={
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "05/2009",
}
).credit_card
oauth_app_gateway = BraintreeGateway(
client_id="client_id$development$integration_client_id",
client_secret="client_secret$development$integration_client_secret",
environment=Environment.Development
)
code = TestHelper.create_grant(oauth_app_gateway, {
"merchant_public_id": "integration_merchant_id",
"scope": "grant_payment_method,shared_vault_transactions"
})
access_token = oauth_app_gateway.oauth.create_token_from_code({
"code": code
}).credentials.access_token
granting_gateway = BraintreeGateway(
access_token=access_token,
)
result = granting_gateway.transaction.sale({
"shared_payment_method_token": credit_card.token,
"shared_customer_id": customer.id,
"shared_shipping_address_id": address.id,
"shared_billing_address_id": address.id,
"amount": "100"
})
self.assertTrue(result.is_success)
self.assertEqual(result.transaction.shipping_details.first_name, address.first_name)
self.assertEqual(result.transaction.billing_details.first_name, address.first_name)
self.assertEqual(result.transaction.customer_details.first_name, customer.first_name)
def test_sale_transacts_ideal_payment(self):
valid_id = TestHelper.generate_valid_ideal_payment_id()
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"order_id": "ABC123",
"merchant_account_id": "ideal_merchant_account",
"payment_method_nonce": valid_id,
"options": {
"submit_for_settlement": True,
},
})
self.assertTrue(result.is_success)
self.assertRegexpMatches(result.transaction.id, r'^\w{6,}$')
self.assertEqual(result.transaction.type, "sale")
self.assertEqual(result.transaction.payment_instrument_type, PaymentInstrumentType.IdealPayment)
self.assertEqual(result.transaction.amount, Decimal(TransactionAmounts.Authorize))
self.assertEqual(result.transaction.status, Transaction.Status.Settled)
self.assertRegexpMatches(result.transaction.ideal_payment_details.ideal_payment_id, r"^idealpayment_\w{6,}")
self.assertRegexpMatches(result.transaction.ideal_payment_details.ideal_transaction_id, r"^\d{16,}$")
self.assertEqual(result.transaction.ideal_payment_details.image_url[:8], 'https://')
self.assertNotEqual(result.transaction.ideal_payment_details.masked_iban, None)
self.assertNotEqual(result.transaction.ideal_payment_details.bic, None)
def test_failed_sale_non_complete_ideal_payment(self):
non_complete_id = TestHelper.generate_valid_ideal_payment_id("3.00")
result = Transaction.sale({
"amount": "3.00",
"order_id": "ABC123",
"merchant_account_id": "ideal_merchant_account",
"payment_method_nonce": non_complete_id,
"options": {
"submit_for_settlement": True,
},
})
error_codes = [
error.code for error in result.errors.for_object("transaction").on("payment_method_nonce")
]
self.assertFalse(result.is_success)
self.assertTrue(ErrorCodes.Transaction.IdealPaymentNotComplete in error_codes)
braintree_python-3.38.0/tests/integration/test_http.py 0000644 0001750 0001750 00000006734 13150065776 021364 0 ustar hle hle from tests.test_helper import *
from distutils.version import LooseVersion
import platform
import braintree
import requests
class TestHttp(unittest.TestCase):
if LooseVersion(requests.__version__) >= LooseVersion('1.0.0'):
SSLError = requests.exceptions.SSLError
else:
SSLError = requests.models.SSLError
@staticmethod
def get_http(environment):
config = Configuration(environment, "merchant_id", public_key="public_key", private_key="private_key")
return config.http()
@raises(AuthenticationError)
def test_successful_connection_sandbox(self):
http = self.get_http(Environment.Sandbox)
http.get("/")
@raises(AuthenticationError)
def test_successful_connection_production(self):
http = self.get_http(Environment.Production)
http.get("/")
def test_wrapping_http_exceptions(self):
config = Configuration(
Environment("test", "localhost", "1", False, None, Environment.Production.ssl_certificate),
"integration_merchant_id",
public_key="integration_public_key",
private_key="integration_private_key",
wrap_http_exceptions=True
)
gateway = braintree.braintree_gateway.BraintreeGateway(config)
try:
gateway.transaction.find("my_id")
except braintree.exceptions.unexpected_error.UnexpectedError:
correct_exception = True
except Exception:
correct_exception = False
self.assertTrue(correct_exception)
def test_unsuccessful_connection_to_good_ssl_server_with_wrong_cert(self):
if platform.system() == "Darwin":
return
#any endpoint that returns valid XML with a status of 3xx or less and serves SSL
environment = Environment("test", "aws.amazon.com/ec2", "443", "http://auth.venmo.dev:9292", True, Environment.Production.ssl_certificate)
http = self.get_http(environment)
try:
http.get("/")
except self.SSLError as e:
self.assertTrue("certificate verify failed" in str(e))
except AuthenticationError:
self.fail("Expected to receive an SSL error but received an Authentication Error instead, check your local openssl installation")
else:
self.fail("Expected to receive an SSL error but no exception was raised")
def test_unsuccessful_connection_to_ssl_server_with_wrong_domain(self):
#ip address of api.braintreegateway.com
environment = Environment("test", "204.109.13.121", "443", "http://auth.venmo.dev:9292", True, Environment.Production.ssl_certificate)
http = self.get_http(environment)
try:
http.get("/")
except self.SSLError:
pass
else:
self.fail("Expected to receive an SSL error but no exception was raised")
def test_timeouts(self):
config = Configuration(
Environment.Development,
"integration_merchant_id",
public_key="integration_public_key",
private_key="integration_private_key",
wrap_http_exceptions=True,
timeout=0.001
)
gateway = braintree.braintree_gateway.BraintreeGateway(config)
try:
gateway.transaction.find("my_id")
except braintree.exceptions.http.timeout_error.TimeoutError:
correct_exception = True
except Exception:
correct_exception = False
self.assertTrue(correct_exception)
braintree_python-3.38.0/tests/integration/test_disbursement.py 0000644 0001750 0001750 00000001713 13150065776 023101 0 ustar hle hle from tests.test_helper import *
from datetime import date
class TestDisbursement(unittest.TestCase):
def test_disbursement_finds_transactions(self):
disbursement = Disbursement(Configuration.gateway(), {
"merchant_account": {
"id": "sub_merchant_account",
"status": "active",
"master_merchant_account": {
"id": "master_merchant_account",
"status": "active"
},
},
"id": "123456",
"exception_message": "invalid_account_number",
"amount": "100.00",
"disbursement_date": date(2013, 4, 10),
"follow_up_action": "update",
"transaction_ids": ["sub_merchant_transaction"]
})
transactions = disbursement.transactions()
self.assertEqual(1, transactions.maximum_size)
self.assertEqual("sub_merchant_transaction", transactions.first.id)
braintree_python-3.38.0/tests/integration/test_merchant_account.py 0000644 0001750 0001750 00000067533 13150065776 023726 0 ustar hle hle from tests.test_helper import *
class TestMerchantAccount(unittest.TestCase):
DEPRECATED_APPLICATION_PARAMS = {
"applicant_details": {
"company_name": "Garbage Garage",
"first_name": "Joe",
"last_name": "Bloggs",
"email": "joe@bloggs.com",
"phone": "555-555-5555",
"address": {
"street_address": "123 Credibility St.",
"postal_code": "60606",
"locality": "Chicago",
"region": "IL",
},
"date_of_birth": "10/9/1980",
"ssn": "123-00-1234",
"tax_id": "123456789",
"routing_number": "122100024",
"account_number": "43759348798"
},
"tos_accepted": True,
"master_merchant_account_id": "sandbox_master_merchant_account"
}
VALID_APPLICATION_PARAMS = {
"individual": {
"first_name": "Joe",
"last_name": "Bloggs",
"email": "joe@bloggs.com",
"phone": "555-555-5555",
"address": {
"street_address": "123 Credibility St.",
"postal_code": "60606",
"locality": "Chicago",
"region": "IL",
},
"date_of_birth": "10/9/1980",
"ssn": "123-00-1234",
},
"business": {
"dba_name": "Garbage Garage",
"legal_name": "Junk Jymnasium",
"tax_id": "123456789",
"address": {
"street_address": "123 Reputation St.",
"postal_code": "40222",
"locality": "Louisville",
"region": "KY",
},
},
"funding": {
"routing_number": "122100024",
"account_number": "43759348798",
"destination": MerchantAccount.FundingDestination.Bank,
"descriptor": "Joes Bloggs KY",
},
"tos_accepted": True,
"master_merchant_account_id": "sandbox_master_merchant_account"
}
def test_create_accepts_deprecated_parameters(self):
result = MerchantAccount.create(self.DEPRECATED_APPLICATION_PARAMS)
self.assertTrue(result.is_success)
self.assertEqual(MerchantAccount.Status.Pending, result.merchant_account.status)
self.assertEqual("sandbox_master_merchant_account", result.merchant_account.master_merchant_account.id)
def test_create_application_with_valid_params_and_no_id(self):
result = MerchantAccount.create(self.VALID_APPLICATION_PARAMS)
self.assertTrue(result.is_success)
self.assertEqual(MerchantAccount.Status.Pending, result.merchant_account.status)
self.assertEqual("sandbox_master_merchant_account", result.merchant_account.master_merchant_account.id)
def test_create_allows_an_id_to_pass(self):
params_with_id = self.VALID_APPLICATION_PARAMS.copy()
rand = str(random.randint(1, 1000000))
params_with_id['id'] = 'sub_merchant_account_id' + rand
result = MerchantAccount.create(params_with_id)
self.assertTrue(result.is_success)
self.assertEqual(MerchantAccount.Status.Pending, result.merchant_account.status)
self.assertEqual(params_with_id['id'], result.merchant_account.id)
self.assertEqual("sandbox_master_merchant_account", result.merchant_account.master_merchant_account.id)
def test_create_handles_unsuccessful_results(self):
result = MerchantAccount.create({})
self.assertFalse(result.is_success)
merchant_account_id_errors = result.errors.for_object("merchant_account").on("master_merchant_account_id")
self.assertEqual(1, len(merchant_account_id_errors))
self.assertEqual(ErrorCodes.MerchantAccount.MasterMerchantAccountIdIsRequired, merchant_account_id_errors[0].code)
def test_create_requires_all_fields(self):
result = MerchantAccount.create(
{"master_merchant_account_id": "sandbox_master_merchant_account",
"applicant_details": {},
"tos_accepted": True}
)
self.assertFalse(result.is_success)
first_name_errors = result.errors.for_object("merchant_account").for_object("applicant_details").on("first_name")
self.assertEqual(1, len(first_name_errors))
self.assertEqual(ErrorCodes.MerchantAccount.ApplicantDetails.FirstNameIsRequired, first_name_errors[0].code)
def test_create_funding_destination_accepts_a_bank(self):
params = self.VALID_APPLICATION_PARAMS.copy()
params['funding']['destination'] = MerchantAccount.FundingDestination.Bank
result = MerchantAccount.create(params)
self.assertTrue(result.is_success)
def test_create_funding_destination_accepts_an_email(self):
params = self.VALID_APPLICATION_PARAMS.copy()
params['funding']['destination'] = MerchantAccount.FundingDestination.Email
params['funding']['email'] = "junkman@hotmail.com"
result = MerchantAccount.create(params)
self.assertTrue(result.is_success)
def test_create_funding_destination_accepts_a_mobile_phone(self):
params = self.VALID_APPLICATION_PARAMS.copy()
params['funding']['destination'] = MerchantAccount.FundingDestination.MobilePhone
params['funding']['mobile_phone'] = "1112223333"
result = MerchantAccount.create(params)
self.assertTrue(result.is_success)
def test_update_all_merchant_account_fields(self):
UPDATE_PARAMS = {
"individual": {
"first_name": "John",
"last_name": "Doe",
"email": "john.doe@example.com",
"phone": "312-555-1234",
"address": {
"street_address": "123 Fake St",
"postal_code": "60622",
"locality": "Chicago",
"region": "IL",
},
"date_of_birth": "1970-01-01",
"ssn": "987-65-4321",
},
"business": {
"dba_name": "James's Bloggs",
"legal_name": "James's Junkyard",
"tax_id": "987654321",
"address": {
"street_address": "456 Fake St",
"postal_code": "48104",
"locality": "Ann Arbor",
"region": "MI",
},
},
"funding": {
"routing_number": "071000013",
"account_number": "666666789",
"destination": MerchantAccount.FundingDestination.Email,
"email": "check@this.com",
"mobile_phone": "9998887777",
"descriptor": "Joes Bloggs MI",
}
}
result = MerchantAccount.update("sandbox_sub_merchant_account", UPDATE_PARAMS)
self.assertTrue(result.is_success)
self.assertEqual(result.merchant_account.status, "active")
self.assertEqual(result.merchant_account.id, "sandbox_sub_merchant_account")
self.assertEqual(result.merchant_account.master_merchant_account.id, "sandbox_master_merchant_account")
self.assertEqual(result.merchant_account.individual_details.first_name, "John")
self.assertEqual(result.merchant_account.individual_details.last_name, "Doe")
self.assertEqual(result.merchant_account.individual_details.email, "john.doe@example.com")
self.assertEqual(result.merchant_account.individual_details.date_of_birth, "1970-01-01")
self.assertEqual(result.merchant_account.individual_details.phone, "3125551234")
self.assertEqual(result.merchant_account.individual_details.address_details.street_address, "123 Fake St")
self.assertEqual(result.merchant_account.individual_details.address_details.locality, "Chicago")
self.assertEqual(result.merchant_account.individual_details.address_details.region, "IL")
self.assertEqual(result.merchant_account.individual_details.address_details.postal_code, "60622")
self.assertEqual(result.merchant_account.business_details.dba_name, "James's Bloggs")
self.assertEqual(result.merchant_account.business_details.legal_name, "James's Junkyard")
self.assertEqual(result.merchant_account.business_details.tax_id, "987654321")
self.assertEqual(result.merchant_account.business_details.address_details.street_address, "456 Fake St")
self.assertEqual(result.merchant_account.business_details.address_details.postal_code, "48104")
self.assertEqual(result.merchant_account.business_details.address_details.locality, "Ann Arbor")
self.assertEqual(result.merchant_account.business_details.address_details.region, "MI")
self.assertEqual(result.merchant_account.funding_details.routing_number, "071000013")
self.assertEqual(result.merchant_account.funding_details.account_number_last_4, "6789")
self.assertEqual(result.merchant_account.funding_details.destination, MerchantAccount.FundingDestination.Email)
self.assertEqual(result.merchant_account.funding_details.email, "check@this.com")
self.assertEqual(result.merchant_account.funding_details.mobile_phone, "9998887777")
self.assertEqual(result.merchant_account.funding_details.descriptor, "Joes Bloggs MI")
def test_update_does_not_require_all_fields(self):
result = MerchantAccount.update("sandbox_sub_merchant_account", {
"individual": {
"first_name": "Jose"
}
})
self.assertTrue(result.is_success)
def test_update_handles_validation_errors_for_blank_fields(self):
params = {
"individual": {
"first_name": "",
"last_name": "",
"email": "",
"phone": "",
"date_of_birth": "",
"ssn": "",
"address": {
"street_address": "",
"postal_code": "",
"locality": "",
"region": "",
},
},
"business": {
"legal_name": "",
"dba_name": "",
"tax_id": ""
},
"funding": {
"destination": "",
"routing_number": "",
"account_number": ""
}
}
result = MerchantAccount.update("sandbox_sub_merchant_account", params)
self.assertFalse(result.is_success)
self.assertEqual(result.errors.for_object("merchant_account").for_object("individual").on("first_name")[0].code, ErrorCodes.MerchantAccount.Individual.FirstNameIsRequired)
self.assertEqual(result.errors.for_object("merchant_account").for_object("individual").on("last_name")[0].code, ErrorCodes.MerchantAccount.Individual.LastNameIsRequired)
self.assertEqual(result.errors.for_object("merchant_account").for_object("individual").on("date_of_birth")[0].code, ErrorCodes.MerchantAccount.Individual.DateOfBirthIsRequired)
self.assertEqual(result.errors.for_object("merchant_account").for_object("individual").on("email")[0].code, ErrorCodes.MerchantAccount.Individual.EmailAddressIsRequired)
self.assertEqual(result.errors.for_object("merchant_account").for_object("individual").for_object("address").on("street_address")[0].code, ErrorCodes.MerchantAccount.Individual.Address.StreetAddressIsRequired)
self.assertEqual(result.errors.for_object("merchant_account").for_object("individual").for_object("address").on("postal_code")[0].code, ErrorCodes.MerchantAccount.Individual.Address.PostalCodeIsRequired)
self.assertEqual(result.errors.for_object("merchant_account").for_object("individual").for_object("address").on("locality")[0].code, ErrorCodes.MerchantAccount.Individual.Address.LocalityIsRequired)
self.assertEqual(result.errors.for_object("merchant_account").for_object("individual").for_object("address").on("region")[0].code, ErrorCodes.MerchantAccount.Individual.Address.RegionIsRequired)
self.assertEqual(result.errors.for_object("merchant_account").for_object("funding").on("destination")[0].code, ErrorCodes.MerchantAccount.Funding.DestinationIsRequired)
self.assertEqual(result.errors.for_object("merchant_account").for_object("individual").on("first_name")[0].code, ErrorCodes.MerchantAccount.Individual.FirstNameIsRequired)
self.assertEqual(result.errors.for_object("merchant_account").for_object("individual").on("last_name")[0].code, ErrorCodes.MerchantAccount.Individual.LastNameIsRequired)
self.assertEqual(result.errors.for_object("merchant_account").for_object("individual").on("date_of_birth")[0].code, ErrorCodes.MerchantAccount.Individual.DateOfBirthIsRequired)
self.assertEqual(result.errors.for_object("merchant_account").for_object("individual").on("email")[0].code, ErrorCodes.MerchantAccount.Individual.EmailAddressIsRequired)
self.assertEqual(result.errors.for_object("merchant_account").for_object("individual").for_object("address").on("street_address")[0].code, ErrorCodes.MerchantAccount.Individual.Address.StreetAddressIsRequired)
self.assertEqual(result.errors.for_object("merchant_account").for_object("individual").for_object("address").on("postal_code")[0].code, ErrorCodes.MerchantAccount.Individual.Address.PostalCodeIsRequired)
self.assertEqual(result.errors.for_object("merchant_account").for_object("individual").for_object("address").on("locality")[0].code, ErrorCodes.MerchantAccount.Individual.Address.LocalityIsRequired)
self.assertEqual(result.errors.for_object("merchant_account").for_object("individual").for_object("address").on("region")[0].code, ErrorCodes.MerchantAccount.Individual.Address.RegionIsRequired)
self.assertEqual(result.errors.for_object("merchant_account").for_object("funding").on("destination")[0].code, ErrorCodes.MerchantAccount.Funding.DestinationIsRequired)
self.assertEqual(0, len(result.errors.for_object("merchant_account").on("base")))
def test_update_handles_validation_errors_for_invalid_fields(self):
params = {
"individual": {
"first_name": "<>",
"last_name": "<>",
"email": "bad",
"phone": "999",
"address": {
"street_address": "nope",
"postal_code": "1",
"region": "QQ",
},
"date_of_birth": "hah",
"ssn": "12345",
},
"business": {
"legal_name": "``{}",
"dba_name": "{}``",
"tax_id": "bad",
"address": {
"street_address": "nope",
"postal_code": "1",
"region": "QQ",
},
},
"funding": {
"destination": "MY WALLET",
"routing_number": "LEATHER",
"account_number": "BACK POCKET",
"email": "BILLFOLD",
"mobile_phone": "TRIFOLD"
},
}
result = MerchantAccount.update("sandbox_sub_merchant_account", params)
self.assertFalse(result.is_success)
self.assertEqual(result.errors.for_object("merchant_account").for_object("individual").on("first_name")[0].code, ErrorCodes.MerchantAccount.Individual.FirstNameIsInvalid)
self.assertEqual(result.errors.for_object("merchant_account").for_object("individual").on("last_name")[0].code, ErrorCodes.MerchantAccount.Individual.LastNameIsInvalid)
self.assertEqual(result.errors.for_object("merchant_account").for_object("individual").on("email")[0].code, ErrorCodes.MerchantAccount.Individual.EmailAddressIsInvalid)
self.assertEqual(result.errors.for_object("merchant_account").for_object("individual").on("phone")[0].code, ErrorCodes.MerchantAccount.Individual.PhoneIsInvalid)
self.assertEqual(result.errors.for_object("merchant_account").for_object("individual").for_object("address").on("street_address")[0].code, ErrorCodes.MerchantAccount.Individual.Address.StreetAddressIsInvalid)
self.assertEqual(result.errors.for_object("merchant_account").for_object("individual").for_object("address").on("postal_code")[0].code, ErrorCodes.MerchantAccount.Individual.Address.PostalCodeIsInvalid)
self.assertEqual(result.errors.for_object("merchant_account").for_object("individual").for_object("address").on("region")[0].code, ErrorCodes.MerchantAccount.Individual.Address.RegionIsInvalid)
self.assertEqual(result.errors.for_object("merchant_account").for_object("individual").on("ssn")[0].code, ErrorCodes.MerchantAccount.Individual.SsnIsInvalid)
self.assertEqual(result.errors.for_object("merchant_account").for_object("business").on("legal_name")[0].code, ErrorCodes.MerchantAccount.Business.LegalNameIsInvalid)
self.assertEqual(result.errors.for_object("merchant_account").for_object("business").on("dba_name")[0].code, ErrorCodes.MerchantAccount.Business.DbaNameIsInvalid)
self.assertEqual(result.errors.for_object("merchant_account").for_object("business").on("tax_id")[0].code, ErrorCodes.MerchantAccount.Business.TaxIdIsInvalid)
self.assertEqual(result.errors.for_object("merchant_account").for_object("business").for_object("address").on("street_address")[0].code, ErrorCodes.MerchantAccount.Business.Address.StreetAddressIsInvalid)
self.assertEqual(result.errors.for_object("merchant_account").for_object("business").for_object("address").on("postal_code")[0].code, ErrorCodes.MerchantAccount.Business.Address.PostalCodeIsInvalid)
self.assertEqual(result.errors.for_object("merchant_account").for_object("business").for_object("address").on("region")[0].code, ErrorCodes.MerchantAccount.Business.Address.RegionIsInvalid)
self.assertEqual(result.errors.for_object("merchant_account").for_object("funding").on("destination")[0].code, ErrorCodes.MerchantAccount.Funding.DestinationIsInvalid)
self.assertEqual(result.errors.for_object("merchant_account").for_object("funding").on("routing_number")[0].code, ErrorCodes.MerchantAccount.Funding.RoutingNumberIsInvalid)
self.assertEqual(result.errors.for_object("merchant_account").for_object("funding").on("account_number")[0].code, ErrorCodes.MerchantAccount.Funding.AccountNumberIsInvalid)
self.assertEqual(result.errors.for_object("merchant_account").for_object("funding").on("email")[0].code, ErrorCodes.MerchantAccount.Funding.EmailAddressIsInvalid)
self.assertEqual(result.errors.for_object("merchant_account").for_object("funding").on("mobile_phone")[0].code, ErrorCodes.MerchantAccount.Funding.MobilePhoneIsInvalid)
self.assertEqual(0, len(result.errors.for_object("merchant_account").on("base")))
def test_update_handles_validation_errors_for_business_fields(self):
result = MerchantAccount.update("sandbox_sub_merchant_account", {
"business": {
"legal_name": "",
"tax_id": "111223333"
}
}
)
self.assertFalse(result.is_success)
self.assertEqual(result.errors.for_object("merchant_account").for_object("business").on("legal_name")[0].code, ErrorCodes.MerchantAccount.Business.LegalNameIsRequiredWithTaxId)
self.assertEqual(result.errors.for_object("merchant_account").for_object("business").on("tax_id")[0].code, ErrorCodes.MerchantAccount.Business.TaxIdMustBeBlank)
result = MerchantAccount.update("sandbox_sub_merchant_account", {
"business": {
"legal_name": "legal name",
"tax_id": ""
}
}
)
self.assertFalse(result.is_success)
self.assertEqual(result.errors.for_object("merchant_account").for_object("business").on("tax_id")[0].code, ErrorCodes.MerchantAccount.Business.TaxIdIsRequiredWithLegalName)
def test_update_handles_validation_errors_for_funding_fields(self):
result = MerchantAccount.update("sandbox_sub_merchant_account", {
"funding": {
"destination": MerchantAccount.FundingDestination.Bank,
"routing_number": "",
"account_number": ""
}
}
)
self.assertFalse(result.is_success)
self.assertEqual(result.errors.for_object("merchant_account").for_object("funding").on("routing_number")[0].code, ErrorCodes.MerchantAccount.Funding.RoutingNumberIsRequired)
self.assertEqual(result.errors.for_object("merchant_account").for_object("funding").on("account_number")[0].code, ErrorCodes.MerchantAccount.Funding.AccountNumberIsRequired)
result = MerchantAccount.update("sandbox_sub_merchant_account", {
"funding": {
"destination": MerchantAccount.FundingDestination.Email,
"email": ""
}
}
)
self.assertFalse(result.is_success)
self.assertEqual(result.errors.for_object("merchant_account").for_object("funding").on("email")[0].code, ErrorCodes.MerchantAccount.Funding.EmailAddressIsRequired)
result = MerchantAccount.update("sandbox_sub_merchant_account", {
"funding": {
"destination": MerchantAccount.FundingDestination.MobilePhone,
"mobile_phone": ""
}
}
)
self.assertFalse(result.is_success)
self.assertEqual(result.errors.for_object("merchant_account").for_object("funding").on("mobile_phone")[0].code, ErrorCodes.MerchantAccount.Funding.MobilePhoneIsRequired)
def test_find(self):
result = MerchantAccount.create(self.VALID_APPLICATION_PARAMS)
self.assertTrue(result.is_success)
merchant_account_id = result.merchant_account.id
MerchantAccount.find(merchant_account_id)
def test_retrieves_master_merchant_account_currency_iso_code(self):
merchant_account = MerchantAccount.find("sandbox_master_merchant_account")
self.assertEqual(merchant_account.currency_iso_code, "USD")
def test_return_all_merchant_accounts(self):
gateway = BraintreeGateway(
client_id="client_id$development$integration_client_id",
client_secret="client_secret$development$integration_client_secret"
)
code = TestHelper.create_grant(gateway, {
"merchant_public_id": "integration_merchant_id",
"scope": "read_write"
})
result = gateway.oauth.create_token_from_code({
"code": code
})
gateway = BraintreeGateway(
access_token=result.credentials.access_token,
environment=Environment.Development
)
result = gateway.merchant_account.all()
merchant_accounts = [ma for ma in result.merchant_accounts.items]
self.assertTrue(len(merchant_accounts) > 20)
def test_returns_merchant_account_with_correct_attributes(self):
gateway = BraintreeGateway(
client_id="client_id$development$integration_client_id",
client_secret="client_secret$development$integration_client_secret"
)
result = gateway.merchant.create({
"email": "name@email.com",
"country_code_alpha3": "USA",
"payment_methods": ["credit_card", "paypal"]
})
gateway = BraintreeGateway(
access_token=result.credentials.access_token
)
result = gateway.merchant_account.all()
merchant_accounts = [ma for ma in result.merchant_accounts.items]
self.assertEqual(len(merchant_accounts), 1)
merchant_account = merchant_accounts[0]
self.assertEqual(merchant_account.currency_iso_code, "USD")
self.assertEqual(merchant_account.status, MerchantAccount.Status.Active)
self.assertTrue(merchant_account.default)
@raises(NotFoundError)
def test_find_404(self):
MerchantAccount.find("not_a_real_id")
def test_merchant_account_create_for_currency(self):
self.gateway = BraintreeGateway(
client_id="client_id$development$integration_client_id",
client_secret="client_secret$development$integration_client_secret"
)
result = self.gateway.merchant.create({
"email": "name@email.com",
"country_code_alpha3": "USA",
"payment_methods": ["credit_card", "paypal"]
})
gateway = BraintreeGateway(
access_token=result.credentials.access_token,
)
result = gateway.merchant_account.create_for_currency({
"currency": "GBP",
"id": "custom_id"
})
self.assertTrue(result.is_success)
self.assertEqual(result.merchant_account.currency_iso_code, "GBP")
self.assertEqual(result.merchant_account.id, "custom_id")
def test_merchant_account_create_for_currency_handles_invalid_currency(self):
self.gateway = BraintreeGateway(
client_id="client_id$development$integration_client_id",
client_secret="client_secret$development$integration_client_secret"
)
result = self.gateway.merchant.create({
"email": "name@email.com",
"country_code_alpha3": "USA",
"payment_methods": ["credit_card", "paypal"]
})
gateway = BraintreeGateway(
access_token=result.credentials.access_token,
)
result = gateway.merchant_account.create_for_currency({
"currency": "DOES_NOT_COMPUTE"
})
self.assertFalse(result.is_success)
self.assertEqual(result.errors.for_object("merchant").on("currency")[0].code, ErrorCodes.Merchant.CurrencyIsInvalid)
def test_merchant_account_create_for_currency_handles_currency_requirement(self):
self.gateway = BraintreeGateway(
client_id="client_id$development$integration_client_id",
client_secret="client_secret$development$integration_client_secret"
)
result = self.gateway.merchant.create({
"email": "name@email.com",
"country_code_alpha3": "USA",
"payment_methods": ["credit_card", "paypal"]
})
gateway = BraintreeGateway(
access_token=result.credentials.access_token,
)
result = gateway.merchant_account.create_for_currency({})
self.assertFalse(result.is_success)
self.assertEqual(result.errors.for_object("merchant").on("currency")[0].code, ErrorCodes.Merchant.CurrencyIsRequired)
def test_merchant_account_create_for_currency_merchant_account_already_existing_for_currency(self):
self.gateway = BraintreeGateway(
client_id="client_id$development$integration_client_id",
client_secret="client_secret$development$integration_client_secret"
)
result = self.gateway.merchant.create({
"email": "name@email.com",
"country_code_alpha3": "USA",
"payment_methods": ["credit_card", "paypal"]
})
gateway = BraintreeGateway(
access_token=result.credentials.access_token,
)
result = gateway.merchant_account.create_for_currency({
"currency": "USD",
})
self.assertFalse(result.is_success)
self.assertEqual(result.errors.for_object("merchant").on("currency")[0].code, ErrorCodes.Merchant.MerchantAccountExistsForCurrency)
def test_merchant_account_create_for_currency_merchant_account_already_existing_for_id(self):
self.gateway = BraintreeGateway(
client_id="client_id$development$integration_client_id",
client_secret="client_secret$development$integration_client_secret"
)
result = self.gateway.merchant.create({
"email": "name@email.com",
"country_code_alpha3": "USA",
"payment_methods": ["credit_card", "paypal"]
})
gateway = BraintreeGateway(
access_token=result.credentials.access_token,
)
result = gateway.merchant_account.create_for_currency({
"currency": "GBP",
"id": result.merchant.merchant_accounts[0].id
})
self.assertFalse(result.is_success)
self.assertEqual(result.errors.for_object("merchant").on("id")[0].code, ErrorCodes.Merchant.MerchantAccountExistsForId)
braintree_python-3.38.0/tests/integration/test_document_upload.py 0000644 0001750 0001750 00000007264 13150065776 023566 0 ustar hle hle import os
from nose.exc import SkipTest
from tests.test_helper import *
from braintree.test.nonces import Nonces
class TestDocumentUpload(unittest.TestCase):
def setUp(self):
file_path = os.path.join(os.path.dirname(__file__), "..", "fixtures/bt_logo.png")
self.png_file = open(file_path, "rb")
def test_create_returns_successful_result_if_valid(self):
result = DocumentUpload.create({
"kind": braintree.DocumentUpload.Kind.EvidenceDocument,
"file": self.png_file
})
self.assertTrue(result.is_success)
self.assertTrue(result.document_upload.id != None)
self.assertEqual(result.document_upload.content_type, "image/png")
self.assertEqual(result.document_upload.kind, braintree.DocumentUpload.Kind.EvidenceDocument)
self.assertEqual(result.document_upload.name, "bt_logo.png")
self.assertEqual(result.document_upload.size, 2443)
def test_create_returns_error_with_unsupported_file_type(self):
file_path = os.path.join(os.path.dirname(__file__), "..", "fixtures/gif_extension_bt_logo.gif")
gif_file = open(file_path, "rb")
result = DocumentUpload.create({
"kind": braintree.DocumentUpload.Kind.EvidenceDocument,
"file": gif_file
})
self.assertEqual(result.errors.for_object("document_upload")[0].code, ErrorCodes.DocumentUpload.FileTypeIsInvalid)
def test_create_returns_error_with_malformed_file(self):
file_path = os.path.join(os.path.dirname(__file__), "..", "fixtures/malformed_pdf.pdf")
bad_pdf_file = open(file_path, "rb")
result = DocumentUpload.create({
"kind": braintree.DocumentUpload.Kind.EvidenceDocument,
"file": bad_pdf_file
})
self.assertEqual(result.errors.for_object("document_upload")[0].code, ErrorCodes.DocumentUpload.FileIsMalformedOrEncrypted)
def test_create_returns_error_with_invalid_kind(self):
result = DocumentUpload.create({
"kind": "invalid_kind",
"file": self.png_file
})
self.assertEqual(result.errors.for_object("document_upload")[0].code, ErrorCodes.DocumentUpload.KindIsInvalid)
def test_create_returns_error_when_file_is_over_4mb(self):
file_path = os.path.join(os.path.dirname(__file__), "..", "fixtures/large_file.png")
try:
f = open(file_path, 'w+')
for i in range(1048577 * 4):
f.write('a')
f.close()
large_file = open(file_path, 'rb')
result = DocumentUpload.create({
"kind": braintree.DocumentUpload.Kind.EvidenceDocument,
"file": large_file
})
self.assertEqual(result.errors.for_object("document_upload")[0].code, ErrorCodes.DocumentUpload.FileIsTooLarge)
finally:
os.remove(file_path)
@raises_with_regexp(KeyError, "'Invalid keys: invalid_key'")
def test_create_returns_invalid_keys_errors_with_invalid_signature(self):
result = DocumentUpload.create({
"kind": braintree.DocumentUpload.Kind.EvidenceDocument,
"invalid_key": "do not add"
})
@raises_with_regexp(ValueError, "file must be a file handle")
def test_create_throws_error_when_not_valid_file(self):
result = DocumentUpload.create({
"kind": braintree.DocumentUpload.Kind.EvidenceDocument,
"file": "not_a_file"
})
@raises_with_regexp(ValueError, "file must be a file handle")
def test_create_throws_error_when_none_file(self):
result = DocumentUpload.create({
"kind": braintree.DocumentUpload.Kind.EvidenceDocument,
"file": None
})
braintree_python-3.38.0/tests/integration/test_customer_search.py 0000644 0001750 0001750 00000012524 13150065776 023565 0 ustar hle hle from tests.test_helper import *
class TestCustomerSearch(unittest.TestCase):
def test_advanced_search_no_results(self):
collection = Transaction.search([
TransactionSearch.billing_first_name == "no_such_person"
])
self.assertEqual(0, collection.maximum_size)
def test_advanced_search_finds_duplicate_cards_given_payment_method_token(self):
credit_card_dict = {
"number": "63049580000009",
"expiration_date": "05/2010"
}
jim_dict = {
"first_name": "Jim",
"credit_card": credit_card_dict
}
joe_dict = {
"first_name": "Joe",
"credit_card": credit_card_dict
}
jim = Customer.create(jim_dict).customer
joe = Customer.create(joe_dict).customer
collection = Customer.search(
CustomerSearch.payment_method_token_with_duplicates == jim.credit_cards[0].token,
)
customer_ids = [customer.id for customer in collection.items]
self.assertTrue(jim.id in customer_ids)
self.assertTrue(joe.id in customer_ids)
def test_advanced_search_searches_all_text_fields(self):
token = "creditcard%s" % random.randint(1, 100000)
customer = Customer.create({
"first_name": "Timmy",
"last_name": "O'Toole",
"company": "O'Toole and Son(s)",
"email": "timmy@example.com",
"fax": "3145551234",
"phone": "5551231234",
"website": "http://example.com",
"credit_card": {
"cardholder_name": "Tim Toole",
"number": "4111111111111111",
"expiration_date": "05/2010",
"token": token,
"billing_address": {
"first_name": "Thomas",
"last_name": "Otool",
"street_address": "1 E Main St",
"extended_address": "Suite 3",
"locality": "Chicago",
"region": "Illinois",
"postal_code": "60622",
"country_name": "United States of America"
}
}
}).customer
search_criteria = {
"first_name": "Timmy",
"last_name": "O'Toole",
"company": "O'Toole and Son(s)",
"email": "timmy@example.com",
"phone": "5551231234",
"fax": "3145551234",
"website": "http://example.com",
"address_first_name": "Thomas",
"address_last_name": "Otool",
"address_street_address": "1 E Main St",
"address_postal_code": "60622",
"address_extended_address": "Suite 3",
"address_locality": "Chicago",
"address_region": "Illinois",
"address_country_name": "United States of America",
"payment_method_token": token,
"cardholder_name": "Tim Toole",
"credit_card_number": "4111111111111111",
"credit_card_expiration_date": "05/2010"
}
criteria = [getattr(CustomerSearch, search_field) == value for search_field, value in search_criteria.items()]
criteria.append(CustomerSearch.id == customer.id)
collection = Customer.search(criteria)
self.assertEqual(1, collection.maximum_size)
self.assertEqual(customer.id, collection.first.id)
for search_field, value in search_criteria.items():
collection = Customer.search(
CustomerSearch.id == customer.id,
getattr(CustomerSearch, search_field) == value
)
self.assertEqual(1, collection.maximum_size)
self.assertEqual(customer.id, collection.first.id)
def test_advanced_search_range_node_created_at(self):
customer = Customer.create().customer
past = customer.created_at - timedelta(minutes=10)
future = customer.created_at + timedelta(minutes=10)
collection = Customer.search(
CustomerSearch.id == customer.id,
CustomerSearch.created_at.between(past, future)
)
self.assertEqual(1, collection.maximum_size)
self.assertEqual(customer.id, collection.first.id)
collection = Customer.search(
CustomerSearch.id == customer.id,
CustomerSearch.created_at <= future
)
self.assertEqual(1, collection.maximum_size)
self.assertEqual(customer.id, collection.first.id)
collection = Customer.search(
CustomerSearch.id == customer.id,
CustomerSearch.created_at >= past
)
self.assertEqual(1, collection.maximum_size)
self.assertEqual(customer.id, collection.first.id)
def test_search_on_paypal_account_email(self):
http = ClientApiHttp.create()
status_code, nonce = http.get_paypal_nonce({
"consent-code": "consent-code",
"options": {"validate": False}
})
self.assertEqual(202, status_code)
customer = Customer.create({"payment_method_nonce": nonce}).customer
collection = Customer.search(
CustomerSearch.paypal_account_email == "jane.doe@example.com",
CustomerSearch.id == customer.id
)
self.assertEqual(1, collection.maximum_size)
self.assertEqual(customer.id, collection.first.id)
braintree_python-3.38.0/tests/integration/test_merchant.py 0000644 0001750 0001750 00000025402 13150065776 022177 0 ustar hle hle from tests.test_helper import *
from braintree.test.nonces import Nonces
class TestMerchantGateway(unittest.TestCase):
def setUp(self):
self.gateway = BraintreeGateway(
client_id="client_id$development$signup_client_id",
client_secret="client_secret$development$signup_client_secret"
)
def test_create_merchant(self):
gateway = BraintreeGateway(
client_id="client_id$development$integration_client_id",
client_secret="client_secret$development$integration_client_secret"
)
result = gateway.merchant.create({
"email": "name@email.com",
"country_code_alpha3": "USA",
"payment_methods": ["credit_card", "paypal"]
})
merchant = result.merchant
self.assertIsNotNone(merchant.id)
self.assertEqual(merchant.email, "name@email.com")
self.assertEqual(merchant.country_code_alpha3, "USA")
self.assertEqual(merchant.country_code_alpha2, "US")
self.assertEqual(merchant.country_code_numeric, "840")
self.assertEqual(merchant.country_name, "United States of America")
self.assertEqual(merchant.company_name, "name@email.com")
self.assertTrue(result.is_success)
credentials = result.credentials
self.assertIsNotNone(credentials.access_token)
self.assertIsNotNone(credentials.expires_at)
self.assertEqual("bearer", credentials.token_type)
def test_returns_error_with_invalid_payment_methods(self):
gateway = BraintreeGateway(
client_id="client_id$development$integration_client_id",
client_secret="client_secret$development$integration_client_secret"
)
result = gateway.merchant.create({
"email": "name@email.com",
"country_code_alpha3": "USA",
"payment_methods": ["fake_money"]
})
self.assertFalse(result.is_success)
self.assertIn("One or more payment methods passed are not accepted.", result.message)
payment_method_errors = result.errors.for_object("merchant").on("payment_methods")
self.assertEqual(1, len(payment_method_errors))
self.assertEqual(payment_method_errors[0].code, ErrorCodes.Merchant.PaymentMethodsAreInvalid)
def test_create_paypal_only_merchant_that_accepts_multiple_currencies(self):
result = self.gateway.merchant.create({
"email": "name@email.com",
"country_code_alpha3": "USA",
"payment_methods": ["paypal"],
"currencies": ["GBP", "USD"],
"paypal_account": {
"client_id": "paypal_client_id",
"client_secret": "paypal_client_secret"
}
})
merchant = result.merchant
self.assertIsNotNone(merchant.id)
self.assertEqual(merchant.email, "name@email.com")
self.assertEqual(merchant.country_code_alpha3, "USA")
self.assertEqual(merchant.country_code_alpha2, "US")
self.assertEqual(merchant.country_code_numeric, "840")
self.assertEqual(merchant.country_name, "United States of America")
self.assertEqual(merchant.company_name, "name@email.com")
self.assertTrue(result.is_success)
credentials = result.credentials
self.assertIsNotNone(credentials.access_token)
self.assertIsNotNone(credentials.expires_at)
self.assertEqual("bearer", credentials.token_type)
merchant_accounts = merchant.merchant_accounts
self.assertEqual(2, len(merchant_accounts))
usd_merchant_account = [ma for ma in merchant_accounts if ma.id == "USD"][0]
self.assertTrue(usd_merchant_account.default)
self.assertEqual(usd_merchant_account.currency_iso_code, "USD")
gbp_merchant_account = [ma for ma in merchant_accounts if ma.id == "GBP"][0]
self.assertFalse(gbp_merchant_account.default)
self.assertEqual(gbp_merchant_account.currency_iso_code, "GBP")
def test_create_us_merchant_that_accepts_multiple_currencies(self):
result = self.gateway.merchant.create({
"email": "name@email.com",
"country_code_alpha3": "USA",
"payment_methods": ["credit_card", "paypal"],
"currencies": ["GBP", "USD"],
"paypal_account": {
"client_id": "paypal_client_id",
"client_secret": "paypal_client_secret"
}
})
merchant = result.merchant
self.assertIsNotNone(merchant.id)
self.assertEqual(merchant.email, "name@email.com")
self.assertEqual(merchant.country_code_alpha3, "USA")
self.assertEqual(merchant.country_code_alpha2, "US")
self.assertEqual(merchant.country_code_numeric, "840")
self.assertEqual(merchant.country_name, "United States of America")
self.assertEqual(merchant.company_name, "name@email.com")
self.assertTrue(result.is_success)
credentials = result.credentials
self.assertIsNotNone(credentials.access_token)
self.assertIsNotNone(credentials.expires_at)
self.assertEqual("bearer", credentials.token_type)
merchant_accounts = merchant.merchant_accounts
self.assertEqual(2, len(merchant_accounts))
usd_merchant_account = [ma for ma in merchant_accounts if ma.id == "USD"][0]
self.assertTrue(usd_merchant_account.default)
self.assertEqual(usd_merchant_account.currency_iso_code, "USD")
gbp_merchant_account = [ma for ma in merchant_accounts if ma.id == "GBP"][0]
self.assertFalse(gbp_merchant_account.default)
self.assertEqual(gbp_merchant_account.currency_iso_code, "GBP")
def test_create_eu_merchant_that_accepts_multiple_currencies(self):
result = self.gateway.merchant.create({
"email": "name@email.com",
"country_code_alpha3": "GBR",
"payment_methods": ["credit_card", "paypal"],
"currencies": ["GBP", "USD"],
"paypal_account": {
"client_id": "paypal_client_id",
"client_secret": "paypal_client_secret"
}
})
merchant = result.merchant
self.assertIsNotNone(merchant.id)
self.assertEqual(merchant.email, "name@email.com")
self.assertEqual(merchant.country_code_alpha3, "GBR")
self.assertEqual(merchant.country_code_alpha2, "GB")
self.assertEqual(merchant.country_code_numeric, "826")
self.assertEqual(merchant.country_name, "United Kingdom")
self.assertEqual(merchant.company_name, "name@email.com")
self.assertTrue(result.is_success)
credentials = result.credentials
self.assertIsNotNone(credentials.access_token)
self.assertIsNotNone(credentials.expires_at)
self.assertEqual("bearer", credentials.token_type)
merchant_accounts = merchant.merchant_accounts
self.assertEqual(2, len(merchant_accounts))
usd_merchant_account = [ma for ma in merchant_accounts if ma.id == "USD"][0]
self.assertFalse(usd_merchant_account.default)
self.assertEqual(usd_merchant_account.currency_iso_code, "USD")
gbp_merchant_account = [ma for ma in merchant_accounts if ma.id == "GBP"][0]
self.assertTrue(gbp_merchant_account.default)
self.assertEqual(gbp_merchant_account.currency_iso_code, "GBP")
def test_allows_creation_of_non_US_merchant_if_onboarding_application_is_internal(self):
result = self.gateway.merchant.create({
"email": "name@email.com",
"country_code_alpha3": "JPN",
"payment_methods": ["paypal"],
"paypal_account": {
"client_id": "paypal_client_id",
"client_secret": "paypal_client_secret"
}
})
merchant = result.merchant
self.assertIsNotNone(merchant.id)
self.assertEqual(merchant.email, "name@email.com")
self.assertEqual(merchant.country_code_alpha3, "JPN")
self.assertEqual(merchant.country_code_alpha2, "JP")
self.assertEqual(merchant.country_code_numeric, "392")
self.assertEqual(merchant.country_name, "Japan")
self.assertEqual(merchant.company_name, "name@email.com")
self.assertTrue(result.is_success)
credentials = result.credentials
self.assertIsNotNone(credentials.access_token)
self.assertIsNotNone(credentials.expires_at)
self.assertEqual("bearer", credentials.token_type)
merchant_accounts = merchant.merchant_accounts
self.assertEqual(1, len(merchant_accounts))
usd_merchant_account = merchant_accounts[0]
self.assertTrue(usd_merchant_account.default)
self.assertEqual(usd_merchant_account.currency_iso_code, "JPY")
def test_defaults_to_USD_for_non_US_merchant_if_onboarding_application_is_internal_and_country_currency_not_supported(self):
result = self.gateway.merchant.create({
"email": "name@email.com",
"country_code_alpha3": "YEM",
"payment_methods": ["paypal"],
"paypal_account": {
"client_id": "paypal_client_id",
"client_secret": "paypal_client_secret"
}
})
merchant = result.merchant
self.assertIsNotNone(merchant.id)
self.assertEqual(merchant.email, "name@email.com")
self.assertEqual(merchant.country_code_alpha3, "YEM")
self.assertEqual(merchant.country_code_alpha2, "YE")
self.assertEqual(merchant.country_code_numeric, "887")
self.assertEqual(merchant.country_name, "Yemen")
self.assertEqual(merchant.company_name, "name@email.com")
self.assertTrue(result.is_success)
credentials = result.credentials
self.assertIsNotNone(credentials.access_token)
self.assertIsNotNone(credentials.expires_at)
self.assertEqual("bearer", credentials.token_type)
merchant_accounts = merchant.merchant_accounts
self.assertEqual(1, len(merchant_accounts))
usd_merchant_account = merchant_accounts[0]
self.assertTrue(usd_merchant_account.default)
self.assertEqual(usd_merchant_account.currency_iso_code, "USD")
def test_returns_error_if_invalid_currency_is_passed(self):
result = self.gateway.merchant.create({
"email": "name@email.com",
"country_code_alpha3": "USA",
"payment_methods": ["credit_card"],
"currencies": ["GBP", "FAKE"],
"paypal_account": {
"client_id": "paypal_client_id",
"client_secret": "paypal_client_secret"
}
})
self.assertFalse(result.is_success)
currencies_errors = result.errors.for_object("merchant").on("currencies")
self.assertEqual(1, len(currencies_errors))
self.assertEqual(ErrorCodes.Merchant.CurrenciesAreInvalid, currencies_errors[0].code)
braintree_python-3.38.0/tests/integration/test_payment_method_nonce.py 0000644 0001750 0001750 00000004660 13150065776 024600 0 ustar hle hle from tests.test_helper import *
class TestPaymentMethodNonce(unittest.TestCase):
def test_create_nonce_from_payment_method(self):
customer_id = Customer.create().customer.id
credit_card_result = CreditCard.create({
"customer_id": customer_id,
"number": "4111111111111111",
"expiration_date": "05/2014",
})
result = PaymentMethodNonce.create(credit_card_result.credit_card.token)
self.assertTrue(result.is_success)
self.assertNotEqual(None, result.payment_method_nonce)
self.assertNotEqual(None, result.payment_method_nonce.nonce)
def test_create_raises_not_found_when_404(self):
self.assertRaises(NotFoundError, PaymentMethodNonce.create, "not-a-token")
def test_find_nonce_shows_details(self):
config = Configuration(
environment=Environment.Development,
merchant_id="integration_merchant_id",
public_key="integration_public_key",
private_key="integration_private_key"
)
gateway = BraintreeGateway(config)
credit_card = {
"credit_card": {
"number": "4111111111111111",
"expiration_month": "12",
"expiration_year": "2020"
}
}
nonce = TestHelper.generate_three_d_secure_nonce(gateway, credit_card)
found_nonce = PaymentMethodNonce.find(nonce)
three_d_secure_info = found_nonce.three_d_secure_info
self.assertEqual("CreditCard", found_nonce.type)
self.assertEqual(nonce, found_nonce.nonce)
self.assertEqual("Y", three_d_secure_info.enrolled)
self.assertEqual("authenticate_successful", three_d_secure_info.status)
self.assertEqual(True, three_d_secure_info.liability_shifted)
self.assertEqual(True, three_d_secure_info.liability_shift_possible)
def test_exposes_null_3ds_info_if_none_exists(self):
http = ClientApiHttp.create()
_, nonce = http.get_paypal_nonce({
"consent-code": "consent-code",
"access-token": "access-token",
"options": {"validate": False}
})
found_nonce = PaymentMethodNonce.find(nonce)
self.assertEqual(nonce, found_nonce.nonce)
self.assertEqual(None, found_nonce.three_d_secure_info)
def test_find_raises_not_found_when_404(self):
self.assertRaises(NotFoundError, PaymentMethodNonce.find, "not-a-nonce")
braintree_python-3.38.0/tests/integration/test_coinbase.py 0000644 0001750 0001750 00000002332 13150065776 022156 0 ustar hle hle from tests.test_helper import *
from braintree.test.nonces import Nonces
from braintree.exceptions.not_found_error import NotFoundError
from braintree.error_codes import ErrorCodes
class TestCoinbase(unittest.TestCase):
def test_customer(self):
result = Customer.create({"payment_method_nonce": Nonces.Coinbase})
self.assertFalse(result.is_success)
self.assertEquals(ErrorCodes.PaymentMethod.PaymentMethodNoLongerSupported, result.errors.for_object("coinbase_account").on("base")[0].code)
def test_vault(self):
result = Customer.create()
result = PaymentMethod.create({
"customer_id": result.customer.id,
"payment_method_nonce": Nonces.Coinbase
})
self.assertFalse(result.is_success)
self.assertEquals(ErrorCodes.PaymentMethod.PaymentMethodNoLongerSupported, result.errors.for_object("coinbase_account").on("base")[0].code)
def test_transaction(self):
result = Transaction.sale({"payment_method_nonce": Nonces.Coinbase, "amount": "1.00"})
self.assertFalse(result.is_success)
self.assertEquals(ErrorCodes.PaymentMethod.PaymentMethodNoLongerSupported, result.errors.for_object("transaction").on("base")[0].code)
braintree_python-3.38.0/tests/integration/test_add_ons.py 0000644 0001750 0001750 00000002276 13150065776 022011 0 ustar hle hle from tests.test_helper import *
class TestAddOn(unittest.TestCase):
def test_all_returns_all_add_ons(self):
new_id = str(random.randint(1, 1000000))
attributes = {
"amount": "100.00",
"description": "some description",
"id": new_id,
"kind": "add_on",
"name": "python_add_on",
"never_expires": False,
"number_of_billing_cycles": 1
}
Configuration.instantiate().http().post(Configuration.instantiate().base_merchant_path() + "/modifications/create_modification_for_tests", {"modification": attributes})
add_ons = AddOn.all()
for add_on in add_ons:
if add_on.id == new_id:
break
else:
add_on = None
self.assertNotEqual(None, add_on)
self.assertEqual(Decimal("100.00"), add_on.amount)
self.assertEqual("some description", add_on.description)
self.assertEqual(new_id, add_on.id)
self.assertEqual("add_on", add_on.kind)
self.assertEqual("python_add_on", add_on.name)
self.assertEqual(False, add_on.never_expires)
self.assertEqual(add_on.number_of_billing_cycles, 1)
braintree_python-3.38.0/tests/integration/test_dispute_search.py 0000644 0001750 0001750 00000003020 13150065776 023370 0 ustar hle hle from tests.test_helper import *
class TestDisputeSearch(unittest.TestCase):
def test_advanced_search_no_results(self):
collection = Dispute.search(
DisputeSearch.id == "non_existent_dispute"
)
disputes = [dispute for dispute in collection.disputes.items]
self.assertEquals(0, len(disputes))
def test_advanced_search_returns_single_dispute_by_id(self):
collection = Dispute.search(
DisputeSearch.id == "open_dispute"
)
disputes = [dispute for dispute in collection.disputes.items]
self.assertEquals(1, len(disputes))
dispute = disputes[0]
self.assertEquals(dispute.id, "open_dispute")
self.assertEquals(dispute.status, Dispute.Status.Open)
def test_advanced_search_returns_disputes_by_multiple_reasons(self):
collection = Dispute.search(
DisputeSearch.reason.in_list([
braintree.Dispute.Reason.ProductUnsatisfactory,
braintree.Dispute.Reason.Retrieval
])
)
disputes = [dispute for dispute in collection.disputes.items]
self.assertEquals(2, len(disputes))
def test_advanced_search_returns_disputes_by_date_range(self):
collection = Dispute.search(
DisputeSearch.received_date.between("03/03/2014", "03/05/2014")
)
disputes = [dispute for dispute in collection.disputes.items]
self.assertEquals(1, len(disputes))
self.assertEquals(disputes[0].received_date, date(2014, 3, 4))
braintree_python-3.38.0/tests/integration/test_subscription.py 0000644 0001750 0001750 00000167121 13150065776 023127 0 ustar hle hle from tests.test_helper import *
from braintree.test.nonces import Nonces
from datetime import date, timedelta
class TestSubscription(unittest.TestCase):
def setUp(self):
self.credit_card = Customer.create({
"first_name": "Mike",
"last_name": "Jones",
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2010",
"cvv": "100"
}
}).customer.credit_cards[0]
self.updateable_subscription = Subscription.create({
"payment_method_token": self.credit_card.token,
"price": Decimal("54.32"),
"plan_id": TestHelper.trialless_plan["id"]
}).subscription
def test_create_returns_successful_result_if_valid(self):
result = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trialless_plan["id"]
})
self.assertTrue(result.is_success)
subscription = result.subscription
self.assertNotEqual(None, re.search(r"\A\w{6}\Z", subscription.id))
self.assertEqual(Decimal("12.34"), subscription.price)
self.assertEqual(Decimal("12.34"), subscription.next_bill_amount)
self.assertEqual(Decimal("12.34"), subscription.next_billing_period_amount)
self.assertEqual(Subscription.Status.Active, subscription.status)
self.assertEqual("integration_trialless_plan", subscription.plan_id)
self.assertEqual(TestHelper.default_merchant_account_id, subscription.merchant_account_id)
self.assertEqual(Decimal("0.00"), subscription.balance)
self.assertEqual(date, type(subscription.first_billing_date))
self.assertEqual(date, type(subscription.next_billing_date))
self.assertEqual(date, type(subscription.billing_period_start_date))
self.assertEqual(date, type(subscription.billing_period_end_date))
self.assertEqual(date, type(subscription.paid_through_date))
self.assertEqual(datetime, type(subscription.created_at))
self.assertEqual(datetime, type(subscription.updated_at))
self.assertEqual(1, subscription.current_billing_cycle)
self.assertEqual(0, subscription.failure_count)
self.assertEqual(self.credit_card.token, subscription.payment_method_token)
self.assertEqual(Subscription.Status.Active, subscription.status_history[0].status)
self.assertEqual(Decimal("12.34"), subscription.status_history[0].price)
self.assertEqual(Decimal("0.00"), subscription.status_history[0].balance)
self.assertEqual(Subscription.Source.Api, subscription.status_history[0].subscription_source)
self.assertEqual("USD", subscription.status_history[0].currency_iso_code)
self.assertEqual(TestHelper.trialless_plan["id"], subscription.status_history[0].plan_id)
def test_create_returns_successful_result_with_payment_method_nonce(self):
config = Configuration.instantiate()
customer_id = Customer.create().customer.id
parsed_client_token = TestHelper.generate_decoded_client_token({"customer_id": customer_id})
authorization_fingerprint = json.loads(parsed_client_token)["authorizationFingerprint"]
http = ClientApiHttp(config, {
"authorization_fingerprint": authorization_fingerprint,
"shared_customer_identifier": "fake_identifier",
"shared_customer_identifier_type": "testing"
})
_, response = http.add_card({
"credit_card": {
"number": "4111111111111111",
"expiration_month": "11",
"expiration_year": "2099",
},
"share": True
})
nonce = json.loads(response)["creditCards"][0]["nonce"]
result = Subscription.create({
"payment_method_nonce": nonce,
"plan_id": TestHelper.trialless_plan["id"]
})
self.assertTrue(result.is_success)
transaction = result.subscription.transactions[0]
self.assertEqual("411111", transaction.credit_card_details.bin)
def test_create_can_set_the_id(self):
new_id = str(random.randint(1, 1000000))
result = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trialless_plan["id"],
"id": new_id
})
self.assertTrue(result.is_success)
self.assertEqual(new_id, result.subscription.id)
def test_create_can_set_the_merchant_account_id(self):
result = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trialless_plan["id"],
"merchant_account_id": TestHelper.non_default_merchant_account_id
})
self.assertTrue(result.is_success)
self.assertEqual(TestHelper.non_default_merchant_account_id, result.subscription.merchant_account_id)
def test_create_defaults_to_plan_without_trial(self):
subscription = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trialless_plan["id"],
}).subscription
self.assertEqual(TestHelper.trialless_plan["trial_period"], subscription.trial_period)
self.assertEqual(None, subscription.trial_duration)
self.assertEqual(None, subscription.trial_duration_unit)
def test_create_defaults_to_plan_with_trial(self):
subscription = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trial_plan["id"],
}).subscription
self.assertEqual(TestHelper.trial_plan["trial_period"], subscription.trial_period)
self.assertEqual(TestHelper.trial_plan["trial_duration"], subscription.trial_duration)
self.assertEqual(TestHelper.trial_plan["trial_duration_unit"], subscription.trial_duration_unit)
def test_create_and_override_plan_with_trial(self):
subscription = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trial_plan["id"],
"trial_duration": 5,
"trial_duration_unit": Subscription.TrialDurationUnit.Month
}).subscription
self.assertEqual(True, subscription.trial_period)
self.assertEqual(5, subscription.trial_duration)
self.assertEqual(Subscription.TrialDurationUnit.Month, subscription.trial_duration_unit)
def test_create_and_override_trial_period(self):
subscription = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trial_plan["id"],
"trial_period": False
}).subscription
self.assertEqual(False, subscription.trial_period)
def test_create_and_override_number_of_billing_cycles(self):
subscription = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trial_plan["id"],
"number_of_billing_cycles": 10
}).subscription
self.assertEqual(10, subscription.number_of_billing_cycles)
def test_create_and_override_number_of_billing_cycles_to_never_expire(self):
subscription = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trial_plan["id"],
"never_expires": True
}).subscription
self.assertEqual(None, subscription.number_of_billing_cycles)
def test_create_creates_a_transaction_if_no_trial_period(self):
subscription = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trialless_plan["id"],
}).subscription
self.assertEqual(1, len(subscription.transactions))
transaction = subscription.transactions[0]
self.assertEqual(Transaction, type(transaction))
self.assertEqual(TestHelper.trialless_plan["price"], transaction.amount)
self.assertEqual("sale", transaction.type)
self.assertEqual(subscription.id, transaction.subscription_id)
def test_create_has_transaction_with_billing_period_dates(self):
subscription = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trialless_plan["id"],
}).subscription
transaction = subscription.transactions[0]
self.assertEqual(subscription.billing_period_start_date, transaction.subscription_details.billing_period_start_date)
self.assertEqual(subscription.billing_period_end_date, transaction.subscription_details.billing_period_end_date)
def test_create_returns_a_transaction_if_transaction_is_declined(self):
result = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trialless_plan["id"],
"price": TransactionAmounts.Decline
})
self.assertFalse(result.is_success)
self.assertEqual(Transaction.Status.ProcessorDeclined, result.transaction.status)
def test_create_doesnt_creates_a_transaction_if_trial_period(self):
subscription = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trial_plan["id"],
}).subscription
self.assertEqual(0, len(subscription.transactions))
def test_create_with_error_result(self):
result = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trial_plan["id"],
"id": "invalid token"
})
self.assertFalse(result.is_success)
id_errors = result.errors.for_object("subscription").on("id")
self.assertEqual(1, len(id_errors))
self.assertEqual("81906", id_errors[0].code)
def test_create_inherits_billing_day_of_month_from_plan(self):
result = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.billing_day_of_month_plan["id"],
})
self.assertTrue(result.is_success)
self.assertEqual(5, result.subscription.billing_day_of_month)
def test_create_allows_overriding_billing_day_of_month(self):
result = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.billing_day_of_month_plan["id"],
"billing_day_of_month": 19
})
self.assertTrue(result.is_success)
self.assertEqual(19, result.subscription.billing_day_of_month)
def test_create_allows_overriding_billing_day_of_month_with_start_immediately(self):
result = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.billing_day_of_month_plan["id"],
"options": {
"start_immediately": True
}
})
self.assertTrue(result.is_success)
self.assertEqual(1, len(result.subscription.transactions))
def test_create_allows_specifying_first_billing_date(self):
result = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.billing_day_of_month_plan["id"],
"first_billing_date": date.today() + timedelta(days=3)
})
self.assertTrue(result.is_success)
self.assertEqual(date.today() + timedelta(days=3), result.subscription.first_billing_date)
self.assertEqual(Subscription.Status.Pending, result.subscription.status)
def test_create_does_not_allow_first_billing_date_in_the_past(self):
result = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.billing_day_of_month_plan["id"],
"first_billing_date": date.today() - timedelta(days=3)
})
self.assertFalse(result.is_success)
billing_date_errors = result.errors.for_object("subscription").on("first_billing_date")
self.assertEqual(1, len(billing_date_errors))
self.assertEqual(ErrorCodes.Subscription.FirstBillingDateCannotBeInThePast, billing_date_errors[0].code)
def test_create_does_not_inherit_add_ons_or_discounts_from_the_plan_when_flag_is_set(self):
subscription = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.add_on_discount_plan["id"],
"options": {
"do_not_inherit_add_ons_or_discounts": True
}
}).subscription
self.assertEqual(0, len(subscription.add_ons))
self.assertEqual(0, len(subscription.discounts))
def test_create_inherits_add_ons_and_discounts_from_the_plan_when_not_specified(self):
subscription = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.add_on_discount_plan["id"]
}).subscription
self.assertEqual(2, len(subscription.add_ons))
add_ons = sorted(subscription.add_ons, key=lambda add_on: add_on.id)
self.assertEqual("increase_10", add_ons[0].id)
self.assertEqual(Decimal("10.00"), add_ons[0].amount)
self.assertEqual(1, add_ons[0].quantity)
self.assertEqual(None, add_ons[0].number_of_billing_cycles)
self.assertTrue(add_ons[0].never_expires)
self.assertEqual(0, add_ons[0].current_billing_cycle)
self.assertEqual("increase_20", add_ons[1].id)
self.assertEqual(Decimal("20.00"), add_ons[1].amount)
self.assertEqual(1, add_ons[1].quantity)
self.assertEqual(None, add_ons[1].number_of_billing_cycles)
self.assertTrue(add_ons[1].never_expires)
self.assertEqual(0, add_ons[1].current_billing_cycle)
self.assertEqual(2, len(subscription.discounts))
discounts = sorted(subscription.discounts, key=lambda discount: discount.id)
self.assertEqual("discount_11", discounts[0].id)
self.assertEqual(Decimal("11.00"), discounts[0].amount)
self.assertEqual(1, discounts[0].quantity)
self.assertEqual(None, discounts[0].number_of_billing_cycles)
self.assertTrue(discounts[0].never_expires)
self.assertEqual(0, discounts[0].current_billing_cycle)
self.assertEqual("discount_7", discounts[1].id)
self.assertEqual(Decimal("7.00"), discounts[1].amount)
self.assertEqual(1, discounts[1].quantity)
self.assertEqual(None, discounts[1].number_of_billing_cycles)
self.assertTrue(discounts[1].never_expires)
self.assertEqual(0, discounts[1].current_billing_cycle)
def test_create_allows_overriding_of_inherited_add_ons_and_discounts(self):
subscription = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.add_on_discount_plan["id"],
"add_ons": {
"update": [
{
"amount": Decimal("50.00"),
"existing_id": "increase_10",
"quantity": 2,
"number_of_billing_cycles": 5
},
{
"amount": Decimal("100.00"),
"existing_id": "increase_20",
"quantity": 4,
"never_expires": True
}
]
},
"discounts": {
"update": [
{
"amount": Decimal("15.00"),
"existing_id": "discount_7",
"quantity": 3,
"number_of_billing_cycles": 19
}
]
}
}).subscription
self.assertEqual(2, len(subscription.add_ons))
add_ons = sorted(subscription.add_ons, key=lambda add_on: add_on.id)
self.assertEqual("increase_10", add_ons[0].id)
self.assertEqual(Decimal("50.00"), add_ons[0].amount)
self.assertEqual(2, add_ons[0].quantity)
self.assertEqual(5, add_ons[0].number_of_billing_cycles)
self.assertFalse(add_ons[0].never_expires)
self.assertEqual(0, add_ons[0].current_billing_cycle)
self.assertEqual("increase_20", add_ons[1].id)
self.assertEqual(Decimal("100.00"), add_ons[1].amount)
self.assertEqual(4, add_ons[1].quantity)
self.assertEqual(None, add_ons[1].number_of_billing_cycles)
self.assertTrue(add_ons[1].never_expires)
self.assertEqual(0, add_ons[1].current_billing_cycle)
self.assertEqual(2, len(subscription.discounts))
discounts = sorted(subscription.discounts, key=lambda discount: discount.id)
self.assertEqual("discount_11", discounts[0].id)
self.assertEqual(Decimal("11.00"), discounts[0].amount)
self.assertEqual(1, discounts[0].quantity)
self.assertEqual(None, discounts[0].number_of_billing_cycles)
self.assertTrue(discounts[0].never_expires)
self.assertEqual(0, discounts[0].current_billing_cycle)
self.assertEqual("discount_7", discounts[1].id)
self.assertEqual(Decimal("15.00"), discounts[1].amount)
self.assertEqual(3, discounts[1].quantity)
self.assertEqual(19, discounts[1].number_of_billing_cycles)
self.assertFalse(discounts[1].never_expires)
self.assertEqual(0, discounts[1].current_billing_cycle)
def test_create_allows_deleting_of_inherited_add_ons_and_discounts(self):
subscription = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.add_on_discount_plan["id"],
"add_ons": {
"remove": ["increase_10", "increase_20"]
},
"discounts": {
"remove": ["discount_7"]
}
}).subscription
self.assertEqual(0, len(subscription.add_ons))
self.assertEqual(1, len(subscription.discounts))
self.assertEqual("discount_11", subscription.discounts[0].id)
def test_create_allows_adding_add_ons_and_discounts(self):
subscription = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.add_on_discount_plan["id"],
"add_ons": {
"add": [
{
"amount": Decimal("50.00"),
"inherited_from_id": "increase_30",
"quantity": 2,
"number_of_billing_cycles": 5
}
],
"remove": ["increase_10", "increase_20"]
},
"discounts": {
"add": [
{
"amount": Decimal("17.00"),
"inherited_from_id": "discount_15",
"never_expires": True
}
],
"remove": ["discount_7", "discount_11"]
}
}).subscription
self.assertEqual(1, len(subscription.add_ons))
self.assertEqual("increase_30", subscription.add_ons[0].id)
self.assertEqual(Decimal("50.00"), subscription.add_ons[0].amount)
self.assertEqual(2, subscription.add_ons[0].quantity)
self.assertEqual(5, subscription.add_ons[0].number_of_billing_cycles)
self.assertFalse(subscription.add_ons[0].never_expires)
self.assertEqual(0, subscription.add_ons[0].current_billing_cycle)
self.assertEqual(1, len(subscription.discounts))
self.assertEqual("discount_15", subscription.discounts[0].id)
self.assertEqual(Decimal("17.00"), subscription.discounts[0].amount)
self.assertEqual(1, subscription.discounts[0].quantity)
self.assertEqual(None, subscription.discounts[0].number_of_billing_cycles)
self.assertTrue(subscription.discounts[0].never_expires)
self.assertEqual(0, subscription.discounts[0].current_billing_cycle)
def test_create_properly_parses_validation_errors_for_arrays(self):
result = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.add_on_discount_plan["id"],
"add_ons": {
"update": [
{
"existing_id": "increase_10",
"amount": "invalid"
},
{
"existing_id": "increase_20",
"quantity": -2
}
]
}
})
self.assertFalse(result.is_success)
self.assertEqual(
ErrorCodes.Subscription.Modification.AmountIsInvalid,
result.errors.for_object("subscription").for_object("add_ons").for_object("update").for_index(0).on("amount")[0].code
)
self.assertEqual(
ErrorCodes.Subscription.Modification.QuantityIsInvalid,
result.errors.for_object("subscription").for_object("add_ons").for_object("update").for_index(1).on("quantity")[0].code
)
def test_descriptors_accepts_name_phone_and_url(self):
result = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trialless_plan["id"],
"descriptor": {
"name": "123*123456789012345678",
"phone": "3334445555",
"url": "ebay.com"
}
})
self.assertTrue(result.is_success)
subscription = result.subscription
self.assertEqual("123*123456789012345678", subscription.descriptor.name)
self.assertEqual("3334445555", subscription.descriptor.phone)
transaction = subscription.transactions[0]
self.assertEqual("123*123456789012345678", transaction.descriptor.name)
self.assertEqual("3334445555", transaction.descriptor.phone)
self.assertEqual("ebay.com", transaction.descriptor.url)
def test_descriptors_has_validation_errors_if_format_is_invalid(self):
result = Transaction.sale({
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2009"
},
"descriptor": {
"name": "badcompanyname12*badproduct12",
"phone": "%bad4445555"
}
})
self.assertFalse(result.is_success)
name_errors = result.errors.for_object("transaction").for_object("descriptor").on("name")
self.assertEqual(1, len(name_errors))
self.assertEqual(ErrorCodes.Descriptor.NameFormatIsInvalid, name_errors[0].code)
phone_errors = result.errors.for_object("transaction").for_object("descriptor").on("phone")
self.assertEqual(1, len(phone_errors))
self.assertEqual(ErrorCodes.Descriptor.PhoneFormatIsInvalid, phone_errors[0].code)
def test_description(self):
http = ClientApiHttp.create()
status_code, nonce = http.get_paypal_nonce({
"consent-code": "consent-code",
"options": {"validate": False}
})
self.assertEqual(202, status_code)
payment_method_token = PaymentMethod.create({
"customer_id": Customer.create().customer.id,
"payment_method_nonce": nonce
}).payment_method.token
result = Subscription.create({
"payment_method_token": payment_method_token,
"plan_id": TestHelper.trialless_plan["id"],
"options": {
"paypal": {
"description": "A great product"
}
}
})
self.assertTrue(result.is_success)
subscription = result.subscription
self.assertEqual("A great product", subscription.description)
transaction = subscription.transactions[0]
paypal_details = transaction.paypal_details
self.assertEqual("A great product", paypal_details.description)
def test_find_with_valid_id(self):
subscription = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trial_plan["id"],
}).subscription
found_subscription = Subscription.find(subscription.id)
self.assertEqual(subscription.id, found_subscription.id)
@raises_with_regexp(NotFoundError, "subscription with id bad_token not found")
def test_find_with_invalid_token(self):
Subscription.find("bad_token")
def test_update_creates_a_prorated_transaction_when_merchant_is_set_to_prorate(self):
result = Subscription.update(self.updateable_subscription.id, {
"price": self.updateable_subscription.price + Decimal("1"),
})
self.assertTrue(result.is_success)
subscription = result.subscription
self.assertEqual(2, len(subscription.transactions))
def test_update_creates_a_prorated_transaction_when_flag_is_passed_as_True(self):
result = Subscription.update(self.updateable_subscription.id, {
"price": self.updateable_subscription.price + Decimal("1"),
"options": {
"prorate_charges": True
}
})
self.assertTrue(result.is_success)
subscription = result.subscription
self.assertEqual(2, len(subscription.transactions))
def test_update_does_not_create_a_prorated_transaction_when_flag_is_passed_as_False(self):
result = Subscription.update(self.updateable_subscription.id, {
"price": self.updateable_subscription.price + Decimal("1"),
"options": {
"prorate_charges": False
}
})
self.assertTrue(result.is_success)
subscription = result.subscription
self.assertEqual(1, len(subscription.transactions))
def test_update_does_not_update_subscription_when_revert_subscription_on_proration_failure_is_true(self):
result = Subscription.update(self.updateable_subscription.id, {
"price": self.updateable_subscription.price + Decimal("2100"),
"options": {
"prorate_charges": True,
"revert_subscription_on_proration_failure": True
}
})
self.assertFalse(result.is_success)
found_subscription = Subscription.find(result.subscription.id)
self.assertEqual(len(self.updateable_subscription.transactions) + 1, len(result.subscription.transactions))
self.assertEqual("processor_declined", result.subscription.transactions[0].status)
self.assertEqual(Decimal("0.00"), found_subscription.balance)
self.assertEqual(self.updateable_subscription.price, found_subscription.price)
def test_update_updates_subscription_when_revert_subscription_on_proration_failure_is_false(self):
result = Subscription.update(self.updateable_subscription.id, {
"price": self.updateable_subscription.price + Decimal("2100"),
"options": {
"prorate_charges": True,
"revert_subscription_on_proration_failure": False
}
})
self.assertTrue(result.is_success)
found_subscription = Subscription.find(result.subscription.id)
self.assertEqual(len(self.updateable_subscription.transactions) + 1, len(result.subscription.transactions))
self.assertEqual("processor_declined", result.subscription.transactions[0].status)
self.assertEqual(result.subscription.transactions[0].amount, Decimal(found_subscription.balance))
self.assertEqual(self.updateable_subscription.price + Decimal("2100"), found_subscription.price)
def test_update_with_successful_result(self):
new_id = str(random.randint(1, 1000000))
result = Subscription.update(self.updateable_subscription.id, {
"id": new_id,
"price": Decimal("9999.88"),
"plan_id": TestHelper.trial_plan["id"]
})
self.assertTrue(result.is_success)
subscription = result.subscription
self.assertEqual(new_id, subscription.id)
self.assertEqual(TestHelper.trial_plan["id"], subscription.plan_id)
self.assertEqual(Decimal("9999.88"), subscription.price)
def test_update_with_merchant_account_id(self):
result = Subscription.update(self.updateable_subscription.id, {
"merchant_account_id": TestHelper.non_default_merchant_account_id,
})
self.assertTrue(result.is_success)
subscription = result.subscription
self.assertEqual(TestHelper.non_default_merchant_account_id, subscription.merchant_account_id)
def test_update_with_payment_method_token(self):
newCard = CreditCard.create({
"customer_id": self.credit_card.customer_id,
"number": "4111111111111111",
"expiration_date": "05/2009",
"cvv": "100",
"cardholder_name": self.credit_card.cardholder_name
}).credit_card
result = Subscription.update(self.updateable_subscription.id, {
"payment_method_token": newCard.token
})
self.assertTrue(result.is_success)
subscription = result.subscription
self.assertEqual(newCard.token, subscription.payment_method_token)
def test_update_with_payment_method_nonce(self):
config = Configuration.instantiate()
customer_id = self.credit_card.customer_id
parsed_client_token = TestHelper.generate_decoded_client_token({"customer_id": customer_id})
authorization_fingerprint = json.loads(parsed_client_token)["authorizationFingerprint"]
http = ClientApiHttp(config, {
"authorization_fingerprint": authorization_fingerprint,
"shared_customer_identifier": "fake_identifier",
"shared_customer_identifier_type": "testing"
})
_, response = http.add_card({
"credit_card": {
"number": "4242424242424242",
"expiration_month": "11",
"expiration_year": "2099",
},
"share": True
})
nonce = json.loads(response)["creditCards"][0]["nonce"]
result = Subscription.update(self.updateable_subscription.id, {
"payment_method_nonce": nonce
})
self.assertTrue(result.is_success)
subscription = result.subscription
newCard = CreditCard.find(subscription.payment_method_token)
self.assertEqual("4242", newCard.last_4)
self.assertNotEqual(newCard.last_4, self.credit_card.last_4)
def test_update_with_number_of_billing_cycles(self):
result = Subscription.update(self.updateable_subscription.id, {
"number_of_billing_cycles": 10
})
self.assertTrue(result.is_success)
subscription = result.subscription
self.assertEqual(10, subscription.number_of_billing_cycles)
def test_update_with_never_expires(self):
result = Subscription.update(self.updateable_subscription.id, {
"never_expires": True
})
self.assertTrue(result.is_success)
subscription = result.subscription
self.assertEqual(None, subscription.number_of_billing_cycles)
def test_update_with_error_result(self):
result = Subscription.update(self.updateable_subscription.id, {
"id": "bad id",
})
self.assertFalse(result.is_success)
id_errors = result.errors.for_object("subscription").on("id")
self.assertEqual(1, len(id_errors))
self.assertEqual("81906", id_errors[0].code)
@raises(NotFoundError)
def test_update_raises_error_when_subscription_not_found(self):
Subscription.update("notfound", {
"id": "newid",
})
def test_update_allows_overriding_of_inherited_add_ons_and_discounts(self):
subscription = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.add_on_discount_plan["id"],
}).subscription
subscription = Subscription.update(subscription.id, {
"add_ons": {
"update": [
{
"amount": Decimal("50.00"),
"existing_id": "increase_10",
"quantity": 2,
"number_of_billing_cycles": 5
},
{
"amount": Decimal("100.00"),
"existing_id": "increase_20",
"quantity": 4,
"never_expires": True
}
]
},
"discounts": {
"update": [
{
"amount": Decimal("15.00"),
"existing_id": "discount_7",
"quantity": 3,
"number_of_billing_cycles": 19
}
]
}
}).subscription
self.assertEqual(2, len(subscription.add_ons))
add_ons = sorted(subscription.add_ons, key=lambda add_on: add_on.id)
self.assertEqual("increase_10", add_ons[0].id)
self.assertEqual(Decimal("50.00"), add_ons[0].amount)
self.assertEqual(2, add_ons[0].quantity)
self.assertEqual(5, add_ons[0].number_of_billing_cycles)
self.assertFalse(add_ons[0].never_expires)
self.assertEqual("increase_20", add_ons[1].id)
self.assertEqual(Decimal("100.00"), add_ons[1].amount)
self.assertEqual(4, add_ons[1].quantity)
self.assertEqual(None, add_ons[1].number_of_billing_cycles)
self.assertTrue(add_ons[1].never_expires)
self.assertEqual(2, len(subscription.discounts))
discounts = sorted(subscription.discounts, key=lambda discount: discount.id)
self.assertEqual("discount_11", discounts[0].id)
self.assertEqual(Decimal("11.00"), discounts[0].amount)
self.assertEqual(1, discounts[0].quantity)
self.assertEqual(None, discounts[0].number_of_billing_cycles)
self.assertTrue(discounts[0].never_expires)
self.assertEqual("discount_7", discounts[1].id)
self.assertEqual(Decimal("15.00"), discounts[1].amount)
self.assertEqual(3, discounts[1].quantity)
self.assertEqual(19, discounts[1].number_of_billing_cycles)
self.assertFalse(discounts[1].never_expires)
def test_update_allows_adding_and_removing_add_ons_and_discounts(self):
subscription = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.add_on_discount_plan["id"],
}).subscription
subscription = Subscription.update(subscription.id, {
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.add_on_discount_plan["id"],
"add_ons": {
"add": [
{
"amount": Decimal("50.00"),
"inherited_from_id": "increase_30",
"quantity": 2,
"number_of_billing_cycles": 5
}
],
"remove": ["increase_10", "increase_20"]
},
"discounts": {
"add": [
{
"amount": Decimal("17.00"),
"inherited_from_id": "discount_15",
"never_expires": True
}
],
"remove": ["discount_7", "discount_11"]
}
}).subscription
self.assertEqual(1, len(subscription.add_ons))
self.assertEqual("increase_30", subscription.add_ons[0].id)
self.assertEqual(Decimal("50.00"), subscription.add_ons[0].amount)
self.assertEqual(2, subscription.add_ons[0].quantity)
self.assertEqual(5, subscription.add_ons[0].number_of_billing_cycles)
self.assertFalse(subscription.add_ons[0].never_expires)
self.assertEqual(1, len(subscription.discounts))
self.assertEqual("discount_15", subscription.discounts[0].id)
self.assertEqual(Decimal("17.00"), subscription.discounts[0].amount)
self.assertEqual(1, subscription.discounts[0].quantity)
self.assertEqual(None, subscription.discounts[0].number_of_billing_cycles)
self.assertTrue(subscription.discounts[0].never_expires)
def test_update_allows_adding_and_removing_unicode_add_ons_and_discounts(self):
subscription = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.add_on_discount_plan["id"],
}).subscription
subscription = Subscription.update(subscription.id, {
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.add_on_discount_plan["id"],
"add_ons": {
"add": [
{
"amount": Decimal("50.00"),
"inherited_from_id": u"increase_30",
"quantity": 2,
"number_of_billing_cycles": 5
}
],
"remove": [u"increase_10", u"increase_20"]
},
"discounts": {
"add": [
{
"amount": Decimal("17.00"),
"inherited_from_id": u"discount_15",
"never_expires": True
}
],
"remove": [u"discount_7", u"discount_11"]
}
}).subscription
self.assertEqual(1, len(subscription.add_ons))
self.assertEqual(u"increase_30", subscription.add_ons[0].id)
self.assertEqual(Decimal("50.00"), subscription.add_ons[0].amount)
self.assertEqual(2, subscription.add_ons[0].quantity)
self.assertEqual(5, subscription.add_ons[0].number_of_billing_cycles)
self.assertFalse(subscription.add_ons[0].never_expires)
self.assertEqual(1, len(subscription.discounts))
self.assertEqual(u"discount_15", subscription.discounts[0].id)
self.assertEqual(Decimal("17.00"), subscription.discounts[0].amount)
self.assertEqual(1, subscription.discounts[0].quantity)
self.assertEqual(None, subscription.discounts[0].number_of_billing_cycles)
self.assertTrue(subscription.discounts[0].never_expires)
def test_update_can_replace_entire_set_of_add_ons_and_discounts(self):
subscription = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.add_on_discount_plan["id"],
}).subscription
subscription = Subscription.update(subscription.id, {
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.add_on_discount_plan["id"],
"add_ons": {
"add": [
{"inherited_from_id": "increase_30"},
{"inherited_from_id": "increase_20"},
],
},
"discounts": {
"add": [
{"inherited_from_id": "discount_15"},
],
},
"options": {
"replace_all_add_ons_and_discounts": True,
},
}).subscription
self.assertEqual(2, len(subscription.add_ons))
add_ons = sorted(subscription.add_ons, key=lambda add_on: add_on.id)
self.assertEqual("increase_20", add_ons[0].id)
self.assertEqual(Decimal("20.00"), add_ons[0].amount)
self.assertEqual(1, add_ons[0].quantity)
self.assertEqual(None, add_ons[0].number_of_billing_cycles)
self.assertTrue(add_ons[0].never_expires)
self.assertEqual("increase_30", add_ons[1].id)
self.assertEqual(Decimal("30.00"), add_ons[1].amount)
self.assertEqual(1, add_ons[1].quantity)
self.assertEqual(None, add_ons[1].number_of_billing_cycles)
self.assertTrue(add_ons[1].never_expires)
self.assertEqual(1, len(subscription.discounts))
self.assertEqual("discount_15", subscription.discounts[0].id)
self.assertEqual(Decimal("15.00"), subscription.discounts[0].amount)
self.assertEqual(1, subscription.discounts[0].quantity)
self.assertEqual(None, subscription.discounts[0].number_of_billing_cycles)
self.assertTrue(subscription.discounts[0].never_expires)
def test_update_descriptor_name_and_phone(self):
result = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trialless_plan["id"],
"descriptor": {
"name": "123*123456789012345678",
"phone": "1234567890"
}
})
self.assertTrue(result.is_success)
subscription = result.subscription
updated_subscription = Subscription.update(subscription.id, {
"descriptor": {
"name": "999*99",
"phone": "1234567890"
}
}).subscription
self.assertEqual("999*99", updated_subscription.descriptor.name)
self.assertEqual("1234567890", updated_subscription.descriptor.phone)
def test_update_description(self):
http = ClientApiHttp.create()
status_code, nonce = http.get_paypal_nonce({
"consent-code": "consent-code",
"options": {"validate": False}
})
self.assertEqual(202, status_code)
payment_method_token = PaymentMethod.create({
"customer_id": Customer.create().customer.id,
"payment_method_nonce": nonce
}).payment_method.token
result = Subscription.create({
"payment_method_token": payment_method_token,
"plan_id": TestHelper.trialless_plan["id"],
"options": {
"paypal": {
"description": "A great product"
}
}
})
self.assertTrue(result.is_success)
subscription = result.subscription
updated_subscription = Subscription.update(subscription.id, {
"options": {
"paypal": {
"description": "An incredible product"
}
}
}).subscription
self.assertEqual("An incredible product", updated_subscription.description)
def test_cancel_with_successful_response(self):
subscription = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trialless_plan["id"]
}).subscription
result = Subscription.cancel(subscription.id)
self.assertTrue(result.is_success)
self.assertEqual("Canceled", result.subscription.status)
def test_unsuccessful_cancel_returns_validation_error(self):
Subscription.cancel(self.updateable_subscription.id)
result = Subscription.cancel(self.updateable_subscription.id)
self.assertFalse(result.is_success)
status_errors = result.errors.for_object("subscription").on("status")
self.assertTrue(len(status_errors), 1)
self.assertEqual("81905", status_errors[0].code)
@raises(NotFoundError)
def test_cancel_raises_not_found_error_with_bad_subscription(self):
Subscription.cancel("notreal")
def test_search_with_argument_list_rather_than_literal_list(self):
trial_subscription = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trial_plan["id"],
"price": Decimal("1")
}).subscription
trialless_subscription = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trialless_plan["id"],
"price": Decimal("1")
}).subscription
collection = Subscription.search(
SubscriptionSearch.plan_id == "integration_trial_plan",
SubscriptionSearch.price == Decimal("1")
)
self.assertTrue(TestHelper.includes(collection, trial_subscription))
self.assertFalse(TestHelper.includes(collection, trialless_subscription))
def test_search_on_billing_cycles_remaining(self):
subscription_5 = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trial_plan["id"],
"number_of_billing_cycles": 5
}).subscription
subscription_10 = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trial_plan["id"],
"number_of_billing_cycles": 10
}).subscription
collection = Subscription.search([
SubscriptionSearch.billing_cycles_remaining >= 7
])
self.assertTrue(TestHelper.includes(collection, subscription_10))
self.assertFalse(TestHelper.includes(collection, subscription_5))
def test_search_on_created_at(self):
subscription = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trialless_plan["id"],
}).subscription
empty_collection = Subscription.search([
SubscriptionSearch.created_at.between(date.today() + timedelta(1), date.today() + timedelta(2))
])
self.assertTrue(empty_collection.maximum_size == 0)
success_collection = Subscription.search([
SubscriptionSearch.created_at.between(date.today() - timedelta(1), date.today() + timedelta(1))
])
self.assertTrue(success_collection.maximum_size > 0)
def test_search_on_days_past_due(self):
subscription = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trialless_plan["id"],
}).subscription
TestHelper.make_past_due(subscription, 3)
collection = Subscription.search([
SubscriptionSearch.days_past_due.between(2, 10)
])
self.assertTrue(collection.maximum_size > 0)
for subscription in collection.items:
self.assertTrue(2 <= subscription.days_past_due <= 10)
def test_search_on_plan_id(self):
trial_subscription = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trial_plan["id"],
"price": Decimal("2")
}).subscription
trialless_subscription = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trialless_plan["id"],
"price": Decimal("2")
}).subscription
collection = Subscription.search([
SubscriptionSearch.plan_id == "integration_trial_plan",
SubscriptionSearch.price == Decimal("2")
])
self.assertTrue(TestHelper.includes(collection, trial_subscription))
self.assertFalse(TestHelper.includes(collection, trialless_subscription))
collection = Subscription.search([
SubscriptionSearch.plan_id.in_list("integration_trial_plan", "integration_trialless_plan"),
SubscriptionSearch.price == Decimal("2")
])
self.assertTrue(TestHelper.includes(collection, trial_subscription))
self.assertTrue(TestHelper.includes(collection, trialless_subscription))
def test_search_on_plan_id_is_acts_like_text_node_instead_of_multiple_value(self):
for plan in [TestHelper.trial_plan, TestHelper.trialless_plan]:
Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": plan["id"],
"price": Decimal("3")
})
collection = Subscription.search([
SubscriptionSearch.plan_id == "no such plan id",
SubscriptionSearch.price == Decimal("3")
])
self.assertEqual(0, collection.maximum_size)
def test_search_on_status(self):
active_subscription = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trialless_plan["id"],
"price": Decimal("3")
}).subscription
canceled_subscription = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trialless_plan["id"],
"price": Decimal("3")
}).subscription
Subscription.cancel(canceled_subscription.id)
collection = Subscription.search([
SubscriptionSearch.status.in_list([Subscription.Status.Active, Subscription.Status.Canceled]),
SubscriptionSearch.price == Decimal("3")
])
self.assertTrue(TestHelper.includes(collection, active_subscription))
self.assertTrue(TestHelper.includes(collection, canceled_subscription))
def test_search_on_merchant_account_id(self):
subscription_default_ma = Subscription.create({
"merchant_account_id": TestHelper.default_merchant_account_id,
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trial_plan["id"],
"price": Decimal("4")
}).subscription
subscription_non_default_ma = Subscription.create({
"merchant_account_id": TestHelper.non_default_merchant_account_id,
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trial_plan["id"],
"price": Decimal("4")
}).subscription
collection = Subscription.search([
SubscriptionSearch.merchant_account_id == TestHelper.default_merchant_account_id,
SubscriptionSearch.price == Decimal("4")
])
self.assertTrue(TestHelper.includes(collection, subscription_default_ma))
self.assertFalse(TestHelper.includes(collection, subscription_non_default_ma))
def test_search_on_bogus_merchant_account_id(self):
subscription = Subscription.create({
"merchant_account_id": TestHelper.default_merchant_account_id,
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trial_plan["id"],
"price": Decimal("4")
}).subscription
collection = Subscription.search([
SubscriptionSearch.merchant_account_id == subscription.merchant_account_id,
SubscriptionSearch.price == Decimal("4")
])
self.assertTrue(TestHelper.includes(collection, subscription))
collection = Subscription.search([
SubscriptionSearch.merchant_account_id.in_list(["totally_bogus_id", subscription.merchant_account_id]),
SubscriptionSearch.price == Decimal("4")
])
self.assertTrue(TestHelper.includes(collection, subscription))
collection = Subscription.search([
SubscriptionSearch.merchant_account_id == "totally_bogus_id",
SubscriptionSearch.price == Decimal("4")
])
self.assertFalse(TestHelper.includes(collection, subscription))
def test_search_on_price(self):
subscription_900 = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trial_plan["id"],
"price": Decimal("900")
}).subscription
subscription_1000 = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trial_plan["id"],
"price": Decimal("1000")
}).subscription
collection = Subscription.search([
SubscriptionSearch.price >= Decimal("950")
])
self.assertTrue(TestHelper.includes(collection, subscription_1000))
self.assertFalse(TestHelper.includes(collection, subscription_900))
def test_search_on_transaction_id(self):
subscription_found = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trialless_plan["id"],
}).subscription
subscription_not_found = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trialless_plan["id"],
}).subscription
collection = Subscription.search(
SubscriptionSearch.transaction_id == subscription_found.transactions[0].id
)
self.assertTrue(TestHelper.includes(collection, subscription_found))
self.assertFalse(TestHelper.includes(collection, subscription_not_found))
def test_search_on_id(self):
subscription_found = Subscription.create({
"id": "find_me_%s" % random.randint(1, 1000000),
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trial_plan["id"],
}).subscription
subscription_not_found = Subscription.create({
"id": "do_not_find_me_%s" % random.randint(1, 1000000),
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trial_plan["id"],
}).subscription
collection = Subscription.search([
SubscriptionSearch.id.starts_with("find_me")
])
self.assertTrue(TestHelper.includes(collection, subscription_found))
self.assertFalse(TestHelper.includes(collection, subscription_not_found))
def test_search_on_next_billing_date(self):
subscription_found = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trialless_plan["id"]
}).subscription
subscription_not_found = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trial_plan["id"]
}).subscription
next_billing_date_cutoff = datetime.today() + timedelta(days=5)
collection = Subscription.search(
SubscriptionSearch.next_billing_date >= next_billing_date_cutoff
)
self.assertTrue(TestHelper.includes(collection, subscription_found))
self.assertFalse(TestHelper.includes(collection, subscription_not_found))
def test_retryCharge_without_amount__deprecated(self):
subscription = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trialless_plan["id"],
}).subscription
TestHelper.make_past_due(subscription)
result = Subscription.retryCharge(subscription.id)
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(subscription.price, transaction.amount)
self.assertNotEqual(None, transaction.processor_authorization_code)
self.assertEqual(Transaction.Type.Sale, transaction.type)
self.assertEqual(Transaction.Status.Authorized, transaction.status)
def test_retry_charge_without_amount(self):
subscription = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trialless_plan["id"],
}).subscription
TestHelper.make_past_due(subscription)
result = Subscription.retry_charge(subscription.id)
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(subscription.price, transaction.amount)
self.assertNotEqual(None, transaction.processor_authorization_code)
self.assertEqual(Transaction.Type.Sale, transaction.type)
self.assertEqual(Transaction.Status.Authorized, transaction.status)
def test_retryCharge_with_amount__deprecated(self):
subscription = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trialless_plan["id"],
}).subscription
TestHelper.make_past_due(subscription)
result = Subscription.retryCharge(subscription.id, Decimal(TransactionAmounts.Authorize))
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(Decimal(TransactionAmounts.Authorize), transaction.amount)
self.assertNotEqual(None, transaction.processor_authorization_code)
self.assertEqual(Transaction.Type.Sale, transaction.type)
self.assertEqual(Transaction.Status.Authorized, transaction.status)
def test_retry_charge_with_amount(self):
subscription = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trialless_plan["id"],
}).subscription
TestHelper.make_past_due(subscription)
result = Subscription.retry_charge(subscription.id, Decimal(TransactionAmounts.Authorize))
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(Decimal(TransactionAmounts.Authorize), transaction.amount)
self.assertNotEqual(None, transaction.processor_authorization_code)
self.assertEqual(Transaction.Type.Sale, transaction.type)
self.assertEqual(Transaction.Status.Authorized, transaction.status)
def test_retry_charge_with_submit_for_settlement(self):
subscription = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trialless_plan["id"],
}).subscription
TestHelper.make_past_due(subscription)
result = Subscription.retry_charge(subscription.id, None, True)
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(subscription.price, transaction.amount)
self.assertNotEqual(None, transaction.processor_authorization_code)
self.assertEqual(Transaction.Type.Sale, transaction.type)
self.assertEqual(Transaction.Status.SubmittedForSettlement, transaction.status)
def test_retry_charge_with_submit_for_settlement_and_amount(self):
subscription = Subscription.create({
"payment_method_token": self.credit_card.token,
"plan_id": TestHelper.trialless_plan["id"],
}).subscription
TestHelper.make_past_due(subscription)
result = Subscription.retry_charge(subscription.id, Decimal(TransactionAmounts.Authorize), True)
self.assertTrue(result.is_success)
transaction = result.transaction
self.assertEqual(Decimal(TransactionAmounts.Authorize), transaction.amount)
self.assertNotEqual(None, transaction.processor_authorization_code)
self.assertEqual(Transaction.Type.Sale, transaction.type)
self.assertEqual(Transaction.Status.SubmittedForSettlement, transaction.status)
def test_create_with_paypal_future_payment_method_token(self):
http = ClientApiHttp.create()
status_code, nonce = http.get_paypal_nonce({
"consent-code": "consent-code",
"options": {"validate": False}
})
self.assertEqual(202, status_code)
payment_method_token = PaymentMethod.create({
"customer_id": Customer.create().customer.id,
"payment_method_nonce": nonce
}).payment_method.token
result = Subscription.create({
"payment_method_token": payment_method_token,
"plan_id": TestHelper.trialless_plan["id"]
})
self.assertTrue(result.is_success)
subscription = result.subscription
self.assertEqual(payment_method_token, subscription.payment_method_token)
def test_create_fails_with_paypal_one_time_payment_method_nonce(self):
result = Subscription.create({
"payment_method_nonce": Nonces.PayPalOneTimePayment,
"plan_id": TestHelper.trialless_plan["id"]
})
self.assertFalse(result.is_success)
self.assertEqual(
ErrorCodes.Subscription.PaymentMethodNonceIsInvalid,
result.errors.for_object("subscription")[0].code
)
def test_create_fails_with_paypal_future_payment_method_nonce(self):
result = Subscription.create({
"payment_method_nonce": Nonces.PayPalFuturePayment,
"plan_id": TestHelper.trialless_plan["id"]
})
self.assertFalse(result.is_success)
self.assertEqual(
ErrorCodes.Subscription.PaymentMethodNonceIsInvalid,
result.errors.for_object("subscription")[0].code
)
braintree_python-3.38.0/tests/integration/test_credentials_parser.py 0000644 0001750 0001750 00000006734 13150065776 024256 0 ustar hle hle from tests.test_helper import *
from braintree.test.nonces import Nonces
from braintree.credentials_parser import CredentialsParser
class TestCredentialsParser(unittest.TestCase):
def test_parses_client_credentials(self):
parser = CredentialsParser(
client_id="client_id$development$integration_client_id",
client_secret="client_secret$development$integration_client_secret"
)
parser.parse_client_credentials()
self.assertEqual("client_id$development$integration_client_id", parser.client_id)
self.assertEqual("client_secret$development$integration_client_secret", parser.client_secret)
self.assertEqual(braintree.Environment.Development, parser.environment)
def test_error_on_inconsistent_environment(self):
with self.assertRaises(ConfigurationError) as error:
parser = CredentialsParser(
client_id="client_id$qa$integration_client_id",
client_secret="client_secret$development$integration_client_secret"
)
parser.parse_client_credentials()
config_error = error.exception
self.assertIn("Mismatched credential environments", str(config_error))
def test_error_on_missing_client_id(self):
with self.assertRaises(ConfigurationError) as error:
parser = CredentialsParser(
client_id=None,
client_secret="client_secret$development$integration_client_secret"
)
parser.parse_client_credentials()
config_error = error.exception
self.assertIn("Missing client_id", str(config_error))
def test_error_on_missing_client_secret(self):
with self.assertRaises(ConfigurationError) as error:
parser = CredentialsParser(
client_id="client_id$development$integration_client_id",
client_secret=None
)
parser.parse_client_credentials()
config_error = error.exception
self.assertIn("Missing client_secret", str(config_error))
def test_error_on_invalid_client_id(self):
with self.assertRaises(ConfigurationError) as error:
parser = CredentialsParser(
client_id="client_secret$development$integration_client_id",
client_secret="client_secret$development$integration_client_secret"
)
parser.parse_client_credentials()
config_error = error.exception
self.assertIn("Value passed for client_id is not a client_id", str(config_error))
def test_error_on_invalid_client_secret(self):
with self.assertRaises(ConfigurationError) as error:
parser = CredentialsParser(
client_id="client_id$development$integration_client_id",
client_secret="client_id$development$integration_client_secret"
)
parser.parse_client_credentials()
config_error = error.exception
self.assertIn("Value passed for client_secret is not a client_secret", str(config_error))
def test_parses_access_token(self):
parser = CredentialsParser(
access_token="access_token$development$integration_merchant_id$fb27c79dd"
)
parser.parse_access_token()
self.assertEqual("access_token$development$integration_merchant_id$fb27c79dd", parser.access_token)
self.assertEqual("integration_merchant_id", parser.merchant_id)
self.assertEqual(braintree.Environment.Development, parser.environment)
braintree_python-3.38.0/tests/integration/test_credit_card_verification_search.py 0000644 0001750 0001750 00000013246 13150065776 026733 0 ustar hle hle from tests.test_helper import *
from braintree.test.credit_card_numbers import CreditCardNumbers
class TestVerificationSearch(unittest.TestCase):
def test_advanced_search_no_results(self):
collection = CreditCardVerification.search([
CreditCardVerificationSearch.credit_card_cardholder_name == "no such person"])
self.assertEqual(0, collection.maximum_size)
def test_search_on_verification_id(self):
customer_id = "%s" % random.randint(1, 10000)
result = Customer.create({
"id": customer_id,
"credit_card": {
"expiration_date": "10/2018",
"number": CreditCardNumbers.FailsSandboxVerification.Visa,
"options": {
"verify_card": True
}
}
})
verification_id = result.credit_card_verification.id
found_verifications = CreditCardVerification.search(
CreditCardVerificationSearch.id == verification_id
)
self.assertEqual(1, found_verifications.maximum_size)
self.assertEqual(verification_id, found_verifications.first.id)
def test_all_text_fields(self):
email = "mark.a@example.com"
cardholder_name = "Tom %s" % random.randint(1, 10000)
customer_id = "%s" % random.randint(1, 10000)
expiration_date = "10/2012"
number = CreditCardNumbers.MasterCard
postal_code = "44444"
customer = Customer.create({
"id": customer_id,
"email": email,
"credit_card": {
"cardholder_name": cardholder_name,
"expiration_date": expiration_date,
"number": number,
"billing_address": {
"postal_code": postal_code
},
"options": {
"verify_card": True
}
}
}).customer
found_verifications = CreditCardVerification.search(
CreditCardVerificationSearch.credit_card_expiration_date == expiration_date,
CreditCardVerificationSearch.credit_card_cardholder_name == cardholder_name,
CreditCardVerificationSearch.credit_card_number == number,
CreditCardVerificationSearch.customer_email == email,
CreditCardVerificationSearch.customer_id == customer_id,
CreditCardVerificationSearch.billing_postal_code == postal_code
)
self.assertEqual(1, found_verifications.maximum_size)
self.assertEqual(customer.credit_cards[0].token, found_verifications.first.credit_card["token"])
def test_multiple_value_fields(self):
cardholder_name = "Tom %s" % random.randint(1, 10000)
number = CreditCardNumbers.FailsSandboxVerification.MasterCard
unsuccessful_result1 = Customer.create({"credit_card": {
"cardholder_name": cardholder_name,
"expiration_date": "10/2013",
"number": number,
"options": {"verify_card": True}
}})
cardholder_name = "Tom %s" % random.randint(1, 10000)
number = CreditCardNumbers.FailsSandboxVerification.Visa
unsuccessful_result2 = Customer.create({"credit_card": {
"cardholder_name": cardholder_name,
"expiration_date": "10/2012",
"number": number,
"options": {"verify_card": True}
}})
verification1 = unsuccessful_result1.credit_card_verification
verification2 = unsuccessful_result2.credit_card_verification
search_results = CreditCardVerification.search(
CreditCardVerificationSearch.ids.in_list([
verification1.id, verification2.id]),
CreditCardVerificationSearch.credit_card_card_type.in_list([
verification1.credit_card["card_type"], verification2.credit_card["card_type"]]),
CreditCardVerificationSearch.status.in_list([
verification1.status, verification2.status])
)
self.assertEqual(2, search_results.maximum_size)
def test_range_field(self):
cardholder_name = "Tom %s" % random.randint(1, 10000)
number = CreditCardNumbers.FailsSandboxVerification.MasterCard
unsuccessful_result = Customer.create({"credit_card": {
"cardholder_name": cardholder_name,
"expiration_date": "10/2013",
"number": number,
"options": {"verify_card": True}
}})
created_verification = unsuccessful_result.credit_card_verification
created_time = created_verification.created_at
before_creation = created_time - timedelta(minutes=10)
after_creation = created_time + timedelta(minutes=10)
found_verifications = CreditCardVerification.search(
CreditCardVerificationSearch.id == created_verification.id,
CreditCardVerificationSearch.created_at.between(before_creation, after_creation))
self.assertEqual(1, found_verifications.maximum_size)
way_before_creation = created_time - timedelta(minutes=10)
just_before_creation = created_time - timedelta(minutes=1)
found_verifications = CreditCardVerification.search(
CreditCardVerificationSearch.id == created_verification.id,
CreditCardVerificationSearch.created_at.between(way_before_creation, just_before_creation))
self.assertEqual(0, found_verifications.maximum_size)
found_verifications = CreditCardVerification.search(
CreditCardVerificationSearch.id == created_verification.id,
CreditCardVerificationSearch.created_at == created_time)
self.assertEqual(1, found_verifications.maximum_size)
braintree_python-3.38.0/tests/integration/test_test_helper.py 0000644 0001750 0001750 00000002226 13150065776 022713 0 ustar hle hle from tests.test_helper import *
from braintree.test.nonces import Nonces
class TestTestHelper(unittest.TestCase):
def setUp(self):
self.transaction = Transaction.sale({
"credit_card": {
"number": "4111111111111111",
"expiration_date": "05/2010",
"cvv": "100"
},
"amount": "100.00",
"options": {
"submit_for_settlement": "true"
}
}).transaction
def test_settle_transaction_settles_transaction(self):
TestHelper.settle_transaction(self.transaction.id)
self.assertEqual(Transaction.Status.Settled, Transaction.find(self.transaction.id).status)
def test_settlement_confirm_transaction(self):
TestHelper.settlement_confirm_transaction(self.transaction.id)
self.assertEqual(Transaction.Status.SettlementConfirmed, Transaction.find(self.transaction.id).status)
def test_settlement_decline_transaction(self):
TestHelper.settlement_decline_transaction(self.transaction.id)
self.assertEqual(Transaction.Status.SettlementDeclined, Transaction.find(self.transaction.id).status)
braintree_python-3.38.0/tests/test_helper.py 0000644 0001750 0001750 00000041420 13150065776 017330 0 ustar hle hle import json
import os
import re
import random
import sys
import unittest
import warnings
import subprocess
if sys.version_info[0] == 2:
from urllib import urlencode, quote_plus
from httplib import HTTPConnection
else:
from urllib.parse import urlencode, quote_plus
from http.client import HTTPConnection
import requests
from base64 import b64decode
from contextlib import contextmanager
from datetime import date, datetime, timedelta
from decimal import Decimal
from subprocess import Popen, PIPE
from nose.tools import make_decorator
from nose.tools import raises
from braintree import *
from braintree.exceptions import *
from braintree.test.nonces import Nonces
from braintree.testing_gateway import *
from braintree.util import *
def raises_with_regexp(expected_exception_class, regexp_to_match):
def decorate(func):
name = func.__name__
def generated_function(*args, **kwargs):
exception_string = None
try:
func(*args, **kwargs)
except expected_exception_class as e:
exception_string = str(e)
except:
raise
if exception_string is None:
message = "%s() did not raise %s" % (name, expected_exception_class.__name__)
raise AssertionError(message)
elif re.match(regexp_to_match, exception_string) is None:
message = "%s() exception message (%s) did not match (%s)" % \
(name, exception_string, regexp_to_match)
raise AssertionError(message)
return make_decorator(func)(generated_function)
return decorate
def reset_braintree_configuration():
Configuration.configure(
Environment.Development,
"integration_merchant_id",
"integration_public_key",
"integration_private_key"
)
reset_braintree_configuration()
def showwarning(*_):
pass
warnings.showwarning = showwarning
class TestHelper(object):
default_merchant_account_id = "sandbox_credit_card"
non_default_merchant_account_id = "sandbox_credit_card_non_default"
non_default_sub_merchant_account_id = "sandbox_sub_merchant_account"
three_d_secure_merchant_account_id = "three_d_secure_merchant_account"
fake_amex_direct_merchant_account_id = "fake_amex_direct_usd"
fake_venmo_account_merchant_account_id = "fake_first_data_venmo_account"
add_on_discount_plan = {
"description": "Plan for integration tests -- with add-ons and discounts",
"id": "integration_plan_with_add_ons_and_discounts",
"price": Decimal("9.99"),
"trial_duration": 2,
"trial_duration_unit": Subscription.TrialDurationUnit.Day,
"trial_period": True
}
billing_day_of_month_plan = {
"description": "Plan for integration tests -- with billing day of month",
"id": "integration_plan_with_billing_day_of_month",
"billing_day_of_month": 5,
"price": Decimal("8.88"),
}
trial_plan = {
"description": "Plan for integration tests -- with trial",
"id": "integration_trial_plan",
"price": Decimal("43.21"),
"trial_period": True,
"trial_duration": 2,
"trial_duration_unit": Subscription.TrialDurationUnit.Day
}
trialless_plan = {
"description": "Plan for integration tests -- without a trial",
"id": "integration_trialless_plan",
"price": Decimal("12.34"),
"trial_period": False
}
valid_token_characters = list("bcdfghjkmnpqrstvwxyz23456789")
text_type = unicode if sys.version_info[0] == 2 else str
raw_type = str if sys.version_info[0] == 2 else bytes
@staticmethod
def make_past_due(subscription, number_of_days_past_due=1):
Configuration.gateway().testing.make_past_due(subscription.id, number_of_days_past_due)
@staticmethod
def escrow_transaction(transaction_id):
Configuration.gateway().testing.escrow_transaction(transaction_id)
@staticmethod
def settle_transaction(transaction_id):
return Configuration.gateway().testing.settle_transaction(transaction_id)
@staticmethod
def settlement_confirm_transaction(transaction_id):
return Configuration.gateway().testing.settlement_confirm_transaction(transaction_id)
@staticmethod
def settlement_decline_transaction(transaction_id):
return Configuration.gateway().testing.settlement_decline_transaction(transaction_id)
@staticmethod
def settlement_pending_transaction(transaction_id):
return Configuration.gateway().testing.settlement_pending_transaction(transaction_id)
@staticmethod
def simulate_tr_form_post(post_params, url=TransparentRedirect.url()):
form_data = urlencode(post_params)
conn = HTTPConnection(Configuration.environment.server_and_port)
conn.request("POST", url, form_data, TestHelper.__headers())
response = conn.getresponse()
query_string = response.getheader("location").split("?", 1)[1]
conn.close()
return query_string
@staticmethod
def create_3ds_verification(merchant_account_id, params):
return Configuration.gateway().testing.create_3ds_verification(merchant_account_id, params)
@staticmethod
@contextmanager
def other_merchant(merchant_id, public_key, private_key):
old_merchant_id = Configuration.merchant_id
old_public_key = Configuration.public_key
old_private_key = Configuration.private_key
Configuration.merchant_id = merchant_id
Configuration.public_key = public_key
Configuration.private_key = private_key
try:
yield
finally:
Configuration.merchant_id = old_merchant_id
Configuration.public_key = old_public_key
Configuration.private_key = old_private_key
@staticmethod
def includes(collection, expected):
for item in collection.items:
if item.id == expected.id:
return True
return False
@staticmethod
def in_list(collection, expected):
for item in collection:
if item == expected:
return True
return False
@staticmethod
def includes_status(collection, status):
for item in collection.items:
if item.status == status:
return True
return False
@staticmethod
def now_minus_offset(offset):
now = datetime.utcnow()
return (now - timedelta(hours=offset)).strftime("%Y-%m-%d")
@staticmethod
def unique(some_list):
return set(some_list)
@staticmethod
def __headers():
return {
"Accept": "application/xml",
"Content-type": "application/x-www-form-urlencoded",
}
@staticmethod
def generate_decoded_client_token(params=None):
client_token = None
if params:
client_token = ClientToken.generate(params)
else:
client_token = ClientToken.generate()
decoded_client_token = b64decode(client_token).decode()
return decoded_client_token
@staticmethod
def nonce_for_paypal_account(paypal_account_details):
client_token = json.loads(TestHelper.generate_decoded_client_token())
client = ClientApiHttp(Configuration.instantiate(), {
"authorization_fingerprint": client_token["authorizationFingerprint"]
})
_, nonce = client.get_paypal_nonce(paypal_account_details)
return nonce
@staticmethod
def random_token_block(x):
string = ""
for i in range(6):
string += random.choice(TestHelper.valid_token_characters)
return string
@staticmethod
def generate_valid_us_bank_account_nonce():
client_token = json.loads(TestHelper.generate_decoded_client_token())
headers = {
"Content-Type": "application/json",
"Braintree-Version": "2015-11-01",
"Authorization": "Bearer " + client_token["braintree_api"]["access_token"]
}
payload = {
"type": "us_bank_account",
"billing_address": {
"street_address": "123 Ave",
"region": "CA",
"locality": "San Francisco",
"postal_code": "94112"
},
"account_type": "checking",
"routing_number": "021000021",
"account_number": "567891234",
"account_holder_name": "Dan Schulman",
"ach_mandate": {
"text": "cl mandate text"
}
}
resp = requests.post(client_token["braintree_api"]["url"] + "/tokens", headers=headers, data=json.dumps(payload) )
respJson = json.loads(resp.text)
return respJson["data"]["id"]
@staticmethod
def generate_invalid_us_bank_account_nonce():
token = "tokenusbankacct"
for i in range(4):
token += "_" + TestHelper.random_token_block('d')
token += "_xxx"
return token
@staticmethod
def generate_valid_ideal_payment_id(amount=TransactionAmounts.Authorize):
client_token = json.loads(TestHelper.generate_decoded_client_token({
"merchant_account_id": "ideal_merchant_account"
}))
client = ClientApiHttp(Configuration.instantiate(), {
"authorization_fingerprint": client_token["authorizationFingerprint"]
})
_, configuration = client.get_configuration()
route_id = json.loads(configuration)["ideal"]["routeId"]
headers = {
"Content-Type": "application/json",
"Braintree-Version": "2015-11-01",
"Authorization": "Bearer " + client_token["braintree_api"]["access_token"]
}
payload = {
"issuer": "RABONL2U",
"order_id": "ABC123",
"amount": amount,
"currency": "EUR",
"route_id": route_id,
"redirect_url": "https://braintree-api.com",
}
resp = requests.post(client_token["braintree_api"]["url"] + "/ideal-payments", headers=headers, data=json.dumps(payload) )
respJson = json.loads(resp.text)
return respJson["data"]["id"]
@staticmethod
def generate_three_d_secure_nonce(gateway, params):
url = gateway.config.base_merchant_path() + "/three_d_secure/create_nonce/" + TestHelper.three_d_secure_merchant_account_id
response = gateway.config.http().post(url, params)
return response["payment_method_nonce"]["nonce"]
@staticmethod
def create_grant(gateway, params):
config = gateway.config
response = config.http().post("/oauth_testing/grants", {
"grant": params
})
return response["grant"]["code"]
@staticmethod
def create_payment_method_grant_fixtures():
config = Configuration(
merchant_id="integration_merchant_public_id",
public_key="oauth_app_partner_user_public_key",
private_key="oauth_app_partner_user_private_key",
environment=Environment.Development
)
gateway = BraintreeGateway(config)
customer = gateway.customer.create().customer
credit_card = gateway.credit_card.create(
params={
"customer_id": customer.id,
"number": "4111111111111111",
"expiration_date": "05/2009",
"billing_address": {
"first_name": "Jon",
"last_name": "Doe",
"postal_code": "95131"
}
}
).credit_card
oauth_app_gateway = BraintreeGateway(
client_id="client_id$development$integration_client_id",
client_secret="client_secret$development$integration_client_secret",
environment=Environment.Development
)
code = TestHelper.create_grant(oauth_app_gateway, {
"merchant_public_id": "integration_merchant_id",
"scope": "grant_payment_method"
})
access_token = oauth_app_gateway.oauth.create_token_from_code({
"code": code
}).credentials.access_token
granting_gateway = BraintreeGateway(
access_token=access_token,
)
return (granting_gateway, credit_card)
class ClientApiHttp(Http):
def __init__(self, config, options):
self.config = config
self.options = options
self.http = Http(config)
@staticmethod
def create():
config = Configuration.instantiate()
client_token = TestHelper.generate_decoded_client_token()
authorization_fingerprint = json.loads(client_token)["authorizationFingerprint"]
return ClientApiHttp(config, {
"authorization_fingerprint": authorization_fingerprint,
"shared_customer_identifier": "fake_identifier",
"shared_customer_identifier_type": "testing"
})
def get(self, path):
return self.__http_do("GET", path)
def post(self, path, params=None):
return self.__http_do("POST", path, params)
def put(self, path, params=None):
return self.__http_do("PUT", path, params)
def __http_do(self, http_verb, path, params=None):
http_strategy = self.config.http_strategy()
request_body = json.dumps(params) if params else None
return http_strategy.http_do(http_verb, path, self.__headers(), (request_body, None))
def set_authorization_fingerprint(self, authorization_fingerprint):
self.options['authorization_fingerprint'] = authorization_fingerprint
def get_configuration(self):
encoded_fingerprint = quote_plus(self.options["authorization_fingerprint"])
url = "/merchants/%s/client_api/v1/configuration" % self.config.merchant_id
url += "?authorizationFingerprint=%s" % encoded_fingerprint
url += "&configVersion=3"
return self.get(url)
def get_cards(self):
encoded_fingerprint = quote_plus(self.options["authorization_fingerprint"])
url = "/merchants/%s/client_api/v1/payment_methods.json" % self.config.merchant_id
url += "?authorizationFingerprint=%s" % encoded_fingerprint
url += "&sharedCustomerIdentifier=%s" % self.options["shared_customer_identifier"]
url += "&sharedCustomerIdentifierType=%s" % self.options["shared_customer_identifier_type"]
return self.get(url)
def add_card(self, params):
url = "/merchants/%s/client_api/v1/payment_methods/credit_cards.json" % self.config.merchant_id
if 'authorization_fingerprint' in self.options:
params['authorizationFingerprint'] = self.options['authorization_fingerprint']
if 'shared_customer_identifier' in self.options:
params['sharedCustomerIdentifier'] = self.options['shared_customer_identifier']
if 'shared_customer_identifier_type' in self.options:
params['sharedCustomerIdentifierType'] = self.options['shared_customer_identifier_type']
return self.post(url, params)
def get_paypal_nonce(self, paypal_params):
url = "/merchants/%s/client_api/v1/payment_methods/paypal_accounts" % self.config.merchant_id
params = {"paypal_account": paypal_params}
if 'authorization_fingerprint' in self.options:
params['authorizationFingerprint'] = self.options['authorization_fingerprint']
status_code, response = self.post(url, params)
nonce = None
if status_code == 202:
nonce = json.loads(response)["paypalAccounts"][0]["nonce"]
return [status_code, nonce]
def get_credit_card_nonce(self, credit_card_params):
url = "/merchants/%s/client_api/v1/payment_methods/credit_cards" % self.config.merchant_id
params = {"credit_card": credit_card_params}
if 'authorization_fingerprint' in self.options:
params['authorizationFingerprint'] = self.options['authorization_fingerprint']
status_code, response = self.post(url, params)
nonce = None
if status_code in [201, 202]:
nonce = json.loads(response)["creditCards"][0]["nonce"]
return [status_code, nonce]
def get_europe_bank_account_nonce(self, europe_bank_account_params):
params = {"sepa_mandate": europe_bank_account_params}
url = "/merchants/%s/client_api/v1/sepa_mandates" % self.config.merchant_id
if 'authorization_fingerprint' in self.options:
params['authorizationFingerprint'] = self.options['authorization_fingerprint']
status_code, response = self.post(url, params)
json_body = json.loads(response)
nonce = None
if status_code == 201:
nonce = json_body["europeBankAccounts"][0]["nonce"]
return nonce
def __headers(self):
return {
"Content-type": "application/json",
"User-Agent": "Braintree Python " + version.Version,
"X-ApiVersion": Configuration.api_version()
}
braintree_python-3.38.0/tests/unit/ 0000755 0001750 0001750 00000000000 13150065776 015416 5 ustar hle hle braintree_python-3.38.0/tests/unit/test_us_bank_account.py 0000644 0001750 0001750 00000003000 13150065776 022156 0 ustar hle hle from tests.test_helper import *
from datetime import date
from braintree.us_bank_account import UsBankAccount
class TestUsBankAccount(unittest.TestCase):
def test_constructor(self):
attributes = {
"last_four": "1234",
"routing_number": "55555",
"account_type": "fake-account",
"account_holder_name": "John Doe",
"token": "7777-7777",
"image_url": "some.png",
"bank_name": "Chase",
"ach_mandate": None,
}
us_bank_account = UsBankAccount({}, attributes)
self.assertEqual(us_bank_account.last_four, "1234")
self.assertEqual(us_bank_account.routing_number, "55555")
self.assertEqual(us_bank_account.account_type, "fake-account")
self.assertEqual(us_bank_account.account_holder_name, "John Doe")
self.assertEqual(us_bank_account.token, "7777-7777")
self.assertEqual(us_bank_account.image_url, "some.png")
self.assertEqual(us_bank_account.bank_name, "Chase")
self.assertEqual(us_bank_account.ach_mandate, None)
attributes["ach_mandate"] = {"text":"Some mandate", "accepted_at": date(2013, 4, 10).strftime("%Y-%m-%dT%H:%M:%S.%fZ")}
us_bank_account_mandated = UsBankAccount({}, attributes)
self.assertEqual(us_bank_account_mandated.ach_mandate.text, "Some mandate")
self.assertEqual(us_bank_account_mandated.ach_mandate.accepted_at.strftime("%Y-%m-%dT%H:%M:%S.%fZ"), date(2013, 4, 10).strftime("%Y-%m-%dT%H:%M:%S.%fZ"))
braintree_python-3.38.0/tests/unit/test_transparent_redirect.py 0000644 0001750 0001750 00000005271 13150065776 023256 0 ustar hle hle from tests.test_helper import *
class TestTransparentRedirect(unittest.TestCase):
def test_tr_data(self):
data = TransparentRedirect.tr_data({"key": "val"}, "http://example.com/path?foo=bar")
self.__assert_valid_tr_data(data)
def __assert_valid_tr_data(self, data):
test_hash, content = data.split("|", 1)
self.assertEqual(test_hash, Crypto.sha1_hmac_hash(Configuration.private_key, content))
@raises(ForgedQueryStringError)
def test_parse_and_validate_query_string_raises_for_invalid_hash(self):
Configuration.gateway().transparent_redirect._parse_and_validate_query_string(
"http_status=200&id=7kdj469tw7yck32j&hash=99c9ff20cd7910a1c1e793ff9e3b2d15586dc6b9"
)
@raises(AuthenticationError)
def test_parse_and_validate_query_string_raises_for_http_status_401(self):
Configuration.gateway().transparent_redirect._parse_and_validate_query_string(
"http_status=401&id=6kdj469tw7yck32j&hash=5a26e3cde5ebedb0ec1ba8d35724360334fbf419"
)
@raises(AuthorizationError)
def test_parse_and_validate_query_string_raises_for_http_status_403(self):
Configuration.gateway().transparent_redirect._parse_and_validate_query_string(
"http_status=403&id=6kdj469tw7yck32j&hash=126d5130b71a4907e460fad23876ed70dd41dcd2"
)
@raises(NotFoundError)
def test_parse_and_validate_query_string_raises_for_http_status_404(self):
Configuration.gateway().transparent_redirect._parse_and_validate_query_string(
"http_status=404&id=6kdj469tw7yck32j&hash=0d3724a45cf1cda5524aa68f1f28899d34d2ff3a"
)
@raises(ServerError)
def test_parse_and_validate_query_string_raises_for_http_status_500(self):
Configuration.gateway().transparent_redirect._parse_and_validate_query_string(
"http_status=500&id=6kdj469tw7yck32j&hash=a839a44ca69d59a3d6f639c294794989676632dc"
)
@raises(DownForMaintenanceError)
def test_parse_and_validate_query_string_raises_for_http_status_503(self):
Configuration.gateway().transparent_redirect._parse_and_validate_query_string(
"http_status=503&id=6kdj469tw7yck32j&hash=1b3d29199a282e63074a7823b76bccacdf732da6"
)
@raises(UnexpectedError)
def test_parse_and_validate_query_string_raises_for_unexpected_http_status(self):
Configuration.gateway().transparent_redirect._parse_and_validate_query_string(
"http_status=600&id=6kdj469tw7yck32j&hash=740633356f93384167d887de0c1d9745e3de8fb6"
)
def test_api_version(self):
data = TransparentRedirect.tr_data({"key": "val"}, "http://example.com/path?foo=bar")
self.assertTrue("api_version=4" in data)
braintree_python-3.38.0/tests/unit/test_xml_util.py 0000644 0001750 0001750 00000014052 13150065776 020666 0 ustar hle hle from tests.test_helper import *
class TestXmlUtil(unittest.TestCase):
def test_dict_from_xml_simple(self):
xml = """
val
"""
expected = {"container": "val"}
self.assertEqual(expected, XmlUtil.dict_from_xml(xml))
def test_dict_from_xml_typecasts_ints(self):
xml = """
1
"""
expected = {"container": 1}
self.assertEqual(expected, XmlUtil.dict_from_xml(xml))
def test_dict_from_xml_typecasts_nils(self):
xml = """
"""
expected = {"root": {"a_nil_value": None, "an_empty_string": ""}}
self.assertEqual(expected, XmlUtil.dict_from_xml(xml))
def test_dict_from_xml_typecasts_booleans(self):
xml = """
true
1
false
anything
true
"""
expected = {
"root": {
"casted_true": True,
"casted_one": True,
"casted_false": False,
"casted_anything": False,
"uncasted_true": "true"
}
}
self.assertEqual(expected, XmlUtil.dict_from_xml(xml))
def test_dict_from_xml_typecasts_datetimes(self):
xml = """
2009-10-28T10:19:49Z
"""
expected = {"root": {"created_at": datetime(2009, 10, 28, 10, 19, 49)}}
self.assertEqual(expected, XmlUtil.dict_from_xml(xml))
def test_dict_from_xml_with_dashes(self):
xml = """
val
"""
expected = {"my_item": "val"}
self.assertEqual(expected, XmlUtil.dict_from_xml(xml))
def test_dict_from_xml_nested(self):
xml = """
val
"""
expected = {"container": {"elem": "val"}}
self.assertEqual(expected, XmlUtil.dict_from_xml(xml))
def test_dict_from_xml_array(self):
xml = """
val1
val2
val3
"""
expected = {"container": {"elements": ["val1", "val2", "val3"]}}
self.assertEqual(expected, XmlUtil.dict_from_xml(xml))
def test_dict_from_xml_with_empty_array(self):
xml = """
"""
expected = {"container": {"elements": []}}
self.assertEqual(expected, XmlUtil.dict_from_xml(xml))
def test_dict_from_xml_array_of_hashes(self):
xml = """
val1
val2
val3
"""
expected = {"container": {"elements": [{"val": "val1"}, {"val": "val2"}, {"val": "val3"}]}}
self.assertEqual(expected, XmlUtil.dict_from_xml(xml))
def test_xml_from_dict_escapes_keys_and_values(self):
test_dict = {"kva&lue", XmlUtil.xml_from_dict(test_dict))
def test_xml_from_dict_simple(self):
test_dict = {"a": "b"}
self.assertEqual(test_dict, self.__xml_and_back(test_dict))
def test_xml_from_dict_with_integer(self):
test_dict = {"a": 1}
self.assertEqual('1', XmlUtil.xml_from_dict(test_dict))
def test_xml_from_dict_with_long(self):
test_dict = {"a": 12341234123412341234}
self.assertEqual('12341234123412341234', XmlUtil.xml_from_dict(test_dict))
def test_xml_from_dict_with_boolean(self):
test_dict = {"a": True}
self.assertEqual(test_dict, self.__xml_and_back(test_dict))
def test_xml_from_dict_simple_xml_and_back_twice(self):
test_dict = {"a": "b"}
self.assertEqual(test_dict, self.__xml_and_back(self.__xml_and_back(test_dict)))
def test_xml_from_dict_nested(self):
test_dict = {"container": {"item": "val"}}
self.assertEqual(test_dict, self.__xml_and_back(test_dict))
def test_xml_from_dict_with_array(self):
test_dict = {"container": {"elements": ["val1", "val2", "val3"]}}
self.assertEqual(test_dict, self.__xml_and_back(test_dict))
def test_xml_from_dict_with_array_of_hashes(self):
test_dict = {"container": {"elements": [{"val": "val1"}, {"val": "val2"}, {"val": "val3"}]}}
self.assertEqual(test_dict, self.__xml_and_back(test_dict))
def test_xml_from_dict_retains_underscores(self):
test_dict = {"container": {"my_element": "val"}}
self.assertEqual(test_dict, self.__xml_and_back(test_dict))
def test_xml_from_dict_escapes_special_chars(self):
test_dict = {"container": {"element": "<&>'\""}}
self.assertEqual(test_dict, self.__xml_and_back(test_dict))
def test_xml_from_dict_with_datetime(self):
test_dict = {"a": datetime(2010, 1, 2, 3, 4, 5)}
self.assertEqual(test_dict, self.__xml_and_back(test_dict))
def test_xml_from_dict_with_unicode_characters(self):
test_dict = {"a": u"\u1f61hat?"}
self.assertEqual('ὡhat?', XmlUtil.xml_from_dict(test_dict))
def test_xml_from_dict_with_dates_formats_as_datetime(self):
test_dict = {"a": date(2010, 1, 2)}
self.assertEqual('2010-01-02T00:00:00Z', XmlUtil.xml_from_dict(test_dict))
@staticmethod
def __xml_and_back(test_dict):
return XmlUtil.dict_from_xml(XmlUtil.xml_from_dict(test_dict))
braintree_python-3.38.0/tests/unit/test_address.py 0000644 0001750 0001750 00000002445 13150065776 020461 0 ustar hle hle from tests.test_helper import *
class TestAddress(unittest.TestCase):
@raises_with_regexp(KeyError, "'Invalid keys: bad_key'")
def test_create_raise_exception_with_bad_keys(self):
Address.create({"customer_id": "12345", "bad_key": "value"})
@raises_with_regexp(KeyError, "'customer_id must be provided'")
def test_create_raises_error_if_no_customer_id_given(self):
Address.create({"country_name": "United States of America"})
@raises_with_regexp(KeyError, "'customer_id contains invalid characters'")
def test_create_raises_key_error_if_given_invalid_customer_id(self):
Address.create({"customer_id": "!@#$%"})
@raises_with_regexp(KeyError, "'Invalid keys: bad_key'")
def test_update_raise_exception_with_bad_keys(self):
Address.update("customer_id", "address_id", {"bad_key": "value"})
@raises(NotFoundError)
def test_finding_address_with_empty_customer_id_raises_not_found_exception(self):
Address.find(" ", "address_id")
@raises(NotFoundError)
def test_finding_address_with_none_customer_id_raises_not_found_exception(self):
Address.find(None, "address_id")
@raises(NotFoundError)
def test_finding_address_with_empty_address_id_raises_not_found_exception(self):
Address.find("customer_id", " ")
braintree_python-3.38.0/tests/unit/test_credit_card_verification.py 0000644 0001750 0001750 00000003007 13150065776 024034 0 ustar hle hle from tests.test_helper import *
class TestCreditCardVerification(unittest.TestCase):
@raises_with_regexp(KeyError, "'Invalid keys: bad_key'")
def test_create_raises_exception_with_bad_keys(self):
CreditCardVerification.create({"bad_key": "value", "credit_card": {"number": "value"}})
def test_constructor_with_amount(self):
attributes = {
'amount': '27.00',
'currency_iso_code': 'USD'
}
verification = CreditCardVerification(None, attributes)
self.assertEqual(verification.amount, Decimal('27.00'))
self.assertEqual(verification.currency_iso_code, 'USD')
def test_constructor_with_bad_amount(self):
attributes = {
'amount': None
}
verification = CreditCardVerification(None, attributes)
self.assertEqual(verification.amount, None)
def test_constructor_without_amount(self):
verification = CreditCardVerification(None, {})
self.assertEqual(verification.amount, None)
self.assertEqual(verification.currency_iso_code, None)
def test_constructor_when_risk_data_is_not_included(self):
verification = CreditCardVerification(None, {"amount": "1.00"})
self.assertEqual(verification.risk_data, None)
@raises(NotFoundError)
def test_finding_empty_id_raises_not_found_exception(self):
CreditCardVerification.find(" ")
@raises(NotFoundError)
def test_finding_none_raises_not_found_exception(self):
CreditCardVerification.find(None)
braintree_python-3.38.0/tests/unit/test_client_token.py 0000644 0001750 0001750 00000001350 13150065776 021504 0 ustar hle hle from tests.test_helper import *
class TestClientToken(unittest.TestCase):
def test_credit_card_options_require_customer_id(self):
for option in ["verify_card", "make_default", "fail_on_duplicate_payment_method"]:
with self.assertRaisesRegexp(InvalidSignatureError, option):
ClientToken.generate({
"options": {option: True}
})
def test_generate_delegates_client_token_generation_to_gateway(self):
class MockGateway:
def generate(self, _):
return "mock_client_token"
mock_gateway = MockGateway()
client_token = ClientToken.generate({}, mock_gateway)
self.assertEqual("mock_client_token", client_token)
braintree_python-3.38.0/tests/unit/test_unknown_payment_method.py 0000644 0001750 0001750 00000000513 13150065776 023622 0 ustar hle hle from tests.test_helper import *
class TestUnknownPaymentMethod(unittest.TestCase):
def test_image_url(self):
unknown_payment_method = UnknownPaymentMethod("gateway", {"token": "TOKEN"})
self.assertEqual("https://assets.braintreegateway.com/payment_method_logo/unknown.png", unknown_payment_method.image_url())
braintree_python-3.38.0/tests/unit/test_search.py 0000644 0001750 0001750 00000012536 13150065776 020303 0 ustar hle hle from tests.test_helper import *
class TestSearch(unittest.TestCase):
def test_text_node_is(self):
node = Search.TextNodeBuilder("name")
self.assertEqual({"is": "value"}, (node == "value").to_param())
def test_text_node_is_not(self):
node = Search.TextNodeBuilder("name")
self.assertEqual({"is_not": "value"}, (node != "value").to_param())
def test_text_node_starts_with(self):
node = Search.TextNodeBuilder("name")
self.assertEqual({"starts_with": "value"}, (node.starts_with("value")).to_param())
def test_text_node_ends_with(self):
node = Search.TextNodeBuilder("name")
self.assertEqual({"ends_with": "value"}, (node.ends_with("value")).to_param())
def test_text_node_contains(self):
node = Search.TextNodeBuilder("name")
self.assertEqual({"contains": "value"}, (node.contains("value")).to_param())
def test_multiple_value_node_in_list(self):
node = Search.MultipleValueNodeBuilder("name")
self.assertEqual(["value1", "value2"], (node.in_list(["value1", "value2"])).to_param())
def test_multiple_value_node_in_list_as_arg_list(self):
node = Search.MultipleValueNodeBuilder("name")
self.assertEqual(["value1", "value2"], (node.in_list("value1", "value2")).to_param())
def test_multiple_value_node_is(self):
node = Search.MultipleValueNodeBuilder("name")
self.assertEqual(["value1"], (node == "value1").to_param())
def test_multiple_value_node_with_value_in_whitelist(self):
node = Search.MultipleValueNodeBuilder("name", ["okay"])
self.assertEqual(["okay"], (node == "okay").to_param())
@raises(AttributeError)
def test_multiple_value_node_with_value_not_in_whitelist(self):
node = Search.MultipleValueNodeBuilder("name", ["okay", "also okay"])
node == "not okay"
def test_multiple_value_or_text_node_is(self):
node = Search.MultipleValueOrTextNodeBuilder("name")
self.assertEqual({"is": "value"}, (node == "value").to_param())
def test_multiple_value_or_text_node_is_not(self):
node = Search.MultipleValueOrTextNodeBuilder("name")
self.assertEqual({"is_not": "value"}, (node != "value").to_param())
def test_multiple_value_or_text_node_starts_with(self):
node = Search.MultipleValueOrTextNodeBuilder("name")
self.assertEqual({"starts_with": "value"}, (node.starts_with("value")).to_param())
def test_multiple_value_or_text_node_ends_with(self):
node = Search.MultipleValueOrTextNodeBuilder("name")
self.assertEqual({"ends_with": "value"}, (node.ends_with("value")).to_param())
def test_multiple_value_or_text_node_contains(self):
node = Search.MultipleValueOrTextNodeBuilder("name")
self.assertEqual({"contains": "value"}, (node.contains("value")).to_param())
def test_multiple_value_or_text_node_in_list(self):
node = Search.MultipleValueOrTextNodeBuilder("name")
self.assertEqual(["value1", "value2"], (node.in_list(["value1", "value2"])).to_param())
def test_multiple_value_or_text_node_in_list_as_arg_list(self):
node = Search.MultipleValueOrTextNodeBuilder("name")
self.assertEqual(["value1", "value2"], (node.in_list("value1", "value2")).to_param())
def test_multiple_value_or_text_node_with_value_in_whitelist(self):
node = Search.MultipleValueOrTextNodeBuilder("name", ["okay"])
self.assertEqual(["okay"], node.in_list("okay").to_param())
@raises(AttributeError)
def test_multiple_value_or_text_node_with_value_not_in_whitelist(self):
node = Search.MultipleValueOrTextNodeBuilder("name", ["okay"])
node.in_list("not okay").to_param()
def test_range_node_min_ge(self):
node = Search.RangeNodeBuilder("name")
self.assertEqual({"min": "value"}, (node >= "value").to_param())
def test_range_node_min_greater_than_or_equal_to(self):
node = Search.RangeNodeBuilder("name")
self.assertEqual({"min": "value"}, (node.greater_than_or_equal_to("value")).to_param())
def test_range_node_max_le(self):
node = Search.RangeNodeBuilder("name")
self.assertEqual({"max": "value"}, (node <= "value").to_param())
def test_range_node_max_less_than_or_equal_to(self):
node = Search.RangeNodeBuilder("name")
self.assertEqual({"max": "value"}, (node.less_than_or_equal_to("value")).to_param())
def test_range_node_between(self):
node = Search.RangeNodeBuilder("name")
self.assertEqual({"min": "min_value", "max": "max_value"}, (node.between("min_value", "max_value")).to_param())
def test_range_node_is(self):
node = Search.RangeNodeBuilder("name")
self.assertEqual({"is": "value"}, (node == "value").to_param())
def test_key_value_node_is_eq(self):
node = Search.KeyValueNodeBuilder("name")
self.assertTrue((node == True).to_param())
def test_key_value_node_is_equal(self):
node = Search.KeyValueNodeBuilder("name")
self.assertEqual(True, (node.is_equal(True)).to_param())
def test_key_value_node_is_not_equal(self):
node = Search.KeyValueNodeBuilder("name")
self.assertEqual(False, (node.is_not_equal(True)).to_param())
def test_key_value_node_symbols_is_not_equal(self):
node = Search.KeyValueNodeBuilder("name")
self.assertEqual(False, (node != True).to_param())
braintree_python-3.38.0/tests/unit/util/ 0000755 0001750 0001750 00000000000 13150065776 016373 5 ustar hle hle braintree_python-3.38.0/tests/unit/util/__init__.py 0000644 0001750 0001750 00000000000 13150065776 020472 0 ustar hle hle braintree_python-3.38.0/tests/unit/util/test_datetime_parser.py 0000644 0001750 0001750 00000003060 13150065776 023153 0 ustar hle hle import unittest
from braintree.util.datetime_parser import parse_datetime as parse
from datetime import datetime
class TestDateParser(unittest.TestCase):
def test_parses_with_zulu_and_symbols(self):
self.assertEqual(parse('2017-04-19T18:51:21Z'), datetime(2017, 4, 19, 18, 51, 21))
self.assertEqual(parse('2017-04-19T18:51:21.45Z'), datetime(2017, 4, 19, 18, 51, 21, 450000))
def test_parses_with_zulu_and_no_symbols(self):
self.assertEqual(parse('20170419T185121Z'), datetime(2017, 4, 19, 18, 51, 21))
self.assertEqual(parse('20170419T185121.123Z'), datetime(2017, 4, 19, 18, 51, 21, 123000))
def test_parses_with_zero_offset(self):
self.assertEqual(parse('2017-04-19T18:51:21+00:00'), datetime(2017, 4, 19, 18, 51, 21))
self.assertEqual(parse('2017-04-19T18:51:21.420+00:00'), datetime(2017, 4, 19, 18, 51, 21, 420000))
def test_parses_with_negative_offset(self):
self.assertEqual(parse('2017-04-19T18:51:21-01:30'), datetime(2017, 4, 19, 20, 21, 21))
self.assertEqual(parse('2017-04-19T18:51:21.987-01:30'), datetime(2017, 4, 19, 20, 21, 21, 987000))
def test_parses_with_positive_offset(self):
self.assertEqual(parse('2017-04-19T18:51:21+07:00'), datetime(2017, 4, 19, 11, 51, 21))
self.assertEqual(parse('2017-04-19T18:51:21.765+07:00'), datetime(2017, 4, 19, 11, 51, 21, 765000))
def test_raises_with_bad_input(self):
with self.assertRaises(ValueError):
parse('20170420')
with self.assertRaises(ValueError):
parse('20170420Z')
braintree_python-3.38.0/tests/unit/util/test_constants.py 0000644 0001750 0001750 00000000426 13150065776 022022 0 ustar hle hle from tests.test_helper import *
class TestConstants(unittest.TestCase):
def test_get_all_constant_values_from_class(self):
self.assertEqual(["Active", "Canceled", "Expired", "Past Due", "Pending"], Constants.get_all_constant_values_from_class(Subscription.Status))
braintree_python-3.38.0/tests/unit/test_errors.py 0000644 0001750 0001750 00000004300 13150065776 020340 0 ustar hle hle from tests.test_helper import *
class TestErrors(unittest.TestCase):
def test_errors_for_the_given_scope(self):
errors = Errors({"level1": {"errors": [{"code": "code1", "attribute": "attr", "message": "message"}]}})
self.assertEqual(1, errors.for_object("level1").size)
self.assertEqual(1, len(errors.for_object("level1")))
def test_for_object_returns_empty_errors_collection_if_no_errors_at_given_scope(self):
errors = Errors({"level1": {"errors": [{"code": "code1", "attribute": "attr", "message": "message"}]}})
self.assertEqual(0, errors.for_object("no_errors_here").size)
self.assertEqual(0, len(errors.for_object("no_errors_here")))
def test_size_returns_number_of_errors_at_first_level_if_only_one_level_exists(self):
test_hash = {
"level1": {"errors": [{"code": "code1", "attribute": "attr", "message": "message"}]}
}
self.assertEqual(1, Errors(test_hash).size)
self.assertEqual(1, len(Errors(test_hash)))
def test_size_returns_number_of_errors_at_all_levels(self):
test_hash = {
"level1": {
"errors": [{"code": "code1", "attribute": "attr", "message": "message"}],
"level2": {
"errors": [
{"code": "code2", "attribute": "attr", "message": "message"},
{"code": "code3", "attribute": "attr", "message": "message"}
]
}
}
}
self.assertEqual(3, Errors(test_hash).size)
self.assertEqual(3, len(Errors(test_hash)))
def test_deep_errors_returns_all_errors(self):
test_hash = {
"level1": {
"errors": [{"code": "code1", "attribute": "attr", "message": "message"}],
"level2": {
"errors": [
{"code": "code2", "attribute": "attr", "message": "message"},
{"code": "code3", "attribute": "attr", "message": "message"}
]
}
}
}
errors = Errors(test_hash).deep_errors
self.assertEqual(["code1", "code2", "code3"], [error.code for error in errors])
braintree_python-3.38.0/tests/unit/merchant_account/ 0000755 0001750 0001750 00000000000 13150065776 020733 5 ustar hle hle braintree_python-3.38.0/tests/unit/merchant_account/test_funding_details.py 0000644 0001750 0001750 00000001275 13150065776 025510 0 ustar hle hle from tests.test_helper import *
from braintree.merchant_account.funding_details import FundingDetails
class TestFundingDetails(unittest.TestCase):
def test_repr_has_all_fields(self):
details = FundingDetails({
"destination": "bank",
"routing_number": "11112222",
"account_number_last_4": "3333",
"email": "lucyloo@work.com",
"mobile_phone": "9998887777"
})
regex = r""
matches = re.match(regex, repr(details))
self.assertTrue(matches)
braintree_python-3.38.0/tests/unit/merchant_account/test_individual_details.py 0000644 0001750 0001750 00000001577 13150065776 026213 0 ustar hle hle from tests.test_helper import *
from braintree.merchant_account.individual_details import IndividualDetails
class TestIndividualDetails(unittest.TestCase):
def test_repr_has_all_fields(self):
details = IndividualDetails({
"first_name": "Sue",
"last_name": "Smith",
"email": "sue@hotmail.com",
"phone": "1112223333",
"date_of_birth": "1980-12-05",
"ssn_last_4": "5555",
"address": {
"street_address": "123 First St",
}
})
regex = r"} at \w+>"
matches = re.match(regex, repr(details))
self.assertTrue(matches)
braintree_python-3.38.0/tests/unit/merchant_account/__init__.py 0000644 0001750 0001750 00000000000 13150065776 023032 0 ustar hle hle braintree_python-3.38.0/tests/unit/merchant_account/test_address_details.py 0000644 0001750 0001750 00000001127 13150065776 025477 0 ustar hle hle from tests.test_helper import *
from braintree.merchant_account.address_details import AddressDetails
class TestAddressDetails(unittest.TestCase):
def test_repr_has_all_fields(self):
details = AddressDetails({
"street_address": "123 First St",
"region": "Las Vegas",
"locality": "NV",
"postal_code": "89913"
})
regex = r""
matches = re.match(regex, repr(details))
self.assertTrue(matches)
braintree_python-3.38.0/tests/unit/merchant_account/test_business_details.py 0000644 0001750 0001750 00000001527 13150065776 025711 0 ustar hle hle from tests.test_helper import *
from braintree.merchant_account.business_details import BusinessDetails
class TestBusinessDetails(unittest.TestCase):
def test_repr_has_all_fields(self):
details = BusinessDetails({
"dba_name": "Bar Suenami",
"legal_name": "Suenami Restaurant Group",
"tax_id": "123001234",
"address": {
"street_address": "123 First St",
"region": "Las Vegas",
"locality": "NV",
}
})
regex = r"} at \w+>"
matches = re.match(regex, repr(details))
self.assertTrue(matches)
braintree_python-3.38.0/tests/unit/__init__.py 0000644 0001750 0001750 00000000000 13150065776 017515 0 ustar hle hle braintree_python-3.38.0/tests/unit/test_dispute.py 0000644 0001750 0001750 00000024231 13150065776 020506 0 ustar hle hle from tests.test_helper import *
from datetime import date
from braintree.dispute import Dispute
class TestDispute(unittest.TestCase):
legacy_attributes = {
"transaction": {
"id": "transaction_id",
"amount": "100.00",
},
"id": "123456",
"currency_iso_code": "USD",
"status": "open",
"amount": "100.00",
"received_date": date(2013, 4, 10),
"reply_by_date": date(2013, 4, 10),
"reason": "fraud",
"transaction_ids": ["asdf", "qwer"],
"date_opened": date(2013, 4, 1),
"date_won": date(2013, 4, 2),
"kind": "chargeback",
}
attributes = {
"amount": "100.00",
"amount_disputed": "100.00",
"amount_won": "0.00",
"case_number": "CB123456",
"created_at": datetime(2013, 4, 10, 10, 50, 39),
"currency_iso_code": "USD",
"date_opened": date(2013, 4, 1),
"date_won": date(2013, 4, 2),
"forwarded_comments": "Forwarded comments",
"id": "123456",
"kind": "chargeback",
"merchant_account_id": "abc123",
"original_dispute_id": "original_dispute_id",
"reason": "fraud",
"reason_code": "83",
"reason_description": "Reason code 83 description",
"received_date": date(2013, 4, 10),
"reference_number": "123456",
"reply_by_date": date(2013, 4, 17),
"status": "open",
"updated_at": datetime(2013, 4, 10, 10, 50, 39),
"evidence": [{
"comment": None,
"created_at": datetime(2013, 4, 11, 10, 50, 39),
"id": "evidence1",
"sent_to_processor_at": None,
"url": "url_of_file_evidence",
},{
"comment": "text evidence",
"created_at": datetime(2013, 4, 11, 10, 50, 39),
"id": "evidence2",
"sent_to_processor_at": "2009-04-11",
"url": None,
}],
"status_history": [{
"effective_date": "2013-04-10",
"status": "open",
"timestamp": datetime(2013, 4, 10, 10, 50, 39),
}],
"transaction": {
"id": "transaction_id",
"amount": "100.00",
"created_at": datetime(2013, 3, 19, 10, 50, 39),
"order_id": None,
"purchase_order_number": "po",
"payment_instrument_subtype": "Visa",
},
}
def test_legacy_constructor(self):
dispute = Dispute(dict(self.legacy_attributes))
self.assertEqual(dispute.id, "123456")
self.assertEqual(dispute.amount, Decimal("100.00"))
self.assertEqual(dispute.currency_iso_code, "USD")
self.assertEqual(dispute.reason, Dispute.Reason.Fraud)
self.assertEqual(dispute.status, Dispute.Status.Open)
self.assertEqual(dispute.transaction_details.id, "transaction_id")
self.assertEqual(dispute.transaction_details.amount, Decimal("100.00"))
self.assertEqual(dispute.date_opened, date(2013, 4, 1))
self.assertEqual(dispute.date_won, date(2013, 4, 2))
self.assertEqual(dispute.kind, Dispute.Kind.Chargeback)
def test_legacy_params_with_new_attributes(self):
dispute = Dispute(dict(self.attributes))
self.assertEqual(dispute.id, "123456")
self.assertEqual(dispute.amount, Decimal("100.00"))
self.assertEqual(dispute.currency_iso_code, "USD")
self.assertEqual(dispute.reason, Dispute.Reason.Fraud)
self.assertEqual(dispute.status, Dispute.Status.Open)
self.assertEqual(dispute.transaction_details.id, "transaction_id")
self.assertEqual(dispute.transaction_details.amount, Decimal("100.00"))
self.assertEqual(dispute.date_opened, date(2013, 4, 1))
self.assertEqual(dispute.date_won, date(2013, 4, 2))
self.assertEqual(dispute.kind, Dispute.Kind.Chargeback)
def test_constructor_populates_new_fields(self):
attributes = dict(self.attributes)
del attributes["amount"]
dispute = Dispute(attributes)
self.assertEqual(dispute.amount_disputed, 100.0)
self.assertEqual(dispute.amount_won, 0.00)
self.assertEqual(dispute.case_number, "CB123456")
self.assertEqual(dispute.created_at, datetime(2013, 4, 10, 10, 50, 39))
self.assertEqual(dispute.forwarded_comments, "Forwarded comments")
self.assertEqual(dispute.merchant_account_id, "abc123")
self.assertEqual(dispute.original_dispute_id, "original_dispute_id")
self.assertEqual(dispute.reason_code, "83")
self.assertEqual(dispute.reason_description, "Reason code 83 description")
self.assertEqual(dispute.reference_number, "123456")
self.assertEqual(dispute.updated_at, datetime(2013, 4, 10, 10, 50, 39))
self.assertIsNone(dispute.evidence[0].comment)
self.assertEqual(dispute.evidence[0].created_at, datetime(2013, 4, 11, 10, 50, 39))
self.assertEqual(dispute.evidence[0].id, "evidence1")
self.assertIsNone(dispute.evidence[0].sent_to_processor_at)
self.assertEqual(dispute.evidence[0].url, "url_of_file_evidence")
self.assertEqual(dispute.evidence[1].comment, "text evidence")
self.assertEqual(dispute.evidence[1].created_at, datetime(2013, 4, 11, 10, 50, 39))
self.assertEqual(dispute.evidence[1].id, "evidence2")
self.assertEqual(dispute.evidence[1].sent_to_processor_at, "2009-04-11")
self.assertIsNone(dispute.evidence[1].url)
self.assertEqual(dispute.status_history[0].effective_date, "2013-04-10")
self.assertEqual(dispute.status_history[0].status, "open")
self.assertEqual(dispute.status_history[0].timestamp, datetime(2013, 4, 10, 10, 50, 39))
def test_constructor_handles_none_fields(self):
attributes = dict(self.attributes)
attributes.update({
"amount": None,
"date_opened": None,
"date_won": None,
"evidence": None,
"reply_by_date": None,
"status_history": None
})
dispute = Dispute(attributes)
self.assertIsNone(dispute.reply_by_date)
self.assertIsNone(dispute.amount)
self.assertIsNone(dispute.date_opened)
self.assertIsNone(dispute.date_won)
self.assertIsNone(dispute.status_history)
def test_constructor_populates_transaction(self):
dispute = Dispute(dict(self.attributes))
self.assertEqual(dispute.transaction.id, "transaction_id")
self.assertEqual(dispute.transaction.amount, Decimal("100.00"))
self.assertEqual(dispute.transaction.created_at, datetime(2013, 3, 19, 10, 50, 39))
self.assertIsNone(dispute.transaction.order_id)
self.assertEqual(dispute.transaction.purchase_order_number, "po")
self.assertEqual(dispute.transaction.payment_instrument_subtype, "Visa")
@raises_with_regexp(NotFoundError, "dispute with id None not found")
def test_accept_none_raises_not_found_exception(self):
Dispute.accept(None)
@raises_with_regexp(NotFoundError, "dispute with id ' ' not found")
def test_accept_empty_id_raises_not_found_exception(self):
Dispute.accept(" ")
@raises_with_regexp(NotFoundError, "dispute with id ' ' not found")
def test_add_text_evidence_empty_id_raises_not_found_exception(self):
Dispute.add_text_evidence(" ", "evidence")
@raises_with_regexp(NotFoundError, "dispute with id None not found")
def test_add_text_evidence_none_id_raises_not_found_exception(self):
Dispute.add_text_evidence(None, "evidence")
@raises_with_regexp(ValueError, "content cannot be blank")
def test_add_text_evidence_empty_evidence_raises_value_exception(self):
Dispute.add_text_evidence("dispute_id", " ")
@raises_with_regexp(ValueError, "content cannot be blank")
def test_add_text_evidence_none_evidence_raises_value_exception(self):
Dispute.add_text_evidence("dispute_id", None)
@raises_with_regexp(NotFoundError, "dispute with id ' ' not found")
def test_add_file_evidence_empty_id_raises_not_found_exception(self):
Dispute.add_file_evidence(" ", 1)
@raises_with_regexp(NotFoundError, "dispute with id None not found")
def test_add_file_evidence_none_id_raises_not_found_exception(self):
Dispute.add_file_evidence(None, 1)
@raises_with_regexp(ValueError, "document_id cannot be blank")
def test_add_file_evidence_empty_evidence_raises_value_exception(self):
Dispute.add_file_evidence("dispute_id", " ")
@raises_with_regexp(ValueError, "document_id cannot be blank")
def test_add_file_evidence_none_evidence_raises_value_exception(self):
Dispute.add_file_evidence("dispute_id", None)
@raises_with_regexp(NotFoundError, "dispute with id None not found")
def test_finalize_none_raises_not_found_exception(self):
Dispute.finalize(None)
@raises_with_regexp(NotFoundError, "dispute with id ' ' not found")
def test_finalize_empty_id_raises_not_found_exception(self):
Dispute.finalize(" ")
@raises_with_regexp(NotFoundError, "dispute with id None not found")
def test_finding_none_raises_not_found_exception(self):
Dispute.find(None)
@raises_with_regexp(NotFoundError, "dispute with id ' ' not found")
def test_finding_empty_id_raises_not_found_exception(self):
Dispute.find(" ")
@raises_with_regexp(NotFoundError, "evidence with id 'evidence' for dispute with id ' ' not found")
def test_remove_evidence_empty_dispute_id_raises_not_found_exception(self):
Dispute.remove_evidence(" ", "evidence")
@raises_with_regexp(NotFoundError, "evidence with id 'evidence' for dispute with id None not found")
def test_remove_evidence_none_dispute_id_raises_not_found_exception(self):
Dispute.remove_evidence(None, "evidence")
@raises_with_regexp(NotFoundError, "evidence with id None for dispute with id 'dispute_id' not found")
def test_remove_evidence_evidence_none_id_raises_not_found_exception(self):
Dispute.remove_evidence("dispute_id", None)
@raises_with_regexp(NotFoundError, "evidence with id ' ' for dispute with id 'dispute_id' not found")
def test_remove_evidence_empty_evidence_id_raises_value_exception(self):
Dispute.remove_evidence("dispute_id", " ")
braintree_python-3.38.0/tests/unit/test_three_d_secure_info.py 0000644 0001750 0001750 00000001230 13150065776 023016 0 ustar hle hle from tests.test_helper import *
from braintree import *
class TestThreeDSecureInfo(unittest.TestCase):
def test_initialization_of_attributes(self):
three_d_secure_info = ThreeDSecureInfo({
"enrolled": "Y",
"status": "authenticate_successful",
"liability_shifted": True,
"liability_shift_possible": True,
})
self.assertEqual("Y", three_d_secure_info.enrolled)
self.assertEqual("authenticate_successful", three_d_secure_info.status)
self.assertEqual(True, three_d_secure_info.liability_shifted)
self.assertEqual(True, three_d_secure_info.liability_shift_possible)
braintree_python-3.38.0/tests/unit/test_customer.py 0000644 0001750 0001750 00000004453 13150065776 020676 0 ustar hle hle from tests.test_helper import *
class TestCustomer(unittest.TestCase):
@raises_with_regexp(KeyError, "'Invalid keys: bad_key'")
def test_create_raise_exception_with_bad_keys(self):
Customer.create({"bad_key": "value"})
@raises_with_regexp(KeyError, "'Invalid keys: credit_card\[bad_key\]'")
def test_create_raise_exception_with_bad_nested_keys(self):
Customer.create({"credit_card": {"bad_key": "value"}})
@raises_with_regexp(KeyError, "'Invalid keys: bad_key'")
def test_update_raise_exception_with_bad_keys(self):
Customer.update("id", {"bad_key": "value"})
@raises_with_regexp(KeyError, "'Invalid keys: credit_card\[bad_key\]'")
def test_update_raise_exception_with_bad_nested_keys(self):
Customer.update("id", {"credit_card": {"bad_key": "value"}})
@raises_with_regexp(KeyError, "'Invalid keys: bad_key'")
def test_tr_data_for_create_raises_error_with_bad_keys(self):
Customer.tr_data_for_create({"bad_key": "value"}, "http://example.com")
@raises_with_regexp(KeyError, "'Invalid keys: bad_key'")
def test_tr_data_for_update_raises_error_with_bad_keys(self):
Customer.tr_data_for_update({"bad_key": "value"}, "http://example.com")
@raises(NotFoundError)
def test_finding_empty_id_raises_not_found_exception(self):
Customer.find(" ")
@raises(NotFoundError)
def test_finding_none_raises_not_found_exception(self):
Customer.find(None)
def test_initialize_sets_paypal_accounts(self):
customer = Customer("gateway", {
"paypal_accounts": [
{"token": "token1"},
{"token": "token2"}
]
})
self.assertEqual(2, len(customer.paypal_accounts))
self.assertEqual("token1", customer.paypal_accounts[0].token)
self.assertEqual("token2", customer.paypal_accounts[1].token)
def test_initialize_sets_europe_bank_accounts(self):
customer = Customer("gateway", {
"europe_bank_accounts": [
{"token": "token1"},
{"token": "token2"}
]
})
self.assertEqual(2, len(customer.europe_bank_accounts))
self.assertEqual("token1", customer.europe_bank_accounts[0].token)
self.assertEqual("token2", customer.europe_bank_accounts[1].token)
braintree_python-3.38.0/tests/unit/test_validation_error_collection.py 0000644 0001750 0001750 00000012054 13150065776 024607 0 ustar hle hle from tests.test_helper import *
class TestValidationErrorCollection(unittest.TestCase):
def test_it_builds_an_array_of_errors_given_an_array_of_hashes(self):
test_hash = {"errors": [{"attribute": "some model attribute", "code": 1, "message": "bad juju"}]}
errors = ValidationErrorCollection(test_hash)
error = errors[0]
self.assertEqual("some model attribute", error.attribute)
self.assertEqual(1, error.code)
self.assertEqual("bad juju", error.message)
def test_for_object_provides_access_to_nested_attributes(self):
test_hash = {
"errors": [{"attribute": "some model attribute", "code": 1, "message": "bad juju"}],
"nested": {
"errors": [{"attribute": "number", "code": 2, "message": "badder juju"}]
}
}
errors = ValidationErrorCollection(test_hash)
error = errors.for_object("nested").on("number")[0]
self.assertEqual("number", error.attribute)
self.assertEqual(2, error.code)
self.assertEqual("badder juju", error.message)
def test_deep_size_non_nested(self):
test_hash = {
"errors": [
{"attribute": "one", "code": 1, "message": "is too long"},
{"attribute": "two", "code": 2, "message": "contains invalid chars"},
{"attribute": "thr", "code": 3, "message": "is invalid"}
]
}
self.assertEqual(3, ValidationErrorCollection(test_hash).deep_size)
def test_deep_size_nested(self):
test_hash = {
"errors": [{"attribute": "one", "code": 1, "message": "is too long"}],
"nested": {
"errors": [{"attribute": "two", "code": 2, "message": "contains invalid chars"}]
}
}
self.assertEqual(2, ValidationErrorCollection(test_hash).deep_size)
def test_deep_size_multiple_nestings(self):
test_hash = {
"errors": [{"attribute": "one", "code": 1, "message": "is too long"}],
"nested": {
"errors": [{"attribute": "two", "code": 2, "message": "contains invalid chars"}],
"nested_again": {
"errors": [
{"attribute": "three", "code": 3, "message": "super nested"},
{"attribute": "four", "code": 4, "message": "super nested 2"}
]
}
}
}
self.assertEqual(4, ValidationErrorCollection(test_hash).deep_size)
def test_len_multiple_nestings(self):
test_hash = {
"errors": [{"attribute": "one", "code": 1, "message": "is too long"}],
"nested": {
"errors": [{"attribute": "two", "code": 2, "message": "contains invalid chars"}],
"nested_again": {
"errors": [
{"attribute": "three", "code": 3, "message": "super nested"},
{"attribute": "four", "code": 4, "message": "super nested 2"}
]
}
}
}
validation_error_collection = ValidationErrorCollection(test_hash)
self.assertEqual(1, len(validation_error_collection))
self.assertEqual(1, len(validation_error_collection.for_object("nested")))
self.assertEqual(2, len(validation_error_collection.for_object("nested").for_object("nested_again")))
def test_deep_errors(self):
test_hash = {
"errors": [{"attribute": "one", "code": 1, "message": "is too long"}],
"nested": {
"errors": [{"attribute": "two", "code": 2, "message": "contains invalid chars"}],
"nested_again": {
"errors": [
{"attribute": "three", "code": 3, "message": "super nested"},
{"attribute": "four", "code": 4, "message": "super nested 2"}
]
}
}
}
validation_error_collection = ValidationErrorCollection(test_hash)
self.assertEqual([1, 2, 3, 4], [error.code for error in validation_error_collection.deep_errors])
def test_errors(self):
test_hash = {
"errors": [{"attribute": "one", "code": 1, "message": "is too long"}],
"nested": {
"errors": [{"attribute": "two", "code": 2, "message": "contains invalid chars"}],
"nested_again": {
"errors": [
{"attribute": "three", "code": 3, "message": "super nested"},
{"attribute": "four", "code": 4, "message": "super nested 2"}
]
}
}
}
validation_error_collection = ValidationErrorCollection(test_hash)
self.assertEqual([1], [error.code for error in validation_error_collection.errors])
self.assertEqual([2], [error.code for error in validation_error_collection.for_object("nested").errors])
self.assertEqual([3, 4], [error.code for error in validation_error_collection.for_object("nested").for_object("nested_again").errors])
braintree_python-3.38.0/tests/unit/test_disbursement_detail.py 0000644 0001750 0001750 00000002050 13150065776 023052 0 ustar hle hle from tests.test_helper import *
from braintree.disbursement_detail import DisbursementDetail
class TestDisbursementDetail(unittest.TestCase):
def test_is_valid_true(self):
detail_hash = {
'settlement_amount': '27.00',
'settlement_currency_iso_code': 'USD',
'settlement_currency_exchange_rate': '1',
'disbursed_at': datetime(2013, 4, 11, 0, 0, 0),
'disbursement_date': date(2013, 4, 10),
'funds_held': False
}
disbursement_details = DisbursementDetail(detail_hash)
self.assertTrue(disbursement_details.is_valid)
def test_is_valid_false(self):
detail_hash = {
'settlement_amount': None,
'settlement_currency_iso_code': None,
'settlement_currency_exchange_rate': None,
'disbursed_at': None,
'disbursement_date': None,
'funds_held': None
}
disbursement_details = DisbursementDetail(detail_hash)
self.assertEqual(False, disbursement_details.is_valid)
braintree_python-3.38.0/tests/unit/test_partner_merchant.py 0000644 0001750 0001750 00000001555 13150065776 022371 0 ustar hle hle from tests.test_helper import *
class TestPartnerMerchant(unittest.TestCase):
def test_representation(self):
merchant = PartnerMerchant(None, {"partner_merchant_id": "abc123",
"private_key": "my_private_key",
"public_key": "my_public_key",
"merchant_public_id": "foobar",
"client_side_encryption_key": "cse_key"})
self.assertTrue("partner_merchant_id: 'abc123'" in repr(merchant))
self.assertTrue("public_key: 'my_public_key'" in repr(merchant))
self.assertTrue("merchant_public_id: 'foobar'" in repr(merchant))
self.assertTrue("client_side_encryption_key: 'cse_key'" in repr(merchant))
self.assertFalse("private_key: 'my_private_key'" in repr(merchant))
braintree_python-3.38.0/tests/unit/test_successful_result.py 0000644 0001750 0001750 00000000466 13150065776 022612 0 ustar hle hle from tests.test_helper import *
class TestSuccessfulResult(unittest.TestCase):
def test_is_success(self):
self.assertTrue(SuccessfulResult({}).is_success)
def test_attributes_are_exposed(self):
result = SuccessfulResult({"name": "drew"})
self.assertEqual("drew", result.name)
braintree_python-3.38.0/tests/unit/test_ideal_payment.py 0000644 0001750 0001750 00000001711 13150065776 021642 0 ustar hle hle from tests.test_helper import *
from datetime import date
from braintree.ideal_payment import IdealPayment
class TestIdealPayment(unittest.TestCase):
def test_constructor(self):
attributes = {
"ideal_payment_id": "idealpayment_abc_123",
"ideal_transaction_id": "1150000008857321",
"image_url": "12************7890",
"masked_iban": "RABONL2U",
"bic": "http://www.example.com/ideal.png",
}
ideal_payment_details = IdealPayment({}, attributes)
self.assertEqual(ideal_payment_details.ideal_payment_id, "idealpayment_abc_123")
self.assertEqual(ideal_payment_details.ideal_transaction_id, "1150000008857321")
self.assertEqual(ideal_payment_details.image_url, "12************7890")
self.assertEqual(ideal_payment_details.masked_iban, "RABONL2U")
self.assertEqual(ideal_payment_details.bic, "http://www.example.com/ideal.png")
braintree_python-3.38.0/tests/unit/test_environment.py 0000644 0001750 0001750 00000004367 13150065776 021405 0 ustar hle hle from tests.test_helper import *
class TestEnvironment(unittest.TestCase):
def test_server_and_port_for_development(self):
port = os.getenv("GATEWAY_PORT") or "3000"
self.assertEqual("localhost:" + port, Environment.Development.server_and_port)
def test_base_url(self):
self.assertEqual("https://api.sandbox.braintreegateway.com:443", Environment.Sandbox.base_url)
self.assertEqual("https://api.braintreegateway.com:443", Environment.Production.base_url)
def test_server_and_port_for_sandbox(self):
self.assertEqual("api.sandbox.braintreegateway.com:443", Environment.Sandbox.server_and_port)
def test_server_and_port_for_production(self):
self.assertEqual("api.braintreegateway.com:443", Environment.Production.server_and_port)
def test_server_for_development(self):
self.assertEqual("localhost", Environment.Development.server)
def test_server_for_sandbox(self):
self.assertEqual("api.sandbox.braintreegateway.com", Environment.Sandbox.server)
def test_server_for_production(self):
self.assertEqual("api.braintreegateway.com", Environment.Production.server)
def test_port_for_development(self):
port = os.getenv("GATEWAY_PORT") or "3000"
port = int(port)
self.assertEqual(port, Environment.Development.port)
def test_port_for_sandbox(self):
self.assertEqual(443, Environment.Sandbox.port)
def test_port_for_production(self):
self.assertEqual(443, Environment.Production.port)
def test_is_ssl_for_development(self):
self.assertFalse(Environment.Development.is_ssl)
def test_is_ssl_for_sandbox(self):
self.assertTrue(Environment.Sandbox.is_ssl)
def test_is_ssl_for_production(self):
self.assertTrue(Environment.Production.is_ssl)
def test_protocol_for_development(self):
self.assertEqual("http://", Environment.Development.protocol)
def test_protocol_for_sandbox(self):
self.assertEqual("https://", Environment.Sandbox.protocol)
def test_protocol_for_production(self):
self.assertEqual("https://", Environment.Production.protocol)
def test_ssl_certificate_for_development(self):
self.assertEqual(None, Environment.Development.ssl_certificate)
braintree_python-3.38.0/tests/unit/test_setup.py 0000644 0001750 0001750 00000002230 13150065776 020164 0 ustar hle hle from tests.test_helper import *
import os
class TestSetup(unittest.TestCase):
def test_packages_includes_all_packages(self):
with open('setup.py', 'r') as f:
setup_contents = f.read()
packages_line = re.findall('packages=.*', setup_contents)
packages_from_setup = re.findall('"(.*?)"', str(packages_line))
packages_from_directories = ['braintree']
directories_that_dont_have_packages = ['braintree.ssl']
for dirname, dirnames, _ in os.walk('braintree'):
for subdirname in dirnames:
package_from_directory = re.sub('/', '.', os.path.join(dirname, subdirname))
if package_from_directory not in directories_that_dont_have_packages and subdirname != '__pycache__':
packages_from_directories.append(package_from_directory)
mismatch_message = "List of packages in setup.py doesn't match subdirectories of 'braintree' - " \
+ "add your new directory to 'packages, or if none, `git clean -df` to remove a stale directory"
self.assertEqual(sorted(packages_from_directories), sorted(packages_from_setup), mismatch_message)
braintree_python-3.38.0/tests/unit/test_payment_method_gateway.py 0000644 0001750 0001750 00000015745 13150065776 023601 0 ustar hle hle from tests.test_helper import *
from braintree.payment_method_gateway import PaymentMethodGateway
if sys.version_info[0] == 2:
from mock import MagicMock
else:
from unittest.mock import MagicMock
class TestPaymentMethodGateway(unittest.TestCase):
def test_parse_response_returns_a_credit_card(self):
payment_method_gateway = PaymentMethodGateway(BraintreeGateway(None))
credit_card = payment_method_gateway._parse_payment_method({
"credit_card": {"bin": "411111", "last_4": "1111"}
})
self.assertEqual(CreditCard, credit_card.__class__)
self.assertEqual("411111", credit_card.bin)
self.assertEqual("1111", credit_card.last_4)
def test_parse_response_returns_a_paypal_account(self):
payment_method_gateway = PaymentMethodGateway(BraintreeGateway(None))
paypal_account = payment_method_gateway._parse_payment_method({
"paypal_account": {"token": "1234", "default": False}
})
self.assertEqual(PayPalAccount, paypal_account.__class__)
self.assertEqual("1234", paypal_account.token)
self.assertFalse(paypal_account.default)
def test_parse_response_returns_an_unknown_payment_method(self):
payment_method_gateway = PaymentMethodGateway(BraintreeGateway(None))
unknown_payment_method = payment_method_gateway._parse_payment_method({
"new_fancy_payment_method": {
"token": "1234",
"default": True,
"other_fancy_thing": "is-shiny"
}
})
self.assertEqual(UnknownPaymentMethod, unknown_payment_method.__class__)
self.assertEqual("1234", unknown_payment_method.token)
self.assertTrue(unknown_payment_method.default)
def test_create_signature(self):
actual_signature = PaymentMethod.signature("create")
expected_signature = [
"billing_address_id",
"cardholder_name",
"customer_id",
"cvv",
"device_data",
"device_session_id",
"expiration_date",
"expiration_month",
"expiration_year",
"number",
"payment_method_nonce",
"token",
{
"billing_address": Address.create_signature()},
{
"options": [
"fail_on_duplicate_payment_method",
"make_default",
"verification_merchant_account_id",
"verify_card",
"verification_amount",
{
"adyen":[
"overwrite_brand",
"selected_brand"
]
},
{
"paypal":[
"payee_email",
"order_id",
"custom_field",
"description",
"amount",
]
},
]
}
]
self.assertEqual(expected_signature, actual_signature)
def test_update_signature(self):
actual_signature = PaymentMethod.update_signature()
expected_signature = [
"billing_address_id",
"cardholder_name",
"cvv",
"device_session_id",
"expiration_date",
"expiration_month",
"expiration_year",
"number",
"token",
"venmo_sdk_payment_method_code",
"device_data",
"fraud_merchant_id",
"payment_method_nonce",
{
"options": [
"make_default",
"verify_card",
"verification_amount",
"verification_merchant_account_id",
"venmo_sdk_session",
{
"adyen":[
"overwrite_brand",
"selected_brand"
]
}
]
},
{
"billing_address" : Address.update_signature() + [{"options": ["update_existing"]}]
}
]
self.assertEqual(expected_signature, actual_signature)
def test_nonce_grant_params(self):
"""
We validate parameters to PaymentMethod.grant properly
"""
payment_method_gateway = PaymentMethodGateway(BraintreeGateway(None))
options = { "include_billing_postal_code": True }
with self.assertRaises(ValueError):
payment_method_gateway.grant("", options)
with self.assertRaises(ValueError):
payment_method_gateway.grant("\t", False)
with self.assertRaises(ValueError):
payment_method_gateway.grant(None, True)
def test_nonce_revoke_params(self):
payment_method_gateway = PaymentMethodGateway(BraintreeGateway(None))
with self.assertRaises(ValueError):
payment_method_gateway.revoke("")
with self.assertRaises(ValueError):
payment_method_gateway.revoke("\t")
with self.assertRaises(ValueError):
payment_method_gateway.revoke(None)
def test_delete_with_revoke_all_grants_value_as_true(self):
payment_method_gateway, http_mock = self.setup_payment_method_gateway_and_mock_http()
payment_method_gateway.delete("some_token", {"revoke_all_grants": True})
self.assertTrue("delete('/merchants/integration_merchant_id/payment_methods/any/some_token?revoke_all_grants=true')" in str(http_mock.mock_calls))
def test_delete_with_revoke_all_grants_value_as_false(self):
payment_method_gateway, http_mock = self.setup_payment_method_gateway_and_mock_http()
payment_method_gateway.delete("some_token", {"revoke_all_grants": False})
self.assertTrue("delete('/merchants/integration_merchant_id/payment_methods/any/some_token?revoke_all_grants=false')" in str(http_mock.mock_calls))
def test_delete_without_revoke_all_grants(self):
payment_method_gateway, http_mock = self.setup_payment_method_gateway_and_mock_http()
payment_method_gateway.delete("some_token")
self.assertTrue("delete('/merchants/integration_merchant_id/payment_methods/any/some_token')" in str(http_mock.mock_calls))
def test_delete_with_invalid_keys_to_raise_error(self):
payment_method_gateway, http_mock = self.setup_payment_method_gateway_and_mock_http()
with self.assertRaises(KeyError):
payment_method_gateway.delete("some_token", {"invalid_keys": False})
def setup_payment_method_gateway_and_mock_http(self):
braintree_gateway = BraintreeGateway(Configuration.instantiate())
payment_method_gateway = PaymentMethodGateway(braintree_gateway)
http_mock = MagicMock(name='config.http.delete')
braintree_gateway.config.http = http_mock
return payment_method_gateway, http_mock
braintree_python-3.38.0/tests/unit/test_exports.py 0000644 0001750 0001750 00000010242 13150065776 020532 0 ustar hle hle from tests.test_helper import *
import braintree
class TestExports(unittest.TestCase):
def test_exports_properties(self):
self.assertNotEqual(braintree.AchMandate, None)
self.assertNotEqual(braintree.AddOn, None)
self.assertNotEqual(braintree.AddOnGateway, None)
self.assertNotEqual(braintree.Address, None)
self.assertNotEqual(braintree.AddressGateway, None)
self.assertNotEqual(braintree.AmexExpressCheckoutCard, None)
self.assertNotEqual(braintree.AndroidPayCard, None)
self.assertNotEqual(braintree.ApplePayCard, None)
self.assertNotEqual(braintree.BraintreeGateway, None)
self.assertNotEqual(braintree.ClientToken, None)
self.assertNotEqual(braintree.Configuration, None)
self.assertNotEqual(braintree.CredentialsParser, None)
self.assertNotEqual(braintree.CreditCard, None)
self.assertNotEqual(braintree.CreditCardGateway, None)
self.assertNotEqual(braintree.CreditCardVerification, None)
self.assertNotEqual(braintree.CreditCardVerificationSearch, None)
self.assertNotEqual(braintree.Customer, None)
self.assertNotEqual(braintree.CustomerGateway, None)
self.assertNotEqual(braintree.CustomerSearch, None)
self.assertNotEqual(braintree.Descriptor, None)
self.assertNotEqual(braintree.Disbursement, None)
self.assertNotEqual(braintree.Discount, None)
self.assertNotEqual(braintree.DiscountGateway, None)
self.assertNotEqual(braintree.Environment, None)
self.assertNotEqual(braintree.ErrorCodes, None)
self.assertNotEqual(braintree.ErrorResult, None)
self.assertNotEqual(braintree.Errors, None)
self.assertNotEqual(braintree.EuropeBankAccount, None)
self.assertNotEqual(braintree.IdealPayment, None)
self.assertNotEqual(braintree.Merchant, None)
self.assertNotEqual(braintree.MerchantAccount, None)
self.assertNotEqual(braintree.MerchantAccountGateway, None)
self.assertNotEqual(braintree.PartnerMerchant, None)
self.assertNotEqual(braintree.PaymentInstrumentType, None)
self.assertNotEqual(braintree.PaymentMethod, None)
self.assertNotEqual(braintree.PaymentMethodNonce, None)
self.assertNotEqual(braintree.PayPalAccount, None)
self.assertNotEqual(braintree.Plan, None)
self.assertNotEqual(braintree.PlanGateway, None)
self.assertNotEqual(braintree.ResourceCollection, None)
self.assertNotEqual(braintree.RiskData, None)
self.assertNotEqual(braintree.Search, None)
self.assertNotEqual(braintree.SettlementBatchSummary, None)
self.assertNotEqual(braintree.SignatureService, None)
self.assertNotEqual(braintree.StatusEvent, None)
self.assertNotEqual(braintree.Subscription, None)
self.assertNotEqual(braintree.SubscriptionGateway, None)
self.assertNotEqual(braintree.SubscriptionSearch, None)
self.assertNotEqual(braintree.SubscriptionStatusEvent, None)
self.assertNotEqual(braintree.SuccessfulResult, None)
self.assertNotEqual(braintree.TestingGateway, None)
self.assertNotEqual(braintree.ThreeDSecureInfo, None)
self.assertNotEqual(braintree.Transaction, None)
self.assertNotEqual(braintree.TransactionAmounts, None)
self.assertNotEqual(braintree.TransactionDetails, None)
self.assertNotEqual(braintree.TransactionGateway, None)
self.assertNotEqual(braintree.TransactionSearch, None)
self.assertNotEqual(braintree.TransparentRedirect, None)
self.assertNotEqual(braintree.TransparentRedirectGateway, None)
self.assertNotEqual(braintree.UnknownPaymentMethod, None)
self.assertNotEqual(braintree.UsBankAccount, None)
self.assertNotEqual(braintree.ValidationErrorCollection, None)
self.assertNotEqual(braintree.VenmoAccount, None)
self.assertNotEqual(braintree.Version, None)
self.assertNotEqual(braintree.WebhookNotification, None)
self.assertNotEqual(braintree.WebhookNotificationGateway, None)
self.assertNotEqual(braintree.WebhookTesting, None)
self.assertNotEqual(braintree.WebhookTestingGateway, None)
braintree_python-3.38.0/tests/unit/test_paginated_collection.py 0000644 0001750 0001750 00000003011 13150065776 023171 0 ustar hle hle from tests.test_helper import *
from braintree.paginated_collection import PaginatedCollection
from braintree.paginated_result import PaginatedResult
class TestPaginatedCollection(unittest.TestCase):
def test_fetches_once_when_page_and_total_sizes_match(self):
def paging_function(current_page):
if current_page > 1:
raise "too many pages fetched"
else:
return PaginatedResult(1, 1, [1])
collection = PaginatedCollection(paging_function)
items = [i for i in collection.items]
self.assertEqual(1, len(items))
def test_fetches_collections_less_than_one_page(self):
def paging_function(current_page):
if current_page > 1:
raise "too many pages fetched"
else:
return PaginatedResult(2, 5, [1, 2])
collection = PaginatedCollection(paging_function)
items = [i for i in collection.items]
self.assertEqual(2, len(items))
self.assertEqual(1, items[0])
self.assertEqual(2, items[1])
def test_fetches_multiple_pages(self):
def paging_function(current_page):
if current_page > 2:
raise "too many pages fetched"
else:
return PaginatedResult(2, 1, [current_page])
collection = PaginatedCollection(paging_function)
items = [i for i in collection.items]
self.assertEqual(2, len(items))
self.assertEqual(1, items[0])
self.assertEqual(2, items[1])
braintree_python-3.38.0/tests/unit/test_risk_data.py 0000644 0001750 0001750 00000000472 13150065776 020773 0 ustar hle hle from tests.test_helper import *
from braintree import *
class TestRiskData(unittest.TestCase):
def test_initialization_of_attributes(self):
risk_data = RiskData({"id": "123", "decision": "Unknown"})
self.assertEqual("123", risk_data.id)
self.assertEqual("Unknown", risk_data.decision)
braintree_python-3.38.0/tests/unit/test_credit_card.py 0000644 0001750 0001750 00000010705 13150065776 021275 0 ustar hle hle from tests.test_helper import *
import datetime
class TestCreditCard(unittest.TestCase):
@raises_with_regexp(KeyError, "'Invalid keys: bad_key'")
def test_create_raises_exception_with_bad_keys(self):
CreditCard.create({"bad_key": "value"})
@raises_with_regexp(KeyError, "'Invalid keys: bad_key'")
def test_update_raises_exception_with_bad_keys(self):
CreditCard.update("token", {"bad_key": "value"})
@raises_with_regexp(KeyError, "'Invalid keys: bad_key'")
def test_tr_data_for_create_raises_error_with_bad_keys(self):
CreditCard.tr_data_for_create({"bad_key": "value"}, "http://example.com")
@raises_with_regexp(KeyError, "'Invalid keys: bad_key'")
def test_tr_data_for_update_raises_error_with_bad_keys(self):
CreditCard.tr_data_for_update({"bad_key": "value"}, "http://example.com")
def test_transparent_redirect_create_url(self):
port = os.getenv("GATEWAY_PORT") or "3000"
self.assertEqual(
"http://localhost:" + port + "/merchants/integration_merchant_id/payment_methods/all/create_via_transparent_redirect_request",
CreditCard.transparent_redirect_create_url()
)
def test_transparent_redirect_update_url(self):
port = os.getenv("GATEWAY_PORT") or "3000"
self.assertEqual(
"http://localhost:" + port + "/merchants/integration_merchant_id/payment_methods/all/update_via_transparent_redirect_request",
CreditCard.transparent_redirect_update_url()
)
@raises(DownForMaintenanceError)
def test_confirm_transaprant_redirect_raises_error_given_503_status_in_query_string(self):
CreditCard.confirm_transparent_redirect(
"http_status=503&id=6kdj469tw7yck32j&hash=1b3d29199a282e63074a7823b76bccacdf732da6"
)
def test_create_signature(self):
expected = ["billing_address_id", "cardholder_name", "cvv", "expiration_date", "expiration_month",
"expiration_year", "device_session_id", "fraud_merchant_id", "number", "token", "venmo_sdk_payment_method_code",
"device_data", "payment_method_nonce",
{
"billing_address": [
"company", "country_code_alpha2", "country_code_alpha3", "country_code_numeric", "country_name",
"extended_address", "first_name", "last_name", "locality", "postal_code", "region", "street_address"
]
},
{"options": ["make_default", "verification_merchant_account_id", "verify_card", "verification_amount", "venmo_sdk_session", "fail_on_duplicate_payment_method", {"adyen":["overwrite_brand", "selected_brand"]}
]},
"customer_id"
]
self.assertEqual(expected, CreditCard.create_signature())
def test_update_signature(self):
expected = ["billing_address_id", "cardholder_name", "cvv", "expiration_date", "expiration_month",
"expiration_year", "device_session_id", "fraud_merchant_id", "number", "token", "venmo_sdk_payment_method_code",
"device_data", "payment_method_nonce",
{
"billing_address": [
"company", "country_code_alpha2", "country_code_alpha3", "country_code_numeric", "country_name",
"extended_address", "first_name", "last_name", "locality", "postal_code", "region", "street_address",
{"options": ["update_existing"]}
]
},
{"options": ["make_default", "verification_merchant_account_id", "verify_card", "verification_amount", "venmo_sdk_session", "fail_on_duplicate_payment_method", {"adyen":["overwrite_brand", "selected_brand"]}
]}
]
self.assertEqual(expected, CreditCard.update_signature())
@raises(NotFoundError)
def test_finding_empty_id_raises_not_found_exception(self):
CreditCard.find(" ")
@raises(NotFoundError)
def test_finding_none_raises_not_found_exception(self):
CreditCard.find(None)
def test_multiple_verifications_sort(self):
verification1 = {"created_at": datetime.datetime(2014, 11, 18, 23, 20, 20), "id": 123, "amount": "0.00"}
verification2 = {"created_at": datetime.datetime(2014, 11, 18, 23, 20, 21), "id": 456, "amount": "1.00"}
credit_card = CreditCard(Configuration.gateway(), {"verifications": [verification1, verification2]})
self.assertEqual(456, credit_card.verification.id)
self.assertEqual(1.00, credit_card.verification.amount)
braintree_python-3.38.0/tests/unit/test_resource.py 0000644 0001750 0001750 00000006346 13150065776 020667 0 ustar hle hle from tests.test_helper import *
from braintree.resource import Resource
class TestResource(unittest.TestCase):
def test_verify_keys_allows_wildcard_keys(self):
signature = [
{"foo": [{"bar": ["__any_key__"]}]}
]
params = {
"foo[bar][lower]": "lowercase",
"foo[bar][UPPER]": "uppercase",
"foo[bar][123]": "numeric",
"foo[bar][under_scores]": "underscores",
"foo[bar][dash-es]": "dashes",
"foo[bar][ABC-abc_123]": "all together"
}
Resource.verify_keys(params, signature)
@raises(KeyError)
def test_verify_keys_escapes_brackets_in_signature(self):
signature = [
{"customer": [{"custom_fields": ["__any_key__"]}]}
]
params = {
"customer_id": "value",
}
Resource.verify_keys(params, signature)
def test_verify_keys_works_with_array_param(self):
signature = [
{"customer": ["one", "two"]}
]
params = {
"customer": {
"one": "foo"
}
}
Resource.verify_keys(params, signature)
@raises(KeyError)
def test_verify_keys_raises_on_bad_array_param(self):
signature = [
{"customer": ["one", "two"]}
]
params = {
"customer": {
"invalid": "foo"
}
}
Resource.verify_keys(params, signature)
def test_verify_keys_works_with_arrays(self):
signature = [
{"add_ons": [{"update": ["existing_id", "quantity"]}]}
]
params = {
"add_ons": {
"update": [
{
"existing_id": "foo",
"quantity": 10
}
]
}
}
Resource.verify_keys(params, signature)
@raises(KeyError)
def test_verify_keys_raises_with_invalid_param_in_arrays(self):
signature = [
{"add_ons": [{"update": ["existing_id", "quantity"]}]}
]
params = {
"add_ons": {
"update": [
{
"invalid": "foo",
"quantity": 10
}
]
}
}
Resource.verify_keys(params, signature)
def test_verify_keys_allows_text(self):
text_string = u"text_string"
assert isinstance(text_string, TestHelper.text_type)
signature = [
{"customer": [{"custom_fields": [text_string]}]}
]
params = {
"customer": {
"custom_fields": {
text_string : text_string
}
}
}
Resource.verify_keys(params, signature)
def test_verify_keys_allows_raw_data(self):
raw_string = str.encode("raw_string")
assert isinstance(raw_string, TestHelper.raw_type)
signature = [
{"customer": [{"custom_fields": [raw_string]}]}
]
params = {
"customer": {
"custom_fields": {
raw_string : raw_string
}
}
}
Resource.verify_keys(params, signature)
braintree_python-3.38.0/tests/unit/test_error_result.py 0000644 0001750 0001750 00000003125 13150065776 021557 0 ustar hle hle from tests.test_helper import *
class TestErrorResult(unittest.TestCase):
def test_it_initializes_params_and_errors(self):
errors = {
"scope": {
"errors": [{"code": 123, "message": "something is invalid", "attribute": "something"}]
}
}
result = ErrorResult("gateway", {"errors": errors, "params": "params", "message": "brief description"})
self.assertFalse(result.is_success)
self.assertEqual("params", result.params)
self.assertEqual(1, result.errors.size)
self.assertEqual("something is invalid", result.errors.for_object("scope")[0].message)
self.assertEqual("something", result.errors.for_object("scope")[0].attribute)
self.assertEqual(123, result.errors.for_object("scope")[0].code)
def test_it_ignores_other_params(self):
errors = {
"scope": {
"errors": [{"code": 123, "message": "something is invalid", "attribute": "something"}]
}
}
result = ErrorResult("gateway", {"errors": errors, "params": "params", "message": "brief description", "other": "stuff"})
self.assertFalse(result.is_success)
def test_transaction_is_none_if_not_set(self):
result = ErrorResult("gateway", {"errors": {}, "params": {}, "message": "brief description"})
self.assertTrue(result.transaction is None)
def test_verification_is_none_if_not_set(self):
result = ErrorResult("gateway", {"errors": {}, "params": {}, "message": "brief description"})
self.assertTrue(result.credit_card_verification is None)
braintree_python-3.38.0/tests/unit/test_transaction.py 0000644 0001750 0001750 00000015674 13150065776 021371 0 ustar hle hle from tests.test_helper import *
from braintree.test.credit_card_numbers import CreditCardNumbers
from datetime import datetime
from datetime import date
if sys.version_info[0] == 2:
from mock import MagicMock
else:
from unittest.mock import MagicMock
class TestTransaction(unittest.TestCase):
@raises_with_regexp(KeyError, "'Invalid keys: bad_key'")
def test_clone_transaction_raises_exception_with_bad_keys(self):
Transaction.clone_transaction("an id", {"bad_key": "value"})
@raises_with_regexp(KeyError, "'Invalid keys: bad_key'")
def test_sale_raises_exception_with_bad_keys(self):
Transaction.sale({"bad_key": "value"})
@raises_with_regexp(KeyError, "'Invalid keys: credit_card\[bad_key\]'")
def test_sale_raises_exception_with_nested_bad_keys(self):
Transaction.sale({"credit_card": {"bad_key": "value"}})
@raises_with_regexp(KeyError, "'Invalid keys: bad_key'")
def test_tr_data_for_sale_raises_error_with_bad_keys(self):
Transaction.tr_data_for_sale({"bad_key": "value"}, "http://example.com")
@raises(NotFoundError)
def test_finding_empty_id_raises_not_found_exception(self):
Transaction.find(" ")
@raises(NotFoundError)
def test_finding_none_raises_not_found_exception(self):
Transaction.find(None)
def test_constructor_includes_disbursement_information(self):
attributes = {
'amount': '27.00',
'tax_amount': '1.00',
'customer_id': '4096',
'merchant_account_id': '8192',
'order_id': '106601',
'channel': '101',
'payment_method_token': 'sometoken',
'purchase_order_number': '20202',
'recurring': 'False',
'disbursement_details': {
'settlement_amount': '27.00',
'settlement_currency_iso_code': 'USD',
'settlement_currency_exchange_rate': '1',
'disbursement_date': date(2013, 4, 10),
'funds_held': False
}
}
transaction = Transaction(None, attributes)
self.assertEqual(transaction.disbursement_details.settlement_amount, Decimal('27.00'))
self.assertEqual(transaction.disbursement_details.settlement_currency_iso_code, 'USD')
self.assertEqual(transaction.disbursement_details.settlement_currency_exchange_rate, Decimal('1'))
self.assertEqual(transaction.disbursement_details.disbursement_date, date(2013, 4, 10))
self.assertEqual(transaction.disbursement_details.funds_held, False)
self.assertEqual(transaction.is_disbursed, True)
def test_transaction_handles_nil_risk_data(self):
attributes = {
'amount': '27.00',
'tax_amount': '1.00',
'customer_id': '4096',
'merchant_account_id': '8192',
'order_id': '106601',
'channel': '101',
'payment_method_token': 'sometoken',
'purchase_order_number': '20202',
'recurring': 'False',
}
transaction = Transaction(None, attributes)
self.assertEqual(transaction.risk_data, None)
def test_is_disbursed_false(self):
attributes = {
'amount': '27.00',
'tax_amount': '1.00',
'customer_id': '4096',
'merchant_account_id': '8192',
'order_id': '106601',
'channel': '101',
'payment_method_token': 'sometoken',
'purchase_order_number': '20202',
'recurring': 'False',
'disbursement_details': {
'settlement_amount': None,
'settlement_currency_iso_code': None,
'settlement_currency_exchange_rate': None,
'disbursement_date': None,
'funds_held': None,
}
}
transaction = Transaction(None, attributes)
self.assertEqual(transaction.is_disbursed, False)
def test_sale_with_skip_advanced_fraud_checking_value_as_true(self):
attributes = {
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": CreditCardNumbers.Visa,
"expiration_date": "05/2009"
},
"options": {
"skip_advanced_fraud_checking": True
}
}
transaction_gateway = self.setup_transaction_gateway_and_mock_post()
transaction_gateway.sale(attributes)
transaction_param = transaction_gateway._post.call_args[0][1]
self.assertTrue(transaction_param['transaction']['options']['skip_advanced_fraud_checking'])
def test_sale_with_skip_advanced_fraud_checking_value_as_false(self):
attributes = {
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": CreditCardNumbers.Visa,
"expiration_date": "05/2009"
},
"options": {
"skip_advanced_fraud_checking": False
}
}
transaction_gateway = self.setup_transaction_gateway_and_mock_post()
transaction_gateway.sale(attributes)
transaction_param = transaction_gateway._post.call_args[0][1]
self.assertFalse(transaction_param['transaction']['options']['skip_advanced_fraud_checking'])
def test_sale_without_skip_advanced_fraud_checking_value_option(self):
attributes = {
"amount": TransactionAmounts.Authorize,
"credit_card": {
"number": CreditCardNumbers.Visa,
"expiration_date": "05/2009"
},
"options": {
"submit_for_settlement": True
}
}
transaction_gateway = self.setup_transaction_gateway_and_mock_post()
transaction_gateway.sale(attributes)
transaction_param = transaction_gateway._post.call_args[0][1]
self.assertTrue('skip_advanced_fraud_checking' not in transaction_param['transaction']['options'])
def setup_transaction_gateway_and_mock_post(self):
transaction_gateway = TransactionGateway(BraintreeGateway(None))
transaction_gateway._post = MagicMock(name='config.http.post')
return transaction_gateway
def test_ideal_payment_details(self):
attributes = {
'amount': '27.00',
'tax_amount': '1.00',
'ideal_payment': {
'ideal_payment_id': 'idealpayment_abc_123',
'masked_iban': '12************7890',
'bic': 'RABONL2U',
'image_url': 'http://www.example.com/ideal.png',
},
}
transaction = Transaction(None, attributes)
self.assertEqual(transaction.ideal_payment_details.ideal_payment_id, 'idealpayment_abc_123')
self.assertEqual(transaction.ideal_payment_details.masked_iban, '12************7890')
self.assertEqual(transaction.ideal_payment_details.bic, 'RABONL2U')
self.assertEqual(transaction.ideal_payment_details.image_url, 'http://www.example.com/ideal.png')
braintree_python-3.38.0/tests/unit/test_http.py 0000644 0001750 0001750 00000003363 13150065776 020013 0 ustar hle hle import traceback
from tests.test_helper import *
from braintree.attribute_getter import AttributeGetter
class TestHttp(unittest.TestCase):
@raises(UpgradeRequiredError)
def test_raise_exception_from_status_for_upgrade_required(self):
Http.raise_exception_from_status(426)
@raises(TooManyRequestsError)
def test_raise_exception_from_too_many_requests(self):
Http.raise_exception_from_status(429)
def test_header_includes_gzip_accept_encoding(self):
config = AttributeGetter({
"base_url": (lambda: ""),
"has_access_token": (lambda: False),
"has_client_credentials": (lambda: False),
"public_key": "",
"private_key": ""})
headers = Http(config, "fake_environment")._Http__headers(Http.ContentType.Xml)
self.assertTrue('Accept-Encoding' in headers)
self.assertEqual('gzip', headers["Accept-Encoding"])
def test_backtrace_preserved_when_not_wrapping_exceptions(self):
class Error(Exception):
pass
def raise_error(*_):
raise Error
http_strategy = AttributeGetter({"http_do": raise_error})
config = AttributeGetter({
"base_url": (lambda: ""),
"has_access_token": (lambda: False),
"has_client_credentials": (lambda: False),
"http_strategy": (lambda: http_strategy),
"public_key": "",
"private_key": "",
"wrap_http_exceptions": False})
try:
Http(config, "fake_environment").post("/example/path/to/reach")
except Error:
_, _, tb = sys.exc_info()
self.assertEqual('raise_error', traceback.extract_tb(tb)[-1][2])
braintree_python-3.38.0/tests/unit/test_authorization_adjustment.py 0000644 0001750 0001750 00000001250 13150065776 024163 0 ustar hle hle from tests.test_helper import *
from datetime import datetime
from braintree.authorization_adjustment import AuthorizationAdjustment
class TestAuthorizationAdjustment(unittest.TestCase):
def test_contstructor(self):
attributes = {
"amount": "-20.00",
"timestamp": datetime(2017, 7, 12, 1, 2, 3),
"success": True,
}
authorization_adjustment = AuthorizationAdjustment(attributes)
self.assertEqual(authorization_adjustment.amount, Decimal("-20.00"))
self.assertEqual(authorization_adjustment.timestamp, datetime(2017, 7, 12, 1, 2, 3))
self.assertEqual(authorization_adjustment.success, True)
braintree_python-3.38.0/tests/unit/test_disbursement.py 0000644 0001750 0001750 00000002057 13150065776 021537 0 ustar hle hle from tests.test_helper import *
from datetime import date
class TestDisbursement(unittest.TestCase):
def test_constructor(self):
attributes = {
"merchant_account": {
"id": "sub_merchant_account",
"status": "active",
"master_merchant_account": {
"id": "master_merchant_account",
"status": "active"
},
},
"id": "123456",
"exception_message": "invalid_account_number",
"amount": "100.00",
"disbursement_date": date(2013, 4, 10),
"follow_up_action": "update",
"transaction_ids": ["asdf", "qwer"]
}
disbursement = Disbursement(None, attributes)
self.assertEqual("123456", disbursement.id)
self.assertEqual(Decimal("100.00"), disbursement.amount)
self.assertEqual(["asdf", "qwer"], disbursement.transaction_ids)
self.assertEqual("master_merchant_account", disbursement.merchant_account.master_merchant_account.id)
braintree_python-3.38.0/tests/unit/test_merchant_account.py 0000644 0001750 0001750 00000005536 13150065776 022355 0 ustar hle hle from tests.test_helper import *
class TestMerchantAccount(unittest.TestCase):
def test_create_new_merchant_account_with_all_params(self):
params = {
"id": "sub_merchant_account",
"status": "active",
"master_merchant_account": {
"id": "master_merchant_account",
"status": "active"
},
"individual": {
"first_name": "John",
"last_name": "Doe",
"email": "john.doe@example.com",
"date_of_birth": "1970-01-01",
"phone": "3125551234",
"ssn_last_4": "6789",
"address": {
"street_address": "123 Fake St",
"locality": "Chicago",
"region": "IL",
"postal_code": "60622",
}
},
"business": {
"dba_name": "James's Bloggs",
"tax_id": "123456789",
},
"funding": {
"account_number_last_4": "8798",
"routing_number": "071000013",
"descriptor": "Joes Bloggs MI",
}
}
merchant_account = MerchantAccount(None, params)
self.assertEqual(merchant_account.status, "active")
self.assertEqual(merchant_account.id, "sub_merchant_account")
self.assertEqual(merchant_account.master_merchant_account.id, "master_merchant_account")
self.assertEqual(merchant_account.master_merchant_account.status, "active")
self.assertEqual(merchant_account.individual_details.first_name, "John")
self.assertEqual(merchant_account.individual_details.last_name, "Doe")
self.assertEqual(merchant_account.individual_details.email, "john.doe@example.com")
self.assertEqual(merchant_account.individual_details.date_of_birth, "1970-01-01")
self.assertEqual(merchant_account.individual_details.phone, "3125551234")
self.assertEqual(merchant_account.individual_details.ssn_last_4, "6789")
self.assertEqual(merchant_account.individual_details.address_details.street_address, "123 Fake St")
self.assertEqual(merchant_account.individual_details.address_details.locality, "Chicago")
self.assertEqual(merchant_account.individual_details.address_details.region, "IL")
self.assertEqual(merchant_account.individual_details.address_details.postal_code, "60622")
self.assertEqual(merchant_account.business_details.dba_name, "James's Bloggs")
self.assertEqual(merchant_account.business_details.tax_id, "123456789")
self.assertEqual(merchant_account.funding_details.account_number_last_4, "8798")
self.assertEqual(merchant_account.funding_details.routing_number, "071000013")
self.assertEqual(merchant_account.funding_details.descriptor, "Joes Bloggs MI")
braintree_python-3.38.0/tests/unit/test_configuration.py 0000644 0001750 0001750 00000014540 13150065776 021702 0 ustar hle hle from tests.test_helper import *
import braintree
import os
import imp
class TestConfiguration(unittest.TestCase):
def test_works_with_unconfigured_configuration(self):
try:
# reset class level attributes on Configuration set in test helper
imp.reload(braintree.configuration)
config = Configuration(
environment=braintree.Environment.Sandbox,
merchant_id='my_merchant_id',
public_key='public_key',
private_key='private_key'
)
config.http_strategy()
except AttributeError as e:
print(e)
self.fail()
finally:
# repopulate class level attributes on Configuration
import tests.test_helper
imp.reload(tests.test_helper)
def test_base_merchant_path_for_development(self):
self.assertEqual("/merchants/integration_merchant_id", Configuration.instantiate().base_merchant_path())
def test_configuration_construction_for_merchant(self):
config = Configuration(
environment=braintree.Environment.Sandbox,
merchant_id='my_merchant_id',
public_key='public_key',
private_key='private_key'
)
self.assertEqual(config.merchant_id, 'my_merchant_id')
self.assertEqual(config.public_key, 'public_key')
self.assertEqual(config.private_key, 'private_key')
def test_configuration_configure_allows_strings_for_environment(self):
try:
for environment_string, environment_object in braintree.Environment.All.items():
braintree.Configuration.configure(
environment_string,
'my_merchant_id',
'public_key',
'private_key'
)
self.assertEqual(braintree.Configuration.environment, environment_object)
finally:
reset_braintree_configuration()
def test_configuration_construction_allows_strings_for_environment(self):
config = Configuration(
environment='sandbox',
merchant_id='my_merchant_id',
public_key='public_key',
private_key='private_key'
)
self.assertEqual(config.environment, braintree.Environment.Sandbox)
def test_configuration_construction_allows_empty_parameter_list(self):
config = Configuration()
self.assertIsInstance(config, braintree.Configuration)
def test_configuration_raises_configuration_error_for_invalid_environment(self):
for environment in [42, 'not_an_env', '']:
def setup_bad_configuration():
Configuration(
environment=environment,
merchant_id='my_merchant_id',
public_key='public_key',
private_key='private_key'
)
self.assertRaises(ConfigurationError, setup_bad_configuration)
def test_configuration_raises_configuration_error_for_empty_merchant_id(self):
def setup_bad_configuration():
Configuration(
environment=braintree.Environment.Sandbox,
merchant_id='',
public_key='public_key',
private_key='private_key'
)
self.assertRaises(ConfigurationError, setup_bad_configuration)
def test_configuration_raises_configuration_error_for_empty_public_key(self):
def setup_bad_configuration():
Configuration(
environment=braintree.Environment.Sandbox,
merchant_id='my_merchant_id',
public_key='',
private_key='private_key'
)
self.assertRaises(ConfigurationError, setup_bad_configuration)
def test_configuration_raises_configuration_error_for_empty_private_key(self):
def setup_bad_configuration():
Configuration(
environment=braintree.Environment.Sandbox,
merchant_id='my_merchant_id',
public_key='public_key',
private_key=''
)
self.assertRaises(ConfigurationError, setup_bad_configuration)
def test_configuration_construction_for_partner(self):
config = Configuration.for_partner(
braintree.Environment.Sandbox,
'my_partner_id',
'public_key',
'private_key'
)
self.assertEqual(config.merchant_id, 'my_partner_id')
self.assertEqual(config.public_key, 'public_key')
self.assertEqual(config.private_key, 'private_key')
def test_configuring_with_an_http_strategy(self):
class FakeStrategy(object):
def __init__(self, config, environment):
pass
strategy = Configuration(http_strategy=FakeStrategy).http_strategy()
self.assertIsInstance(strategy, FakeStrategy)
def test_partner_configuration_does_not_use_default_http_strategy(self):
old_http_strategy = Configuration.default_http_strategy
class FakeStrategy(object):
def __init__(self, config, environment):
pass
try:
Configuration.default_http_strategy = FakeStrategy
config = Configuration.for_partner(
braintree.Environment.Sandbox,
'my_partner_id',
'public_key',
'private_key'
)
self.assertNotIsInstance(config.http_strategy(), FakeStrategy)
finally:
Configuration.default_http_strategy = old_http_strategy
def test_instantiate_with_a_default_http_strategy(self):
old_http_strategy = Configuration.default_http_strategy
class FakeStrategy(object):
def __init__(self, config, environment):
pass
try:
Configuration.default_http_strategy = FakeStrategy
strategy = Configuration.instantiate().http_strategy()
self.assertIsInstance(strategy, FakeStrategy)
finally:
Configuration.default_http_strategy = old_http_strategy
def test_configuring_with_partial_client_credentials(self):
with self.assertRaises(ConfigurationError) as error:
Configuration(client_id='client_id$development$integration_client_id')
self.assertIn("Missing client_secret when constructing BraintreeGateway", str(error.exception))
braintree_python-3.38.0/tests/unit/test_document_upload.py 0000644 0001750 0001750 00000000371 13150065776 022212 0 ustar hle hle from tests.test_helper import *
class TestDocumentUpload(unittest.TestCase):
@raises_with_regexp(KeyError, "'Invalid keys: bad_key'")
def test_create_raises_exception_with_bad_keys(self):
DocumentUpload.create({"bad_key": "value"})
braintree_python-3.38.0/tests/unit/test_crypto.py 0000644 0001750 0001750 00000001570 13150065776 020352 0 ustar hle hle from tests.test_helper import *
class TestCrypto(unittest.TestCase):
def test_sha1_hmac_hash(self):
actual = Crypto.sha1_hmac_hash("secretKey", "hello world")
self.assertEqual("d503d7a1a6adba1e6474e9ff2c4167f9dfdf4247", actual)
def test_sha256_hmac_hash(self):
actual = Crypto.sha256_hmac_hash("secret-key", "secret-message")
self.assertEqual("68e7f2ecab71db67b1aca2a638f5122810315c3013f27c2196cd53e88709eecc", actual)
def test_secure_compare_returns_true_when_same(self):
self.assertTrue(Crypto.secure_compare("a_string", "a_string"))
def test_secure_compare_returns_false_when_different_lengths(self):
self.assertFalse(Crypto.secure_compare("a_string", "a_string_that_is_longer"))
def test_secure_compare_returns_false_when_different(self):
self.assertFalse(Crypto.secure_compare("a_string", "a_strong"))
braintree_python-3.38.0/tests/unit/test_subscription_search.py 0000644 0001750 0001750 00000004020 13150065776 023074 0 ustar hle hle from tests.test_helper import *
class TestSubscriptionSearch(unittest.TestCase):
def test_billing_cycles_remaining_is_a_range_node(self):
self.assertEqual(Search.RangeNodeBuilder, type(SubscriptionSearch.billing_cycles_remaining))
def test_created_at_is_a_range_node(self):
self.assertEqual(Search.RangeNodeBuilder, type(SubscriptionSearch.created_at))
def test_days_past_due_is_a_range_node(self):
self.assertEqual(Search.RangeNodeBuilder, type(SubscriptionSearch.days_past_due))
def test_id_is_a_text_node(self):
self.assertEqual(Search.TextNodeBuilder, type(SubscriptionSearch.id))
def test_merchant_account_id_is_a_multiple_value_node(self):
self.assertEqual(Search.MultipleValueNodeBuilder, type(SubscriptionSearch.merchant_account_id))
def test_plan_id_is_a_multiple_value_or_text_node(self):
self.assertEqual(Search.MultipleValueOrTextNodeBuilder, type(SubscriptionSearch.plan_id))
def test_price_is_a_range_node(self):
self.assertEqual(Search.RangeNodeBuilder, type(SubscriptionSearch.price))
def test_status_is_a_multiple_value_node(self):
self.assertEqual(Search.MultipleValueNodeBuilder, type(SubscriptionSearch.status))
def test_in_trial_period_is_multiple_value_node(self):
self.assertEqual(Search.MultipleValueNodeBuilder, type(SubscriptionSearch.in_trial_period))
def test_status_whitelist(self):
SubscriptionSearch.status.in_list(
Subscription.Status.Active,
Subscription.Status.Canceled,
Subscription.Status.Expired,
Subscription.Status.PastDue
)
@raises(AttributeError)
def test_status_not_in_whitelist(self):
SubscriptionSearch.status.in_list(
Subscription.Status.Active,
Subscription.Status.Canceled,
Subscription.Status.Expired,
"not a status"
)
def test_ids_is_a_multiple_value_node(self):
self.assertEqual(Search.MultipleValueNodeBuilder, type(SubscriptionSearch.ids))
braintree_python-3.38.0/tests/unit/test_subscription.py 0000644 0001750 0001750 00000001040 13150065776 021546 0 ustar hle hle from tests.test_helper import *
class TestSubscription(unittest.TestCase):
@raises_with_regexp(KeyError, "'Invalid keys: bad_key'")
def test_create_raises_exception_with_bad_keys(self):
Subscription.create({"bad_key": "value"})
@raises_with_regexp(KeyError, "'Invalid keys: bad_key'")
def test_update_raises_exception_with_bad_keys(self):
Subscription.update("id", {"bad_key": "value"})
@raises(NotFoundError)
def test_finding_empty_id_raises_not_found_exception(self):
Subscription.find(" ")
braintree_python-3.38.0/tests/unit/test_resource_collection.py 0000644 0001750 0001750 00000004020 13150065776 023065 0 ustar hle hle from tests.test_helper import *
class TestResourceCollection(unittest.TestCase):
collection_data = {
"search_results": {
"page_size": 2,
"ids": ["0", "1", "2", "3", "4"]
}
}
class TestResource:
items = ["a", "b", "c", "d", "e"]
@staticmethod
def fetch(_, ids):
return [TestResourceCollection.TestResource.items[int(resource_id)] for resource_id in ids]
def test_iterating_over_contents(self):
collection = ResourceCollection("some_query", self.collection_data, TestResourceCollection.TestResource.fetch)
new_items = []
index = 0
for item in collection.items:
self.assertEqual(TestResourceCollection.TestResource.items[index], item)
new_items.append(item)
index += 1
self.assertEqual(5, len(new_items))
def test_iterate_using_iterator_protocol(self):
collection = ResourceCollection("some_query", self.collection_data, TestResourceCollection.TestResource.fetch)
for test_elem, coll_elem in zip(self.TestResource.items, collection):
self.assertEqual(test_elem, coll_elem)
def test_ids_returns_array_of_ids(self):
collection = ResourceCollection("some_query", self.collection_data, TestResourceCollection.TestResource.fetch)
self.assertEqual(collection.ids, self.collection_data['search_results']['ids'])
def test_ids_returns_array_of_empty_ids(self):
empty_collection_data = {
"search_results": {
"page_size": 2,
"ids": []
}
}
collection = ResourceCollection("some_query", empty_collection_data, TestResourceCollection.TestResource.fetch)
self.assertEqual(collection.ids, [])
@raises_with_regexp(UnexpectedError, "Unprocessable entity due to an invalid request")
def test_no_search_results(self):
bad_collection_data = {}
ResourceCollection("some_query", bad_collection_data, TestResourceCollection.TestResource.fetch)
braintree_python-3.38.0/tests/unit/test_europe_bank_account.py 0000644 0001750 0001750 00000000426 13150065776 023037 0 ustar hle hle from tests.test_helper import *
class TestEuropeBankAccount(unittest.TestCase):
def test_mandate_type_constants(self):
self.assertEqual("business", EuropeBankAccount.MandateType.Business)
self.assertEqual("consumer", EuropeBankAccount.MandateType.Consumer)
braintree_python-3.38.0/tests/unit/test_webhooks.py 0000644 0001750 0001750 00000054233 13150065776 020657 0 ustar hle hle from tests.test_helper import *
from datetime import date
from braintree.dispute import Dispute
class TestWebhooks(unittest.TestCase):
def test_sample_notification_builds_a_parsable_notification(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.SubscriptionWentPastDue, notification.kind)
self.assertEqual("my_id", notification.subscription.id)
self.assertTrue((datetime.utcnow() - notification.timestamp).seconds < 10)
@raises(InvalidSignatureError)
def test_completely_invalid_signature(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
WebhookNotification.parse("bad_stuff", sample_notification['bt_payload'])
def test_parse_raises_when_public_key_is_wrong(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
config = Configuration(
environment=Environment.Development,
merchant_id="integration_merchant_id",
public_key="wrong_public_key",
private_key="wrong_private_key"
)
gateway = BraintreeGateway(config)
try:
gateway.webhook_notification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
except InvalidSignatureError as e:
self.assertEqual("no matching public key", str(e))
else:
self.assertFalse("raises exception")
def test_invalid_signature_when_payload_modified(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
try:
WebhookNotification.parse(sample_notification['bt_signature'], b"badstuff" + sample_notification['bt_payload'])
except InvalidSignatureError as e:
self.assertEqual("signature does not match payload - one has been modified", str(e))
else:
self.assertFalse("raises exception")
def test_invalid_signature_when_contains_invalid_characters(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
try:
WebhookNotification.parse(sample_notification['bt_signature'], "~* invalid! *~")
except InvalidSignatureError as e:
self.assertEqual("payload contains illegal characters", str(e))
else:
self.assertFalse("raises exception")
def test_parse_allows_all_valid_characters(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
try:
WebhookNotification.parse(sample_notification['bt_signature'], "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+=/\n")
except InvalidSignatureError as e:
self.assertNotEqual("payload contains illegal characters", str(e))
def test_parse_retries_payload_with_a_newline(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'].rstrip())
self.assertEqual(WebhookNotification.Kind.SubscriptionWentPastDue, notification.kind)
self.assertEqual("my_id", notification.subscription.id)
self.assertTrue((datetime.utcnow() - notification.timestamp).seconds < 10)
def test_verify_returns_a_correct_challenge_response(self):
response = WebhookNotification.verify("20f9f8ed05f77439fe955c977e4c8a53")
self.assertEqual("integration_public_key|d9b899556c966b3f06945ec21311865d35df3ce4", response)
def test_verify_raises_when_challenge_is_invalid(self):
try:
WebhookNotification.verify("bad challenge")
except InvalidChallengeError as e:
self.assertEqual("challenge contains non-hex characters", str(e))
else:
self.assertFalse("raises exception")
def test_builds_notification_for_approved_sub_merchant_account(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.SubMerchantAccountApproved,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.SubMerchantAccountApproved, notification.kind)
self.assertEqual("my_id", notification.merchant_account.id)
self.assertEqual(MerchantAccount.Status.Active, notification.merchant_account.status)
self.assertEqual("master_ma_for_my_id", notification.merchant_account.master_merchant_account.id)
self.assertEqual(MerchantAccount.Status.Active, notification.merchant_account.master_merchant_account.status)
def test_builds_notification_for_declined_sub_merchant_account(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.SubMerchantAccountDeclined,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.SubMerchantAccountDeclined, notification.kind)
self.assertEqual("my_id", notification.merchant_account.id)
self.assertEqual(MerchantAccount.Status.Suspended, notification.merchant_account.status)
self.assertEqual("master_ma_for_my_id", notification.merchant_account.master_merchant_account.id)
self.assertEqual(MerchantAccount.Status.Suspended, notification.merchant_account.master_merchant_account.status)
self.assertEqual("Credit score is too low", notification.message)
self.assertEqual(ErrorCodes.MerchantAccount.DeclinedOFAC, notification.errors.for_object("merchant_account").on("base")[0].code)
def test_builds_notification_for_disbursed_transactions(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.TransactionDisbursed,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.TransactionDisbursed, notification.kind)
self.assertEqual("my_id", notification.transaction.id)
self.assertEqual(100, notification.transaction.amount)
self.assertEqual(datetime(2013, 7, 9, 18, 23, 29), notification.transaction.disbursement_details.disbursement_date)
def test_builds_notification_for_settled_transactions(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.TransactionSettled,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.TransactionSettled, notification.kind)
self.assertEqual("my_id", notification.transaction.id)
self.assertEqual("settled", notification.transaction.status)
self.assertEqual(100, notification.transaction.amount)
self.assertEqual(notification.transaction.us_bank_account.routing_number, "123456789")
self.assertEqual(notification.transaction.us_bank_account.last_4, "1234")
self.assertEqual(notification.transaction.us_bank_account.account_type, "checking")
self.assertEqual(notification.transaction.us_bank_account.account_holder_name, "Dan Schulman")
def test_builds_notification_for_settlement_declined_transactions(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.TransactionSettlementDeclined,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.TransactionSettlementDeclined, notification.kind)
self.assertEqual("my_id", notification.transaction.id)
self.assertEqual("settlement_declined", notification.transaction.status)
self.assertEqual(100, notification.transaction.amount)
self.assertEqual(notification.transaction.us_bank_account.routing_number, "123456789")
self.assertEqual(notification.transaction.us_bank_account.last_4, "1234")
self.assertEqual(notification.transaction.us_bank_account.account_type, "checking")
self.assertEqual(notification.transaction.us_bank_account.account_holder_name, "Dan Schulman")
def test_builds_notification_for_disbursements(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.Disbursement,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.Disbursement, notification.kind)
self.assertEqual("my_id", notification.disbursement.id)
self.assertEqual(100, notification.disbursement.amount)
self.assertEqual(None, notification.disbursement.exception_message)
self.assertEqual(None, notification.disbursement.follow_up_action)
self.assertEqual(date(2014, 2, 9), notification.disbursement.disbursement_date)
def test_builds_notification_for_disbursement_exceptions(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.DisbursementException,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.DisbursementException, notification.kind)
self.assertEqual("my_id", notification.disbursement.id)
self.assertEqual(100, notification.disbursement.amount)
self.assertEqual("bank_rejected", notification.disbursement.exception_message)
self.assertEqual("update_funding_information", notification.disbursement.follow_up_action)
self.assertEqual(date(2014, 2, 9), notification.disbursement.disbursement_date)
def test_builds_notification_for_old_dispute_opened(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.DisputeOpened,
"legacy_dispute_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.DisputeOpened, notification.kind)
self.assertEqual("legacy_dispute_id", notification.dispute.id)
self.assertEqual(Dispute.Status.Open, notification.dispute.status)
self.assertEqual(Dispute.Kind.Chargeback, notification.dispute.kind)
self.assertEqual(notification.dispute.date_opened, date(2014, 3, 28))
def test_builds_notification_for_old_dispute_lost(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.DisputeLost,
"legacy_dispute_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.DisputeLost, notification.kind)
self.assertEqual("legacy_dispute_id", notification.dispute.id)
self.assertEqual(Dispute.Status.Lost, notification.dispute.status)
self.assertEqual(Dispute.Kind.Chargeback, notification.dispute.kind)
self.assertEqual(notification.dispute.date_opened, date(2014, 3, 28))
def test_builds_notification_for_old_dispute_won(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.DisputeWon,
"legacy_dispute_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.DisputeWon, notification.kind)
self.assertEqual("legacy_dispute_id", notification.dispute.id)
self.assertEqual(Dispute.Status.Won, notification.dispute.status)
self.assertEqual(Dispute.Kind.Chargeback, notification.dispute.kind)
self.assertEqual(notification.dispute.date_opened, date(2014, 3, 28))
self.assertEqual(notification.dispute.date_won, date(2014, 9, 1))
def test_builds_notification_for_new_dispute_opened(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.DisputeOpened,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.DisputeOpened, notification.kind)
self.assertEqual("my_id", notification.dispute.id)
self.assertEqual(Dispute.Status.Open, notification.dispute.status)
self.assertEqual(Dispute.Kind.Chargeback, notification.dispute.kind)
self.assertEqual(notification.dispute.date_opened, date(2014, 3, 28))
def test_builds_notification_for_new_dispute_lost(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.DisputeLost,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.DisputeLost, notification.kind)
self.assertEqual("my_id", notification.dispute.id)
self.assertEqual(Dispute.Status.Lost, notification.dispute.status)
self.assertEqual(Dispute.Kind.Chargeback, notification.dispute.kind)
self.assertEqual(notification.dispute.date_opened, date(2014, 3, 28))
def test_builds_notification_for_new_dispute_won(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.DisputeWon,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.DisputeWon, notification.kind)
self.assertEqual("my_id", notification.dispute.id)
self.assertEqual(Dispute.Status.Won, notification.dispute.status)
self.assertEqual(Dispute.Kind.Chargeback, notification.dispute.kind)
self.assertEqual(notification.dispute.date_opened, date(2014, 3, 28))
self.assertEqual(notification.dispute.date_won, date(2014, 9, 1))
def test_builds_notification_for_partner_merchant_connected(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.PartnerMerchantConnected,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.PartnerMerchantConnected, notification.kind)
self.assertEqual("abc123", notification.partner_merchant.partner_merchant_id)
self.assertEqual("public_key", notification.partner_merchant.public_key)
self.assertEqual("private_key", notification.partner_merchant.private_key)
self.assertEqual("public_id", notification.partner_merchant.merchant_public_id)
self.assertEqual("cse_key", notification.partner_merchant.client_side_encryption_key)
self.assertTrue((datetime.utcnow() - notification.timestamp).seconds < 10)
def test_builds_notification_for_partner_merchant_disconnected(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.PartnerMerchantDisconnected,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.PartnerMerchantDisconnected, notification.kind)
self.assertEqual("abc123", notification.partner_merchant.partner_merchant_id)
self.assertTrue((datetime.utcnow() - notification.timestamp).seconds < 10)
def test_builds_notification_for_partner_merchant_declined(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.PartnerMerchantDeclined,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.PartnerMerchantDeclined, notification.kind)
self.assertEqual("abc123", notification.partner_merchant.partner_merchant_id)
self.assertTrue((datetime.utcnow() - notification.timestamp).seconds < 10)
def test_builds_notification_for_connected_merchant_status_transitioned(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.ConnectedMerchantStatusTransitioned,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.ConnectedMerchantStatusTransitioned, notification.kind)
self.assertEqual("new_status", notification.connected_merchant_status_transitioned.status)
self.assertEqual("my_id", notification.connected_merchant_status_transitioned.merchant_public_id)
self.assertEqual("oauth_application_client_id", notification.connected_merchant_status_transitioned.oauth_application_client_id)
def test_builds_notification_for_connected_merchant_paypal_status_changed(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.ConnectedMerchantPayPalStatusChanged,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.ConnectedMerchantPayPalStatusChanged, notification.kind)
self.assertEqual("link", notification.connected_merchant_paypal_status_changed.action)
self.assertEqual("my_id", notification.connected_merchant_paypal_status_changed.merchant_public_id)
self.assertEqual("oauth_application_client_id", notification.connected_merchant_paypal_status_changed.oauth_application_client_id)
def test_builds_notification_for_subscription_charged_successfully(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.SubscriptionChargedSuccessfully,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.SubscriptionChargedSuccessfully, notification.kind)
self.assertEqual("my_id", notification.subscription.id)
self.assertTrue(len(notification.subscription.transactions) == 1)
transaction = notification.subscription.transactions.pop()
self.assertEqual("submitted_for_settlement", transaction.status)
self.assertEqual(Decimal("49.99"), transaction.amount)
def test_builds_notification_for_check(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.Check,
""
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.Check, notification.kind)
def test_builds_notification_for_account_updater_daily_report_webhook(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.AccountUpdaterDailyReport,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.AccountUpdaterDailyReport, notification.kind)
self.assertEqual("link-to-csv-report", notification.account_updater_daily_report.report_url)
self.assertEqual(date(2016, 1, 14), notification.account_updater_daily_report.report_date)
def test_ideal_payment_complete_webhook(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.IdealPaymentComplete,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
ideal_payment = notification.ideal_payment
self.assertEqual(WebhookNotification.Kind.IdealPaymentComplete, notification.kind)
self.assertEqual("my_id", ideal_payment.id)
self.assertEqual("COMPLETE", ideal_payment.status);
self.assertEqual("ORDERABC", ideal_payment.order_id);
self.assertEqual("10.00", ideal_payment.amount);
self.assertEqual("https://example.com", ideal_payment.approval_url);
self.assertEqual("1234567890", ideal_payment.ideal_transaction_id);
def test_ideal_payment_failed_webhook(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.IdealPaymentFailed,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
ideal_payment = notification.ideal_payment
self.assertEqual(WebhookNotification.Kind.IdealPaymentFailed, notification.kind)
self.assertEqual("my_id", ideal_payment.id)
self.assertEqual("FAILED", ideal_payment.status);
self.assertEqual("ORDERABC", ideal_payment.order_id);
self.assertEqual("10.00", ideal_payment.amount);
self.assertEqual("https://example.com", ideal_payment.approval_url);
self.assertEqual("1234567890", ideal_payment.ideal_transaction_id);
braintree_python-3.38.0/tests/unit/test_signature_service.py 0000644 0001750 0001750 00000000705 13150065776 022552 0 ustar hle hle from tests.test_helper import *
class FakeDigest(object):
@staticmethod
def hmac_hash(key, data):
return "%s_signed_with_%s" % (data, key)
class TestSignatureService(unittest.TestCase):
def test_hashes_with_digest(self):
signature_service = SignatureService("fake_key", FakeDigest.hmac_hash)
signed = signature_service.sign({"foo": "bar"})
self.assertEqual("foo=bar_signed_with_fake_key|foo=bar", signed)
braintree_python-3.38.0/tests/fixtures/ 0000755 0001750 0001750 00000000000 13150065776 016310 5 ustar hle hle braintree_python-3.38.0/tests/fixtures/malformed_pdf.pdf 0000644 0001750 0001750 00000000226 13150065776 021602 0 ustar hle hle XXXXXXXXXXX¾?^gfkbfu¶šÙú”¼Åxc¯ÄÂÖÂñ•:x„BºS·É=]ÂóqçÅÒÃwî+= x wü/7ú7ÀÛeÀÅA¿8?À‹6Ã2[î(†¤Ö@+3[ß}
braintree_python-3.38.0/tests/fixtures/gif_extension_bt_logo.gif 0000644 0001750 0001750 00000004613 13150065776 023351 0 ustar hle hle ‰PNG
IHDR u ,G7ø sBIT|dˆ pHYs Ä Ä•+ tEXtSoftware www.inkscape.org›î< IDAThí›{°WUÇ?KyÉ› (ò
sCËÔñA0db¦å£$¨f´TC™b„|›SC# DÖÊR0)ˆ‚¢‚¼®€p/÷Ûký¼‡Ã9¿‹è½€ý¾3gÎïì½ÖÚk¿÷^kýŒc’ç›Ìlò‘Öçh„Ij—‘Wl4³òÚU©8$ÝüXefÝj@~ 5Pnf>mùµIÛ•
I«%Ý")«ãk’î Ý^!ùýBþë5!¿6Pxht ö+#¯1ÐèLÚ7Õ¾Ša°%žò éòkSé
%ý:òÊ%µ8R:Ö>+35f¶[Ò|†ÖN¶HM?”áû]_À€%À]föFHR#à`p:¾:¬f 3ÍLi=¢¬RÉïšÙø,½%ΉÏ]ÀÀ`0ÐX<
Ì(”'i"Ð89øZIšžý¶™Ý™(§05©0ø>p9¾7o 5³ÇR:ÖF— ð3Ì«A;7§^LJÜ+ñÔ€ÕÀ¤Û.o¦FÞ¥‘·CÒ ‰ô_¤öß©’veìËïH:9x:IÚPd §22hs÷TI%èÊ$Ê)ï7 žbzðrºcÒ:Iš—Ã;.Áw¢¤eEÊù¼“e5•´ ÏÓ’êguêVIã™
–Ç32UHoIתªÁ*%m”tµ¤¶’ºFÞ>I£‚§Ž¤Y’^‘4DRIŸ—46ø%éìŒNê%é;ñÜtÅ:õ«’nKT¸"êÓKR;IÓ"}¿¤Ó‚gxÔçW‘·9¾“Ï%©rŽ‹ô‚N…:üNRŸ¨ÛÏ"mEЛ¤ç"m½¤‹äÛ\Óµ;ònK•5+Ò7IºBRcIBïm‘7%«Só0«PùŒükÐìÔ6•×FRãTZ=Iu3ä,9cò:+è¾tEO¿’º$ô›Ê;^Ò–ÈœÊûØ{ª¤þ‰²&¥òLR—ÚrI3dŠü²BÛIê–VÏÐÈÛ'©uzOÝÜ¿O Nâëþy’™Ù¿rêö¸™½™Lȹ絮–Ôß¿Êð=îs‘ß(GþáBÀƒ)½öKZ´êgr*€ ©²ü;‘Ô?ÞeÀ]ÒAGˆÂ€oŒŸžIðì~œÁc@eðHwêf63•6IÒ}Àð«M²±2'ý#HÌÄL9>ˆZ}ªãýøÀ̶f¤WÖ@Yo›Ù¶jhšÅ»pY5´mR<
…§èé7Åx§v/B³ïäLÅ;ôAàV3Û ©%0‹üS›(tv½Ãà=”6XïÕÀAç‡v§xÞÃû ¢ÏžjDÑà?ŒÏþ»ÉÍo…=÷þB‡šg®ìOïÆûTI“’Α4âÊ
ïü/ #Íl[ò¶ã³±©™í
žùÀN|;¼)Í|C€SÌìC“4·&uÇGÆâ„-ðÆ®à‹Íìé¨à|üîÚßW%d»™´LȯL¿ã³v?p0_†Þ ÖšÙÁ3
¿›Ð_®? ^H¤¯0³±Á37úŸe, f›ÙTIჴ/>˜–ïG§{I‹ƒ÷-`°è|·“ÃÌæÊo#¢zg´ßd3›ŸÑ〻ãóoÀ`+ÐïÐøêif»‚ç»ÀCÁ³xŸ¹§ßŒvÜô¨Îö[ÀRI\þ%í-Bÿ^º"Ás®ªNI¬“´$ñ]žà¹ûô“¤ç