Files
ssh-netbox-wrapper/cmd/netssh/link_test.go
Sebastian UnterschützandClaude Opus 5.5 e905a39068 feat: add netssh link and shell aliases for links
netssh link add|list|remove manages links; netssh NAME follows them, links
complete with Tab and get a shell alias.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:07:09 +01:00

86 lines
2.3 KiB
Go

package main
import (
"os"
"path/filepath"
"strings"
"testing"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/hook"
)
func TestLinksResolveAndBecomeAliases(t *testing.T) {
dnsEnv(t, "links:\n mx123: prod/web07\n")
cfg, err := config.Load()
if err != nil {
t.Fatal(err)
}
h, err := resolveTargetE(cfg, "MX123", false)
if err != nil || h.Name != "prod/web07" {
t.Fatalf("link not followed: %+v %v", h, err)
}
var found bool
for _, a := range hook.BuildAliasEntries(nil, *cfg) {
if a.Name == "mx123" && a.Host == "mx123" {
found = true
}
}
if !found {
t.Fatal("link has no shell alias")
}
if got := completeHosts("mx"); len(got) == 0 || got[0] != "mx123" {
t.Fatalf("completion: %v", got)
}
}
func TestLinkAddListRemove(t *testing.T) {
dnsEnv(t, "")
stubTerminal(t, false)
run := func(args ...string) (string, error) {
var out strings.Builder
cmd := rootCmd()
cmd.SetOut(&out)
cmd.SetArgs(args)
err := cmd.Execute()
return out.String(), err
}
if _, err := run("link", "add", "mx123", "prod/web07"); err != nil {
t.Fatal(err)
}
data, _ := os.ReadFile(filepath.Join(os.Getenv("XDG_CONFIG_HOME"), "netssh.yaml"))
if !strings.Contains(string(data), "links:\n mx123: \"prod/web07\"") {
t.Fatalf("link not written:\n%s", data)
}
if out, _ := run("link", "list"); !strings.Contains(out, "mx123 prod/web07") {
t.Fatalf("list: %q", out)
}
if _, err := run("link", "add", "x", "missing-host"); err == nil {
t.Fatal("link to unknown host accepted")
}
if _, err := run("link", "remove", "mx123"); err != nil {
t.Fatal(err)
}
cfg, _ := config.Load()
if len(cfg.Links) != 0 {
t.Fatalf("not removed: %v", cfg.Links)
}
}
func TestValidateLinks(t *testing.T) {
for _, tc := range []struct {
cfg config.Config
ok bool
}{
{config.Config{Links: map[string]string{"mx123": "prod/web07"}}, true},
{config.Config{Links: map[string]string{"bad name": "web"}}, false},
{config.Config{Links: map[string]string{"a": "-oProxyCommand=x"}}, false},
{config.Config{Links: map[string]string{"a": "b", "b": "web"}}, false},
{config.Config{Links: map[string]string{"router": "web"}, Hosts: []config.StaticHost{{Name: "router", Address: "1.2.3.4"}}}, false},
} {
if err := tc.cfg.ValidateLinks(); (err == nil) != tc.ok {
t.Errorf("%v: %v", tc.cfg.Links, err)
}
}
}