Skip to content
This repository has been archived by the owner on Sep 15, 2023. It is now read-only.

Commit

Permalink
Validação do card_number (#97)
Browse files Browse the repository at this point in the history
* adiciona biblioteca de validação de cartão

* adiciona método de validação do número de cartão
  • Loading branch information
rodrigondec committed Aug 3, 2020
1 parent 0538d6e commit be41560
Show file tree
Hide file tree
Showing 8 changed files with 89 additions and 15 deletions.
7 changes: 5 additions & 2 deletions examples/transaction/add_transaction_invoice.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,14 @@
Mas é recomendado utilizar como variável de ambiente em um '.env'
"""
from zoop_wrapper.constants import MARKETPLACE_ID, ZOOP_KEY
from examples.seller.retrieve_seller import seller_id
from examples.buyer.retrieve_buyer import buyer_id


client = ZoopWrapper(marketplace_id=MARKETPLACE_ID, key=ZOOP_KEY)

seller_id = "3b94dc92dbad422ea49d44364f3b7b4b"
buyer_or_seller_id = "f85c8b84749c431ab0db044812ca7a57"
# seller_id = "3b94dc92dbad422ea49d44364f3b7b4b"
buyer_or_seller_id = buyer_id


quantia_em_centavos = "1000"
Expand All @@ -31,6 +33,7 @@
customer=buyer_or_seller_id,
description="meu boleto gerado para teste",
on_behalf_of=seller_id,
capture=True,
payment_type="boleto",
payment_method=Invoice(
expiration_date=vencimento,
Expand Down
3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
requests==2.23.0
python-decouple==3.3
pycpfcnpj==1.5.1
pycpfcnpj==1.5.1
card-identifier==1.*
7 changes: 6 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,12 @@
"",
],
python_requires=">=3.6",
install_requires=["requests>=2.23.0", "python-decouple>=3.3", "pycpfcnpj>=1.5.1"],
install_requires=[
"requests>=2.23.0",
"python-decouple>=3.3",
"pycpfcnpj>=1.5.1",
"card-identifier==1.0",
],
keywords="Zoop API client wrapper",
project_urls={
"Documentation": "https://zoop-wrapper.readthedocs.io",
Expand Down
53 changes: 45 additions & 8 deletions tests/models/test_token.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
from unittest.mock import MagicMock

from pycpfcnpj import gen
from factory.faker import Faker

from tests.utils import SetTestCase
from zoop_wrapper.models.bank_account import BankAccount
from zoop_wrapper.models.card import Card
from zoop_wrapper.models.token import Token
from zoop_wrapper.exceptions import ValidationError
from tests.factories.token import (
from ..utils import SetTestCase
from ..factories.token import (
CardTokenFactory,
CreateCardTokenFactory,
BankAccountTokenFactory,
CreateIndividualBankAccountTokenFactory,
CreateBusinessBankAccountTokenFactory,
)
from tests.factories.card import CardFactory
from tests.factories.bank_account import IndividualBankAccountFactory
from ..factories.card import CardFactory
from ..factories.bank_account import IndividualBankAccountFactory
from zoop_wrapper.models.bank_account import BankAccount
from zoop_wrapper.models.card import Card
from zoop_wrapper.models.token import Token
from zoop_wrapper.exceptions import ValidationError, FieldError


class TokenTestCase(SetTestCase):
Expand Down Expand Up @@ -92,6 +93,42 @@ def test_init_custom_fields_bank_account_individual(self):
self.assertEqual(instance.token_type, instance.BANK_ACCOUNT_TYPE)
self.assertEqual(instance.taxpayer_id, cpf)

def test_validate_custom_fields_card(self):
"""
Dado que está sendo criado um token de cartão t1 com número de cartão válido
Quando for chamado t1.validate_custom_fields(**kwargs)
Então a lista de erros deve estar vazia
"""

instance: Token = MagicMock(
card_number=Faker("credit_card_number").generate(),
token_type=Token.CARD_TYPE,
CARD_TYPE=Token.CARD_TYPE,
)

errors = Token.validate_custom_fields(instance)

self.assertEqual(len(errors), 0)

def test_validate_custom_fields_card_raise(self):
"""
Dado que está sendo criado um token de cartão t1 com número de cartão inválido
Quando for chamado t1.validate_custom_fields(**kwargs)
Então a lista de erros deve ter um elemento com as mensagens corretas
"""

instance: Token = MagicMock(
card_number="123", token_type=Token.CARD_TYPE, CARD_TYPE=Token.CARD_TYPE
)

result = Token.validate_custom_fields(instance)

self.assertEqual(len(result), 1)
error = result[0]
self.assertIsInstance(error, FieldError)
self.assertEqual(error.name, "card_number")
self.assertEqual(error.reason, "O número do cartão é inválido!")

def test_get_non_required_fields(self):
self.assertIsSubSet({"type", "used"}, Token.get_non_required_fields())

Expand Down
4 changes: 3 additions & 1 deletion zoop_wrapper/models/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,9 @@ def validate_fields(self, raise_exception=True, **kwargs):
for validation_field in self.get_validation_fields():
value = getattr(self, validation_field, None)
if value is None:
errors.append(FieldError(validation_field, "missing required field"))
errors.append(
FieldError(validation_field, "campo obrigatório faltando!")
)

errors.extend(self.validate_custom_fields(**kwargs))

Expand Down
2 changes: 1 addition & 1 deletion zoop_wrapper/models/base.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class ZoopObject:
def validate_fields(
self, raise_exception: Optional[bool] = ..., **kwargs: Dict[str, Any]
) -> None: ...
def validate_custom_fields(self, **kwargs: Dict[str, Any]) -> List[Any]: ...
def validate_custom_fields(self, **kwargs: Any) -> List[Any]: ...
def get_validation_fields(self) -> set: ...
def get_all_fields(self) -> set: ...
def get_original_different_fields_mapping(self) -> Dict[str, str]: ...
Expand Down
25 changes: 25 additions & 0 deletions zoop_wrapper/models/token.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from card_identifier.cardutils import validate_card

from .base import ResourceModel, BusinessOrIndividualModel
from .bank_account import BankAccount
from .card import Card
Expand Down Expand Up @@ -192,6 +194,29 @@ def get_all_fields(self):
else:
return fields.union(self.get_non_required_fields())

def validate_custom_fields(self, **kwargs):
"""
Valida campos do token.
Se for um token de cartão, valida o :attr:`.card_number`.
Args:
**kwargs:
Returns:
Lista com os erros ocorridos (se tiver algum!)
"""

errors = []
if self.token_type == self.CARD_TYPE:

if not validate_card(self.card_number):
errors.append(
FieldError("card_number", "O número do cartão é inválido!")
)

return errors

@classmethod
def get_non_required_fields(cls):
fields = super().get_non_required_fields()
Expand Down
3 changes: 2 additions & 1 deletion zoop_wrapper/models/token.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ from zoop_wrapper.models.base import (
)
from zoop_wrapper.models.card import Card as Card
from zoop_wrapper.utils import get_logger as get_logger
from typing import Any, Optional, Set, Dict, Union
from typing import Any, Optional, Set, Dict, Union, List

logger: Any

Expand Down Expand Up @@ -50,6 +50,7 @@ class Token(ResourceModel):
def get_bank_account_type(self): ...
def get_validation_fields(self): ...
def get_all_fields(self): ...
def validate_custom_fields(self, **kwargs: Any) -> List[Any]: ...
@classmethod
def get_non_required_fields(cls): ...
@classmethod
Expand Down

0 comments on commit be41560

Please sign in to comment.