Skip to content

Commit 076b2be

Browse files
committed
refactor(company): ensure reproducibility using injected random source for company and cnpj generation
1 parent 0fbbe3f commit 076b2be

File tree

2 files changed

+9
-6
lines changed

2 files changed

+9
-6
lines changed

pkg/mocai/entities/cnpj/generator.go

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,20 @@ import (
88
"time"
99
)
1010

11-
// GenerateCNPJ generates a valid CNPJ number.
11+
// GenerateCNPJ generates a valid CNPJ number using a custom random source.
1212
// If formatted is true, the CNPJ will be returned in the format XX.XXX.XXX/XXXX-XX.
1313
// If formatted is false, the CNPJ will be returned as a plain string of 14 digits.
14-
func GenerateCNPJ(formatted bool) (string, error) {
15-
src := rand.NewSource(time.Now().UnixNano())
16-
r := rand.New(src)
14+
// If rnd is nil, a default random source will be used.
15+
func GenerateCNPJ(formatted bool, rnd interface{ Intn(n int) int }) (string, error) {
16+
// Fallback to default if rnd is nil
17+
if rnd == nil {
18+
rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
19+
}
1720

1821
// Generate the first 12 digits
1922
digits := make([]int, 12)
2023
for i := 0; i < 8; i++ {
21-
digits[i] = r.Intn(10)
24+
digits[i] = rnd.Intn(10)
2225
}
2326
// Set the branch identifier to 0001 (common for new companies)
2427
digits[8], digits[9], digits[10], digits[11] = 0, 0, 0, 1

pkg/mocai/entities/company/countries/brazilian_company.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ func GenerateBrazilianCompany(lang string, formatted bool, rnd translations.Rand
2525
}
2626
companyName := companyNames[rnd.Intn(len(companyNames))]
2727

28-
cnpjVal, err := cnpj.GenerateCNPJ(formatted)
28+
cnpjVal, err := cnpj.GenerateCNPJ(formatted, rnd)
2929
if err != nil {
3030
return BrazilianCompany{}, err
3131
}

0 commit comments

Comments
 (0)