Skip to content

Commit

Permalink
1.0.0 - Validando e gerando documentos com máscaras
Browse files Browse the repository at this point in the history
  • Loading branch information
alvarofpp committed Mar 18, 2019
1 parent 182b83e commit 2b3e562
Show file tree
Hide file tree
Showing 11 changed files with 57 additions and 33 deletions.
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

setuptools.setup(
name="validate_docbr",
version="0.3.0",
version="1.0.0",
author="Álvaro Ferreira Pires de Paiva",
author_email="[email protected]",
description="Validate brazilian documents.",
Expand Down
7 changes: 6 additions & 1 deletion validate_docbr.egg-info/PKG-INFO
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
Metadata-Version: 2.1
Name: validate-docbr
Version: 0.3.0
Version: 1.0.0
Summary: Validate brazilian documents.
Home-page: https://github.com/alvarofpp/validate-docbr
Author: Álvaro Ferreira Pires de Paiva
Author-email: [email protected]
License: UNKNOWN
Description: # validate-docbr
<a href="https://pypi.org/project/validate-docbr/">
<img src="https://img.shields.io/pypi/v/validate-docbr.svg" alt="latest release" />
</a>

Pacote Python para validação de documentos brasileiros.

Para instalar o pacote:
Expand Down Expand Up @@ -67,6 +71,7 @@ Description: # validate-docbr
cns.validate(new_cns)

```

Platform: UNKNOWN
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Expand Down
1 change: 0 additions & 1 deletion validate_docbr.egg-info/SOURCES.txt
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ validate_docbr.egg-info/PKG-INFO
validate_docbr.egg-info/SOURCES.txt
validate_docbr.egg-info/dependency_links.txt
validate_docbr.egg-info/top_level.txt
validate_docbr/test/__init__.py
validate_docbr/test/t_CNPJ.py
validate_docbr/test/t_CNS.py
validate_docbr/test/t_CPF.py
12 changes: 8 additions & 4 deletions validate_docbr/BaseDoc.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,14 @@
class BaseDoc(ABC):
"""Classe base para todas as classes referentes a documentos."""

def validate(self, doc):
def validate(self, doc: str) -> bool:
"""Método para validar o documento desejado."""
return
pass

def generate(self):
def generate(self, mask: bool = False) -> str:
"""Método para gerar um documento válido."""
return
pass

def _only_digits(self, doc: str) -> str:
"""Remove os outros caracteres que não sejam dígitos."""
return "".join([x for x in doc if x.isdigit()])
16 changes: 11 additions & 5 deletions validate_docbr/CNPJ.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@ def __init__(self):
self.weights_first = list(range(5, 1, -1)) + list(range(9, 1, -1))
self.weights_second = list(range(6, 1, -1)) + list(range(9, 1, -1))

def validate(self, doc):
def validate(self, doc: str) -> bool:
"""Validar CNPJ."""
doc = self._only_digits(doc)

if len(doc) != 14:
return False

Expand All @@ -22,7 +24,7 @@ def validate(self, doc):
return self._generate_first_digit(doc) == doc[12]\
and self._generate_second_digit(doc) == doc[13]

def generate(self):
def generate(self, mask: bool = False) -> str:
"""Gerar CNPJ."""
# Os doze primeiros dígitos
cnpj = [str(sample(self.digits, 1)[0]) for i in range(12)]
Expand All @@ -31,9 +33,13 @@ def generate(self):
cnpj.append(self._generate_first_digit(cnpj))
cnpj.append(self._generate_second_digit(cnpj))

return "".join(cnpj)
cnpj = "".join(cnpj)
if mask:
return "53.977.783/0001-24".format(cnpj[:2], cnpj[2:5], cnpj[5:8], cnpj[8:12], cnpj[-2:])

return cnpj

def _generate_first_digit(self, doc):
def _generate_first_digit(self, doc: (str, list)) -> str:
"""Gerar o primeiro dígito verificador do CNPJ."""
sum = 0

Expand All @@ -49,7 +55,7 @@ def _generate_first_digit(self, doc):

return str(sum)

def _generate_second_digit(self, doc):
def _generate_second_digit(self, doc: (str, list)) -> str:
"""Gerar o segundo dígito verificador do CNPJ."""
sum = 0

Expand Down
30 changes: 17 additions & 13 deletions validate_docbr/CNS.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,28 +9,28 @@ def __init__(self):
self.digits = list(range(10))
self.first_digit = [1, 2, 7, 8, 9]

def validate(self, doc):
def validate(self, doc: str) -> bool:
"""Validar CNS."""
doc = list(doc)
doc = list(self._only_digits(doc))

if len(doc) != 15 or int(doc[0]) not in self.first_digit:
return False

return self._check_cns_valid(doc)

def _validate_first_case(self, doc):
def _validate_first_case(self, doc: list) -> bool:
"""Validar CNSs que comecem com 1 ou 2."""
cns = self._generate_first_case(doc)

return cns == doc

def _validate_second_case(self, doc):
def _validate_second_case(self, doc: list) -> bool:
"""Validar CNSs que comecem com 7, 8 ou 9."""
sum = self._sum_algorithm(doc)

return sum % 11 == 0

def generate(self):
def generate(self, mask: bool = False) -> str:
"""Gerar CNS."""
# Primeiro dígito válido
cns = [str(sample(self.first_digit, 1)[0])]
Expand All @@ -41,9 +41,13 @@ def generate(self):
else:
cns = self._generate_second_case(cns)

return "".join(cns)
cns = "".join(cns)
if mask:
return "{} {} {} {}".format(cns[:3], cns[3:7], cns[7:11], cns[-4:])

def _generate_first_case(self, cns, generate_random=False):
return cns

def _generate_first_case(self, cns: list, generate_random=False) -> list:
"""Gera um CNS válido para os casos que se inicia com 1 ou 2."""
if generate_random:
# Adiciona os próximos 10 dígitos
Expand All @@ -69,7 +73,7 @@ def _generate_first_case(self, cns, generate_random=False):

return cns

def _generate_second_case(self, cns):
def _generate_second_case(self, cns: list) -> list:
"""Gera um CNS válido para os casos que se inicia com 7, 8 ou 9."""
# Gerar os próximos 14 dígitos
cns = cns + [str(sample(list(range(10)), 1)[0]) for i in range(14)]
Expand All @@ -85,7 +89,7 @@ def _generate_second_case(self, cns):
# Verificar qual é o mais próximo
return self._change_cns(cns, 15 - diff, diff)

def _change_cns(self, cns, i, val):
def _change_cns(self, cns: list, i: int, val: int) -> list:
"""Altera o CNS recursivamente para que atenda as especificações de validade dele."""
if val == 0:
if self._check_cns_valid(cns):
Expand All @@ -103,21 +107,21 @@ def _change_cns(self, cns, i, val):
cns[i] = str(int(cns[i]) + 1)
val -= (15 - i)
else:
val += (15-i)
cns[i] = str(int(cns[i])-1)
val += (15 - i)
cns[i] = str(int(cns[i]) - 1)
i -= 1

return self._change_cns(cns, i, val)

def _sum_algorithm(self, cns, n=15):
def _sum_algorithm(self, cns: list, n: int = 15) -> int:
"""Realiza o processo de soma necessária para o CNS."""
sum = 0
for i in range(n):
sum += int(cns[i]) * (15 - i)

return sum

def _check_cns_valid(self, cns):
def _check_cns_valid(self, cns: list) -> bool:
"""Checa se o CNS é válido."""
if cns[0] in ['1', '2']:
return self._validate_first_case(cns)
Expand Down
16 changes: 11 additions & 5 deletions validate_docbr/CPF.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,17 @@ class CPF(BaseDoc):
def __init__(self):
self.digits = list(range(10))

def validate(self, doc):
def validate(self, doc: str) -> bool:
"""Validar CPF."""
doc = list(self._only_digits(doc))

if len(doc) != 11:
return False

return self._generate_first_digit(doc) == doc[9]\
and self._generate_second_digit(doc) == doc[10]

def generate(self):
def generate(self, mask: bool = False) -> str:
"""Gerar CPF."""
# Os nove primeiros dígitos
cpf = [str(sample(self.digits, 1)[0]) for i in range(9)]
Expand All @@ -25,9 +27,13 @@ def generate(self):
cpf.append(self._generate_first_digit(cpf))
cpf.append(self._generate_second_digit(cpf))

return "".join(cpf)
cpf = "".join(cpf)
if mask:
return "{}.{}.{}-{}".format(cpf[:3], cpf[3:6], cpf[6:9], cpf[-2:])

return cpf

def _generate_first_digit(self, doc):
def _generate_first_digit(self, doc: list) -> str:
"""Gerar o primeiro dígito verificador do CPF."""
sum = 0

Expand All @@ -41,7 +47,7 @@ def _generate_first_digit(self, doc):

return str(sum)

def _generate_second_digit(self, doc):
def _generate_second_digit(self, doc: list) -> str:
"""Gerar o segundo dígito verificador do CPF."""
sum = 0

Expand Down
Empty file removed validate_docbr/test/__init__.py
Empty file.
2 changes: 1 addition & 1 deletion validate_docbr/test/t_CNPJ.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

cnpj = CNPJ()

cnpjs = [cnpj.generate() for i in range(10000)]
cnpjs = [cnpj.generate() for i in range(10000)] + [cnpj.generate(mask=True) for i in range(10000)]

for i in cnpjs:
assert cnpj.validate(i)
2 changes: 1 addition & 1 deletion validate_docbr/test/t_CNS.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

cns = CNS()

cnss = [cns.generate() for i in range(10000)]
cnss = [cns.generate() for i in range(10000)] + [cns.generate(mask=True) for i in range(10000)]

for i in cnss:
assert cns.validate(i)
2 changes: 1 addition & 1 deletion validate_docbr/test/t_CPF.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

cpf = CPF()

cpfs = [cpf.generate() for i in range(10000)]
cpfs = [cpf.generate() for i in range(10000)] + [cpf.generate(mask=True) for i in range(10000)]

for i in cpfs:
assert cpf.validate(i)

0 comments on commit 2b3e562

Please sign in to comment.