From bfafa2acb7000a8b8edfffb58243a0a84886461b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Niko=20K=C3=B6ser?= Date: Mon, 25 Apr 2022 23:53:28 +0200 Subject: [PATCH] feat(notify): Add NewWithServices() constructor function AddNewWithServices() accepts a variadic list of services and returns a new, by New() created, Notify instance with the list of services set as its notifiers. If no services are given it's the functionally identical to just calling New(). Calling NewWithServices() with a list of services is functionally equal to calling New() and then UseServices(). --- notify.go | 9 +++++++++ notify_test.go | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/notify.go b/notify.go index fb31747..4886279 100644 --- a/notify.go +++ b/notify.go @@ -66,6 +66,15 @@ func New() *Notify { return NewWithOptions() } +// NewWithServices returns a new instance of Notify with the given services. By default, the Notify instance is enabled. +// If no services are provided, it returns a new Notify instance with default options. +func NewWithServices(services ...Notifier) *Notify { + n := New() + n.UseServices(services...) + + return n +} + // Create the package level Notify instance. var std = New() diff --git a/notify_test.go b/notify_test.go index fca6f9a..b1af06d 100644 --- a/notify_test.go +++ b/notify_test.go @@ -4,6 +4,8 @@ import ( "testing" "github.com/google/go-cmp/cmp" + + "github.com/nikoksr/notify/service/mail" ) func TestNew(t *testing.T) { @@ -64,3 +66,34 @@ func TestDefault(t *testing.T) { t.Error("Default() did not return the default Notifier") } } + +func TestNewWithServices(t *testing.T) { + t.Parallel() + + n1 := NewWithServices() + if n1 == nil { + t.Fatal("NewWithServices() returned nil") + } + + n2 := NewWithServices(nil) + if n2 == nil { + t.Fatal("NewWithServices(nil) returned nil") + } + if len(n2.notifiers) != 0 { + t.Error("NewWithServices(nil) did not return empty Notifier") + } + + mailService := mail.New("", "") + n3 := NewWithServices(mailService) + if n3 == nil { + t.Fatal("NewWithServices(mail.New()) returned nil") + } + if len(n3.notifiers) != 1 { + t.Errorf("NewWithServices(mail.New()) was expected to have 1 notifier but had %d", len(n3.notifiers)) + } else { + diff := cmp.Diff(n3.notifiers[0], mailService, cmp.AllowUnexported(mail.Mail{})) + if diff != "" { + t.Errorf("NewWithServices(mail.New()) did not correctly use service:\n%s", diff) + } + } +}