Skip to content

Commit 1680414

Browse files
committed
feat(crud): add utils for crud package
1 parent 1a4498b commit 1680414

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed

internal/crud/utils.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package crud
2+
3+
import (
4+
"fmt"
5+
"strings"
6+
)
7+
8+
func ValidateName(name string) error {
9+
name = strings.TrimSpace(name)
10+
if name == "" {
11+
return fmt.Errorf("name cannot be empty")
12+
}
13+
if len(name) > 100 {
14+
return fmt.Errorf("name cannot exceed 100 characters")
15+
}
16+
return nil
17+
}
18+
19+
func ValidateID(id int64) error {
20+
if id <= 0 {
21+
return fmt.Errorf("ID must be positive")
22+
}
23+
return nil
24+
}

internal/crud/utils_test.go

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package crud
2+
3+
import "testing"
4+
5+
func TestValidateName(t *testing.T) {
6+
tests := []struct {
7+
name string
8+
valid bool
9+
}{
10+
{"valid-name", true},
11+
{"", false},
12+
{" ", false},
13+
{string(make([]byte, 101)), false},
14+
{"normal name", true},
15+
}
16+
17+
for _, test := range tests {
18+
err := ValidateName(test.name)
19+
if test.valid && err != nil {
20+
t.Errorf("expected %q to be valid, got error: %v", test.name, err)
21+
}
22+
if !test.valid && err == nil {
23+
t.Errorf("expected %q to be invalid, got no error", test.name)
24+
}
25+
}
26+
}
27+
28+
func TestValidateID(t *testing.T) {
29+
tests := []struct {
30+
id int64
31+
valid bool
32+
}{
33+
{1, true},
34+
{100, true},
35+
{0, false},
36+
{-1, false},
37+
}
38+
39+
for _, test := range tests {
40+
err := ValidateID(test.id)
41+
if test.valid && err != nil {
42+
t.Errorf("expected ID %d to be valid, got error: %v", test.id, err)
43+
}
44+
if !test.valid && err == nil {
45+
t.Errorf("expected ID %d to be invalid, got no error", test.id)
46+
}
47+
}
48+
}

0 commit comments

Comments
 (0)