Files
nuntius/internal/config/config_test.go
T

111 lines
2.5 KiB
Go

// Copyright (c) 2026 Petr Balvín <opensource@petrbalvin.org> (https://petrbalvin.org)
// SPDX-License-Identifier: MIT
//go:build linux || freebsd
package config
import (
"os"
"path/filepath"
"testing"
)
func TestLoadWritesAndParsesDefault(t *testing.T) {
path := filepath.Join(t.TempDir(), "config.toml")
// The first Load writes the default template, then parses it back.
cfg, err := Load(path)
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.Server.Port != 8080 {
t.Errorf("Server.Port = %d, want 8080", cfg.Server.Port)
}
if cfg.DataDir != "./data" {
t.Errorf("DataDir = %q, want ./data", cfg.DataDir)
}
if len(cfg.Forms) != 3 {
t.Fatalf("len(Forms) = %d, want 3", len(cfg.Forms))
}
if cfg.Forms[0].Name != "contact" || cfg.Forms[0].SMTP.Host != "smtp.example.com" {
t.Errorf("Forms[0] = %#v", cfg.Forms[0])
}
if cfg.Forms[2].RateLimitPerHour != 100 {
t.Errorf("newsletter rate_limit_per_hour = %d, want 100", cfg.Forms[2].RateLimitPerHour)
}
}
func TestLoadExpandsEnvVars(t *testing.T) {
path := filepath.Join(t.TempDir(), "config.toml")
doc := `
data_dir = "./data"
[server]
port = 9000
[[forms]]
name = "contact"
type = "contact"
path = "/api/nuntius/contact"
to = "you@example.com"
[forms.smtp]
host = "smtp.example.com"
port = 587
user = "u@example.com"
password = "${NUNTIUS_TEST_PW}"
`
if err := os.WriteFile(path, []byte(doc), 0o644); err != nil {
t.Fatal(err)
}
t.Setenv("NUNTIUS_TEST_PW", "s3cret")
cfg, err := Load(path)
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.Forms[0].SMTP.Password != "s3cret" {
t.Errorf("password = %q, want s3cret", cfg.Forms[0].SMTP.Password)
}
}
func TestLoadRejectsUnknownField(t *testing.T) {
path := filepath.Join(t.TempDir(), "config.toml")
doc := `
bogus = true
[server]
port = 8080
[[forms]]
name = "contact"
path = "/api/nuntius/contact"
to = "you@example.com"
[forms.smtp]
host = "smtp.example.com"
port = 587
user = "u@example.com"
`
if err := os.WriteFile(path, []byte(doc), 0o644); err != nil {
t.Fatal(err)
}
if _, err := Load(path); err == nil {
t.Fatal("expected an error for an unknown field")
}
}
func TestConfigPath(t *testing.T) {
if got := ConfigPath(); got != "/etc/nuntius/config.toml" {
t.Errorf("ConfigPath() = %q, want %q", got, "/etc/nuntius/config.toml")
}
}
func TestSMTPConfigAddrFor(t *testing.T) {
smtp := SMTPConfig{Host: "smtp.example.com", Port: 587}
if got := smtp.AddrFor(); got != "smtp.example.com:587" {
t.Errorf("AddrFor() = %q, want %q", got, "smtp.example.com:587")
}
}