This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
package configuration
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func validConfiguration() Configuration {
|
||||
return Configuration{
|
||||
Host: "0.0.0.0",
|
||||
Port: 9090,
|
||||
LogLevel: 4,
|
||||
Shelly: ShellyConfiguration{
|
||||
TimeoutSeconds: 10,
|
||||
Devices: []DeviceConfiguration{
|
||||
{Name: "office", Product: "plug_s", URL: "http://192.168.0.30", Username: "admin", Password: "secret"},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigurationValidate(t *testing.T) {
|
||||
config := validConfiguration()
|
||||
if err := config.Validate(); err != nil {
|
||||
t.Fatalf("Validate() returned an unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigurationRejectsDuplicateDeviceNames(t *testing.T) {
|
||||
config := validConfiguration()
|
||||
config.Shelly.Devices = append(config.Shelly.Devices, config.Shelly.Devices[0])
|
||||
|
||||
err := config.Validate()
|
||||
if err == nil || !strings.Contains(err.Error(), "configured more than once") {
|
||||
t.Fatalf("Validate() error = %v, want duplicate name error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadAppliesTimeoutDefaultAndRejectsUnknownFields(t *testing.T) {
|
||||
directory := t.TempDir()
|
||||
validPath := filepath.Join(directory, "valid.yaml")
|
||||
validYAML := []byte(`host: 0.0.0.0
|
||||
port: 9090
|
||||
logLevel: 4
|
||||
shelly:
|
||||
devices:
|
||||
- name: office
|
||||
product: plug_s
|
||||
url: http://192.168.0.30
|
||||
`)
|
||||
if err := os.WriteFile(validPath, validYAML, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
config, err := Load(validPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Load() returned an unexpected error: %v", err)
|
||||
}
|
||||
if config.Shelly.TimeoutSeconds != defaultTimeoutSeconds {
|
||||
t.Fatalf("TimeoutSeconds = %d, want %d", config.Shelly.TimeoutSeconds, defaultTimeoutSeconds)
|
||||
}
|
||||
|
||||
invalidPath := filepath.Join(directory, "invalid.yaml")
|
||||
if err := os.WriteFile(invalidPath, append(validYAML, []byte("unknown: true\n")...), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := Load(invalidPath); err == nil {
|
||||
t.Fatal("Load() accepted an unknown field")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user