1 // SPDX-License-Identifier: GPL-3.0-or-later
2 // Copyright (C) 2021-2024 Simon Ruderich
12 "ruderich.org/simon/safcm"
13 "ruderich.org/simon/safcm/testutil"
16 func TestLoadTemplates(t *testing.T) {
17 cwd, err := os.Getwd()
21 defer os.Chdir(cwd) //nolint:errcheck
23 err = os.Chdir("../testdata/project")
28 allHosts, err := LoadHosts()
32 allGroups, err := LoadGroups(&Config{}, allHosts)
36 host := "host1.example.org"
37 groups, err := ResolveHostGroups(host, allGroups,
38 []string{"detected_amd64", "detected_linux"})
45 exp map[string]*safcm.File
57 map[string]*safcm.File{
60 Mode: fs.ModeDir | 0755,
66 Mode: fs.ModeDir | 0755,
82 Data: []byte(`Welcome to Host ONE
85 This is GNU/Linux host
100 Path: "/etc/rc.local",
104 Data: []byte("#!/bin/sh\n"),
106 "/etc/resolv.conf": {
107 Path: "/etc/resolv.conf",
111 Data: []byte("nameserver ::1\n"),
115 Mode: fs.ModeSymlink | 0777,
118 Data: []byte("doesnt-exist"),
125 "templates-invalid-group",
126 map[string]*safcm.File{
129 Mode: fs.ModeDir | 0755,
135 Mode: fs.ModeDir | 0755,
145 {{if .InGroup "invalid-group"}}
151 fmt.Errorf("templates-invalid-group/templates.yaml: template: templates-invalid-group/files/etc/motd:2:5: executing \"templates-invalid-group/files/etc/motd\" at <.InGroup>: error calling InGroup: group \"invalid-group\" does not exist"),
154 "templates-invalid-host",
155 map[string]*safcm.File{
158 Mode: fs.ModeDir | 0755,
164 Mode: fs.ModeDir | 0755,
174 {{if .IsHost "invalid-host"}}
180 fmt.Errorf("templates-invalid-host/templates.yaml: template: templates-invalid-host/files/etc/motd:2:5: executing \"templates-invalid-host/files/etc/motd\" at <.IsHost>: error calling IsHost: host \"invalid-host\" does not exist"),
183 "templates-invalid-path",
185 fmt.Errorf("templates-invalid-path/templates.yaml: \"/etc/motd\" does not exist in files/"),
188 "templates-invalid-template",
189 map[string]*safcm.File{
192 Mode: fs.ModeDir | 0755,
198 Mode: fs.ModeDir | 0755,
207 Data: []byte("{{\n"),
210 fmt.Errorf("templates-invalid-template/templates.yaml: invalid template: templates-invalid-template/files/etc/motd:2: unclosed action started at templates-invalid-template/files/etc/motd:1"),
213 "templates-invalid-type",
214 map[string]*safcm.File{
217 Mode: fs.ModeDir | 0755,
223 Mode: fs.ModeDir | 0755,
235 fmt.Errorf("templates-invalid-type/templates.yaml: \"/etc\" is not a regular file"),
239 for _, tc := range tests {
240 t.Run(tc.group, func(t *testing.T) {
241 // Use LoadFiles() so we work on real data and don't
242 // make any mistakes generating it
243 files, err := LoadFiles(tc.group)
245 t.Fatalf("err = %#v, want nil", err)
247 err = LoadTemplates(tc.group, files,
248 host, groups, allHosts, allGroups)
250 testutil.AssertEqual(t, "res", files, tc.exp)
251 testutil.AssertErrorEqual(t, "err", err, tc.expErr)