This commit is contained in:
Lucas F. 2026-07-16 11:30:46 -03:00
commit 12b78d8483
8 changed files with 296 additions and 0 deletions

103
cnpj/generate_test.go Normal file
View file

@ -0,0 +1,103 @@
package cnpj
import (
"testing"
)
func TestGenerate(t *testing.T) {
for range 100 {
cnpj := Generate()
if len(cnpj) != 14 {
t.Fatalf("expected 14 digits, got %d: %s", len(cnpj), cnpj)
}
for _, c := range cnpj {
if c < '0' || c > '9' {
t.Fatalf("non-digit character %c in %s", c, cnpj)
}
}
if isRepetitive(cnpj) {
t.Fatalf("repetitive CNPJ generated: %s", cnpj)
}
if !validateDV(cnpj, false) {
t.Fatalf("invalid check digits for %s", cnpj)
}
}
}
func TestGenerateAlpha(t *testing.T) {
for range 100 {
cnpj := GenerateAlpha()
if len(cnpj) != 14 {
t.Fatalf("expected 14 chars, got %d: %s", len(cnpj), cnpj)
}
for _, c := range cnpj[:12] {
if !isAlphaNumeric(byte(c)) {
t.Fatalf("non-alphanumeric character %c in base of %s", c, cnpj)
}
}
for _, c := range cnpj[12:] {
if c < '0' || c > '9' {
t.Fatalf("DV must be digit, got %c in %s", c, cnpj)
}
}
if isRepetitive(cnpj) {
t.Fatalf("repetitive CNPJ generated: %s", cnpj)
}
if !validateDV(cnpj, true) {
t.Fatalf("invalid check digits for %s", cnpj)
}
}
}
func TestUniqueness(t *testing.T) {
seen := make(map[string]bool)
for range 50 {
cnpj := Generate()
if seen[cnpj] {
t.Fatalf("duplicate CNPJ generated: %s", cnpj)
}
seen[cnpj] = true
}
for range 50 {
cnpj := GenerateAlpha()
if seen[cnpj] {
t.Fatalf("duplicate CNPJ generated: %s", cnpj)
}
seen[cnpj] = true
}
}
func TestFormat(t *testing.T) {
tests := []struct {
input string
want string
}{
{"12345678000195", "12.345.678/0001-95"},
{"11111111111111", "11.111.111/1111-11"},
{"", ""},
{"123", "123"},
{"ABCDEFGHIJKLMN", "AB.CDE.FGH/IJKL-MN"},
}
for _, tt := range tests {
got := Format(tt.input)
if got != tt.want {
t.Errorf("Format(%q) = %q; want %q", tt.input, got, tt.want)
}
}
}
func isAlphaNumeric(c byte) bool {
return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z')
}
func validateDV(s string, alpha bool) bool {
if len(s) != 14 {
return false
}
if isRepetitive(s) {
return false
}
dv1 := computeDV(s[:12], cnpjP1, alpha)
dv2 := computeDV(s[:12]+string(byte('0'+dv1)), cnpjP2, alpha)
return int(s[12]-'0') == dv1 && int(s[13]-'0') == dv2
}