def register(): cs = CardSchema() payload = request.json try: card_data = cs.load(payload) # informações tradatas/validadas except ValidationError as e: return e.args[0] card_number = card_data['number'] cc = CreditCard(card_number) if not cc.is_valid(): return "Número de cartão de crédito inválido" exp_date = format_date(card_data["exp_date"]) card = Card() card.number = card_data["number"] card.cvv = card_data["cvv"] card.holder = card_data["holder"] card.exp_date = exp_date try: card.brand = cc.get_brand() except BrandNotFound: return {"message": "Card brand not found"} current_app.db.session.add(card) current_app.db.session.commit() return {"message": "Card saved"}
class CardSchema(CardResponseSchema): holder_name = fields.Str( required=True, ) cvv = fields.Str( required=True, ) brand = fields.Str( required=False, ) @post_load def add_extra_data(self, data): data["brand"] = self._creditcard.brand().value return data @validates("number") def validate_number(self, number): self._creditcard = CreditCard(number) if self._creditcard.is_valid() is False: raise ValidationError("Invalid credit card.") @validates("expiration_date") def validate_expiration_date(self, expiration_date): if re.match(r'\d{2}/\d{4}', expiration_date) is None: raise ValidationError("The expiration_date isn't valid date.") expiration_date_parse = datetime.datetime.strptime( expiration_date, "%m/%Y" ) if expiration_date_parse.date() < datetime.datetime.today().date(): raise ValidationError( "The credit card it's expired") @validates("holder_name") def validate_holder_name(self, holder_name): if len(holder_name.split(" ")) < 2: raise ValidationError("The holder_name it's invalid.")
def test_brand_method_should_get_unknown_for_brands_without_support(): credit_card = CreditCard("6062829888053968") assert credit_card.is_valid() assert credit_card.brand() == Brands.UNKNOWN
def test_get_true_for_mastercard(): credit_card = CreditCard("5558078345914460") assert credit_card.is_valid() assert credit_card.brand() == Brands.MASTERCARD
def test_get_true_for_visa_card(): credit_card = CreditCard("4114047196786871") assert credit_card.is_valid() assert credit_card.brand() == Brands.VISA
def test_get_false_when_setting_none_number(): credit_card = CreditCard(None) assert credit_card.is_valid() is False assert credit_card.brand() == Brands.UNKNOWN
def test_get_false_and_unknow_for_any_number(): credit_card = CreditCard("xxxxaa") assert credit_card.is_valid() is False assert credit_card.brand() == Brands.UNKNOWN
def test_get_true_even_with_blank_space(): credit_card = CreditCard("411 4047 1967 868 71") assert credit_card.is_valid() assert credit_card.brand() == Brands.VISA
def validate_number(self, number): self._creditcard = CreditCard(number) if self._creditcard.is_valid() is False: raise ValidationError("Invalid credit card.")