From a7aa55aff04247d1b158e7ecc76fd0d8eb1e47ca Mon Sep 17 00:00:00 2001 From: orvice Date: Sun, 17 May 2026 01:03:14 +0800 Subject: [PATCH] refactor: improve testability across app, ip, dns, notify, config - App.Run now uses a Ticker, returns error instead of os.Exit, and exposes WithInterval for tests; updateIP split into findRecord / appendRecord / updateRecord helpers. - IfconfigCo accepts an injectable HTTP client and URL via the new NewIfconfigCo constructor; production path unchanged. - dns.New returns (LibDNS, error) so unknown providers fail loudly; empty value still defaults to Cloudflare. - notify drops the package-level notifiers slice / Init / AddNotifier / Notify globals. TelegramNotifier now depends on a minimal tgSender interface; new MultiNotifier replaces the global fan-out. - config.New uses an independent viper.New() instance with explicit BindEnv calls so tests can run without sharing global viper state. - main.go propagates Run errors and exits non-zero on failure. - Added unit tests with hand-written fakes for app, ip (httptest), dns provider selection, and notify (fake bot + MultiNotifier). Co-Authored-By: Craft Agent Co-Authored-By: Claude Opus 4.7 (1M context) --- cmd/ddns/main.go | 9 +-- dns/dns.go | 25 +++++-- dns/dns_test.go | 21 ++++++ internal/app/app.go | 118 ++++++++++++++++------------- internal/app/app_test.go | 153 ++++++++++++++++++++++++++++++++++++++ internal/config/config.go | 39 ++++++++-- internal/ip/ip.go | 55 +++++++++++--- internal/ip/ip_test.go | 44 ++++++++++- internal/wire/wire_gen.go | 5 +- notify/notify.go | 39 +++++++--- notify/notify_test.go | 61 +++++++++++++++ 11 files changed, 470 insertions(+), 99 deletions(-) create mode 100644 internal/app/app_test.go create mode 100644 notify/notify_test.go diff --git a/cmd/ddns/main.go b/cmd/ddns/main.go index a098eda..8af2a09 100644 --- a/cmd/ddns/main.go +++ b/cmd/ddns/main.go @@ -8,15 +8,14 @@ import ( "github.com/orvice/ddns/internal/wire" ) -var ( - IPNotifyFormat = "[%s] ip changed, old IP: %s new IP: %s" -) - func main() { app, err := wire.NewApp() if err != nil { slog.Error("init app error", "error", err) os.Exit(1) } - app.Run(context.Background()) + if err := app.Run(context.Background()); err != nil { + slog.Error("app run error", "error", err) + os.Exit(1) + } } diff --git a/dns/dns.go b/dns/dns.go index 1a7ae49..b5dd1ad 100644 --- a/dns/dns.go +++ b/dns/dns.go @@ -1,35 +1,44 @@ package dns import ( + "fmt" + "github.com/libdns/alidns" "github.com/libdns/cloudflare" "github.com/libdns/libdns" "github.com/orvice/ddns/internal/config" ) +const ( + ProviderCloudflare = "cloudflare" + ProviderAliyun = "aliyun" +) + type LibDNS interface { libdns.RecordGetter libdns.RecordAppender libdns.RecordSetter } -func New(conf *config.Config) LibDNS { +// New returns the DNS provider selected by conf.DNSProvider. An empty value +// defaults to Cloudflare; an unknown value returns an error so misconfiguration +// fails loudly. +func New(conf *config.Config) (LibDNS, error) { switch conf.DNSProvider { - case "cloudflare": - return NewCloudFlare(conf) - case "aliyun": - return NewAliyun(conf) + case "", ProviderCloudflare: + return NewCloudFlare(conf), nil + case ProviderAliyun: + return NewAliyun(conf), nil + default: + return nil, fmt.Errorf("unknown dns provider: %q", conf.DNSProvider) } - return NewCloudFlare(conf) } -// cloudflare func NewCloudFlare(conf *config.Config) LibDNS { provider := cloudflare.Provider{APIToken: conf.CFToken} return &provider } -// aliyun func NewAliyun(conf *config.Config) LibDNS { provider := alidns.Provider{ AccKeyID: conf.AliyunAccessKeyID, diff --git a/dns/dns_test.go b/dns/dns_test.go index 353b556..f562168 100644 --- a/dns/dns_test.go +++ b/dns/dns_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/libdns/cloudflare" + "github.com/orvice/ddns/internal/config" ) func TestCloudFlare(t *testing.T) { @@ -17,3 +18,23 @@ func TestCloudFlare(t *testing.T) { } t.Log(records) } + +func TestNew_DefaultsToCloudflare(t *testing.T) { + d, err := New(&config.Config{}) + if err != nil || d == nil { + t.Fatalf("expected default cloudflare provider, got err=%v d=%v", err, d) + } +} + +func TestNew_Aliyun(t *testing.T) { + d, err := New(&config.Config{DNSProvider: "aliyun"}) + if err != nil || d == nil { + t.Fatalf("expected aliyun provider, got err=%v d=%v", err, d) + } +} + +func TestNew_UnknownProvider(t *testing.T) { + if _, err := New(&config.Config{DNSProvider: "nope"}); err == nil { + t.Fatal("expected error for unknown provider") + } +} diff --git a/internal/app/app.go b/internal/app/app.go index 265d201..c89ec91 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "log/slog" - "os" "strings" "time" @@ -17,6 +16,8 @@ import ( var ( IPNotifyFormat = "[%s] ip changed, old IP: %s new IP: %s" + + DefaultInterval = 3 * time.Minute ) type App struct { @@ -25,6 +26,7 @@ type App struct { dnsProvider dns.LibDNS ipGetter ip.Getter notifier notify.Notifier + interval time.Duration } func New(logger *slog.Logger, config *config.Config, dnsProvider dns.LibDNS, ipGetter ip.Getter, notifier notify.Notifier) *App { @@ -34,85 +36,99 @@ func New(logger *slog.Logger, config *config.Config, dnsProvider dns.LibDNS, ipG dnsProvider: dnsProvider, ipGetter: ipGetter, notifier: notifier, + interval: DefaultInterval, } } -func (a *App) Run(ctx context.Context) { +// WithInterval overrides the polling interval. Useful for tests. +func (a *App) WithInterval(d time.Duration) *App { + a.interval = d + return a +} + +// Run polls and syncs until ctx is cancelled or an unrecoverable error occurs. +// It returns the cause; nil if ctx was cancelled cleanly. +func (a *App) Run(ctx context.Context) error { + ticker := time.NewTicker(a.interval) + defer ticker.Stop() + + if err := a.UpdateIP(ctx); err != nil { + return err + } for { select { case <-ctx.Done(): - return - default: - err := a.updateIP(ctx) - if err != nil { - a.logger.Error("update ip error", "error", err.Error()) - os.Exit(1) + return nil + case <-ticker.C: + if err := a.UpdateIP(ctx); err != nil { + return err } - time.Sleep(time.Minute * 3) } } } -func (a *App) updateIP(ctx context.Context) error { - ip, err := a.ipGetter.GetIP() +// UpdateIP performs one sync cycle: fetch current IP, look up the existing +// record, and create or update it as needed. +func (a *App) UpdateIP(ctx context.Context) error { + currentIP, err := a.ipGetter.GetIP() if err != nil { a.logger.Error("Get ip error", "error", err) return err } name, zone := zoneFromDomain(a.config.Domain) - a.logger.Info("zone from domain", - "name", name, - "zone", zone) + a.logger.Info("zone from domain", "name", name, "zone", zone) - currentIP, err := a.dnsProvider.GetRecords(ctx, zone) + records, err := a.dnsProvider.GetRecords(ctx, zone) if err != nil { a.logger.Error("Get records error", "error", err) return err } - var found bool - var record *libdns.Record - for _, r := range currentIP { - if r.Name == name { - found = true - record = &r - break - } + record, found := findRecord(records, name) + if !found { + return a.appendRecord(ctx, zone, name, currentIP) } - if found { - if record.Value == ip { - a.logger.Info("ip is same, skip update", "ip", ip) - return nil - } - oldIP := record.Value - record.Value = ip - _, err = a.dnsProvider.SetRecords(ctx, zone, []libdns.Record{ - *record, - }) - if err != nil { - a.logger.Error("Set records error", "error", err) - return err - } - _ = a.notifier.Send(ctx, fmt.Sprintf(IPNotifyFormat, a.config.Domain, oldIP, ip)) - } else { - _, err = a.dnsProvider.AppendRecords(ctx, zone, []libdns.Record{ - { - Name: name, - Value: ip, - Type: "A", - }, - }) - if err != nil { - a.logger.Error("Append records error", "error", err) - return err - } + if record.Value == currentIP { + a.logger.Info("ip is same, skip update", "ip", currentIP) + return nil } + return a.updateRecord(ctx, zone, record, currentIP) +} +func (a *App) appendRecord(ctx context.Context, zone, name, ip string) error { + _, err := a.dnsProvider.AppendRecords(ctx, zone, []libdns.Record{ + {Name: name, Value: ip, Type: "A"}, + }) + if err != nil { + a.logger.Error("Append records error", "error", err) + } + return err +} + +func (a *App) updateRecord(ctx context.Context, zone string, record libdns.Record, newIP string) error { + oldIP := record.Value + record.Value = newIP + if _, err := a.dnsProvider.SetRecords(ctx, zone, []libdns.Record{record}); err != nil { + a.logger.Error("Set records error", "error", err) + return err + } + if a.notifier != nil { + _ = a.notifier.Send(ctx, fmt.Sprintf(IPNotifyFormat, a.config.Domain, oldIP, newIP)) + } return nil } -// zoneFromDomain return zone and domain +func findRecord(records []libdns.Record, name string) (libdns.Record, bool) { + for _, r := range records { + if r.Name == name { + return r, true + } + } + return libdns.Record{}, false +} + +// zoneFromDomain return name and zone. func zoneFromDomain(domain string) (string, string) { arr := strings.SplitN(domain, ".", 2) if len(arr) == 1 { diff --git a/internal/app/app_test.go b/internal/app/app_test.go new file mode 100644 index 0000000..f3b4ca7 --- /dev/null +++ b/internal/app/app_test.go @@ -0,0 +1,153 @@ +package app + +import ( + "context" + "errors" + "io" + "log/slog" + "testing" + + "github.com/libdns/libdns" + "github.com/orvice/ddns/internal/config" +) + +type fakeIPGetter struct { + ip string + err error +} + +func (f *fakeIPGetter) GetIP() (string, error) { return f.ip, f.err } + +type fakeDNS struct { + getRecords []libdns.Record + getErr error + appendCalls [][]libdns.Record + setCalls [][]libdns.Record + appendErr error + setErr error + lastZoneGet string + lastZoneApp string + lastZoneSet string +} + +func (f *fakeDNS) GetRecords(_ context.Context, zone string) ([]libdns.Record, error) { + f.lastZoneGet = zone + return f.getRecords, f.getErr +} + +func (f *fakeDNS) AppendRecords(_ context.Context, zone string, recs []libdns.Record) ([]libdns.Record, error) { + f.lastZoneApp = zone + f.appendCalls = append(f.appendCalls, recs) + return recs, f.appendErr +} + +func (f *fakeDNS) SetRecords(_ context.Context, zone string, recs []libdns.Record) ([]libdns.Record, error) { + f.lastZoneSet = zone + f.setCalls = append(f.setCalls, recs) + return recs, f.setErr +} + +type fakeNotifier struct { + messages []string + err error +} + +func (f *fakeNotifier) Send(_ context.Context, s string) error { + f.messages = append(f.messages, s) + return f.err +} + +func newTestApp(getter *fakeIPGetter, dns *fakeDNS, notif *fakeNotifier) *App { + return New( + slog.New(slog.NewTextHandler(io.Discard, nil)), + &config.Config{Domain: "host.example.com"}, + dns, + getter, + notif, + ) +} + +func TestZoneFromDomain(t *testing.T) { + cases := []struct { + in, name, zone string + }{ + {"host.example.com", "host", "example.com"}, + {"example.com", "example", "com"}, + {"single", "", ""}, + } + for _, c := range cases { + n, z := zoneFromDomain(c.in) + if n != c.name || z != c.zone { + t.Errorf("zoneFromDomain(%q) = (%q,%q), want (%q,%q)", c.in, n, z, c.name, c.zone) + } + } +} + +func TestUpdateIP_AppendWhenNotFound(t *testing.T) { + ctx := context.Background() + dns := &fakeDNS{getRecords: nil} + notif := &fakeNotifier{} + a := newTestApp(&fakeIPGetter{ip: "1.2.3.4"}, dns, notif) + + if err := a.UpdateIP(ctx); err != nil { + t.Fatalf("unexpected error: %v", err) + } + if len(dns.appendCalls) != 1 || len(dns.appendCalls[0]) != 1 { + t.Fatalf("expected 1 append call, got %+v", dns.appendCalls) + } + rec := dns.appendCalls[0][0] + if rec.Name != "host" || rec.Value != "1.2.3.4" || rec.Type != "A" { + t.Errorf("unexpected record: %+v", rec) + } + if len(notif.messages) != 0 { + t.Errorf("should not notify on first-time create, got %v", notif.messages) + } +} + +func TestUpdateIP_SkipWhenSame(t *testing.T) { + ctx := context.Background() + dns := &fakeDNS{getRecords: []libdns.Record{{Name: "host", Value: "1.2.3.4", Type: "A"}}} + notif := &fakeNotifier{} + a := newTestApp(&fakeIPGetter{ip: "1.2.3.4"}, dns, notif) + + if err := a.UpdateIP(ctx); err != nil { + t.Fatalf("unexpected error: %v", err) + } + if len(dns.setCalls) != 0 || len(dns.appendCalls) != 0 { + t.Errorf("no updates expected, got set=%v append=%v", dns.setCalls, dns.appendCalls) + } + if len(notif.messages) != 0 { + t.Errorf("no notification expected, got %v", notif.messages) + } +} + +func TestUpdateIP_SetWhenChanged(t *testing.T) { + ctx := context.Background() + dns := &fakeDNS{getRecords: []libdns.Record{{Name: "host", Value: "1.1.1.1", Type: "A"}}} + notif := &fakeNotifier{} + a := newTestApp(&fakeIPGetter{ip: "9.9.9.9"}, dns, notif) + + if err := a.UpdateIP(ctx); err != nil { + t.Fatalf("unexpected error: %v", err) + } + if len(dns.setCalls) != 1 || dns.setCalls[0][0].Value != "9.9.9.9" { + t.Fatalf("expected set to 9.9.9.9, got %+v", dns.setCalls) + } + if len(notif.messages) != 1 { + t.Fatalf("expected 1 notification, got %v", notif.messages) + } +} + +func TestUpdateIP_PropagatesGetIPError(t *testing.T) { + a := newTestApp(&fakeIPGetter{err: errors.New("boom")}, &fakeDNS{}, &fakeNotifier{}) + if err := a.UpdateIP(context.Background()); err == nil { + t.Fatal("expected error, got nil") + } +} + +func TestUpdateIP_PropagatesGetRecordsError(t *testing.T) { + a := newTestApp(&fakeIPGetter{ip: "1.2.3.4"}, &fakeDNS{getErr: errors.New("dns boom")}, &fakeNotifier{}) + if err := a.UpdateIP(context.Background()); err == nil { + t.Fatal("expected error, got nil") + } +} diff --git a/internal/config/config.go b/internal/config/config.go index 0cb676e..a5a9dfd 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -16,15 +16,38 @@ type Config struct { AliyunAccessKeySecret string `mapstructure:"ALIYUN_ACCESS_KEY_SECRET"` } +// New loads configuration from environment variables (and optionally an `app` +// file in the working directory). It uses a fresh viper instance so tests can +// run in parallel without sharing state. func New() (*Config, error) { - path := "." - viper.AddConfigPath(path) - viper.SetConfigName("app") + return Load(".") +} + +// Load is like New but lets callers specify the search path. Useful for tests. +func Load(path string) (*Config, error) { + v := viper.New() + v.AddConfigPath(path) + v.SetConfigName("app") + v.SetConfigType("env") + v.AutomaticEnv() + + // Viper's AutomaticEnv only resolves keys that have been registered. + // Bind every struct tag so env vars are picked up reliably. + for _, key := range []string{ + "DNS_PROVIDER", + "DOMAIN", + "TELEGRAM_CHATID", + "TELEGRAM_TOKEN", + "CF_TOKEN", + "ALIYUN_ACCESS_KEY_ID", + "ALIYUN_ACCESS_KEY_SECRET", + } { + _ = v.BindEnv(key) + } - viper.SetConfigType("env") - viper.AutomaticEnv() - // viper.ReadInConfig() var config Config - err := viper.Unmarshal(&config) - return &config, err + if err := v.Unmarshal(&config); err != nil { + return nil, err + } + return &config, nil } diff --git a/internal/ip/ip.go b/internal/ip/ip.go index 3205d93..31c189d 100644 --- a/internal/ip/ip.go +++ b/internal/ip/ip.go @@ -2,8 +2,10 @@ package ip import ( "encoding/json" + "fmt" "io" "log/slog" + "net/http" "github.com/hashicorp/go-retryablehttp" ) @@ -20,35 +22,66 @@ type Getter interface { GetIP() (string, error) } +// httpDoer is the minimal HTTP surface IfconfigCo needs. It is satisfied by +// *http.Client and by retryablehttp's standard client wrapper, and is easy to +// fake in tests. +type httpDoer interface { + Do(req *http.Request) (*http.Response, error) +} + type IfconfigCo struct { + client httpDoer + url string + logger *slog.Logger } +// NewIfGetter returns the production IfconfigCo backed by retryablehttp. func NewIfGetter() Getter { - return new(IfconfigCo) + retryClient := retryablehttp.NewClient() + retryClient.RetryMax = 3 + return &IfconfigCo{ + client: retryClient.StandardClient(), + url: ipConfigCoAddr, + logger: slog.Default(), + } +} + +// NewIfconfigCo builds an IfconfigCo with caller-supplied HTTP client and URL. +// Intended for tests; production code should use NewIfGetter. +func NewIfconfigCo(client httpDoer, url string, logger *slog.Logger) *IfconfigCo { + if logger == nil { + logger = slog.Default() + } + return &IfconfigCo{client: client, url: url, logger: logger} } func (i *IfconfigCo) GetIP() (string, error) { - logger := slog.Default() - retryClient := retryablehttp.NewClient() - retryClient.RetryMax = 3 - resp, err := retryClient.Get(ipConfigCoAddr) + req, err := http.NewRequest(http.MethodGet, i.url, nil) + if err != nil { + i.logger.Error("build request error", "error", err) + return "", err + } + resp, err := i.client.Do(req) if err != nil { - logger.Error("get ip error", "error", err) + i.logger.Error("get ip error", "error", err) return "", err } defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return "", fmt.Errorf("ifconfig.co returned status %d", resp.StatusCode) + } + s, err := io.ReadAll(resp.Body) if err != nil { - logger.Error("read body error", "error", err) + i.logger.Error("read body error", "error", err) return "", err } var ret Response - err = json.Unmarshal(s, &ret) - if err != nil { - logger.Error("unmarshal error", "error", err) + if err := json.Unmarshal(s, &ret); err != nil { + i.logger.Error("unmarshal error", "error", err) return "", err } - logger.Info("get ip", "ip", ret.IP) + i.logger.Info("get ip", "ip", ret.IP) return ret.IP, nil } diff --git a/internal/ip/ip_test.go b/internal/ip/ip_test.go index 20b7563..48e17fa 100644 --- a/internal/ip/ip_test.go +++ b/internal/ip/ip_test.go @@ -1,10 +1,48 @@ package ip import ( + "net/http" + "net/http/httptest" "testing" ) -func TestGetIP(t *testing.T) { - ip, err := NewIfGetter().GetIP() - t.Log(ip, err) +func TestIfconfigCo_GetIP_Success(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"ip":"1.2.3.4"}`)) + })) + defer server.Close() + + g := NewIfconfigCo(server.Client(), server.URL, nil) + got, err := g.GetIP() + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if got != "1.2.3.4" { + t.Fatalf("want 1.2.3.4, got %q", got) + } +} + +func TestIfconfigCo_GetIP_BadStatus(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + })) + defer server.Close() + + g := NewIfconfigCo(server.Client(), server.URL, nil) + if _, err := g.GetIP(); err == nil { + t.Fatal("expected error on 500, got nil") + } +} + +func TestIfconfigCo_GetIP_BadJSON(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte(`not-json`)) + })) + defer server.Close() + + g := NewIfconfigCo(server.Client(), server.URL, nil) + if _, err := g.GetIP(); err == nil { + t.Fatal("expected unmarshal error, got nil") + } } diff --git a/internal/wire/wire_gen.go b/internal/wire/wire_gen.go index 20e642e..cd36df4 100644 --- a/internal/wire/wire_gen.go +++ b/internal/wire/wire_gen.go @@ -23,7 +23,10 @@ func NewApp() (*app.App, error) { if err != nil { return nil, err } - libDNS := dns.New(configConfig) + libDNS, err := dns.New(configConfig) + if err != nil { + return nil, err + } getter := ip.NewIfGetter() notifier, err := notify.NewTelegramNotifier(configConfig) if err != nil { diff --git a/notify/notify.go b/notify/notify.go index e3e70b1..d8b22ad 100644 --- a/notify/notify.go +++ b/notify/notify.go @@ -8,17 +8,20 @@ import ( "github.com/orvice/ddns/internal/config" ) -var notifiers []Notifier - type Notifier interface { Send(ctx context.Context, s string) error } -var _ Notifier = new(TelegramNotifier) +// tgSender is the minimal surface TelegramNotifier needs from the bot API. +// Implemented by *tgbotapi.BotAPI; trivially fakable in tests. +type tgSender interface { + Send(c tgbotapi.Chattable) (tgbotapi.Message, error) +} + +var _ Notifier = (*TelegramNotifier)(nil) type TelegramNotifier struct { - bot *tgbotapi.BotAPI - token string + bot tgSender chatID int64 } @@ -29,11 +32,16 @@ func NewTelegramNotifier(conf *config.Config) (Notifier, error) { } return &TelegramNotifier{ bot: bot, - token: conf.TelegramToken, chatID: conf.TelegramChatID, }, nil } +// NewTelegramNotifierWithSender builds a TelegramNotifier with an injected +// sender. Intended for tests. +func NewTelegramNotifierWithSender(bot tgSender, chatID int64) *TelegramNotifier { + return &TelegramNotifier{bot: bot, chatID: chatID} +} + func (t *TelegramNotifier) Send(_ context.Context, s string) error { msg := tgbotapi.NewMessage(t.chatID, s) resp, err := t.bot.Send(msg) @@ -45,16 +53,23 @@ func (t *TelegramNotifier) Send(_ context.Context, s string) error { return nil } -func Init() { - notifiers = make([]Notifier, 0) +// MultiNotifier fans out one Send call to multiple underlying notifiers. +// Errors are logged but not aggregated, matching prior best-effort semantics. +type MultiNotifier struct { + notifiers []Notifier +} + +func NewMultiNotifier(ns ...Notifier) *MultiNotifier { + return &MultiNotifier{notifiers: ns} } -func AddNotifier(n Notifier) { - notifiers = append(notifiers, n) +func (m *MultiNotifier) Add(n Notifier) { + m.notifiers = append(m.notifiers, n) } -func Notify(ctx context.Context, s string) { - for _, n := range notifiers { +func (m *MultiNotifier) Send(ctx context.Context, s string) error { + for _, n := range m.notifiers { _ = n.Send(ctx, s) } + return nil } diff --git a/notify/notify_test.go b/notify/notify_test.go new file mode 100644 index 0000000..167a221 --- /dev/null +++ b/notify/notify_test.go @@ -0,0 +1,61 @@ +package notify + +import ( + "context" + "errors" + "testing" + + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" +) + +type fakeBot struct { + sent []tgbotapi.Chattable + err error +} + +func (f *fakeBot) Send(c tgbotapi.Chattable) (tgbotapi.Message, error) { + f.sent = append(f.sent, c) + return tgbotapi.Message{}, f.err +} + +func TestTelegramNotifier_Send(t *testing.T) { + bot := &fakeBot{} + n := NewTelegramNotifierWithSender(bot, 42) + + if err := n.Send(context.Background(), "hello"); err != nil { + t.Fatalf("unexpected error: %v", err) + } + if len(bot.sent) != 1 { + t.Fatalf("expected 1 send, got %d", len(bot.sent)) + } + msg, ok := bot.sent[0].(tgbotapi.MessageConfig) + if !ok { + t.Fatalf("expected MessageConfig, got %T", bot.sent[0]) + } + if msg.ChatID != 42 || msg.Text != "hello" { + t.Errorf("unexpected message: chatID=%d text=%q", msg.ChatID, msg.Text) + } +} + +func TestTelegramNotifier_SendError(t *testing.T) { + n := NewTelegramNotifierWithSender(&fakeBot{err: errors.New("boom")}, 1) + if err := n.Send(context.Background(), "x"); err == nil { + t.Fatal("expected error") + } +} + +type captureNotifier struct{ msgs []string } + +func (c *captureNotifier) Send(_ context.Context, s string) error { + c.msgs = append(c.msgs, s) + return nil +} + +func TestMultiNotifier_FansOut(t *testing.T) { + a, b := &captureNotifier{}, &captureNotifier{} + m := NewMultiNotifier(a, b) + _ = m.Send(context.Background(), "hi") + if len(a.msgs) != 1 || len(b.msgs) != 1 { + t.Errorf("expected each notifier to receive 1 msg, got a=%v b=%v", a.msgs, b.msgs) + } +}