diff --git a/faker/providers/company/pt_BR/__init__.py b/faker/providers/company/pt_BR/__init__.py index f301f0ee24..9bf4e519db 100644 --- a/faker/providers/company/pt_BR/__init__.py +++ b/faker/providers/company/pt_BR/__init__.py @@ -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}}', @@ -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:]) diff --git a/faker/tests/pt_BR/__init__.py b/faker/tests/pt_BR/__init__.py index 68e0d2546f..c11146ca00 100644 --- a/faker/tests/pt_BR/__init__.py +++ b/faker/tests/pt_BR/__init__.py @@ -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 @@ -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))