1//+build integration
2
3package integration
4
5import (
6	"net"
7	"net/http"
8
9	. "gopkg.in/check.v1"
10
11	"gotest.tools/v3/fs"
12	"gotest.tools/v3/icmd"
13)
14
15type MergeDatasourceSuite struct {
16	tmpDir *fs.Dir
17	l      *net.TCPListener
18}
19
20var _ = Suite(&MergeDatasourceSuite{})
21
22func (s *MergeDatasourceSuite) SetUpSuite(c *C) {
23	s.tmpDir = fs.NewDir(c, "gomplate-inttests",
24		fs.WithFiles(map[string]string{
25			"config.json": `{"foo": {"bar": "baz"}, "isDefault": false, "isOverride": true}`,
26			"default.yml": "foo:\n  bar: qux\nother: true\nisDefault: true\nisOverride: false\n",
27		}),
28	)
29
30	var err error
31	s.l, err = net.ListenTCP("tcp", &net.TCPAddr{IP: net.ParseIP("127.0.0.1")})
32	handle(c, err)
33
34	http.HandleFunc("/foo.json", typeHandler("application/json", `{"foo": "bar"}`))
35	http.HandleFunc("/1.env", typeHandler("application/x-env", "FOO=1\nBAR=2\n"))
36	http.HandleFunc("/2.env", typeHandler("application/x-env", "FOO=3\n"))
37	go http.Serve(s.l, nil)
38}
39
40func (s *MergeDatasourceSuite) TearDownSuite(c *C) {
41	s.l.Close()
42	s.tmpDir.Remove()
43}
44
45func (s *MergeDatasourceSuite) TestMergeDatasource(c *C) {
46	result := icmd.RunCommand(GomplateBin,
47		"-d", "user="+s.tmpDir.Join("config.json"),
48		"-d", "default="+s.tmpDir.Join("default.yml"),
49		"-d", "config=merge:user|default",
50		"-i", `{{ ds "config" | toJSON }}`,
51	)
52	result.Assert(c, icmd.Expected{ExitCode: 0, Out: `{"foo":{"bar":"baz"},"isDefault":false,"isOverride":true,"other":true}`})
53
54	result = icmd.RunCommand(GomplateBin,
55		"-d", "default="+s.tmpDir.Join("default.yml"),
56		"-d", "config=merge:user|default",
57		"-i", `{{ defineDatasource "user" `+"`"+s.tmpDir.Join("config.json")+"`"+` }}{{ ds "config" | toJSON }}`,
58	)
59	result.Assert(c, icmd.Expected{ExitCode: 0, Out: `{"foo":{"bar":"baz"},"isDefault":false,"isOverride":true,"other":true}`})
60
61	result = icmd.RunCommand(GomplateBin,
62		"-d", "default="+s.tmpDir.Join("default.yml"),
63		"-d", "config=merge:http://"+s.l.Addr().String()+"/foo.json|default",
64		"-i", `{{ ds "config" | toJSON }}`,
65	)
66	result.Assert(c, icmd.Expected{ExitCode: 0, Out: `{"foo":"bar","isDefault":true,"isOverride":false,"other":true}`})
67
68	result = icmd.RunCommand(GomplateBin,
69		"-c", "merged=merge:http://"+s.l.Addr().String()+"/2.env|http://"+s.l.Addr().String()+"/1.env",
70		"-i", `FOO is {{ .merged.FOO }}`,
71	)
72	result.Assert(c, icmd.Expected{ExitCode: 0, Out: `FOO is 3`})
73}
74