diff --git a/changes/1317-samuelcolvin.md b/changes/1317-samuelcolvin.md new file mode 100644 index 0000000..af16af0 --- /dev/null +++ b/changes/1317-samuelcolvin.md @@ -0,0 +1 @@ +fix card number length check in `PaymentCardNumber`, `PaymentCardBrand` now inherits from `str`. diff --git a/pydantic/types.py b/pydantic/types.py index 2aa4c96..b7627bb 100644 --- a/pydantic/types.py +++ b/pydantic/types.py @@ -591,7 +591,7 @@ class SecretBytes: return self._secret_value -class PaymentCardBrand(Enum): +class PaymentCardBrand(str, Enum): amex = 'American Express' mastercard = 'Mastercard' visa = 'Visa' @@ -666,7 +666,7 @@ class PaymentCardNumber(str): https://en.wikipedia.org/wiki/Payment_card_number#Issuer_identification_number_(IIN) """ required_length: Optional[int] = None - if card_number.brand is (PaymentCardBrand.visa or PaymentCardBrand.mastercard): + if card_number.brand in {PaymentCardBrand.visa, PaymentCardBrand.mastercard}: required_length = 16 valid = len(card_number) == required_length elif card_number.brand is PaymentCardBrand.amex: diff --git a/tests/test_types_payment_card_number.py b/tests/test_types_payment_card_number.py index 28cbe15..dcf321c 100644 --- a/tests/test_types_payment_card_number.py +++ b/tests/test_types_payment_card_number.py @@ -78,6 +78,7 @@ def test_validate_luhn_check_digit(card_number: str, valid: bool): (VALID_AMEX, PaymentCardBrand.amex, True), (VALID_OTHER, PaymentCardBrand.other, True), (LEN_INVALID, PaymentCardBrand.visa, False), + (VALID_AMEX, PaymentCardBrand.mastercard, False), ], ) def test_length_for_brand(card_number: str, brand: PaymentCardBrand, valid: bool): @@ -123,3 +124,21 @@ def test_error_types(card_number: Any, error_message: str): with pytest.raises(ValidationError, match=error_message) as exc_info: PaymentCard(card_number=card_number) assert exc_info.value.json().startswith('[') + + +def test_payment_card_brand(): + b = PaymentCardBrand.visa + assert str(b) == 'Visa' + assert b is PaymentCardBrand.visa + assert b == PaymentCardBrand.visa + assert b in {PaymentCardBrand.visa, PaymentCardBrand.mastercard} + + b = 'Visa' + assert b is not PaymentCardBrand.visa + assert b == PaymentCardBrand.visa + assert b in {PaymentCardBrand.visa, PaymentCardBrand.mastercard} + + b = PaymentCardBrand.amex + assert b is not PaymentCardBrand.visa + assert b != PaymentCardBrand.visa + assert b not in {PaymentCardBrand.visa, PaymentCardBrand.mastercard}