-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathomitempty_test.go
More file actions
106 lines (89 loc) · 2.3 KB
/
omitempty_test.go
File metadata and controls
106 lines (89 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package piml
import (
"bytes"
"strings"
"testing"
)
type ComprehensiveOmitemptyStruct struct {
Name string `piml:"name,omitempty"`
Age int `piml:"age,omitempty"`
Price float64 `piml:"price,omitempty"`
IsActive bool `piml:"is_active,omitempty"`
Tags []string `piml:"tags,omitempty"`
Meta map[string]string `piml:"meta,omitempty"`
Ptr *int `piml:"ptr,omitempty"`
Address string `piml:"address"` // Required field
}
func TestOmitempty_AllEmpty(t *testing.T) {
s := ComprehensiveOmitemptyStruct{
Address: "123 Main St",
}
var buf bytes.Buffer
enc := NewEncoder(&buf)
err := enc.Encode(s)
if err != nil {
t.Fatalf("Encode failed: %v", err)
}
got := buf.String()
expectedMissing := []string{
"name", "age", "price", "is_active", "tags", "meta", "ptr",
}
for _, field := range expectedMissing {
if strings.Contains(got, field) {
t.Errorf("Expected '%s' to be omitted, but it was found in output:\n%s", field, got)
}
}
if !strings.Contains(got, "address") {
t.Errorf("Expected 'address' to be present, but it was missing.")
}
}
func TestOmitempty_NoneEmpty(t *testing.T) {
val := 42
s := ComprehensiveOmitemptyStruct{
Name: "Alice",
Age: 30,
Price: 19.99,
IsActive: true,
Tags: []string{"a", "b"},
Meta: map[string]string{"key": "value"},
Ptr: &val,
Address: "123 Main St",
}
var buf bytes.Buffer
enc := NewEncoder(&buf)
err := enc.Encode(s)
if err != nil {
t.Fatalf("Encode failed: %v", err)
}
got := buf.String()
expectedPresent := []string{
"name", "age", "price", "is_active", "tags", "meta", "ptr", "address",
}
for _, field := range expectedPresent {
if !strings.Contains(got, field) {
t.Errorf("Expected '%s' to be present, but it was missing in output:\n%s", field, got)
}
}
}
func TestOmitempty_Partial(t *testing.T) {
s := ComprehensiveOmitemptyStruct{
Name: "Bob",
Address: "456 Side St",
// Age: 0 (omit)
// Price: 0.0 (omit)
// IsActive: false (omit)
}
var buf bytes.Buffer
enc := NewEncoder(&buf)
err := enc.Encode(s)
if err != nil {
t.Fatalf("Encode failed: %v", err)
}
got := buf.String()
if !strings.Contains(got, "name") {
t.Errorf("Expected 'name' to be present.")
}
if strings.Contains(got, "age") {
t.Errorf("Expected 'age' to be omitted.")
}
}