Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
lima-vm
GitHub Repository: lima-vm/lima
Path: blob/master/pkg/textutil/textutil_test.go
2611 views
1
// SPDX-FileCopyrightText: Copyright The Lima Authors
2
// SPDX-License-Identifier: Apache-2.0
3
4
package textutil
5
6
import (
7
"bytes"
8
"testing"
9
"text/template"
10
11
"gotest.tools/v3/assert"
12
)
13
14
func TestPrefixString(t *testing.T) {
15
assert.Equal(t, "", PrefixString("- ", ""))
16
assert.Equal(t, "\n", PrefixString("- ", "\n"))
17
assert.Equal(t, "- foo", PrefixString("- ", "foo"))
18
assert.Equal(t, "- foo\n- bar\n", PrefixString("- ", "foo\nbar\n"))
19
assert.Equal(t, "- foo\n\n- bar\n", PrefixString("- ", "foo\n\nbar\n"))
20
}
21
22
func TestIndentString(t *testing.T) {
23
assert.Equal(t, " foo", IndentString(2, "foo"))
24
assert.Equal(t, " foo\n bar\n", IndentString(2, "foo\nbar\n"))
25
}
26
27
func TestMissingString(t *testing.T) {
28
assert.Equal(t, "no", MissingString("no", ""))
29
assert.Equal(t, "msg", MissingString("no", "msg"))
30
}
31
32
func TestTemplateFuncs(t *testing.T) {
33
type X struct {
34
Foo int `json:"foo" yaml:"foo"`
35
Bar string `json:"bar" yaml:"bar"`
36
Message string `json:"message,omitempty" yaml:"message,omitempty"`
37
Missing string `json:"missing,omitempty" yaml:"missing,omitempty"`
38
}
39
x := X{Foo: 42, Bar: "hello", Message: "One\nTwo\nThree", Missing: ""}
40
41
testCases := map[string]string{
42
"{{json .}}": `{"foo":42,"bar":"hello","message":"One\nTwo\nThree"}`,
43
"{{yaml .}}": `---
44
foo: 42
45
bar: hello
46
message: |-
47
One
48
Two
49
Three`,
50
`{{.Bar}}{{"\n"}}{{.Message | missing "<no message>" | indent 2}}`: "hello\n One\n Two\n Three",
51
`{{.Message | indent}}`: " One\n Two\n Three",
52
`{{.Missing | missing}}`: "<missing>",
53
}
54
55
for format, expected := range testCases {
56
tmpl, err := template.New("format").Funcs(TemplateFuncMap).Parse(format)
57
assert.NilError(t, err)
58
var b bytes.Buffer
59
assert.NilError(t, tmpl.Execute(&b, x))
60
assert.Equal(t, expected, b.String())
61
}
62
}
63
64