Home

cfg @5edec76b62d532dbb0e67a427b43377277660ad2 - refs - log -
-
https://git.jolheiser.com/cfg.git
Convert between various configuration formats
cfg / cfg_test.go
- raw
 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
package cfg

import (
	"testing"

	"github.com/matryer/is"
	"go.jolheiser.com/nixfig"
)

type TestData struct {
	Foo string
	Baz bool
	Bux int
	Qux TestSubData
}

type TestSubData struct {
	Honk  string
	Chonk int
	Gonk  bool
}

func TestEncoding(t *testing.T) {
	final := TestData{
		Foo: "bar",
		Baz: true,
		Bux: 10,
		Qux: TestSubData{
			Honk:  "bonk",
			Chonk: 50,
			Gonk:  false,
		},
	}

	// Each decode-only [Encoding]
	tt := []struct {
		Name     string
		Input    string
		Encoding Encoding
	}{
		{
			Name: "dhall",
			Input: `
		{
			Foo = "bar"
			, Baz = True
			, Bux = 10
			, Qux = {
				Honk = "bonk"
				, Chonk = 50
				, Gonk = False
			}
		}
	`,
			Encoding: DHALL,
		}, {
			Name: "jsonnet",
			Input: `
		{
			Foo: "bar",
			Baz: true,
			Bux: 10,
			Qux: {
				Honk: "bonk",
				Chonk: 50,
				Gonk: false,
			}
		}
	`,
			Encoding: JSONNET,
		},
	}

	encoders := []Encoding{JSON, JSONC, YAML, TOML, KDL}
	// Only test nix if it's available
	if nixfig.Nix != "" {
		encoders = append(encoders, NIX)
	}

	for _, tc := range tt {
		t.Run(tc.Name, func(t *testing.T) {
			assert := is.New(t)
			var data TestData
			err := tc.Encoding.Unmarshal([]byte(tc.Input), &data)
			assert.NoErr(err) // Should be able to unmarshal

			for _, e := range encoders {
				out, err := e.Marshal(data)
				assert.NoErr(err) // Should be able to marshal
				err = e.Unmarshal(out, &data)
				assert.NoErr(err) // Should be able to unmarshal
			}
			assert.Equal(data, final) // Final structs should be equal
		})
	}
}