Skip to content

Commit 0660581

Browse files
committed
Merge pull request joke2k#277 from ericchaves/master
added support for brazilian SSN (called CPF)
2 parents 348f03c + 504d768 commit 0660581

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

faker/providers/ssn/pt_BR/__init__.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# -*- coding: utf-8 -*-
2+
3+
from __future__ import unicode_literals
4+
from .. import Provider as SsnProvider
5+
from faker.generator import random
6+
7+
8+
def checksum(digits):
9+
s = 0
10+
p = len(digits) + 1
11+
for i in range(0, len(digits)):
12+
s += digits[i] * p
13+
p -= 1
14+
15+
reminder = s % 11
16+
if reminder == 0 or reminder == 1:
17+
return 1
18+
else:
19+
return 11 - reminder
20+
21+
22+
class Provider(SsnProvider):
23+
"""
24+
Provider for Brazilian SSN also known in Brazil as CPF.
25+
There are two methods Provider.ssn and Provider.cpf
26+
The snn returns a valid number with numbers only
27+
The cpf return a valid number formatted with brazilian mask. eg nnn.nnn.nnn-nn
28+
"""
29+
30+
@classmethod
31+
def ssn(cls):
32+
digits = random.sample(range(10), 9)
33+
34+
dv = checksum(digits)
35+
digits.append(dv)
36+
digits.append(checksum(digits))
37+
38+
return ''.join(map(str, digits))
39+
40+
@classmethod
41+
def cpf(cls):
42+
c = Provider.ssn()
43+
return c[:3] + '.' + c[3:6] + '.' + c[6:9] + '-' + c[9:]

faker/tests/pt_BR/__init__.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# -*- coding: utf-8 -*-
2+
3+
from __future__ import unicode_literals
4+
5+
import unittest
6+
import re
7+
8+
from faker import Factory
9+
from faker.providers.ssn.pt_BR import Provider, checksum
10+
11+
12+
class pt_BR_FactoryTestCase(unittest.TestCase):
13+
def setUp(self):
14+
self.factory = Factory.create('pt_BR')
15+
16+
def test_pt_BR_ssn_checksum(self):
17+
self.assertEqual(checksum([8, 8, 2, 8, 2, 1, 6, 5, 2]), 2)
18+
self.assertEqual(checksum([8, 8, 2, 8, 2, 1, 6, 5, 2, 2]), 1)
19+
20+
def test_pt_BR_ssn(self):
21+
for i in range(100):
22+
self.assertTrue(re.search(r'^\d{11}$', Provider.ssn()))
23+
24+
def test_pt_BR_cpf(self):
25+
for i in range(100):
26+
self.assertTrue(re.search(r'\d{3}\.\d{3}\.\d{3}\-\d{2}', Provider.cpf()))

0 commit comments

Comments
 (0)