import (
"fmt"
"os"
+ "strings"
"gopkg.in/yaml.v2"
)
hostMap := make(map[string]*Host)
for _, x := range hostList {
+ errPrefix := fmt.Sprintf("%s: host %q:", path, x.Name)
+ if x.Name == GroupAll {
+ return nil, fmt.Errorf(
+ "%s conflict with pre-defined group %q",
+ errPrefix, x.Name)
+ }
+ if strings.HasPrefix(x.Name, GroupDetectedPrefix) {
+ return nil, fmt.Errorf(
+ "%s name must not start with %q "+
+ "(reserved for detected groups)",
+ errPrefix, GroupDetectedPrefix)
+ }
+ if strings.Contains(x.Name, GroupSpecialSeparator) {
+ return nil, fmt.Errorf(
+ "%s name must not contain %q",
+ errPrefix, GroupSpecialSeparator)
+ }
+
hostMap[x.Name] = x
}
--- /dev/null
+// Copyright (C) 2021 Simon Ruderich
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+package config
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "reflect"
+ "testing"
+
+ "github.com/google/go-cmp/cmp"
+)
+
+func TestLoadHosts(t *testing.T) {
+ cwd, err := os.Getwd()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer os.Chdir(cwd)
+
+ sliceToHosts := func(hosts []*Host) *Hosts {
+ res := &Hosts{
+ List: hosts,
+ Map: make(map[string]*Host),
+ }
+ for _, x := range hosts {
+ res.Map[x.Name] = x
+ }
+ return res
+ }
+
+ tests := []struct {
+ path string
+ exp *Hosts
+ expErr error
+ }{
+
+ {
+ "../testdata/project",
+ sliceToHosts([]*Host{
+ {
+ Name: "host1.example.org",
+ },
+ {
+ Name: "host2",
+ },
+ {
+ Name: "host3.example.net",
+ },
+ }),
+ nil,
+ },
+
+ {
+ "../testdata/host-invalid-all",
+ nil,
+ fmt.Errorf("hosts.yaml: host \"all\": conflict with pre-defined group \"all\""),
+ },
+ {
+ "../testdata/host-invalid-detected",
+ nil,
+ fmt.Errorf("hosts.yaml: host \"detected\": name must not start with \"detected\" (reserved for detected groups)"),
+ },
+ {
+ "../testdata/host-invalid-special",
+ nil,
+ fmt.Errorf("hosts.yaml: host \"special:host\": name must not contain \":\""),
+ },
+ }
+
+ for _, tc := range tests {
+ err := os.Chdir(filepath.Join(cwd, tc.path))
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ res, err := LoadHosts()
+
+ if !reflect.DeepEqual(tc.exp, res) {
+ t.Errorf("%s: res: %s", tc.path,
+ cmp.Diff(tc.exp, res))
+ }
+ // Ugly but the simplest way to compare errors (including nil)
+ if fmt.Sprintf("%s", err) != fmt.Sprintf("%s", tc.expErr) {
+ t.Errorf("%s: err = %#v, want %#v",
+ tc.path, err, tc.expErr)
+ }
+ }
+}