Skip to content

Commit 1a73063

Browse files
committed
chore: yaml helper
1 parent 434e8e0 commit 1a73063

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-0
lines changed

internal/fn/fn.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,12 @@ package fn
22

33
import (
44
"bufio"
5+
"fmt"
56
"os"
67
"sort"
78
"strings"
9+
10+
"gopkg.in/yaml.v2"
811
)
912

1013
func GetUserInputFromStdin() string {
@@ -31,3 +34,12 @@ func GetOrderMaps(m map[string]string) map[string]string {
3134
}
3235
return n
3336
}
37+
38+
func GetYamlBytes(data any) []byte {
39+
yamlData, err := yaml.Marshal(&data)
40+
if err != nil {
41+
fmt.Println("Error marshaling to YAML:", err)
42+
return nil
43+
}
44+
return yamlData
45+
}

internal/fn/fn_test.go

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package fn_test
22

33
import (
4+
"fmt"
45
"io"
56
"os"
67
"reflect"
@@ -94,3 +95,66 @@ func TestGetOrderMaps(t *testing.T) {
9495
})
9596
}
9697
}
98+
99+
func TestGetYamlBytes(t *testing.T) {
100+
tests := []struct {
101+
name string
102+
data interface{}
103+
want []byte
104+
}{
105+
{
106+
name: "Simple struct",
107+
data: struct {
108+
Name string
109+
Age int
110+
}{
111+
Name: "John Doe",
112+
Age: 30,
113+
},
114+
want: []byte("name: John Doe\nage: 30\n"),
115+
},
116+
{
117+
name: "Map",
118+
data: map[string]interface{}{
119+
"key1": "value1",
120+
"key2": 42,
121+
},
122+
want: []byte("key1: value1\nkey2: 42\n"),
123+
},
124+
{
125+
name: "Slice",
126+
data: []string{"apple", "banana", "cherry"},
127+
want: []byte("- apple\n- banana\n- cherry\n"),
128+
},
129+
{
130+
name: "Nil input",
131+
data: nil,
132+
want: []byte("null\n"),
133+
},
134+
}
135+
136+
for _, tt := range tests {
137+
t.Run(tt.name, func(t *testing.T) {
138+
got := Fn.GetYamlBytes(tt.data)
139+
if !reflect.DeepEqual(got, tt.want) {
140+
t.Errorf("GetYamlBytes() = %v, want %v", string(got), string(tt.want))
141+
}
142+
})
143+
}
144+
}
145+
146+
type UnmarshalableType struct{}
147+
148+
func (u UnmarshalableType) MarshalYAML() (interface{}, error) {
149+
return nil, fmt.Errorf("cannot marshal UnmarshalableType")
150+
}
151+
152+
func TestGetYamlBytesError(t *testing.T) {
153+
t.Run("Invalid input", func(t *testing.T) {
154+
invalidData := UnmarshalableType{}
155+
result := Fn.GetYamlBytes(invalidData)
156+
if result != nil {
157+
t.Errorf("GetYamlBytes(%v) = %v, want nil", invalidData, result)
158+
}
159+
})
160+
}

0 commit comments

Comments
 (0)