Skip to content

Commit

Permalink
Merge pull request #411 from lamenezes/pt-br-company-id
Browse files Browse the repository at this point in the history
Add support to brazilian company IDs (CNPJ)
  • Loading branch information
fcurella authored Oct 28, 2016
2 parents 7a96bac + c1a7531 commit aa0b3a6
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
29 changes: 29 additions & 0 deletions faker/providers/company/pt_BR/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,23 @@
from .. import Provider as CompanyProvider


def company_id_checksum(digits):
digits = list(digits)
weights = 6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2

dv = sum(w * d for w, d in zip(weights[1:], digits))
dv = (11 - dv) % 11
dv = 0 if dv >= 10 else dv
digits.append(dv)

dv2 = sum(w * d for w, d in zip(weights, digits))
dv2 = (11 - dv2) % 11
dv2 = 0 if dv2 >= 10 else dv2
digits.append(dv2)

return digits[-2:]


class Provider(CompanyProvider):
formats = (
'{{last_name}} {{company_suffix}}',
Expand Down Expand Up @@ -62,3 +79,15 @@ def catch_phrase(self):
catch_phrase = self.generator.parse(pattern)
catch_phrase = catch_phrase[0].upper() + catch_phrase[1:]
return catch_phrase

@classmethod
def company_id(cls):
digits = cls.random_sample(range(10), 8) + [0, 0, 0, 1]
digits += company_id_checksum(digits)
return ''.join(str(d) for d in digits)

@classmethod
def cnpj(cls):
digits = cls.company_id()
return '{}.{}.{}/{}-{}'.format(digits[:2], digits[2:5], digits[5:8],
digits[8:12], digits[12:])
18 changes: 16 additions & 2 deletions faker/tests/pt_BR/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import re

from faker import Factory
from faker.providers.company.pt_BR import Provider as CompanyProvider, company_id_checksum
from faker.providers.ssn.pt_BR import Provider, checksum


Expand All @@ -18,9 +19,22 @@ def test_pt_BR_ssn_checksum(self):
self.assertEqual(checksum([8, 8, 2, 8, 2, 1, 6, 5, 2, 2]), 1)

def test_pt_BR_ssn(self):
for i in range(100):
for _ in range(100):
self.assertTrue(re.search(r'^\d{11}$', Provider.ssn()))

def test_pt_BR_cpf(self):
for i in range(100):
for _ in range(100):
self.assertTrue(re.search(r'\d{3}\.\d{3}\.\d{3}\-\d{2}', Provider.cpf()))

def test_pt_BR_company_id_checksum(self):
self.assertEqual(company_id_checksum([9, 4, 9, 5, 3, 4, 4, 1, 0, 0, 0, 1]), [5, 1])
self.assertEqual(company_id_checksum([1, 6, 0, 0, 4, 6, 3, 9, 0, 0, 0, 1]), [8, 5])

def test_pt_BR_company_id(self):
for _ in range(100):
self.assertTrue(re.search(r'^\d{14}$', CompanyProvider.company_id()))

def test_pt_BR_cnpj(self):
for _ in range(100):
cnpj = CompanyProvider.cnpj()
self.assertTrue(re.search(r'\d{2}\.\d{3}\.\d{3}/0001-\d{2}', cnpj))

0 comments on commit aa0b3a6

Please sign in to comment.