diff --git a/.golangci.yml b/.golangci.yml index e872f4ca..72ff08fd 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,5 +1,6 @@ formatters: enable: + - gofumpt - goimports settings: @@ -21,17 +22,16 @@ linters: - govet - importas - misspell + - perfsprint + - revive - staticcheck + - testifylint - thelper - tparallel - unparam - usestdlibvars - usetesting - whitespace - disable: - - perfsprint # Performance optimizations cause many changes - - testifylint # Test assertion order changes cause large diffs - - revive # Too many style changes (265+ issues) exclusions: rules: @@ -154,8 +154,7 @@ linters: - name: duplicated-imports - name: early-return - arguments: - - preserveScope + disabled: true - name: empty-block disabled: true @@ -177,8 +176,7 @@ linters: - name: increment-decrement - name: indent-error-flow - arguments: - - preserveScope + disabled: true - name: modifies-parameter @@ -218,11 +216,7 @@ linters: - name: var-declaration - name: var-naming - arguments: - - - ID - - - VM - - - skipPackageNameChecks: true - upperCaseConst: true + disabled: true staticcheck: checks: diff --git a/examples/certmanager/README.md b/examples/certmanager/README.md index 05842e0d..e5ec5097 100644 --- a/examples/certmanager/README.md +++ b/examples/certmanager/README.md @@ -27,8 +27,8 @@ notificationsFactory := api.NewFactory(api.Settings{ ConfigMapName: "cert-manager-notifications-cm", SecretName: "cert-manager-notifications-secret", InitGetVars: func(cfg *api.Config, configMap *v1.ConfigMap, secret *v1.Secret) (api.GetVars, error) { - return func(obj map[string]interface{}, dest services.Destination) map[string]interface{} { - return map[string]interface{}{"cert": obj} + return func(obj map[string]any, dest services.Destination) map[string]any { + return map[string]any{"cert": obj} }, nil }, }, namespace, secrets, configMaps) @@ -128,8 +128,8 @@ func main() { ConfigMapName: "cert-manager-notifications-cm", SecretName: "cert-manager-notifications-secret", InitGetVars: func(cfg *api.Config, configMap *v1.ConfigMap, secret *v1.Secret) (api.GetVars, error) { - return func(obj map[string]interface{}, dest services.Destination) map[string]interface{} { - return map[string]interface{}{"cert": obj} + return func(obj map[string]any, dest services.Destination) map[string]any { + return map[string]any{"cert": obj} }, nil }, }) diff --git a/examples/certmanager/cli/main.go b/examples/certmanager/cli/main.go index 8eb239d4..29243747 100644 --- a/examples/certmanager/cli/main.go +++ b/examples/certmanager/cli/main.go @@ -20,9 +20,9 @@ func main() { }, api.Settings{ ConfigMapName: "cert-manager-notifications-cm", SecretName: "cert-manager-notifications-secret", - InitGetVars: func(cfg *api.Config, configMap *corev1.ConfigMap, secret *corev1.Secret) (api.GetVars, error) { - return func(obj map[string]interface{}, dest services.Destination) map[string]interface{} { - return map[string]interface{}{"cert": obj} + InitGetVars: func(_ *api.Config, _ *corev1.ConfigMap, _ *corev1.Secret) (api.GetVars, error) { + return func(obj map[string]any, _ services.Destination) map[string]any { + return map[string]any{"cert": obj} }, nil }, }) diff --git a/examples/certmanager/controller/main.go b/examples/certmanager/controller/main.go index c977c80d..1cda2b82 100644 --- a/examples/certmanager/controller/main.go +++ b/examples/certmanager/controller/main.go @@ -28,12 +28,10 @@ import ( ) func main() { - var ( - clientConfig clientcmd.ClientConfig - ) - var command = cobra.Command{ + var clientConfig clientcmd.ClientConfig + command := cobra.Command{ Use: "controller", - Run: func(c *cobra.Command, args []string) { + Run: func(_ *cobra.Command, _ []string) { // Optionally set the annotations prefix // subscriptions.SetAnnotationPrefix("example.prefix.io") @@ -59,9 +57,9 @@ func main() { notificationsFactory := api.NewFactory(api.Settings{ ConfigMapName: "cert-manager-notifications-cm", SecretName: "cert-manager-notifications-secret", - InitGetVars: func(cfg *api.Config, configMap *corev1.ConfigMap, secret *corev1.Secret) (api.GetVars, error) { - return func(obj map[string]interface{}, dest services.Destination) map[string]interface{} { - return map[string]interface{}{"cert": obj} + InitGetVars: func(_ *api.Config, _ *corev1.ConfigMap, _ *corev1.Secret) (api.GetVars, error) { + return func(obj map[string]any, _ services.Destination) map[string]any { + return map[string]any{"cert": obj} }, nil }, }, namespace, secrets, configMaps) @@ -74,7 +72,7 @@ func main() { ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { return certClient.List(context.Background(), options) }, - WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { + WatchFunc: func(_ metav1.ListOptions) (watch.Interface, error) { return certClient.Watch(context.Background(), metav1.ListOptions{}) }, }, &unstructured.Unstructured{}, time.Minute, cache.Indexers{}) diff --git a/pkg/api/api.go b/pkg/api/api.go index b1e27703..ba834bff 100644 --- a/pkg/api/api.go +++ b/pkg/api/api.go @@ -15,12 +15,12 @@ const ( //go:generate mockgen -destination=../mocks/api.go -package=mocks github.com/argoproj/notifications-engine/pkg/api API -type GetVars func(obj map[string]interface{}, dest services.Destination) map[string]interface{} +type GetVars func(obj map[string]any, dest services.Destination) map[string]any // API provides high level interface to send notifications and manage notification services type API interface { - Send(obj map[string]interface{}, templates []string, dest services.Destination) error - RunTrigger(triggerName string, vars map[string]interface{}) ([]triggers.ConditionResult, error) + Send(obj map[string]any, templates []string, dest services.Destination) error + RunTrigger(triggerName string, vars map[string]any) ([]triggers.ConditionResult, error) AddNotificationService(name string, service services.NotificationService) GetNotificationServices() map[string]services.NotificationService GetConfig() Config @@ -49,7 +49,7 @@ func (n *api) GetNotificationServices() map[string]services.NotificationService } // Send sends notification using specified service and template to the specified destination -func (n *api) Send(obj map[string]interface{}, templates []string, dest services.Destination) error { +func (n *api) Send(obj map[string]any, templates []string, dest services.Destination) error { notificationService, ok := n.notificationServices[dest.Service] if !ok { return fmt.Errorf("notification service '%s' is not supported", dest.Service) @@ -57,7 +57,7 @@ func (n *api) Send(obj map[string]interface{}, templates []string, dest services vars := n.getVars(obj, dest) - in := make(map[string]interface{}) + in := make(map[string]any) for k := range vars { in[k] = vars[k] } @@ -71,7 +71,7 @@ func (n *api) Send(obj map[string]interface{}, templates []string, dest services return notificationService.Send(*notification, dest) } -func (n *api) RunTrigger(triggerName string, obj map[string]interface{}) ([]triggers.ConditionResult, error) { +func (n *api) RunTrigger(triggerName string, obj map[string]any) ([]triggers.ConditionResult, error) { vars := n.getVars(obj, services.Destination{}) return n.triggersService.Run(triggerName, vars) } diff --git a/pkg/api/api_test.go b/pkg/api/api_test.go index b0bf8263..ecf74930 100644 --- a/pkg/api/api_test.go +++ b/pkg/api/api_test.go @@ -5,12 +5,13 @@ import ( "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/argoproj/notifications-engine/pkg/services" "github.com/argoproj/notifications-engine/pkg/services/mocks" ) -func getVars(in map[string]interface{}, _ services.Destination) map[string]interface{} { +func getVars(in map[string]any, _ services.Destination) map[string]any { return in } @@ -32,6 +33,7 @@ func getConfig(ctrl *gomock.Controller, opts ...func(service *mocks.MockNotifica }, } } + func TestSend(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -44,12 +46,10 @@ func TestSend(t *testing.T) { Recipient: "my-channel", }).Return(nil) }), getVars) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) err = api.Send( - map[string]interface{}{"foo": "world"}, + map[string]any{"foo": "world"}, []string{"my-template"}, services.Destination{Service: "slack", Recipient: "my-channel"}, ) @@ -61,9 +61,7 @@ func TestAddService(t *testing.T) { defer ctrl.Finish() api, err := NewAPI(getConfig(ctrl), getVars) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) api.AddNotificationService("hello", mocks.NewMockNotificationService(ctrl)) diff --git a/pkg/api/config_test.go b/pkg/api/config_test.go index fedaf98b..48dd4e61 100644 --- a/pkg/api/config_test.go +++ b/pkg/api/config_test.go @@ -7,23 +7,21 @@ import ( "github.com/argoproj/notifications-engine/pkg/subscriptions" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/labels" ) -var ( - emptySecret = &corev1.Secret{Data: map[string][]byte{}} -) +var emptySecret = &corev1.Secret{Data: map[string][]byte{}} func TestParseConfig_Services(t *testing.T) { cfg, err := ParseConfig(&corev1.ConfigMap{Data: map[string]string{ "service.slack": ` token: my-token -`}}, emptySecret) +`, + }}, emptySecret) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.NotNil(t, cfg.Services["slack"]) } @@ -32,11 +30,10 @@ func TestParseConfig_Templates(t *testing.T) { cfg, err := ParseConfig(&corev1.ConfigMap{Data: map[string]string{ "template.my-template": ` message: hello world -`}}, emptySecret) +`, + }}, emptySecret) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, map[string]services.Notification{ "my-template": {Message: "hello world"}, @@ -48,11 +45,10 @@ func TestParseConfig_DefaultServiceTriggers(t *testing.T) { "defaultTriggers.slack": ` - trigger-a - trigger-b -`}}, emptySecret) +`, + }}, emptySecret) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, map[string][]string{ "slack": { @@ -100,7 +96,7 @@ headers: result, err := replaceServiceConfigSecrets(input, &secrets) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, string(result)) } @@ -126,7 +122,7 @@ apiKeys: result, err := replaceServiceConfigSecrets(input, &secrets) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, string(result)) } @@ -154,7 +150,7 @@ installationID: 67890 result, err := replaceServiceConfigSecrets(input, &secrets) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, string(result)) } @@ -165,9 +161,7 @@ func TestParseConfig_DefaultTriggers(t *testing.T) { }, }, emptySecret) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, []string{"trigger1", "trigger2"}, cfg.DefaultTriggers) } @@ -181,14 +175,10 @@ func TestParseConfig_Subscriptions(t *testing.T) { }, }, emptySecret) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) label, err := labels.Parse("test=true") - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, subscriptions.DefaultSubscriptions([]subscriptions.DefaultSubscription{ {Triggers: []string{"my-trigger2"}, Selector: label}, }), cfg.Subscriptions) diff --git a/pkg/api/factory.go b/pkg/api/factory.go index 0d57d4cb..5fa8b30e 100644 --- a/pkg/api/factory.go +++ b/pkg/api/factory.go @@ -58,31 +58,33 @@ func NewFactory(settings Settings, defaultNamespace string, secretsInformer cach } _, _ = secretsInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj interface{}) { + AddFunc: func(obj any) { factory.invalidateIfHasName(settings.SecretName, obj) }, - DeleteFunc: func(obj interface{}) { + DeleteFunc: func(obj any) { factory.invalidateIfHasName(settings.SecretName, obj) }, - UpdateFunc: func(oldObj, newObj interface{}) { + UpdateFunc: func(_, newObj any) { factory.invalidateIfHasName(settings.SecretName, newObj) - }}) + }, + }) _, _ = cmInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj interface{}) { + AddFunc: func(obj any) { factory.invalidateIfHasName(settings.ConfigMapName, obj) }, - DeleteFunc: func(obj interface{}) { + DeleteFunc: func(obj any) { factory.invalidateIfHasName(settings.ConfigMapName, obj) }, - UpdateFunc: func(oldObj, newObj interface{}) { + UpdateFunc: func(_, newObj any) { factory.invalidateIfHasName(settings.ConfigMapName, newObj) - }}) + }, + }) return factory } -func (f *apiFactory) invalidateIfHasName(name string, obj interface{}) { +func (f *apiFactory) invalidateIfHasName(name string, obj any) { metaObj, ok := obj.(metav1.Object) if !ok { return diff --git a/pkg/api/factory_test.go b/pkg/api/factory_test.go index 8db531b8..458ef548 100644 --- a/pkg/api/factory_test.go +++ b/pkg/api/factory_test.go @@ -16,13 +16,11 @@ import ( "github.com/argoproj/notifications-engine/pkg/services" ) -var ( - settings = Settings{ConfigMapName: "my-config-map", SecretName: "my-secret", InitGetVars: func(cfg *Config, configMap *corev1.ConfigMap, secret *corev1.Secret) (GetVars, error) { - return func(obj map[string]interface{}, dest services.Destination) map[string]interface{} { - return map[string]interface{}{"obj": obj} - }, nil - }} -) +var settings = Settings{ConfigMapName: "my-config-map", SecretName: "my-secret", InitGetVars: func(_ *Config, _ *corev1.ConfigMap, _ *corev1.Secret) (GetVars, error) { + return func(obj map[string]any, _ services.Destination) map[string]any { + return map[string]any{"obj": obj} + }, nil +}} func TestGetAPI(t *testing.T) { cm := &corev1.ConfigMap{ @@ -60,7 +58,7 @@ func TestGetAPI(t *testing.T) { "service.email": `{"username": "test"}`, }, }, metav1.UpdateOptions{}) - assert.NoError(t, err) + require.NoError(t, err) time.Sleep(1 * time.Second) diff --git a/pkg/cmd/context.go b/pkg/cmd/context.go index 3dcc9087..694caf3a 100644 --- a/pkg/cmd/context.go +++ b/pkg/cmd/context.go @@ -62,7 +62,7 @@ func splitYAML(yamlData []byte) ([]*unstructured.Unstructured, error) { return objs, nil } -func (c *commandContext) unmarshalFromFile(filePath string, name string, gk schema.GroupKind, result interface{}) error { +func (c *commandContext) unmarshalFromFile(filePath string, name string, gk schema.GroupKind, result any) error { var err error var data []byte if filePath == "-" { diff --git a/pkg/cmd/context_test.go b/pkg/cmd/context_test.go index 27ec5b69..349eec05 100644 --- a/pkg/cmd/context_test.go +++ b/pkg/cmd/context_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/argoproj/notifications-engine/pkg/api" ) @@ -48,7 +49,7 @@ func Test_getSecretFromFile(t *testing.T) { } secret, err := ctx.getSecret() - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, secret) - assert.Equal(t, secret.Name, "argocd-notifications-secret") + assert.Equal(t, "argocd-notifications-secret", secret.Name) } diff --git a/pkg/cmd/template.go b/pkg/cmd/template.go index cef873f2..31c1233e 100644 --- a/pkg/cmd/template.go +++ b/pkg/cmd/template.go @@ -13,10 +13,10 @@ import ( ) func newTemplateCommand(cmdContext *commandContext) *cobra.Command { - var command = cobra.Command{ + command := cobra.Command{ Use: "template", Short: "Notification templates related commands", - RunE: func(c *cobra.Command, args []string) error { + RunE: func(_ *cobra.Command, _ []string) error { return errors.New("select child command") }, } @@ -27,10 +27,8 @@ func newTemplateCommand(cmdContext *commandContext) *cobra.Command { } func newTemplateNotifyCommand(cmdContext *commandContext) *cobra.Command { - var ( - recipients []string - ) - var command = cobra.Command{ + var recipients []string + command := cobra.Command{ Use: "notify NAME RESOURCE_NAME", Example: fmt.Sprintf(` # Trigger notification using in-cluster config map and secret @@ -40,7 +38,7 @@ func newTemplateNotifyCommand(cmdContext *commandContext) *cobra.Command { %s template notify app-sync-succeeded guestbook `, cmdContext.cliName, cmdContext.cliName), Short: "Generates notification using the specified template and send it to specified recipients", - RunE: func(c *cobra.Command, args []string) error { + RunE: func(_ *cobra.Command, args []string) error { cancel := withDebugLogs() defer cancel() if len(args) < 2 { @@ -83,10 +81,8 @@ func newTemplateNotifyCommand(cmdContext *commandContext) *cobra.Command { } func newTemplateGetCommand(cmdContext *commandContext) *cobra.Command { - var ( - output string - ) - var command = cobra.Command{ + var output string + command := cobra.Command{ Use: "get", Example: fmt.Sprintf(` # prints all templates @@ -95,7 +91,7 @@ func newTemplateGetCommand(cmdContext *commandContext) *cobra.Command { %s template get app-sync-succeeded -o=yaml `, cmdContext.cliName, cmdContext.cliName), Short: "Prints information about configured templates", - RunE: func(c *cobra.Command, args []string) error { + RunE: func(_ *cobra.Command, args []string) error { var name string if len(args) == 1 { name = args[0] diff --git a/pkg/cmd/template_test.go b/pkg/cmd/template_test.go index a2c757c4..fdbf95ab 100644 --- a/pkg/cmd/template_test.go +++ b/pkg/cmd/template_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestTemplateNotifyConsole(t *testing.T) { @@ -16,14 +17,12 @@ message: hello {{.app.metadata.name}}`, var stdout bytes.Buffer var stderr bytes.Buffer ctx, closer, err := newTestContext(&stdout, &stderr, cmData, newTestResource("guestbook")) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) defer closer() command := newTemplateNotifyCommand(ctx) err = command.RunE(command, []string{"my-template", "guestbook"}) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, stderr.String()) assert.Contains(t, stdout.String(), "hello guestbook") } @@ -37,14 +36,12 @@ func TestTemplateGet(t *testing.T) { var stdout bytes.Buffer var stderr bytes.Buffer ctx, closer, err := newTestContext(&stdout, &stderr, cmData) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) defer closer() command := newTemplateGetCommand(ctx) err = command.RunE(command, nil) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, stderr.String()) assert.Contains(t, stdout.String(), "my-template1") assert.Contains(t, stdout.String(), "my-template2") diff --git a/pkg/cmd/tools.go b/pkg/cmd/tools.go index 64290678..a81d2065 100644 --- a/pkg/cmd/tools.go +++ b/pkg/cmd/tools.go @@ -1,7 +1,6 @@ package cmd import ( - "fmt" "os" "github.com/argoproj/notifications-engine/pkg/api" @@ -27,17 +26,15 @@ func addOutputFlags(cmd *cobra.Command, output *string) { } func NewToolsCommand(name string, cliName string, resource schema.GroupVersionResource, settings api.Settings, opts ...func(cfg clientcmd.ClientConfig)) *cobra.Command { - var ( - cmdContext = commandContext{ - Settings: settings, - resource: resource, - stdout: os.Stdout, - stderr: os.Stderr, - stdin: os.Stdin, - cliName: cliName, - } - ) - var command = cobra.Command{ + cmdContext := commandContext{ + Settings: settings, + resource: resource, + stdout: os.Stdout, + stderr: os.Stderr, + stdin: os.Stdin, + cliName: cliName, + } + command := cobra.Command{ Use: name, Short: "Set of CLI commands that helps manage notifications settings", Run: func(c *cobra.Command, args []string) { @@ -49,11 +46,11 @@ func NewToolsCommand(name string, cliName string, resource schema.GroupVersionRe command.AddCommand(newTemplateCommand(&cmdContext)) command.PersistentFlags().StringVar(&cmdContext.configMapPath, - "config-map", "", fmt.Sprintf("%s.yaml file path", settings.ConfigMapName)) + "config-map", "", settings.ConfigMapName+".yaml file path") command.PersistentFlags().StringVar(&cmdContext.secretPath, - "secret", "", fmt.Sprintf("%s.yaml file path. Use empty secret if provided value is ':empty'", settings.SecretName)) + "secret", "", settings.SecretName+".yaml file path. Use empty secret if provided value is ':empty'") clientConfig := addK8SFlagsToCmd(&command) - command.PersistentPreRun = func(cmd *cobra.Command, args []string) { + command.PersistentPreRun = func(_ *cobra.Command, _ []string) { for i := range opts { opts[i](clientConfig) } diff --git a/pkg/cmd/tools_test.go b/pkg/cmd/tools_test.go index fa4de713..66828e6b 100644 --- a/pkg/cmd/tools_test.go +++ b/pkg/cmd/tools_test.go @@ -7,6 +7,7 @@ import ( "github.com/argoproj/notifications-engine/pkg/util/misc" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPrintFormatterJson(t *testing.T) { @@ -15,7 +16,7 @@ func TestPrintFormatterJson(t *testing.T) { "foo": "bar", }, "json", &out) - assert.NoError(t, err) + require.NoError(t, err) assert.Contains(t, out.String(), `{ "foo": "bar" }`) @@ -27,6 +28,6 @@ func TestPrintFormatterYaml(t *testing.T) { "foo": "bar", }, "yaml", &out) - assert.NoError(t, err) + require.NoError(t, err) assert.Contains(t, out.String(), `foo: bar`) } diff --git a/pkg/cmd/trigger.go b/pkg/cmd/trigger.go index 8963c85b..b14fa5fe 100644 --- a/pkg/cmd/trigger.go +++ b/pkg/cmd/trigger.go @@ -13,10 +13,10 @@ import ( ) func newTriggerCommand(cmdContext *commandContext) *cobra.Command { - var command = cobra.Command{ + command := cobra.Command{ Use: "trigger", Short: "Notification triggers related commands", - RunE: func(c *cobra.Command, args []string) error { + RunE: func(_ *cobra.Command, _ []string) error { return errors.New("select child command") }, } @@ -27,7 +27,7 @@ func newTriggerCommand(cmdContext *commandContext) *cobra.Command { } func newTriggerRunCommand(cmdContext *commandContext) *cobra.Command { - var command = cobra.Command{ + command := cobra.Command{ Use: "run NAME RESOURCE_NAME", Short: "Evaluates specified trigger condition and prints the result", Example: fmt.Sprintf(` @@ -37,7 +37,7 @@ func newTriggerRunCommand(cmdContext *commandContext) *cobra.Command { # Execute trigger using my-config-map.yaml instead of '%s' ConfigMap %s trigger run on-sync-status-unknown ./sample-app.yaml \ --config-map ./my-config-map.yaml`, cmdContext.cliName, cmdContext.ConfigMapName, cmdContext.cliName), - RunE: func(c *cobra.Command, args []string) error { + RunE: func(_ *cobra.Command, args []string) error { if len(args) < 2 { return fmt.Errorf("expected two arguments, got %d", len(args)) } @@ -83,10 +83,8 @@ func newTriggerRunCommand(cmdContext *commandContext) *cobra.Command { } func newTriggerGetCommand(cmdContext *commandContext) *cobra.Command { - var ( - output string - ) - var command = cobra.Command{ + var output string + command := cobra.Command{ Use: "get", Example: fmt.Sprintf(` # prints all triggers @@ -95,7 +93,7 @@ func newTriggerGetCommand(cmdContext *commandContext) *cobra.Command { %s trigger get on-sync-failed -o=yaml `, cmdContext.cliName, cmdContext.cliName), Short: "Prints information about configured triggers", - RunE: func(c *cobra.Command, args []string) error { + RunE: func(_ *cobra.Command, args []string) error { var name string if len(args) == 1 { name = args[0] diff --git a/pkg/cmd/trigger_test.go b/pkg/cmd/trigger_test.go index dfe6efdb..e3e964f5 100644 --- a/pkg/cmd/trigger_test.go +++ b/pkg/cmd/trigger_test.go @@ -11,6 +11,7 @@ import ( "github.com/argoproj/notifications-engine/pkg/services" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" @@ -61,8 +62,8 @@ func newTestContext(stdout io.Writer, stderr io.Writer, data map[string]string, configMapPath: tmpFile.Name(), resource: schema.GroupVersionResource{Group: "argoproj.io", Resource: "applications", Version: "v1alpha1"}, dynamicClient: dynamicfake.NewSimpleDynamicClientWithCustomListKinds(runtime.NewScheme(), map[schema.GroupVersionResource]string{ - schema.GroupVersionResource{Group: "argoproj.io", Resource: "applications", Version: "v1alpha1"}: "List", - schema.GroupVersionResource{Group: "argoproj.io", Resource: "appprojects", Version: "v1alpha1"}: "List", + {Group: "argoproj.io", Resource: "applications", Version: "v1alpha1"}: "List", + {Group: "argoproj.io", Resource: "appprojects", Version: "v1alpha1"}: "List", }, resources...), k8sClient: fake.NewSimpleClientset(), namespace: "default", @@ -70,9 +71,9 @@ func newTestContext(stdout io.Writer, stderr io.Writer, data map[string]string, Settings: api.Settings{ ConfigMapName: "my-config-map", SecretName: "my-secret", - InitGetVars: func(cfg *api.Config, configMap *corev1.ConfigMap, secret *corev1.Secret) (api.GetVars, error) { - return func(obj map[string]interface{}, _ services.Destination) map[string]interface{} { - return map[string]interface{}{"app": obj} + InitGetVars: func(_ *api.Config, _ *corev1.ConfigMap, _ *corev1.Secret) (api.GetVars, error) { + return func(obj map[string]any, _ services.Destination) map[string]any { + return map[string]any{"app": obj} }, nil }, }, @@ -94,14 +95,12 @@ message: hello {{.app.metadata.name}}`, var stdout bytes.Buffer var stderr bytes.Buffer ctx, closer, err := newTestContext(&stdout, &stderr, cmData, newTestResource("guestbook")) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) defer closer() command := newTriggerRunCommand(ctx) err = command.RunE(command, []string{"my-trigger", "guestbook"}) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, stderr.String()) assert.Contains(t, stdout.String(), "true") } @@ -121,14 +120,12 @@ message: hello {{.app.metadata.name}}`, var stdout bytes.Buffer var stderr bytes.Buffer ctx, closer, err := newTestContext(&stdout, &stderr, cmData) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) defer closer() command := newTriggerGetCommand(ctx) err = command.RunE(command, nil) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, stderr.String()) assert.Contains(t, stdout.String(), "my-trigger1") assert.Contains(t, stdout.String(), "my-trigger2") diff --git a/pkg/controller/controller.go b/pkg/controller/controller.go index 5439cd78..aaeb137d 100644 --- a/pkg/controller/controller.go +++ b/pkg/controller/controller.go @@ -107,13 +107,13 @@ func NewController( queue := workqueue.NewTypedRateLimitingQueue(workqueue.DefaultTypedControllerRateLimiter[string]()) _, _ = informer.AddEventHandler( cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj interface{}) { + AddFunc: func(obj any) { key, err := cache.MetaNamespaceKeyFunc(obj) if err == nil { queue.Add(key) } }, - UpdateFunc: func(old, new interface{}) { + UpdateFunc: func(_, new any) { key, err := cache.MetaNamespaceKeyFunc(new) if err == nil { queue.Add(key) @@ -359,7 +359,7 @@ func (c *notificationController) processResource(api api.API, resource metav1.Ob } if !mapsEqual(resource.GetAnnotations(), annotations) { - annotationsPatch := make(map[string]interface{}) + annotationsPatch := make(map[string]any) for k, v := range annotations { annotationsPatch[k] = v } @@ -369,7 +369,7 @@ func (c *notificationController) processResource(api api.API, resource metav1.Ob } } - patchData, err := json.Marshal(map[string]map[string]interface{}{ + patchData, err := json.Marshal(map[string]map[string]any{ "metadata": {"annotations": annotationsPatch}, }) if err != nil { diff --git a/pkg/controller/controller_test.go b/pkg/controller/controller_test.go index 8237b8a3..c803acf5 100644 --- a/pkg/controller/controller_test.go +++ b/pkg/controller/controller_test.go @@ -12,6 +12,7 @@ import ( "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" @@ -36,7 +37,7 @@ var ( notifiedAnnotationKey = subscriptions.NotifiedAnnotationKey() ) -func mustToJson(val interface{}) string { +func mustToJson(val any) string { res, err := json.Marshal(val) if err != nil { panic(err) @@ -146,12 +147,12 @@ func TestSendsNotificationIfTriggered(t *testing.T) { })) ctrl, api, err := newController(t, ctx, newFakeClient(app)) - assert.NoError(t, err) + require.NoError(t, err) - receivedObj := map[string]interface{}{} + receivedObj := map[string]any{} api.EXPECT().GetConfig().Return(notificationApi.Config{}).AnyTimes() api.EXPECT().RunTrigger("my-trigger", gomock.Any()).Return([]triggers.ConditionResult{{Triggered: true, Templates: []string{"test"}}}, nil) - api.EXPECT().Send(mock.MatchedBy(func(obj map[string]interface{}) bool { + api.EXPECT().Send(mock.MatchedBy(func(obj map[string]any) bool { receivedObj = obj return true }), []string{"test"}, services.Destination{Service: "mock", Recipient: "recipient"}).Return(nil) @@ -161,7 +162,7 @@ func TestSendsNotificationIfTriggered(t *testing.T) { logEntry.Errorf("Failed to process: %v", err) } - assert.NoError(t, err) + require.NoError(t, err) state := NewState(annotations[notifiedAnnotationKey]) assert.NotNil(t, state[StateItemKey(false, "", "mock", triggers.ConditionResult{}, services.Destination{Service: "mock", Recipient: "recipient"})]) @@ -178,7 +179,7 @@ func TestDoesNotSendNotificationIfAnnotationPresent(t *testing.T) { notifiedAnnotationKey: mustToJson(state), })) ctrl, api, err := newController(t, ctx, newFakeClient(app)) - assert.NoError(t, err) + require.NoError(t, err) api.EXPECT().GetConfig().Return(notificationApi.Config{}).AnyTimes() api.EXPECT().RunTrigger("my-trigger", gomock.Any()).Return([]triggers.ConditionResult{{Triggered: true, Templates: []string{"test"}}}, nil) @@ -187,7 +188,7 @@ func TestDoesNotSendNotificationIfAnnotationPresent(t *testing.T) { if err != nil { logEntry.Errorf("Failed to process: %v", err) } - assert.NoError(t, err) + require.NoError(t, err) } func TestRemovesAnnotationIfNoTrigger(t *testing.T) { @@ -201,7 +202,7 @@ func TestRemovesAnnotationIfNoTrigger(t *testing.T) { notifiedAnnotationKey: mustToJson(state), })) ctrl, api, err := newController(t, ctx, newFakeClient(app)) - assert.NoError(t, err) + require.NoError(t, err) api.EXPECT().GetConfig().Return(notificationApi.Config{}).AnyTimes() api.EXPECT().RunTrigger("my-trigger", gomock.Any()).Return([]triggers.ConditionResult{{Triggered: false}}, nil) @@ -210,7 +211,7 @@ func TestRemovesAnnotationIfNoTrigger(t *testing.T) { if err != nil { logEntry.Errorf("Failed to process: %v", err) } - assert.NoError(t, err) + require.NoError(t, err) state = NewState(annotations[notifiedAnnotationKey]) assert.Empty(t, state) } @@ -235,7 +236,7 @@ func TestUpdatedAnnotationsSavedAsPatch(t *testing.T) { return true, nil, nil }) ctrl, api, err := newController(t, ctx, client) - assert.NoError(t, err) + require.NoError(t, err) api.EXPECT().GetConfig().Return(notificationApi.Config{}).AnyTimes() api.EXPECT().RunTrigger("my-trigger", gomock.Any()).Return([]triggers.ConditionResult{{Triggered: false}}, nil) @@ -245,11 +246,11 @@ func TestUpdatedAnnotationsSavedAsPatch(t *testing.T) { case <-time.After(time.Second * 5): t.Error("application was not patched") case patchData := <-patchCh: - patch := map[string]interface{}{} + patch := map[string]any{} err = json.Unmarshal(patchData, &patch) - assert.NoError(t, err) + require.NoError(t, err) val, ok, err := unstructured.NestedFieldNoCopy(patch, "metadata", "annotations", notifiedAnnotationKey) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, ok) assert.Nil(t, val) } @@ -349,7 +350,7 @@ func TestWithEventCallback(t *testing.T) { description: "EventCallback should be invoked with non-nil error on api failure", apiErr: errors.New("this is an api error"), expectedErrors: []error{ - fmt.Errorf("this is an api error"), + errors.New("this is an api error"), }, }, } @@ -369,12 +370,12 @@ func TestWithEventCallback(t *testing.T) { ctrl, api, err := newController(t, ctx, newFakeClient(app), WithEventCallback(mockEventCallback)) ctrl.namespaceSupport = false api.EXPECT().GetConfig().Return(notificationApi.Config{}).AnyTimes() - assert.NoError(t, err) + require.NoError(t, err) ctrl.apiFactory = &mocks.FakeFactory{Api: api, Err: tc.apiErr} if tc.apiErr == nil { api.EXPECT().RunTrigger(triggerName, gomock.Any()).Return([]triggers.ConditionResult{{Triggered: true, Templates: []string{"test"}}}, nil) - api.EXPECT().Send(mock.MatchedBy(func(obj map[string]interface{}) bool { + api.EXPECT().Send(mock.MatchedBy(func(_ map[string]any) bool { return true }), []string{"test"}, destination).Return(tc.sendErr) } @@ -383,7 +384,7 @@ func TestWithEventCallback(t *testing.T) { assert.Equal(t, app, actualSequence.Resource) - assert.Equal(t, len(tc.expectedDeliveries), len(actualSequence.Delivered)) + assert.Len(t, actualSequence.Delivered, len(tc.expectedDeliveries)) for i, event := range actualSequence.Delivered { assert.Equal(t, tc.expectedDeliveries[i].Trigger, event.Trigger) assert.Equal(t, tc.expectedDeliveries[i].Destination, event.Destination) @@ -404,18 +405,18 @@ func TestProcessResourceWithAPIWithSelfService(t *testing.T) { })) ctrl, api, err := newController(t, ctx, newFakeClient(app)) - assert.NoError(t, err) + require.NoError(t, err) ctrl.namespaceSupport = true trigger := "my-trigger" namespace := "my-namespace" - receivedObj := map[string]interface{}{} + receivedObj := map[string]any{} // SelfService API: config has IsSelfServiceConfig set to true api.EXPECT().GetConfig().Return(notificationApi.Config{IsSelfServiceConfig: true, Namespace: namespace}).AnyTimes() api.EXPECT().RunTrigger(trigger, gomock.Any()).Return([]triggers.ConditionResult{{Triggered: true, Templates: []string{"test"}}}, nil) - api.EXPECT().Send(mock.MatchedBy(func(obj map[string]interface{}) bool { + api.EXPECT().Send(mock.MatchedBy(func(obj map[string]any) bool { receivedObj = obj return true }), []string{"test"}, services.Destination{Service: "mock", Recipient: "recipient"}).Return(nil) @@ -425,7 +426,7 @@ func TestProcessResourceWithAPIWithSelfService(t *testing.T) { logEntry.Errorf("Failed to process: %v", err) } - assert.NoError(t, err) + require.NoError(t, err) state := NewState(annotations[notifiedAnnotationKey]) assert.NotZero(t, state[StateItemKey(true, namespace, trigger, triggers.ConditionResult{}, services.Destination{Service: "mock", Recipient: "recipient"})]) @@ -449,19 +450,19 @@ func TestProcessItemsWithSelfService(t *testing.T) { })) ctrl, apiMap, err := newControllerWithNamespaceSupport(t, ctx, newFakeClient(app), WithEventCallback(mockEventCallback)) - assert.NoError(t, err) + require.NoError(t, err) ctrl.namespaceSupport = true // SelfService API: config has IsSelfServiceConfig set to true apiMap["selfservice_namespace"].(*mocks.MockAPI).EXPECT().GetConfig().Return(notificationApi.Config{IsSelfServiceConfig: true, Namespace: "selfservice_namespace"}).Times(3) apiMap["selfservice_namespace"].(*mocks.MockAPI).EXPECT().RunTrigger(triggerName, gomock.Any()).Return([]triggers.ConditionResult{{Triggered: true, Templates: []string{"test"}}}, nil) - apiMap["selfservice_namespace"].(*mocks.MockAPI).EXPECT().Send(mock.MatchedBy(func(obj map[string]interface{}) bool { + apiMap["selfservice_namespace"].(*mocks.MockAPI).EXPECT().Send(mock.MatchedBy(func(_ map[string]any) bool { return true }), []string{"test"}, destination).Return(nil).AnyTimes() apiMap["default"].(*mocks.MockAPI).EXPECT().GetConfig().Return(notificationApi.Config{IsSelfServiceConfig: false, Namespace: "default"}).Times(3) apiMap["default"].(*mocks.MockAPI).EXPECT().RunTrigger(triggerName, gomock.Any()).Return([]triggers.ConditionResult{{Triggered: true, Templates: []string{"test"}}}, nil) - apiMap["default"].(*mocks.MockAPI).EXPECT().Send(mock.MatchedBy(func(obj map[string]interface{}) bool { + apiMap["default"].(*mocks.MockAPI).EXPECT().Send(mock.MatchedBy(func(_ map[string]any) bool { return true }), []string{"test"}, destination).Return(nil).AnyTimes() diff --git a/pkg/controller/metrics.go b/pkg/controller/metrics.go index 8eb9cb24..9f8de92c 100644 --- a/pkg/controller/metrics.go +++ b/pkg/controller/metrics.go @@ -1,7 +1,6 @@ package controller import ( - "fmt" "strconv" "github.com/prometheus/client_golang/prometheus" @@ -10,7 +9,7 @@ import ( func NewMetricsRegistry(prefix string) *MetricsRegistry { deliveriesCounter := prometheus.NewCounterVec( prometheus.CounterOpts{ - Name: fmt.Sprintf("%s_notifications_deliveries_total", prefix), + Name: prefix + "_notifications_deliveries_total", Help: "Number of delivered notifications.", }, []string{"trigger", "service", "succeeded"}, @@ -18,7 +17,7 @@ func NewMetricsRegistry(prefix string) *MetricsRegistry { triggerEvaluationsCounter := prometheus.NewCounterVec( prometheus.CounterOpts{ - Name: fmt.Sprintf("%s_notifications_trigger_eval_total", prefix), + Name: prefix + "_notifications_trigger_eval_total", Help: "Number of trigger evaluations.", }, []string{"name", "triggered"}, diff --git a/pkg/services/alertmanager.go b/pkg/services/alertmanager.go index 28967fde..2a5051f5 100644 --- a/pkg/services/alertmanager.go +++ b/pkg/services/alertmanager.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -67,7 +68,7 @@ type alertmanagerService struct { // GetTemplater parse text template func (n AlertmanagerNotification) GetTemplater(name string, f texttemplate.FuncMap) (Templater, error) { - return func(notification *Notification, vars map[string]interface{}) error { + return func(notification *Notification, vars map[string]any) error { if notification.Alertmanager == nil { notification.Alertmanager = &AlertmanagerNotification{} } @@ -97,7 +98,7 @@ func (n AlertmanagerNotification) GetTemplater(name string, f texttemplate.FuncM } if len(n.Labels) == 0 { - return fmt.Errorf("at least one label pair required") + return errors.New("at least one label pair required") } notification.Alertmanager.Labels = n.Labels @@ -115,7 +116,7 @@ func (n AlertmanagerNotification) GetTemplater(name string, f texttemplate.FuncM }, nil } -func (n *AlertmanagerNotification) parseAnnotations(name string, f texttemplate.FuncMap, vars map[string]interface{}) error { +func (n *AlertmanagerNotification) parseAnnotations(name string, f texttemplate.FuncMap, vars map[string]any) error { for k, v := range n.Annotations { var tempData bytes.Buffer tmpl, err := texttemplate.New(name).Funcs(f).Parse(v) @@ -133,7 +134,7 @@ func (n *AlertmanagerNotification) parseAnnotations(name string, f texttemplate. return nil } -func (n *AlertmanagerNotification) parseLabels(name string, f texttemplate.FuncMap, vars map[string]interface{}) error { +func (n *AlertmanagerNotification) parseLabels(name string, f texttemplate.FuncMap, vars map[string]any) error { foundAlertname := false for k, v := range n.Labels { @@ -162,12 +163,12 @@ func (n *AlertmanagerNotification) parseLabels(name string, f texttemplate.FuncM } // Send using create alertmanager events -func (s alertmanagerService) Send(notification Notification, dest Destination) error { +func (s alertmanagerService) Send(notification Notification, _ Destination) error { if notification.Alertmanager == nil { - return fmt.Errorf("notification alertmanager no config") + return errors.New("notification alertmanager no config") } if len(notification.Alertmanager.Labels) == 0 { - return fmt.Errorf("alertmanager at least one label pair required") + return errors.New("alertmanager at least one label pair required") } rawBody, err := json.Marshal([]*AlertmanagerNotification{notification.Alertmanager}) @@ -198,7 +199,7 @@ func (s alertmanagerService) Send(notification Notification, dest Destination) e wg.Wait() if numSuccess == 0 { - return fmt.Errorf("no events were successfully received by alertmanager") + return errors.New("no events were successfully received by alertmanager") } return nil diff --git a/pkg/services/alertmanager_test.go b/pkg/services/alertmanager_test.go index f2db8191..84b1bfe5 100644 --- a/pkg/services/alertmanager_test.go +++ b/pkg/services/alertmanager_test.go @@ -5,6 +5,7 @@ import ( "text/template" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGetTemplater_Alertmanager(t *testing.T) { @@ -19,13 +20,13 @@ func TestGetTemplater_Alertmanager(t *testing.T) { }, } - vars := map[string]interface{}{ - "app": map[string]interface{}{ - "metadata": map[string]interface{}{ + vars := map[string]any{ + "app": map[string]any{ + "metadata": map[string]any{ "name": "argocd-notifications", }, - "spec": map[string]interface{}{ - "source": map[string]interface{}{ + "spec": map[string]any{ + "source": map[string]any{ "repoURL": "https://github.com/argoproj-labs/argocd-notifications.git", }, }, @@ -34,15 +35,11 @@ func TestGetTemplater_Alertmanager(t *testing.T) { t.Run("test_Labels_Annotations", func(t *testing.T) { templater, err := n.GetTemplater("", template.FuncMap{}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) var notification Notification err = templater(¬ification, vars) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, "App_Deployed", notification.Alertmanager.Labels["alertname"]) assert.Equal(t, "argocd-notifications", notification.Alertmanager.Annotations["appname"]) @@ -50,15 +47,11 @@ func TestGetTemplater_Alertmanager(t *testing.T) { t.Run("test_default_GeneratorURL", func(t *testing.T) { templater, err := n.GetTemplater("", template.FuncMap{}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) var notification Notification err = templater(¬ification, vars) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, "https://github.com/argoproj-labs/argocd-notifications.git", notification.Alertmanager.GeneratorURL) }) @@ -67,18 +60,16 @@ func TestGetTemplater_Alertmanager(t *testing.T) { n.Alertmanager.GeneratorURL = "{{.app.metadata.name}}" templater, err := n.GetTemplater("", template.FuncMap{}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) var notification Notification - _ = templater(¬ification, map[string]interface{}{ - "app": map[string]interface{}{ - "metadata": map[string]interface{}{ + _ = templater(¬ification, map[string]any{ + "app": map[string]any{ + "metadata": map[string]any{ "name": "argocd-notifications", }, - "spec": map[string]interface{}{ - "source": map[string]interface{}{ + "spec": map[string]any{ + "source": map[string]any{ "repoURL": "https://github.com/argoproj-labs/argocd-notifications.git", }, }, @@ -92,18 +83,16 @@ func TestGetTemplater_Alertmanager(t *testing.T) { n.Alertmanager.GeneratorURL = "{{.app.spec.source.repoURL}}" templater, err := n.GetTemplater("", template.FuncMap{}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) var notification Notification - _ = templater(¬ification, map[string]interface{}{ - "app": map[string]interface{}{ - "metadata": map[string]interface{}{ + _ = templater(¬ification, map[string]any{ + "app": map[string]any{ + "metadata": map[string]any{ "name": "argocd-notifications", }, - "spec": map[string]interface{}{ - "source": map[string]interface{}{ + "spec": map[string]any{ + "source": map[string]any{ "repoURL": "git@github.com:argoproj-labs/argocd-notifications.git", }, }, diff --git a/pkg/services/awssqs.go b/pkg/services/awssqs.go index b69c5b33..67997a14 100644 --- a/pkg/services/awssqs.go +++ b/pkg/services/awssqs.go @@ -73,6 +73,7 @@ func (s awsSqsService) sendMessageInput(queueUrl *string, notif Notification) *s DelaySeconds: 10, } } + func (s awsSqsService) getQueueInput(dest Destination) *sqs.GetQueueUrlInput { result := &sqs.GetQueueUrlInput{} result.QueueName = &s.opts.Queue @@ -131,7 +132,7 @@ func (n *AwsSqsNotification) GetTemplater(name string, f texttemplate.FuncMap) ( return nil, err } - return func(notification *Notification, vars map[string]interface{}) error { + return func(notification *Notification, vars map[string]any) error { if notification.AwsSqs == nil { notification.AwsSqs = &AwsSqsNotification{} } @@ -155,7 +156,7 @@ func (n *AwsSqsNotification) GetTemplater(name string, f texttemplate.FuncMap) ( }, nil } -func (n *AwsSqsNotification) parseMessageAttributes(name string, f texttemplate.FuncMap, vars map[string]interface{}) error { +func (n *AwsSqsNotification) parseMessageAttributes(name string, f texttemplate.FuncMap, vars map[string]any) error { for k, v := range n.MessageAttributes { var tempData bytes.Buffer diff --git a/pkg/services/awssqs_test.go b/pkg/services/awssqs_test.go index a8206cee..e1832b9f 100644 --- a/pkg/services/awssqs_test.go +++ b/pkg/services/awssqs_test.go @@ -10,6 +10,7 @@ import ( "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/sqs" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGetTemplater_AwsSqs(t *testing.T) { @@ -24,21 +25,17 @@ func TestGetTemplater_AwsSqs(t *testing.T) { } templater, err := n.GetTemplater("", template.FuncMap{}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) var notification Notification - err = templater(¬ification, map[string]interface{}{ + err = templater(¬ification, map[string]any{ "message": "abcdef", "messageAttributeValue": "123456", "messageGroupId": "a1b2c3", }) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, "abcdef", notification.Message) assert.Equal(t, map[string]string{ "attributeKey": "123456", @@ -89,7 +86,7 @@ func TestSendFail_AwsSqs(t *testing.T) { AwsSqs: &AwsSqsNotification{}, } queueUrl, err := GetQueueURL(context.TODO(), client, s.getQueueInput(destination)) - assert.NoError(t, err) + require.NoError(t, err) if _, err := SendMsg(context.TODO(), client, SendMessageInput(s, queueUrl.QueueUrl, notification)); err != nil { assert.Error(t, err) @@ -110,7 +107,7 @@ func TestGetConfigOptions_AwsSqs(t *testing.T) { optionsF := GetConfigOptions(s) for _, f := range optionsF { - assert.NoError(t, f(options)) + require.NoError(t, f(options)) } // Verify region properly set assert.Equal(t, "us-east-1", options.Region) @@ -132,7 +129,7 @@ func TestGetConfigOptionsFromEnv_AwsSqs(t *testing.T) { options := GetConfigOptions(s) cfg, err := config.LoadDefaultConfig(context.TODO(), options...) - assert.NoError(t, err) + require.NoError(t, err) creds, _ := cfg.Credentials.Retrieve(context.TODO()) @@ -159,7 +156,7 @@ func TestGetConfigOptionsOverrideCredentials_AwsSqs(t *testing.T) { options := GetConfigOptions(s) cfg, err := config.LoadDefaultConfig(context.TODO(), options...) - assert.NoError(t, err) + require.NoError(t, err) creds, _ := cfg.Credentials.Retrieve(context.TODO()) @@ -185,7 +182,7 @@ func TestGetConfigOptionsCustomEndpointUrl_AwsSqs(t *testing.T) { options := GetConfigOptions(s) cfg, err := config.LoadDefaultConfig(context.TODO(), options...) - assert.NoError(t, err) + require.NoError(t, err) creds, _ := cfg.Credentials.Retrieve(context.TODO()) @@ -210,13 +207,15 @@ func TestGetClientOptionsCustomEndpointUrl_AwsSqs(t *testing.T) { }) options := GetClientOptions(s) - assert.Equal(t, 2, len(options)) + assert.Len(t, options, 2) } // Helpers -var GetConfigOptions = (*awsSqsService).getConfigOptions -var GetClientOptions = (*awsSqsService).getClientOptions -var SendMessageInput = (*awsSqsService).sendMessageInput +var ( + GetConfigOptions = (*awsSqsService).getConfigOptions + GetClientOptions = (*awsSqsService).getClientOptions + SendMessageInput = (*awsSqsService).sendMessageInput +) var NewTypedAwsSqsService = func(opts AwsSqsOptions) *awsSqsService { return &awsSqsService{opts: opts} @@ -227,13 +226,13 @@ type fakeApi struct { MessageId string } -func (a fakeApi) SendMessage(ctx context.Context, params *sqs.SendMessageInput, optFns ...func(*sqs.Options)) (*sqs.SendMessageOutput, error) { +func (a fakeApi) SendMessage(_ context.Context, _ *sqs.SendMessageInput, _ ...func(*sqs.Options)) (*sqs.SendMessageOutput, error) { return &sqs.SendMessageOutput{ MessageId: aws.String(a.MessageId), }, fmt.Errorf("%s", "fail scenario") } -func (a fakeApi) GetQueueUrl(ctx context.Context, params *sqs.GetQueueUrlInput, optFns ...func(*sqs.Options)) (*sqs.GetQueueUrlOutput, error) { +func (a fakeApi) GetQueueUrl(_ context.Context, _ *sqs.GetQueueUrlInput, _ ...func(*sqs.Options)) (*sqs.GetQueueUrlOutput, error) { var err error return &sqs.GetQueueUrlOutput{ @@ -241,8 +240,8 @@ func (a fakeApi) GetQueueUrl(ctx context.Context, params *sqs.GetQueueUrlInput, }, err } -func mockSendMsg(messageId string, errorMsg string) func(c context.Context, api SQSSendMessageAPI, input *sqs.SendMessageInput) (*sqs.SendMessageOutput, error) { - return func(c context.Context, api SQSSendMessageAPI, input *sqs.SendMessageInput) (*sqs.SendMessageOutput, error) { +func mockSendMsg(messageId string, errorMsg string) func(_ context.Context, api SQSSendMessageAPI, _ *sqs.SendMessageInput) (*sqs.SendMessageOutput, error) { + return func(_ context.Context, _ SQSSendMessageAPI, _ *sqs.SendMessageInput) (*sqs.SendMessageOutput, error) { var err error if errorMsg != "" { err = fmt.Errorf("%s", errorMsg) @@ -253,8 +252,8 @@ func mockSendMsg(messageId string, errorMsg string) func(c context.Context, api } } -func mockGetQueueURL(queueUrl string, errorMsg string) func(c context.Context, api SQSSendMessageAPI, input *sqs.GetQueueUrlInput) (*sqs.GetQueueUrlOutput, error) { - return func(c context.Context, api SQSSendMessageAPI, input *sqs.GetQueueUrlInput) (*sqs.GetQueueUrlOutput, error) { +func mockGetQueueURL(queueUrl string, errorMsg string) func(_ context.Context, api SQSSendMessageAPI, _ *sqs.GetQueueUrlInput) (*sqs.GetQueueUrlOutput, error) { + return func(_ context.Context, _ SQSSendMessageAPI, _ *sqs.GetQueueUrlInput) (*sqs.GetQueueUrlOutput, error) { var err error if errorMsg != "" { err = fmt.Errorf("%s", errorMsg) diff --git a/pkg/services/email.go b/pkg/services/email.go index 5b2de78c..c7ba2492 100644 --- a/pkg/services/email.go +++ b/pkg/services/email.go @@ -26,7 +26,7 @@ func (n *EmailNotification) GetTemplater(name string, f texttemplate.FuncMap) (T return nil, err } - return func(notification *Notification, vars map[string]interface{}) error { + return func(notification *Notification, vars map[string]any) error { if notification.Email == nil { notification.Email = &EmailNotification{} } diff --git a/pkg/services/email_test.go b/pkg/services/email_test.go index 34797821..b6f1d651 100644 --- a/pkg/services/email_test.go +++ b/pkg/services/email_test.go @@ -5,6 +5,7 @@ import ( "text/template" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "gomodules.xyz/notify" "k8s.io/utils/strings/slices" ) @@ -17,20 +18,16 @@ func TestGetTemplater_Email(t *testing.T) { } templater, err := n.GetTemplater("", template.FuncMap{}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) var notification Notification - err = templater(¬ification, map[string]interface{}{ + err = templater(¬ification, map[string]any{ "foo": "hello", "bar": "world", }) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, "hello", notification.Email.Subject) assert.Equal(t, "world", notification.Email.Body) @@ -84,7 +81,7 @@ func TestSend_MultipleRecepient(t *testing.T) { func TestNewEmailService(t *testing.T) { es := NewEmailService(EmailOptions{Html: true}) - if es.html != true { + if !es.html { t.Error("Html set incorrectly") } } diff --git a/pkg/services/github.go b/pkg/services/github.go index 5971db5e..241b70ad 100644 --- a/pkg/services/github.go +++ b/pkg/services/github.go @@ -3,6 +3,7 @@ package services import ( "bytes" "context" + "errors" "fmt" "net/http" "regexp" @@ -21,15 +22,13 @@ import ( "github.com/argoproj/notifications-engine/pkg/util/text" ) -var ( - gitSuffix = regexp.MustCompile(`\.git$`) -) +var gitSuffix = regexp.MustCompile(`\.git$`) type GitHubOptions struct { - AppID interface{} `json:"appID"` - InstallationID interface{} `json:"installationID"` - PrivateKey string `json:"privateKey"` - EnterpriseBaseURL string `json:"enterpriseBaseURL"` + AppID any `json:"appID"` + InstallationID any `json:"installationID"` + PrivateKey string `json:"privateKey"` + EnterpriseBaseURL string `json:"enterpriseBaseURL"` } type GitHubNotification struct { @@ -204,7 +203,7 @@ func (g *GitHubNotification) GetTemplater(name string, f texttemplate.FuncMap) ( } } - return func(notification *Notification, vars map[string]interface{}) error { + return func(notification *Notification, vars map[string]any) error { if notification.GitHub == nil { notification.GitHub = &GitHubNotification{ RepoURLPath: g.RepoURLPath, @@ -495,7 +494,7 @@ func fullNameByRepoURL(rawURL string) string { func (g gitHubService) Send(notification Notification, _ Destination) error { if notification.GitHub == nil { - return fmt.Errorf("config is empty") + return errors.New("config is empty") } u := strings.Split(fullNameByRepoURL(notification.GitHub.repoURL), "/") @@ -692,7 +691,6 @@ func (g gitHubService) Send(notification Notification, _ Destination) error { Output: checkRunOutput, }, ) - if err != nil { return err } diff --git a/pkg/services/github_test.go b/pkg/services/github_test.go index 80b0032b..1ab2c600 100644 --- a/pkg/services/github_test.go +++ b/pkg/services/github_test.go @@ -8,6 +8,7 @@ import ( "github.com/google/go-github/v69/github" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGetTemplater_GitHub(t *testing.T) { @@ -22,28 +23,26 @@ func TestGetTemplater_GitHub(t *testing.T) { } templater, err := n.GetTemplater("", template.FuncMap{}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) var notification Notification - err = templater(¬ification, map[string]interface{}{ - "context": map[string]interface{}{ + err = templater(¬ification, map[string]any{ + "context": map[string]any{ "argocdUrl": "https://example.com", "state": "success", }, - "app": map[string]interface{}{ - "metadata": map[string]interface{}{ + "app": map[string]any{ + "metadata": map[string]any{ "name": "argocd-notifications", }, - "spec": map[string]interface{}{ - "source": map[string]interface{}{ + "spec": map[string]any{ + "source": map[string]any{ "repoURL": "https://github.com/argoproj-labs/argocd-notifications.git", }, }, - "status": map[string]interface{}{ - "operationState": map[string]interface{}{ - "syncResult": map[string]interface{}{ + "status": map[string]any{ + "operationState": map[string]any{ + "syncResult": map[string]any{ "revision": "0123456789", }, }, @@ -51,9 +50,7 @@ func TestGetTemplater_GitHub(t *testing.T) { }, }) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, "https://github.com/argoproj-labs/argocd-notifications.git", notification.GitHub.repoURL) assert.Equal(t, "0123456789", notification.GitHub.revision) @@ -75,30 +72,26 @@ func TestGetTemplater_GitHub_Custom_Resource(t *testing.T) { } templater, err := n.GetTemplater("", template.FuncMap{}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) var notification Notification - err = templater(¬ification, map[string]interface{}{ - "sync": map[string]interface{}{ - "metadata": map[string]interface{}{ + err = templater(¬ification, map[string]any{ + "sync": map[string]any{ + "metadata": map[string]any{ "name": "root-sync-test", }, - "spec": map[string]interface{}{ - "git": map[string]interface{}{ + "spec": map[string]any{ + "git": map[string]any{ "repo": "https://github.com/argoproj-labs/argocd-notifications.git", }, }, - "status": map[string]interface{}{ + "status": map[string]any{ "lastSyncedCommit": "0123456789", }, }, }) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, "{{.sync.spec.git.repo}}", notification.GitHub.RepoURLPath) assert.Equal(t, "{{.sync.status.lastSyncedCommit}}", notification.GitHub.RevisionPath) @@ -106,7 +99,7 @@ func TestGetTemplater_GitHub_Custom_Resource(t *testing.T) { assert.Equal(t, "0123456789", notification.GitHub.revision) assert.Equal(t, "synced", notification.GitHub.Status.State) assert.Equal(t, "continuous-delivery/root-sync-test", notification.GitHub.Status.Label) - assert.Equal(t, "", notification.GitHub.Status.TargetURL) + assert.Empty(t, notification.GitHub.Status.TargetURL) } func TestSend_GitHubService_BadURL(t *testing.T) { @@ -145,30 +138,26 @@ func TestGetTemplater_GitHub_Deployment(t *testing.T) { } templater, err := n.GetTemplater("", template.FuncMap{}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) var notification Notification - err = templater(¬ification, map[string]interface{}{ - "sync": map[string]interface{}{ - "metadata": map[string]interface{}{ + err = templater(¬ification, map[string]any{ + "sync": map[string]any{ + "metadata": map[string]any{ "name": "root-sync-test", }, - "spec": map[string]interface{}{ - "git": map[string]interface{}{ + "spec": map[string]any{ + "git": map[string]any{ "repo": "https://github.com/argoproj-labs/argocd-notifications.git", }, }, - "status": map[string]interface{}{ + "status": map[string]any{ "lastSyncedCommit": "0123456789", }, }, }) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, "{{.sync.spec.git.repo}}", notification.GitHub.RepoURLPath) assert.Equal(t, "{{.sync.status.lastSyncedCommit}}", notification.GitHub.RevisionPath) @@ -178,7 +167,7 @@ func TestGetTemplater_GitHub_Deployment(t *testing.T) { assert.Equal(t, "production", notification.GitHub.Deployment.Environment) assert.Equal(t, "https://argoproj.github.io", notification.GitHub.Deployment.EnvironmentURL) assert.Equal(t, "https://argoproj.github.io/log", notification.GitHub.Deployment.LogURL) - assert.Len(t, notification.GitHub.Deployment.RequiredContexts, 0) + assert.Empty(t, notification.GitHub.Deployment.RequiredContexts) assert.Equal(t, &f, notification.GitHub.Deployment.AutoMerge) assert.Equal(t, &tr, notification.GitHub.Deployment.TransientEnvironment) assert.Equal(t, "v0.0.1", notification.GitHub.Deployment.Reference) @@ -187,7 +176,7 @@ func TestGetTemplater_GitHub_Deployment(t *testing.T) { func TestNewGitHubService_GitHubOptions(t *testing.T) { tests := []struct { name string - appID, installationID interface{} + appID, installationID any }{ { name: "nil", @@ -214,9 +203,7 @@ func TestNewGitHubService_GitHubOptions(t *testing.T) { PrivateKey: "-----BEGIN RSA PRIVATE KEY-----\nMIICWgIBAAKBgFPm23ojxbC1wC8X73f3aE9JEUrNEGuuj9TXscgp8HEqCHEOSh2/\nlwiPckhcdxnvu23uHGL4jwSHJe5jj4IgOUDjl/KSplJFuZYYfegQYjsOR512s4zn\nNVFsstfCNH6w7SQKsT5jVe3WPsCCuVyCZMTgEpJF2cQ7VNDYMT6hZn0NAgMBAAEC\ngYAVL7V6STAxaCPIgI3KyGHBq5y/O7sKxgCx6WmONvDtUoThL4+NpYSY98gO97Jn\njT7SCo+Gemd66Dmu0ds6K7LpIsqdGOJwp/YxgGBSxAjhL1qFHnOjhPgzE80c0aMB\ngFUnfqrxl7OqpUisrQP8K4XOPzRC/ukhI4YPG23zRi9l4QJBAJPeuqu5P0Aiy8TV\nsyxNSEaLp5QSjhrV41ooF/7Yb41crGoDPHwT5dIKi9jLMpzERY2wtL0SomNN1Bv8\nBOJIHHkCQQCRQUWVqHHLpMhmWLk9b/8q3ZFZ7mNinTaZjekhtYP1CcuFG1b9UCJE\nuJeEUH+ijYUrRKv/y8mkzkB7l5VaZ1g1AkBmxhFcNV6+xvB1mEn16qjnTz1j7xmR\nkUN5cBBtciTmTZkP/bvWSUYcnHPidChzSP9GoaCdIQx4lKlt4dXLKG+RAkBoXNxR\nFdCE/2UY2+Bj+wb71mvrkHMJ1Gj5VNPO62re8OWwQh9zK1MjyvjaEThTI5ktqE5o\nIBRF/AaqhhPB+4SNAkBko5ygyfmdooxEeM2PSCIcL/Jjs8ogOk+kPYMRtVKzdaGU\naDbUQ7GRzo2mJEuq4pGhkAh3b00Zc5Eapy5EFQlu\n-----END RSA PRIVATE KEY-----", }) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) }) } } @@ -233,30 +220,26 @@ func TestGetTemplater_Github_PullRequestComment(t *testing.T) { } templater, err := n.GetTemplater("", template.FuncMap{}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) var notification Notification - err = templater(¬ification, map[string]interface{}{ - "sync": map[string]interface{}{ - "metadata": map[string]interface{}{ + err = templater(¬ification, map[string]any{ + "sync": map[string]any{ + "metadata": map[string]any{ "name": "root-sync-test", }, - "spec": map[string]interface{}{ - "git": map[string]interface{}{ + "spec": map[string]any{ + "git": map[string]any{ "repo": "https://github.com/argoproj-labs/argocd-notifications.git", }, }, - "status": map[string]interface{}{ + "status": map[string]any{ "lastSyncedCommit": "0123456789", }, }, }) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, "{{.sync.spec.git.repo}}", notification.GitHub.RepoURLPath) assert.Equal(t, "{{.sync.status.lastSyncedCommit}}", notification.GitHub.RevisionPath) @@ -277,22 +260,22 @@ func TestGetTemplater_Github_PullRequestCommentWithTag(t *testing.T) { }, } templater, err := n.GetTemplater("", template.FuncMap{}) - assert.NoError(t, err) + require.NoError(t, err) var notification Notification - err = templater(¬ification, map[string]interface{}{ - "sync": map[string]interface{}{ - "spec": map[string]interface{}{ - "git": map[string]interface{}{ + err = templater(¬ification, map[string]any{ + "sync": map[string]any{ + "spec": map[string]any{ + "git": map[string]any{ "repo": "https://github.com/owner/repo", }, }, - "status": map[string]interface{}{ + "status": map[string]any{ "lastSyncedCommit": "abc123", }, }, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "This is a comment\n", notification.GitHub.PullRequestComment.Content) } @@ -315,16 +298,16 @@ func TestGitHubCheckRunNotification(t *testing.T) { CheckRun: checkRun, } - vars := map[string]interface{}{ - "app": map[string]interface{}{ - "spec": map[string]interface{}{ - "source": map[string]interface{}{ + vars := map[string]any{ + "app": map[string]any{ + "spec": map[string]any{ + "source": map[string]any{ "repoURL": "https://github.com/argoproj/argo-cd.git", }, }, - "status": map[string]interface{}{ - "operationState": map[string]interface{}{ - "syncResult": map[string]interface{}{ + "status": map[string]any{ + "operationState": map[string]any{ + "syncResult": map[string]any{ "revision": "abc123", }, }, @@ -333,12 +316,12 @@ func TestGitHubCheckRunNotification(t *testing.T) { } templater, err := githubNotification.GetTemplater("checkRun", nil) - assert.NoError(t, err) + require.NoError(t, err) notification := &Notification{} err = templater(notification, vars) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, notification.GitHub) assert.NotNil(t, notification.GitHub.CheckRun) @@ -359,25 +342,25 @@ type mockPullRequestsService struct { type mockRepositoriesService struct{} -func (m *mockRepositoriesService) CreateStatus(ctx context.Context, owner, repo, ref string, status *github.RepoStatus) (*github.RepoStatus, *github.Response, error) { +func (m *mockRepositoriesService) CreateStatus(_ context.Context, _, _, _ string, status *github.RepoStatus) (*github.RepoStatus, *github.Response, error) { return status, nil, nil } -func (m *mockRepositoriesService) ListDeployments(ctx context.Context, owner, repo string, opts *github.DeploymentsListOptions) ([]*github.Deployment, *github.Response, error) { +func (m *mockRepositoriesService) ListDeployments(_ context.Context, _, _ string, _ *github.DeploymentsListOptions) ([]*github.Deployment, *github.Response, error) { return nil, nil, nil } -func (m *mockRepositoriesService) CreateDeployment(ctx context.Context, owner, repo string, request *github.DeploymentRequest) (*github.Deployment, *github.Response, error) { +func (m *mockRepositoriesService) CreateDeployment(_ context.Context, _, _ string, _ *github.DeploymentRequest) (*github.Deployment, *github.Response, error) { return &github.Deployment{ID: github.Ptr(int64(1))}, nil, nil } -func (m *mockRepositoriesService) CreateDeploymentStatus(ctx context.Context, owner, repo string, deploymentID int64, request *github.DeploymentStatusRequest) (*github.DeploymentStatus, *github.Response, error) { +func (m *mockRepositoriesService) CreateDeploymentStatus(_ context.Context, _, _ string, _ int64, _ *github.DeploymentStatusRequest) (*github.DeploymentStatus, *github.Response, error) { return &github.DeploymentStatus{}, nil, nil } type mockChecksService struct{} -func (m *mockChecksService) CreateCheckRun(ctx context.Context, owner, repo string, opts github.CreateCheckRunOptions) (*github.CheckRun, *github.Response, error) { +func (m *mockChecksService) CreateCheckRun(_ context.Context, _, _ string, _ github.CreateCheckRunOptions) (*github.CheckRun, *github.Response, error) { return &github.CheckRun{}, nil, nil } @@ -422,28 +405,28 @@ func TestGitHubService_Send_PullRequestCommentWithTag(t *testing.T) { }, }, Destination{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, issues.comments, 1) assert.Contains(t, *issues.comments[0].Body, "test comment") assert.Contains(t, *issues.comments[0].Body, "") } // Update mock implementation to match the interface from github.go -func (m *mockPullRequestsService) ListPullRequestsWithCommit(ctx context.Context, owner, repo, sha string, opts *github.PullRequestListOptions) ([]*github.PullRequest, *github.Response, error) { +func (m *mockPullRequestsService) ListPullRequestsWithCommit(_ context.Context, _, _, _ string, _ *github.PullRequestListOptions) ([]*github.PullRequest, *github.Response, error) { return m.prs, nil, nil } // Add these methods back -func (m *mockIssuesService) ListComments(ctx context.Context, owner, repo string, number int, opts *github.IssueListCommentsOptions) ([]*github.IssueComment, *github.Response, error) { +func (m *mockIssuesService) ListComments(_ context.Context, _, _ string, _ int, _ *github.IssueListCommentsOptions) ([]*github.IssueComment, *github.Response, error) { return m.comments, nil, nil } -func (m *mockIssuesService) CreateComment(ctx context.Context, owner, repo string, number int, comment *github.IssueComment) (*github.IssueComment, *github.Response, error) { +func (m *mockIssuesService) CreateComment(_ context.Context, _, _ string, _ int, comment *github.IssueComment) (*github.IssueComment, *github.Response, error) { m.comments = append(m.comments, comment) return comment, nil, nil } -func (m *mockIssuesService) EditComment(ctx context.Context, owner, repo string, commentID int64, comment *github.IssueComment) (*github.IssueComment, *github.Response, error) { +func (m *mockIssuesService) EditComment(_ context.Context, _, _ string, commentID int64, comment *github.IssueComment) (*github.IssueComment, *github.Response, error) { for i, c := range m.comments { if c.ID != nil && *c.ID == commentID { m.comments[i] = comment @@ -485,7 +468,7 @@ func TestGitHubService_Send_UpdateExistingComment(t *testing.T) { }, }, Destination{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, issues.comments, 1) assert.Equal(t, "updated comment\n", *issues.comments[0].Body) } diff --git a/pkg/services/googlechat.go b/pkg/services/googlechat.go index 9322a170..41270e0c 100644 --- a/pkg/services/googlechat.go +++ b/pkg/services/googlechat.go @@ -47,7 +47,7 @@ func (n *GoogleChatNotification) GetTemplater(name string, f texttemplate.FuncMa return nil, fmt.Errorf("error in '%s' googlechat.threadKey : %w", name, err) } - return func(notification *Notification, vars map[string]interface{}) error { + return func(notification *Notification, vars map[string]any) error { if notification.GoogleChat == nil { notification.GoogleChat = &GoogleChatNotification{} } diff --git a/pkg/services/googlechat_test.go b/pkg/services/googlechat_test.go index 8b99bcee..777691d2 100644 --- a/pkg/services/googlechat_test.go +++ b/pkg/services/googlechat_test.go @@ -11,6 +11,7 @@ import ( "google.golang.org/api/chat/v1" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestTextMessage_GoogleChat(t *testing.T) { @@ -26,10 +27,9 @@ func TestTextMessage_GoogleChat(t *testing.T) { notification := Notification{} - err = templater(¬ification, map[string]interface{}{ + err = templater(¬ification, map[string]any{ "value": "value", }) - if err != nil { t.Error(err) return @@ -44,7 +44,7 @@ func TestTextMessage_GoogleChat(t *testing.T) { } assert.NotNil(t, message) - assert.Equal(t, message.Text, "message value") + assert.Equal(t, "message value", message.Text) } func TestTextMessageWithThreadKey_GoogleChat(t *testing.T) { @@ -63,18 +63,17 @@ func TestTextMessageWithThreadKey_GoogleChat(t *testing.T) { notification := Notification{} - err = templater(¬ification, map[string]interface{}{ + err = templater(¬ification, map[string]any{ "value": "value", "threadKey": "testThreadKey", }) - if err != nil { t.Error(err) return } assert.NotNil(t, notification.GoogleChat) - assert.Equal(t, notification.GoogleChat.ThreadKey, "testThreadKey") + assert.Equal(t, "testThreadKey", notification.GoogleChat.ThreadKey) message, err := googleChatNotificationToMessage(notification) if err != nil { @@ -111,13 +110,12 @@ func TestCardMessage_GoogleChat(t *testing.T) { notification := Notification{} - err = templater(¬ification, map[string]interface{}{ + err = templater(¬ification, map[string]any{ "text": "text", "topLabel": "topLabel", "imageUrl": "imageUrl", "button": "button", }) - if err != nil { t.Error(err) return @@ -130,7 +128,7 @@ func TestCardMessage_GoogleChat(t *testing.T) { } assert.NotNil(t, message) - assert.Equal(t, message.Cards, []chat.Card{ + assert.Equal(t, []chat.Card{ { Sections: []*chat.Section{ { @@ -160,7 +158,7 @@ func TestCardMessage_GoogleChat(t *testing.T) { }, }, }, - }) + }, message.Cards) } func TestCardV2Message_GoogleChat(t *testing.T) { @@ -201,12 +199,11 @@ func TestCardV2Message_GoogleChat(t *testing.T) { notification := Notification{} - err = templater(¬ification, map[string]interface{}{ + err = templater(¬ification, map[string]any{ "action": "test", "text": "text", "button": "button", }) - if err != nil { t.Error(err) return @@ -274,7 +271,7 @@ func TestCreateClient_NoError(t *testing.T) { opts := GoogleChatOptions{WebhookUrls: map[string]string{"test": "testUrl"}} service := NewGoogleChatService(opts).(*googleChatService) client, err := service.getClient("test") - assert.Nil(t, err) + require.NoError(t, err) assert.NotNil(t, client) assert.Equal(t, "testUrl", client.url) } @@ -283,7 +280,7 @@ func TestCreateClient_Error(t *testing.T) { opts := GoogleChatOptions{WebhookUrls: map[string]string{"test": "testUrl"}} service := NewGoogleChatService(opts).(*googleChatService) client, err := service.getClient("another") - assert.NotNil(t, err) + require.Error(t, err) assert.Nil(t, client) } @@ -310,7 +307,7 @@ func TestSendMessage_NoError(t *testing.T) { notification := Notification{Message: ""} destination := Destination{Recipient: "test"} err := service.Send(notification, destination) - assert.Nil(t, err) + require.NoError(t, err) assert.True(t, called) } @@ -337,6 +334,6 @@ func TestSendMessageWithThreadKey_NoError(t *testing.T) { notification := Notification{Message: "", GoogleChat: &GoogleChatNotification{ThreadKey: "testThreadKey"}} destination := Destination{Recipient: "test"} err := service.Send(notification, destination) - assert.Nil(t, err) + require.NoError(t, err) assert.True(t, called) } diff --git a/pkg/services/grafana.go b/pkg/services/grafana.go index bfd37d14..9d724e45 100644 --- a/pkg/services/grafana.go +++ b/pkg/services/grafana.go @@ -56,7 +56,6 @@ func (s *grafanaService) Send(notification Notification, dest Destination) error jsonValue, _ := json.Marshal(ga) apiUrl, err := url.Parse(s.opts.ApiUrl) - if err != nil { return err } @@ -69,7 +68,7 @@ func (s *grafanaService) Send(notification Notification, dest Destination) error } req.Header.Set("Content-Type", "application/json") - req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", s.opts.ApiKey)) + req.Header.Set("Authorization", "Bearer "+s.opts.ApiKey) response, err := client.Do(req) if err != nil { diff --git a/pkg/services/grafana_test.go b/pkg/services/grafana_test.go index 10e96393..cc17c447 100644 --- a/pkg/services/grafana_test.go +++ b/pkg/services/grafana_test.go @@ -7,15 +7,16 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGrafana_SuccessfullySendsNotification(t *testing.T) { var receivedHeaders http.Header var receivedBody string - server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + server := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, request *http.Request) { receivedHeaders = request.Header data, err := io.ReadAll(request.Body) - assert.NoError(t, err) + require.NoError(t, err) receivedBody = string(data) })) defer server.Close() @@ -29,7 +30,7 @@ func TestGrafana_SuccessfullySendsNotification(t *testing.T) { Notification{ Message: "Annotation description", }, Destination{Recipient: "tag1|tag2", Service: "test-service"}) - assert.NoError(t, err) + require.NoError(t, err) assert.Contains(t, receivedBody, "tag1") assert.Contains(t, receivedBody, "tag2") @@ -40,7 +41,7 @@ func TestGrafana_SuccessfullySendsNotification(t *testing.T) { func TestGrafana_UnSuccessfullySendsNotification(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { _, err := io.ReadAll(request.Body) - assert.NoError(t, err) + require.NoError(t, err) writer.WriteHeader(http.StatusInternalServerError) })) defer server.Close() diff --git a/pkg/services/mattermost.go b/pkg/services/mattermost.go index 8ad19c0e..00fc02c0 100644 --- a/pkg/services/mattermost.go +++ b/pkg/services/mattermost.go @@ -22,7 +22,7 @@ func (n *MattermostNotification) GetTemplater(name string, f texttemplate.FuncMa if err != nil { return nil, err } - return func(notification *Notification, vars map[string]interface{}) error { + return func(notification *Notification, vars map[string]any) error { if notification.Mattermost == nil { notification.Mattermost = &MattermostNotification{} } @@ -56,7 +56,7 @@ func (m *mattermostService) Send(notification Notification, dest Destination) er Transport: httputil.NewLoggingRoundTripper(transport, log.WithField("service", "mattermost")), } - attachments := []interface{}{} + attachments := []any{} if notification.Mattermost != nil { if notification.Mattermost.Attachments != "" { if err := json.Unmarshal([]byte(notification.Mattermost.Attachments), &attachments); err != nil { @@ -65,10 +65,10 @@ func (m *mattermostService) Send(notification Notification, dest Destination) er } } - body := map[string]interface{}{ + body := map[string]any{ "channel_id": dest.Recipient, "message": notification.Message, - "props": map[string]interface{}{ + "props": map[string]any{ "attachments": attachments, }, } @@ -79,7 +79,7 @@ func (m *mattermostService) Send(notification Notification, dest Destination) er return fmt.Errorf("failed to create request: %w", err) } req.Header.Set("Content-Type", "application/json") - req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", m.opts.Token)) + req.Header.Set("Authorization", "Bearer "+m.opts.Token) res, err := client.Do(req) if err != nil { diff --git a/pkg/services/mattermost_test.go b/pkg/services/mattermost_test.go index 0bad3898..c2e8e162 100644 --- a/pkg/services/mattermost_test.go +++ b/pkg/services/mattermost_test.go @@ -8,14 +8,13 @@ import ( "text/template" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestSend_Mattermost(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ts := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { b, err := io.ReadAll(r.Body) - if !assert.NoError(t, err) { - t.FailNow() - } + require.NoError(t, err) assert.JSONEq(t, `{ "channel_id": "channel", @@ -67,9 +66,7 @@ func TestSend_Mattermost(t *testing.T) { Service: "mattermost", Recipient: "channel", }) - if !assert.NoError(t, err) { - t.FailNow() - } + require.NoError(t, err) } func TestGetTemplater_Mattermost(t *testing.T) { @@ -80,18 +77,14 @@ func TestGetTemplater_Mattermost(t *testing.T) { } templater, err := n.GetTemplater("", template.FuncMap{}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) var notification Notification - err = templater(¬ification, map[string]interface{}{ + err = templater(¬ification, map[string]any{ "foo": "hello", }) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, "hello", notification.Mattermost.Attachments) } diff --git a/pkg/services/newrelic.go b/pkg/services/newrelic.go index f0717be1..35924e42 100644 --- a/pkg/services/newrelic.go +++ b/pkg/services/newrelic.go @@ -61,7 +61,7 @@ func (n *NewrelicNotification) GetTemplater(name string, f texttemplate.FuncMap) return nil, err } - return func(notification *Notification, vars map[string]interface{}) error { + return func(notification *Notification, vars map[string]any) error { if notification.Newrelic == nil { notification.Newrelic = &NewrelicNotification{} } diff --git a/pkg/services/newrelic_test.go b/pkg/services/newrelic_test.go index d8978865..b657a9f1 100644 --- a/pkg/services/newrelic_test.go +++ b/pkg/services/newrelic_test.go @@ -8,6 +8,7 @@ import ( "text/template" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGetTemplater_Newrelic(t *testing.T) { @@ -20,24 +21,22 @@ func TestGetTemplater_Newrelic(t *testing.T) { } templater, err := n.GetTemplater("newrelic", template.FuncMap{}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) var notification Notification - err = templater(¬ification, map[string]interface{}{ - "context": map[string]interface{}{ + err = templater(¬ification, map[string]any{ + "context": map[string]any{ "argocdUrl": "https://example.com", "user": "somebot", }, - "app": map[string]interface{}{ - "metadata": map[string]interface{}{ + "app": map[string]any{ + "metadata": map[string]any{ "name": "argocd-notifications", }, - "status": map[string]interface{}{ - "operationState": map[string]interface{}{ - "syncResult": map[string]interface{}{ + "status": map[string]any{ + "operationState": map[string]any{ + "syncResult": map[string]any{ "revision": "0123456789", }, }, @@ -45,9 +44,7 @@ func TestGetTemplater_Newrelic(t *testing.T) { }, }) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, "0123456789", notification.Newrelic.Revision) assert.Equal(t, "Added: /v2/deployments.rb", notification.Newrelic.Changelog) @@ -57,15 +54,13 @@ func TestGetTemplater_Newrelic(t *testing.T) { func TestSend_Newrelic(t *testing.T) { t.Run("revision deployment marker", func(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ts := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { b, err := io.ReadAll(r.Body) - if !assert.NoError(t, err) { - t.FailNow() - } + require.NoError(t, err) - assert.Equal(t, r.URL.Path, "/v2/applications/123456789/deployments.json") - assert.Equal(t, r.Header["Content-Type"], []string{"application/json"}) - assert.Equal(t, r.Header["X-Api-Key"], []string{"NRAK-5F2FIVA5UTA4FFDD11XCXVA7WPJ"}) + assert.Equal(t, "/v2/applications/123456789/deployments.json", r.URL.Path) + assert.Equal(t, []string{"application/json"}, r.Header["Content-Type"]) + assert.Equal(t, []string{"NRAK-5F2FIVA5UTA4FFDD11XCXVA7WPJ"}, r.Header["X-Api-Key"]) assert.JSONEq(t, `{ "deployment": { @@ -92,21 +87,17 @@ func TestSend_Newrelic(t *testing.T) { Recipient: "123456789", }) - if !assert.NoError(t, err) { - t.FailNow() - } + require.NoError(t, err) }) t.Run("complete deployment marker", func(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ts := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { b, err := io.ReadAll(r.Body) - if !assert.NoError(t, err) { - t.FailNow() - } + require.NoError(t, err) - assert.Equal(t, r.URL.Path, "/v2/applications/123456789/deployments.json") - assert.Equal(t, r.Header["Content-Type"], []string{"application/json"}) - assert.Equal(t, r.Header["X-Api-Key"], []string{"NRAK-5F2FIVA5UTA4FFDD11XCXVA7WPJ"}) + assert.Equal(t, "/v2/applications/123456789/deployments.json", r.URL.Path) + assert.Equal(t, []string{"application/json"}, r.Header["Content-Type"]) + assert.Equal(t, []string{"NRAK-5F2FIVA5UTA4FFDD11XCXVA7WPJ"}, r.Header["X-Api-Key"]) assert.JSONEq(t, `{ "deployment": { @@ -136,9 +127,7 @@ func TestSend_Newrelic(t *testing.T) { Recipient: "123456789", }) - if !assert.NoError(t, err) { - t.FailNow() - } + require.NoError(t, err) }) t.Run("missing config", func(t *testing.T) { diff --git a/pkg/services/opsgenie.go b/pkg/services/opsgenie.go index 5c238581..77912246 100644 --- a/pkg/services/opsgenie.go +++ b/pkg/services/opsgenie.go @@ -3,6 +3,7 @@ package services import ( "bytes" "context" + "errors" "fmt" "net/http" texttemplate "text/template" @@ -130,7 +131,7 @@ func (n *OpsgenieNotification) GetTemplater(name string, f texttemplate.FuncMap) } } - return func(notification *Notification, vars map[string]interface{}) error { + return func(notification *Notification, vars map[string]any) error { if notification.Opsgenie == nil { notification.Opsgenie = &OpsgenieNotification{} } @@ -266,7 +267,7 @@ func (s *opsgenieService) Send(notification Notification, dest Destination) erro if notification.Opsgenie != nil { if notification.Opsgenie.Description == "" { - return fmt.Errorf("opsgenie notification description is missing") + return errors.New("opsgenie notification description is missing") } description = notification.Opsgenie.Description diff --git a/pkg/services/opsgenie_test.go b/pkg/services/opsgenie_test.go index 0566539c..bceb072e 100644 --- a/pkg/services/opsgenie_test.go +++ b/pkg/services/opsgenie_test.go @@ -9,6 +9,7 @@ import ( "github.com/opsgenie/opsgenie-go-sdk-v2/alert" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) // Mock Opsgenie service for testing purposes @@ -16,7 +17,7 @@ type mockOpsgenieService struct { options OpsgenieOptions } -func NewOpsgenieServiceWithClient(options OpsgenieOptions, client *http.Client) *mockOpsgenieService { +func NewOpsgenieServiceWithClient(options OpsgenieOptions, _ *http.Client) *mockOpsgenieService { return &mockOpsgenieService{ options: options, } @@ -33,6 +34,7 @@ func (s *mockOpsgenieService) Send(notification Notification, destination Destin // Return nil to simulate successful sending of notification return nil } + func TestOpsgenieNotification_GetTemplater(t *testing.T) { // Prepare test data name := "testTemplate" @@ -73,11 +75,11 @@ func TestOpsgenieNotification_GetTemplater(t *testing.T) { templater, err := notification.GetTemplater(name, f) // Assert that no error occurred during the call - assert.NoError(t, err) + require.NoError(t, err) // Prepare mock data for the Templater function mockNotification := &Notification{} - vars := map[string]interface{}{ + vars := map[string]any{ "foo": "bar", "entity": "entity1", "user": "user1", @@ -93,7 +95,7 @@ func TestOpsgenieNotification_GetTemplater(t *testing.T) { err = templater(mockNotification, vars) // Assert that no error occurred during the execution of the Templater function - assert.NoError(t, err) + require.NoError(t, err) // Assert that the OpsgenieNotification's fields were correctly updated assert.Equal(t, "Test Opsgenie alert: bar", mockNotification.Opsgenie.Description) @@ -127,11 +129,11 @@ func TestOpsgenieNotification_GetTemplater(t *testing.T) { templater, err := notification.GetTemplater(name, f) // Assert that no error occurred during the call - assert.NoError(t, err) + require.NoError(t, err) // Prepare mock data for the Templater function mockNotification := &Notification{} - vars := map[string]interface{}{ + vars := map[string]any{ "foo": "bar", } @@ -139,7 +141,7 @@ func TestOpsgenieNotification_GetTemplater(t *testing.T) { err = templater(mockNotification, vars) // Assert that no error occurred during the execution of the Templater function - assert.NoError(t, err) + require.NoError(t, err) // Assert that the OpsgenieNotification's Details field was correctly updated assert.Equal(t, map[string]string{ @@ -161,11 +163,11 @@ func TestOpsgenieNotification_GetTemplater(t *testing.T) { templater, err := notification.GetTemplater(name, f) // Assert that no error occurred during the call - assert.NoError(t, err) + require.NoError(t, err) // Prepare mock data for the Templater function mockNotification := &Notification{} - vars := map[string]interface{}{ + vars := map[string]any{ "responderType1": "user", "responder1": "responder1_id", "responderName1": "Responder One", @@ -180,7 +182,7 @@ func TestOpsgenieNotification_GetTemplater(t *testing.T) { err = templater(mockNotification, vars) // Assert that no error occurred during the execution of the Templater function - assert.NoError(t, err) + require.NoError(t, err) // Assert that the OpsgenieNotification's VisibleTo field was correctly updated assert.Equal(t, []alert.Responder{ @@ -234,11 +236,11 @@ func TestOpsgenieNotification_GetTemplater(t *testing.T) { templater, err := notification.GetTemplater(name, f) // Assert that no error occurred during the call - assert.NoError(t, err) + require.NoError(t, err) // Prepare mock data for the Templater function mockNotification := &Notification{} - vars := map[string]interface{}{ + vars := map[string]any{ "foo": "bar", } @@ -246,7 +248,7 @@ func TestOpsgenieNotification_GetTemplater(t *testing.T) { err = templater(mockNotification, vars) // Assert that no error occurred during the execution of the Templater function - assert.NoError(t, err) + require.NoError(t, err) // Assert that the OpsgenieNotification's actions field was correctly updated assert.Equal(t, []string{"action1: bar", "action2: bar"}, mockNotification.Opsgenie.Actions) @@ -258,14 +260,15 @@ func TestOpsgenieNotification_GetTemplater(t *testing.T) { func TestOpsgenie_SendNotification_MissingAPIKey(t *testing.T) { // Create a mock HTTP server - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })) defer server.Close() service := NewOpsgenieService(OpsgenieOptions{ ApiUrl: server.URL, - ApiKeys: map[string]string{}}) + ApiKeys: map[string]string{}, + }) // Prepare test data recipient := "testRecipient" @@ -290,12 +293,13 @@ func TestOpsgenie_SendNotification_MissingAPIKey(t *testing.T) { err := service.Send(notification, Destination{Recipient: recipient, Service: "opsgenie"}) // Assert the result for missing API Key - assert.Error(t, err) + require.Error(t, err) assert.Contains(t, err.Error(), "no API key configured for recipient testRecipient") } + func TestOpsgenie_SendNotification_WithMessageOnly(t *testing.T) { // Create a mock HTTP server - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })) defer server.Close() @@ -308,7 +312,8 @@ func TestOpsgenie_SendNotification_WithMessageOnly(t *testing.T) { ApiUrl: server.URL, ApiKeys: map[string]string{ "testRecipient": "testApiKey", - }}, mockClient) + }, + }, mockClient) // Prepare test data recipient := "testRecipient" @@ -323,13 +328,13 @@ func TestOpsgenie_SendNotification_WithMessageOnly(t *testing.T) { err := service.Send(notification, Destination{Recipient: recipient, Service: "opsgenie"}) // Assert the result for missing description and priority - assert.Error(t, err) + require.Error(t, err) assert.Contains(t, err.Error(), "Description is missing") } func TestOpsgenie_SendNotification_WithDescriptionOnly(t *testing.T) { // Create a mock HTTP server - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })) defer server.Close() @@ -367,7 +372,7 @@ func TestOpsgenie_SendNotification_WithDescriptionOnly(t *testing.T) { func TestOpsgenie_SendNotification_WithDescriptionAndPriority(t *testing.T) { // Create a mock HTTP server - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })) defer server.Close() @@ -380,7 +385,8 @@ func TestOpsgenie_SendNotification_WithDescriptionAndPriority(t *testing.T) { ApiUrl: server.URL, ApiKeys: map[string]string{ "testRecipient": "testApiKey", - }}, mockClient) + }, + }, mockClient) // Prepare test data recipient := "testRecipient" @@ -406,7 +412,7 @@ func TestOpsgenie_SendNotification_WithDescriptionAndPriority(t *testing.T) { func TestOpsgenie_SendNotification_WithAllFields(t *testing.T) { // Create a mock HTTP server - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })) defer server.Close() @@ -419,7 +425,8 @@ func TestOpsgenie_SendNotification_WithAllFields(t *testing.T) { ApiUrl: server.URL, ApiKeys: map[string]string{ "testRecipient": "testApiKey", - }}, mockClient) + }, + }, mockClient) // Prepare test data recipient := "testRecipient" diff --git a/pkg/services/pagerduty.go b/pkg/services/pagerduty.go index 447deb92..2a3bf27d 100644 --- a/pkg/services/pagerduty.go +++ b/pkg/services/pagerduty.go @@ -40,7 +40,7 @@ func (p *PagerDutyNotification) GetTemplater(name string, f texttemplate.FuncMap return nil, err } - return func(notification *Notification, vars map[string]interface{}) error { + return func(notification *Notification, vars map[string]any) error { if notification.Pagerduty == nil { notification.Pagerduty = &PagerDutyNotification{} } diff --git a/pkg/services/pagerduty_test.go b/pkg/services/pagerduty_test.go index 8f5acd90..20f31e64 100644 --- a/pkg/services/pagerduty_test.go +++ b/pkg/services/pagerduty_test.go @@ -5,6 +5,7 @@ import ( "text/template" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGetTemplater_PagerDuty(t *testing.T) { @@ -15,22 +16,18 @@ func TestGetTemplater_PagerDuty(t *testing.T) { } templater, err := n.GetTemplater("", template.FuncMap{}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) var notification Notification - err = templater(¬ification, map[string]interface{}{ + err = templater(¬ification, map[string]any{ "title": "hello", "body": "world", "urg": "high", "prid": "PE456Y", }) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, "hello", notification.Pagerduty.Title) assert.Equal(t, "world", notification.Pagerduty.Body) diff --git a/pkg/services/pagerdutyv2.go b/pkg/services/pagerdutyv2.go index 57496d0b..c4f45c34 100644 --- a/pkg/services/pagerdutyv2.go +++ b/pkg/services/pagerdutyv2.go @@ -3,6 +3,7 @@ package services import ( "bytes" "context" + "errors" "fmt" texttemplate "text/template" @@ -54,7 +55,7 @@ func (p *PagerDutyV2Notification) GetTemplater(name string, f texttemplate.FuncM return nil, err } - return func(notification *Notification, vars map[string]interface{}) error { + return func(notification *Notification, vars map[string]any) error { if notification.PagerdutyV2 == nil { notification.PagerdutyV2 = &PagerDutyV2Notification{} } @@ -119,7 +120,7 @@ func (p pagerdutyV2Service) Send(notification Notification, dest Destination) er } if notification.PagerdutyV2 == nil { - return fmt.Errorf("no config found for pagerdutyv2") + return errors.New("no config found for pagerdutyv2") } event := buildEvent(routingKey, notification) diff --git a/pkg/services/pagerdutyv2_test.go b/pkg/services/pagerdutyv2_test.go index b73810c6..c82c52e3 100644 --- a/pkg/services/pagerdutyv2_test.go +++ b/pkg/services/pagerdutyv2_test.go @@ -6,6 +6,7 @@ import ( "text/template" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGetTemplater_PagerDutyV2(t *testing.T) { @@ -23,13 +24,11 @@ func TestGetTemplater_PagerDutyV2(t *testing.T) { } templater, err := n.GetTemplater("", template.FuncMap{}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) var notification Notification - err = templater(¬ification, map[string]interface{}{ + err = templater(¬ification, map[string]any{ "summary": "hello", "severity": "critical", "source": "my-app", @@ -39,9 +38,7 @@ func TestGetTemplater_PagerDutyV2(t *testing.T) { "url": "http://example.com", }) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, "hello", notification.PagerdutyV2.Summary) assert.Equal(t, "critical", notification.PagerdutyV2.Severity) @@ -179,28 +176,24 @@ func TestGetTemplater_PagerDutyV2(t *testing.T) { } templater, err := n.GetTemplater("", template.FuncMap{}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) var notification Notification - err = templater(¬ification, map[string]interface{}{ + err = templater(¬ification, map[string]any{ "summary": "hello", "severity": "critical", "source": "my-app", }) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, "hello", notification.PagerdutyV2.Summary) assert.Equal(t, "critical", notification.PagerdutyV2.Severity) assert.Equal(t, "my-app", notification.PagerdutyV2.Source) - assert.Equal(t, "", notification.PagerdutyV2.Component) - assert.Equal(t, "", notification.PagerdutyV2.Group) - assert.Equal(t, "", notification.PagerdutyV2.Class) + assert.Empty(t, notification.PagerdutyV2.Component) + assert.Empty(t, notification.PagerdutyV2.Group) + assert.Empty(t, notification.PagerdutyV2.Class) }) } diff --git a/pkg/services/rocketchat.go b/pkg/services/rocketchat.go index a8a1d186..3264a0c1 100644 --- a/pkg/services/rocketchat.go +++ b/pkg/services/rocketchat.go @@ -24,7 +24,7 @@ func (n *RocketChatNotification) GetTemplater(name string, f texttemplate.FuncMa if err != nil { return nil, err } - return func(notification *Notification, vars map[string]interface{}) error { + return func(notification *Notification, vars map[string]any) error { if notification.RocketChat == nil { notification.RocketChat = &RocketChatNotification{} } diff --git a/pkg/services/rocketchat_test.go b/pkg/services/rocketchat_test.go index 3598d12d..b9c69f19 100644 --- a/pkg/services/rocketchat_test.go +++ b/pkg/services/rocketchat_test.go @@ -5,20 +5,21 @@ import ( "text/template" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestValidEmoji(t *testing.T) { - assert.Equal(t, true, validEmoji.MatchString(":slack:")) - assert.Equal(t, true, validEmoji.MatchString(":chart_with_upwards_trend:")) - assert.Equal(t, false, validEmoji.MatchString("http://lorempixel.com/48/48")) + assert.True(t, validEmoji.MatchString(":slack:")) + assert.True(t, validEmoji.MatchString(":chart_with_upwards_trend:")) + assert.False(t, validEmoji.MatchString("http://lorempixel.com/48/48")) } func TestValidAvatarURL(t *testing.T) { - assert.Equal(t, true, isValidAvatarURL("http://lorempixel.com/48/48")) - assert.Equal(t, true, isValidAvatarURL("https://lorempixel.com/48/48")) - assert.Equal(t, false, isValidAvatarURL("favicon.ico")) - assert.Equal(t, false, isValidAvatarURL("ftp://favicon.ico")) - assert.Equal(t, false, isValidAvatarURL("ftp://lorempixel.com/favicon.ico")) + assert.True(t, isValidAvatarURL("http://lorempixel.com/48/48")) + assert.True(t, isValidAvatarURL("https://lorempixel.com/48/48")) + assert.False(t, isValidAvatarURL("favicon.ico")) + assert.False(t, isValidAvatarURL("ftp://favicon.ico")) + assert.False(t, isValidAvatarURL("ftp://lorempixel.com/favicon.ico")) } func TestGetTemplater_RocketChat(t *testing.T) { @@ -29,18 +30,14 @@ func TestGetTemplater_RocketChat(t *testing.T) { } templater, err := n.GetTemplater("", template.FuncMap{}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) var notification Notification - err = templater(¬ification, map[string]interface{}{ + err = templater(¬ification, map[string]any{ "foo": "hello", }) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, "hello", notification.RocketChat.Attachments) } diff --git a/pkg/services/services.go b/pkg/services/services.go index ba6376aa..c3a09b9f 100644 --- a/pkg/services/services.go +++ b/pkg/services/services.go @@ -253,7 +253,7 @@ func (n *Notification) getTemplater(name string, f texttemplate.FuncMap, sources return nil, err } - templaters := []Templater{func(notification *Notification, vars map[string]interface{}) error { + templaters := []Templater{func(notification *Notification, vars map[string]any) error { var messageData bytes.Buffer if err := message.Execute(&messageData, vars); err != nil { return err @@ -273,7 +273,7 @@ func (n *Notification) getTemplater(name string, f texttemplate.FuncMap, sources templaters = append(templaters, t) } - return func(notification *Notification, vars map[string]interface{}) error { + return func(notification *Notification, vars map[string]any) error { for _, t := range templaters { if err := t(notification, vars); err != nil { return err @@ -283,7 +283,7 @@ func (n *Notification) getTemplater(name string, f texttemplate.FuncMap, sources }, nil } -type Templater func(notification *Notification, vars map[string]interface{}) error +type Templater func(notification *Notification, vars map[string]any) error type TemplaterSource interface { GetTemplater(name string, f texttemplate.FuncMap) (Templater, error) diff --git a/pkg/services/services_test.go b/pkg/services/services_test.go index a907a690..2e47c3ed 100644 --- a/pkg/services/services_test.go +++ b/pkg/services/services_test.go @@ -5,25 +5,22 @@ import ( "text/template" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGetTemplater(t *testing.T) { n := Notification{Message: "{{.foo}}"} templater, err := n.GetTemplater("", template.FuncMap{}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) var notification Notification - err = templater(¬ification, map[string]interface{}{ + err = templater(¬ification, map[string]any{ "foo": "hello", }) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, "hello", notification.Message) } diff --git a/pkg/services/slack.go b/pkg/services/slack.go index ce0a2e23..6e988f37 100644 --- a/pkg/services/slack.go +++ b/pkg/services/slack.go @@ -55,7 +55,7 @@ func (n *SlackNotification) GetTemplater(name string, f texttemplate.FuncMap) (T return nil, err } - return func(notification *Notification, vars map[string]interface{}) error { + return func(notification *Notification, vars map[string]any) error { if notification.Slack == nil { notification.Slack = &SlackNotification{} } diff --git a/pkg/services/slack_test.go b/pkg/services/slack_test.go index 55b6481c..c57975f3 100644 --- a/pkg/services/slack_test.go +++ b/pkg/services/slack_test.go @@ -12,20 +12,21 @@ import ( slackutil "github.com/argoproj/notifications-engine/pkg/util/slack" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestValidIconEmoji(t *testing.T) { - assert.Equal(t, true, validIconEmoji.MatchString(":slack:")) - assert.Equal(t, true, validIconEmoji.MatchString(":chart_with_upwards_trend:")) - assert.Equal(t, false, validIconEmoji.MatchString("http://lorempixel.com/48/48")) + assert.True(t, validIconEmoji.MatchString(":slack:")) + assert.True(t, validIconEmoji.MatchString(":chart_with_upwards_trend:")) + assert.False(t, validIconEmoji.MatchString("http://lorempixel.com/48/48")) } func TestValidIconURL(t *testing.T) { - assert.Equal(t, true, isValidIconURL("http://lorempixel.com/48/48")) - assert.Equal(t, true, isValidIconURL("https://lorempixel.com/48/48")) - assert.Equal(t, false, isValidIconURL("favicon.ico")) - assert.Equal(t, false, isValidIconURL("ftp://favicon.ico")) - assert.Equal(t, false, isValidIconURL("ftp://lorempixel.com/favicon.ico")) + assert.True(t, isValidIconURL("http://lorempixel.com/48/48")) + assert.True(t, isValidIconURL("https://lorempixel.com/48/48")) + assert.False(t, isValidIconURL("favicon.ico")) + assert.False(t, isValidIconURL("ftp://favicon.ico")) + assert.False(t, isValidIconURL("ftp://lorempixel.com/favicon.ico")) } func TestGetTemplater_Slack(t *testing.T) { @@ -41,33 +42,29 @@ func TestGetTemplater_Slack(t *testing.T) { } templater, err := n.GetTemplater("", template.FuncMap{}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) var notification Notification - err = templater(¬ification, map[string]interface{}{ + err = templater(¬ification, map[string]any{ "foo": "hello", "bar": "world", }) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, "world-hello", notification.Slack.Username) assert.Equal(t, ":hello:", notification.Slack.Icon) assert.Equal(t, "hello", notification.Slack.Attachments) assert.Equal(t, "world", notification.Slack.Blocks) assert.Equal(t, "hello-world", notification.Slack.GroupingKey) - assert.Equal(t, true, notification.Slack.NotifyBroadcast) + assert.True(t, notification.Slack.NotifyBroadcast) } func TestBuildMessageOptionsWithNonExistTemplate(t *testing.T) { n := Notification{} sn, opts, err := buildMessageOptions(n, SlackOptions{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, opts, 1) assert.Empty(t, sn.GroupingKey) assert.Equal(t, slackutil.Post, sn.DeliveryPolicy) @@ -87,12 +84,12 @@ func TestSlack_SendNotification(t *testing.T) { MessageTimeStamp: "1503435956.000247", Text: "text", }) - assert.NoError(t, err) + require.NoError(t, err) t.Run("only message", func(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { data, err := io.ReadAll(request.Body) - assert.NoError(t, err) + require.NoError(t, err) v := url.Values{} v.Add("channel", "test-channel") v.Add("text", "Annotation description") @@ -101,7 +98,7 @@ func TestSlack_SendNotification(t *testing.T) { writer.WriteHeader(http.StatusOK) _, err = writer.Write(dummyResponse) - assert.NoError(t, err) + require.NoError(t, err) })) defer server.Close() @@ -115,15 +112,13 @@ func TestSlack_SendNotification(t *testing.T) { Notification{Message: "Annotation description"}, Destination{Recipient: "test-channel", Service: "slack"}, ) - if !assert.NoError(t, err) { - t.FailNow() - } + require.NoError(t, err) }) t.Run("attachments", func(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { data, err := io.ReadAll(request.Body) - assert.NoError(t, err) + require.NoError(t, err) v := url.Values{} v.Add("attachments", `[{"pretext":"pre-hello","text":"text-world","blocks":null}]`) v.Add("channel", "test") @@ -133,7 +128,7 @@ func TestSlack_SendNotification(t *testing.T) { writer.WriteHeader(http.StatusOK) _, err = writer.Write(dummyResponse) - assert.NoError(t, err) + require.NoError(t, err) })) defer server.Close() @@ -152,15 +147,13 @@ func TestSlack_SendNotification(t *testing.T) { }, Destination{Recipient: "test", Service: "slack"}, ) - if !assert.NoError(t, err) { - t.FailNow() - } + require.NoError(t, err) }) t.Run("blocks", func(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { data, err := io.ReadAll(request.Body) - assert.NoError(t, err) + require.NoError(t, err) v := url.Values{} v.Add("attachments", "[]") v.Add("blocks", `[{"type":"section","text":{"type":"plain_text","text":"Hello world"}}]`) @@ -171,7 +164,7 @@ func TestSlack_SendNotification(t *testing.T) { writer.WriteHeader(http.StatusOK) _, err = writer.Write(dummyResponse) - assert.NoError(t, err) + require.NoError(t, err) })) defer server.Close() @@ -190,9 +183,7 @@ func TestSlack_SendNotification(t *testing.T) { }, Destination{Recipient: "test", Service: "slack"}, ) - if !assert.NoError(t, err) { - t.FailNow() - } + require.NoError(t, err) }) } @@ -203,12 +194,12 @@ func TestSlack_SetUsernameAndIcon(t *testing.T) { MessageTimeStamp: "1503435956.000247", Text: "text", }) - assert.NoError(t, err) + require.NoError(t, err) t.Run("no set", func(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { data, err := io.ReadAll(request.Body) - assert.NoError(t, err) + require.NoError(t, err) v := url.Values{} v.Add("channel", "test") v.Add("text", "test") @@ -217,7 +208,7 @@ func TestSlack_SetUsernameAndIcon(t *testing.T) { writer.WriteHeader(http.StatusOK) _, err = writer.Write(dummyResponse) - assert.NoError(t, err) + require.NoError(t, err) })) defer server.Close() @@ -233,15 +224,13 @@ func TestSlack_SetUsernameAndIcon(t *testing.T) { }, Destination{Recipient: "test", Service: "slack"}, ) - if !assert.NoError(t, err) { - t.FailNow() - } + require.NoError(t, err) }) t.Run("set service config", func(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { data, err := io.ReadAll(request.Body) - assert.NoError(t, err) + require.NoError(t, err) v := url.Values{} v.Add("channel", "test") v.Add("icon_emoji", ":smile:") @@ -253,7 +242,7 @@ func TestSlack_SetUsernameAndIcon(t *testing.T) { writer.WriteHeader(http.StatusOK) _, err = writer.Write(dummyResponse) - assert.NoError(t, err) + require.NoError(t, err) })) defer server.Close() @@ -271,15 +260,13 @@ func TestSlack_SetUsernameAndIcon(t *testing.T) { }, Destination{Recipient: "test", Service: "slack"}, ) - if !assert.NoError(t, err) { - t.FailNow() - } + require.NoError(t, err) }) t.Run("set service config and template", func(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { data, err := io.ReadAll(request.Body) - assert.NoError(t, err) + require.NoError(t, err) v := url.Values{} v.Add("attachments", "[]") v.Add("channel", "test") @@ -292,7 +279,7 @@ func TestSlack_SetUsernameAndIcon(t *testing.T) { writer.WriteHeader(http.StatusOK) _, err = writer.Write(dummyResponse) - assert.NoError(t, err) + require.NoError(t, err) })) defer server.Close() @@ -314,8 +301,6 @@ func TestSlack_SetUsernameAndIcon(t *testing.T) { }, Destination{Recipient: "test", Service: "slack"}, ) - if !assert.NoError(t, err) { - t.FailNow() - } + require.NoError(t, err) }) } diff --git a/pkg/services/teams.go b/pkg/services/teams.go index 009a4b35..88e36c8e 100644 --- a/pkg/services/teams.go +++ b/pkg/services/teams.go @@ -65,7 +65,7 @@ func (n *TeamsNotification) GetTemplater(name string, f texttemplate.FuncMap) (T return nil, fmt.Errorf("error in '%s' teams.potentialAction: %w", name, err) } - return func(notification *Notification, vars map[string]interface{}) error { + return func(notification *Notification, vars map[string]any) error { if notification.Teams == nil { notification.Teams = &TeamsNotification{} } @@ -166,7 +166,6 @@ func (s teamsService) Send(notification Notification, dest Destination) error { } response, err := client.Post(webhookUrl, "application/json", bytes.NewReader(message)) - if err != nil { return err } @@ -224,7 +223,7 @@ func teamsNotificationToMessage(n Notification) (*teamsMessage, error) { } if n.Teams.Facts != "" { - unmarshalledFacts := make([]map[string]interface{}, 2) + unmarshalledFacts := make([]map[string]any, 2) err := json.Unmarshal([]byte(n.Teams.Facts), &unmarshalledFacts) if err != nil { return nil, fmt.Errorf("teams facts unmarshalling error %w", err) @@ -252,13 +251,11 @@ func teamsNotificationToReader(n Notification) ([]byte, error) { } message, err := teamsNotificationToMessage(n) - if err != nil { return nil, err } marshal, err := json.Marshal(message) - if err != nil { return nil, err } @@ -277,5 +274,7 @@ type teamsMessage struct { Sections []teamsSection `json:"sections,omitempty"` } -type teamsSection = map[string]interface{} -type teamsAction map[string]interface{} +type ( + teamsSection = map[string]any + teamsAction map[string]any +) diff --git a/pkg/services/teams_test.go b/pkg/services/teams_test.go index d4e66410..19582b94 100644 --- a/pkg/services/teams_test.go +++ b/pkg/services/teams_test.go @@ -9,6 +9,7 @@ import ( "text/template" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGetTemplater_Teams(t *testing.T) { @@ -26,7 +27,6 @@ func TestGetTemplater_Teams(t *testing.T) { } templater, err := notificationTemplate.GetTemplater("test", template.FuncMap{}) - if err != nil { t.Error(err) return @@ -34,36 +34,35 @@ func TestGetTemplater_Teams(t *testing.T) { notification := Notification{} - err = templater(¬ification, map[string]interface{}{ + err = templater(¬ification, map[string]any{ "value": "value", }) - if err != nil { t.Error(err) return } - assert.Equal(t, notification.Teams.Template, "template value") - assert.Equal(t, notification.Teams.Title, "title value") - assert.Equal(t, notification.Teams.Summary, "summary value") - assert.Equal(t, notification.Teams.Text, "text value") - assert.Equal(t, notification.Teams.Sections, "sections value") - assert.Equal(t, notification.Teams.Facts, "facts value") - assert.Equal(t, notification.Teams.PotentialAction, "actions value") - assert.Equal(t, notification.Teams.ThemeColor, "theme color value") + assert.Equal(t, "template value", notification.Teams.Template) + assert.Equal(t, "title value", notification.Teams.Title) + assert.Equal(t, "summary value", notification.Teams.Summary) + assert.Equal(t, "text value", notification.Teams.Text) + assert.Equal(t, "sections value", notification.Teams.Sections) + assert.Equal(t, "facts value", notification.Teams.Facts) + assert.Equal(t, "actions value", notification.Teams.PotentialAction) + assert.Equal(t, "theme color value", notification.Teams.ThemeColor) } func TestTeams_DefaultMessage(t *testing.T) { var receivedBody teamsMessage server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { data, err := io.ReadAll(request.Body) - assert.NoError(t, err) + require.NoError(t, err) err = json.Unmarshal(data, &receivedBody) - assert.NoError(t, err) + require.NoError(t, err) _, err = writer.Write([]byte("1")) - assert.NoError(t, err) + require.NoError(t, err) })) defer server.Close() @@ -84,7 +83,7 @@ func TestTeams_DefaultMessage(t *testing.T) { }, ) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, receivedBody.Text, notification.Message) } @@ -93,12 +92,12 @@ func TestTeams_TemplateMessage(t *testing.T) { var receivedBody string server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { data, err := io.ReadAll(request.Body) - assert.NoError(t, err) + require.NoError(t, err) receivedBody = string(data) _, err = writer.Write([]byte("1")) - assert.NoError(t, err) + require.NoError(t, err) })) defer server.Close() @@ -121,7 +120,7 @@ func TestTeams_TemplateMessage(t *testing.T) { }, ) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, receivedBody, notification.Teams.Template) } @@ -130,13 +129,13 @@ func TestTeams_MessageFields(t *testing.T) { var receivedBody teamsMessage server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { data, err := io.ReadAll(request.Body) - assert.NoError(t, err) + require.NoError(t, err) err = json.Unmarshal(data, &receivedBody) - assert.NoError(t, err) + require.NoError(t, err) _, err = writer.Write([]byte("1")) - assert.NoError(t, err) + require.NoError(t, err) })) defer server.Close() @@ -166,7 +165,7 @@ func TestTeams_MessageFields(t *testing.T) { }, ) - assert.NoError(t, err) + require.NoError(t, err) assert.Contains(t, receivedBody.Text, notification.Teams.Text) assert.Contains(t, receivedBody.Title, notification.Teams.Title) @@ -174,10 +173,9 @@ func TestTeams_MessageFields(t *testing.T) { assert.Contains(t, receivedBody.ThemeColor, notification.Teams.ThemeColor) assert.Contains(t, receivedBody.PotentialAction, teamsAction{"actions": true}) assert.Contains(t, receivedBody.Sections, teamsSection{"sections": true}) - assert.EqualValues(t, receivedBody.Sections[len(receivedBody.Sections)-1]["facts"], - []interface{}{ - map[string]interface{}{ - "facts": true, - }, - }) + assert.EqualValues(t, []any{ + map[string]any{ + "facts": true, + }, + }, receivedBody.Sections[len(receivedBody.Sections)-1]["facts"]) } diff --git a/pkg/services/webex.go b/pkg/services/webex.go index ed6ed674..0c6bc76d 100644 --- a/pkg/services/webex.go +++ b/pkg/services/webex.go @@ -41,7 +41,7 @@ func NewWebexService(opts WebexOptions) NotificationService { var validEmail = regexp.MustCompile(`^\S+@\S+\.\S+$`) func (w webexService) Send(notification Notification, dest Destination) error { - requestURL := fmt.Sprintf("%s/v1/messages", w.opts.ApiURL) + requestURL := w.opts.ApiURL + "/v1/messages" client := &http.Client{ Transport: httputil.NewLoggingRoundTripper( @@ -69,7 +69,7 @@ func (w webexService) Send(notification Notification, dest Destination) error { return err } - apiToken := fmt.Sprintf("Bearer %s", w.opts.Token) + apiToken := "Bearer " + w.opts.Token req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", apiToken) diff --git a/pkg/services/webex_test.go b/pkg/services/webex_test.go index 8bf1c751..fc588165 100644 --- a/pkg/services/webex_test.go +++ b/pkg/services/webex_test.go @@ -7,26 +7,25 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestValidEmail(t *testing.T) { - assert.Equal(t, true, validEmail.MatchString("test@test.com")) - assert.Equal(t, true, validEmail.MatchString("test.test@test.com")) - assert.Equal(t, false, validEmail.MatchString("notAnEmail")) - assert.Equal(t, false, validEmail.MatchString("notAnEmail@")) + assert.True(t, validEmail.MatchString("test@test.com")) + assert.True(t, validEmail.MatchString("test.test@test.com")) + assert.False(t, validEmail.MatchString("notAnEmail")) + assert.False(t, validEmail.MatchString("notAnEmail@")) } func TestSend_Webex(t *testing.T) { t.Run("successful attempt - email", func(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ts := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { b, err := io.ReadAll(r.Body) - if !assert.NoError(t, err) { - t.FailNow() - } + require.NoError(t, err) - assert.Equal(t, r.URL.Path, "/v1/messages") - assert.Equal(t, r.Header["Content-Type"], []string{"application/json"}) - assert.Equal(t, r.Header["Authorization"], []string{"Bearer NRAK-5F2FIVA5UTA4FFDD11XCXVA7WPJ"}) + assert.Equal(t, "/v1/messages", r.URL.Path) + assert.Equal(t, []string{"application/json"}, r.Header["Content-Type"]) + assert.Equal(t, []string{"Bearer NRAK-5F2FIVA5UTA4FFDD11XCXVA7WPJ"}, r.Header["Authorization"]) assert.JSONEq(t, `{ "toPersonEmail": "test@test.com", @@ -46,21 +45,17 @@ func TestSend_Webex(t *testing.T) { Recipient: "test@test.com", }) - if !assert.NoError(t, err) { - t.FailNow() - } + require.NoError(t, err) }) t.Run("successful attempt - room", func(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ts := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { b, err := io.ReadAll(r.Body) - if !assert.NoError(t, err) { - t.FailNow() - } + require.NoError(t, err) - assert.Equal(t, r.URL.Path, "/v1/messages") - assert.Equal(t, r.Header["Content-Type"], []string{"application/json"}) - assert.Equal(t, r.Header["Authorization"], []string{"Bearer NRAK-5F2FIVA5UTA4FFDD11XCXVA7WPJ"}) + assert.Equal(t, "/v1/messages", r.URL.Path) + assert.Equal(t, []string{"application/json"}, r.Header["Content-Type"]) + assert.Equal(t, []string{"Bearer NRAK-5F2FIVA5UTA4FFDD11XCXVA7WPJ"}, r.Header["Authorization"]) assert.JSONEq(t, `{ "roomId": "roomId123", @@ -80,22 +75,18 @@ func TestSend_Webex(t *testing.T) { Recipient: "roomId123", }) - if !assert.NoError(t, err) { - t.FailNow() - } + require.NoError(t, err) }) t.Run("auth error", func(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusUnauthorized) b, err := io.ReadAll(r.Body) - if !assert.NoError(t, err) { - t.FailNow() - } + require.NoError(t, err) - assert.Equal(t, r.URL.Path, "/v1/messages") - assert.Equal(t, r.Header["Content-Type"], []string{"application/json"}) - assert.Equal(t, r.Header["Authorization"], []string{"Bearer NRAK-5F2FIVA5UTA4FFDD11XCXVA7WPJ"}) + assert.Equal(t, "/v1/messages", r.URL.Path) + assert.Equal(t, []string{"application/json"}, r.Header["Content-Type"]) + assert.Equal(t, []string{"Bearer NRAK-5F2FIVA5UTA4FFDD11XCXVA7WPJ"}, r.Header["Authorization"]) assert.JSONEq(t, `{ "toPersonEmail": "test@test.com", @@ -115,8 +106,6 @@ func TestSend_Webex(t *testing.T) { Recipient: "test@test.com", }) - if !assert.Error(t, err) { - t.FailNow() - } + require.Error(t, err) }) } diff --git a/pkg/services/webhook.go b/pkg/services/webhook.go index a2a257b0..a9bc3e93 100644 --- a/pkg/services/webhook.go +++ b/pkg/services/webhook.go @@ -44,7 +44,7 @@ func (n WebhookNotifications) GetTemplater(name string, f texttemplate.FuncMap) } webhooks[k] = compiledWebhookTemplate{body: body, method: v.Method, path: path} } - return func(notification *Notification, vars map[string]interface{}) error { + return func(notification *Notification, vars map[string]any) error { for k, v := range webhooks { if notification.Webhook == nil { notification.Webhook = map[string]WebhookNotification{} diff --git a/pkg/services/webhook_test.go b/pkg/services/webhook_test.go index 11ff43cf..c1751392 100644 --- a/pkg/services/webhook_test.go +++ b/pkg/services/webhook_test.go @@ -1,7 +1,6 @@ package services import ( - "fmt" "io" "net/http" "net/http/httptest" @@ -10,15 +9,16 @@ import ( "text/template" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestWebhook_SuccessfullySendsNotification(t *testing.T) { var receivedHeaders http.Header var receivedBody string - server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + server := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, request *http.Request) { receivedHeaders = request.Header data, err := io.ReadAll(request.Body) - assert.NoError(t, err) + require.NoError(t, err) receivedBody = string(data) })) defer server.Close() @@ -35,20 +35,20 @@ func TestWebhook_SuccessfullySendsNotification(t *testing.T) { "test": {Body: "hello world", Method: http.MethodPost}, }, }, Destination{Recipient: "test", Service: "test"}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "hello world", receivedBody) - assert.Equal(t, receivedHeaders.Get("testHeader"), "testHeaderValue") + assert.Equal(t, "testHeaderValue", receivedHeaders.Get("testHeader")) assert.Contains(t, receivedHeaders.Get("Authorization"), "Basic") } func TestWebhook_WithNoOverrides_SuccessfullySendsNotification(t *testing.T) { var receivedHeaders http.Header var receivedBody string - server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + server := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, request *http.Request) { receivedHeaders = request.Header data, err := io.ReadAll(request.Body) - assert.NoError(t, err) + require.NoError(t, err) receivedBody = string(data) })) defer server.Close() @@ -59,22 +59,22 @@ func TestWebhook_WithNoOverrides_SuccessfullySendsNotification(t *testing.T) { Headers: []Header{{Name: "testHeader", Value: "testHeaderValue"}}, }) err := service.Send(Notification{}, Destination{Recipient: "test", Service: "test"}) - assert.NoError(t, err) + require.NoError(t, err) - assert.Equal(t, "", receivedBody) - assert.Equal(t, receivedHeaders.Get("testHeader"), "testHeaderValue") + assert.Empty(t, receivedBody) + assert.Equal(t, "testHeaderValue", receivedHeaders.Get("testHeader")) assert.Contains(t, receivedHeaders.Get("Authorization"), "Basic") } func TestWebhook_SubPath(t *testing.T) { var receivedPath string - server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + server := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, request *http.Request) { receivedPath = request.URL.Path })) defer server.Close() service := NewWebhookService(WebhookOptions{ - URL: fmt.Sprintf("%s/subpath1", server.URL), + URL: server.URL + "/subpath1", }) err := service.Send(Notification{ @@ -82,7 +82,7 @@ func TestWebhook_SubPath(t *testing.T) { "test": {Body: "hello world", Method: http.MethodPost}, }, }, Destination{Recipient: "test", Service: "test"}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "/subpath1", receivedPath) err = service.Send(Notification{ @@ -90,7 +90,7 @@ func TestWebhook_SubPath(t *testing.T) { "test": {Body: "hello world", Method: http.MethodPost, Path: "/subpath2"}, }, }, Destination{Recipient: "test", Service: "test"}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "/subpath1/subpath2", receivedPath) } @@ -106,29 +106,25 @@ func TestGetTemplater_Webhook(t *testing.T) { } templater, err := n.GetTemplater("", template.FuncMap{}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) var notification Notification - err = templater(¬ification, map[string]interface{}{ + err = templater(¬ification, map[string]any{ "foo": "hello", "bar": "world", }) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) - assert.Equal(t, notification.Webhook["github"].Method, "POST") - assert.Equal(t, notification.Webhook["github"].Body, "hello") - assert.Equal(t, notification.Webhook["github"].Path, "world") + assert.Equal(t, "POST", notification.Webhook["github"].Method) + assert.Equal(t, "hello", notification.Webhook["github"].Body) + assert.Equal(t, "world", notification.Webhook["github"].Path) } func TestWebhookService_Send_Retry(t *testing.T) { // Set up a mock server to receive requests count := 0 - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { count++ if count < 5 { w.WriteHeader(http.StatusInternalServerError) diff --git a/pkg/subscriptions/annotations.go b/pkg/subscriptions/annotations.go index 3c6ab6ab..f626ea1e 100644 --- a/pkg/subscriptions/annotations.go +++ b/pkg/subscriptions/annotations.go @@ -10,9 +10,7 @@ import ( "github.com/argoproj/notifications-engine/pkg/services" ) -var ( - annotationPrefix = "notifications.argoproj.io" -) +var annotationPrefix = "notifications.argoproj.io" // SetAnnotationPrefix sets the annotationPrefix to the provided string. // defaults to "notifications.argoproj.io" @@ -21,7 +19,7 @@ func SetAnnotationPrefix(prefix string) { } func NotifiedAnnotationKey() string { - return fmt.Sprintf("notified.%s", annotationPrefix) + return "notified." + annotationPrefix } func parseRecipients(v string) []string { @@ -173,7 +171,7 @@ func (a Annotations) Unsubscribe(trigger string, service string, recipient strin func (a Annotations) Has(service string, recipient string) bool { has := false - a.iterate(func(t string, s string, r []string, k string) { + a.iterate(func(_ string, s string, r []string, _ string) { if s != service { return } @@ -189,7 +187,7 @@ func (a Annotations) Has(service string, recipient string) bool { func (a Annotations) GetDestinations(defaultTriggers []string, serviceDefaultTriggers map[string][]string) services.Destinations { dests := services.Destinations{} - a.iterate(func(trigger string, service string, recipients []string, v string) { + a.iterate(func(trigger string, service string, recipients []string, _ string) { for _, recipient := range recipients { triggers := defaultTriggers if trigger != "" { diff --git a/pkg/subscriptions/annotations_test.go b/pkg/subscriptions/annotations_test.go index 8c4f177e..c1d40b1a 100644 --- a/pkg/subscriptions/annotations_test.go +++ b/pkg/subscriptions/annotations_test.go @@ -25,6 +25,7 @@ var data_without_trigger = ` - recipient-1 - recipient-2 ` + var data_without_destinations = ` - trigger: [my-trigger1, my-trigger2, my-trigger3] ` @@ -235,7 +236,7 @@ func TestSubscribe(t *testing.T) { a := Annotations(map[string]string{}) a.Subscribe("my-trigger", "slack", "my-channel1") - assert.Equal(t, a["notifications.argoproj.io/subscribe.my-trigger.slack"], "my-channel1") + assert.Equal(t, "my-channel1", a["notifications.argoproj.io/subscribe.my-trigger.slack"]) } func TestSubscribe_AddSecondRecipient(t *testing.T) { @@ -244,7 +245,7 @@ func TestSubscribe_AddSecondRecipient(t *testing.T) { }) a.Subscribe("my-trigger", "slack", "my-channel2") - assert.Equal(t, a["notifications.argoproj.io/subscribe.my-trigger.slack"], "my-channel1;my-channel2") + assert.Equal(t, "my-channel1;my-channel2", a["notifications.argoproj.io/subscribe.my-trigger.slack"]) } func TestUnsubscribe(t *testing.T) { @@ -252,7 +253,7 @@ func TestUnsubscribe(t *testing.T) { "notifications.argoproj.io/subscribe.my-trigger.slack": "my-channel1;my-channel2", }) a.Unsubscribe("my-trigger", "slack", "my-channel1") - assert.Equal(t, a["notifications.argoproj.io/subscribe.my-trigger.slack"], "my-channel2") + assert.Equal(t, "my-channel2", a["notifications.argoproj.io/subscribe.my-trigger.slack"]) a.Unsubscribe("my-trigger", "slack", "my-channel2") _, ok := a["notifications.argoproj.io/subscribe.my-trigger.slack"] assert.False(t, ok) diff --git a/pkg/templates/service.go b/pkg/templates/service.go index 386c7b07..b60c8fff 100644 --- a/pkg/templates/service.go +++ b/pkg/templates/service.go @@ -9,7 +9,7 @@ import ( ) type Service interface { - FormatNotification(vars map[string]interface{}, templates ...string) (*services.Notification, error) + FormatNotification(vars map[string]any, templates ...string) (*services.Notification, error) } type service struct { @@ -32,7 +32,7 @@ func NewService(templates map[string]services.Notification) (*service, error) { return svc, nil } -func (s *service) FormatNotification(vars map[string]interface{}, templates ...string) (*services.Notification, error) { +func (s *service) FormatNotification(vars map[string]any, templates ...string) (*services.Notification, error) { var notification services.Notification for _, templateName := range templates { templater, ok := s.templaters[templateName] diff --git a/pkg/templates/service_test.go b/pkg/templates/service_test.go index 48283e9e..d3716768 100644 --- a/pkg/templates/service_test.go +++ b/pkg/templates/service_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/argoproj/notifications-engine/pkg/services" ) @@ -15,17 +16,13 @@ func TestFormat_Message(t *testing.T) { }, }) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) - notification, err := svc.FormatNotification(map[string]interface{}{ + notification, err := svc.FormatNotification(map[string]any{ "foo": "hello", }, "test") - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, "hello", notification.Message) } diff --git a/pkg/triggers/service.go b/pkg/triggers/service.go index 0563014c..8e8047a3 100644 --- a/pkg/triggers/service.go +++ b/pkg/triggers/service.go @@ -3,6 +3,7 @@ package triggers import ( "crypto/sha1" "encoding/base64" + "errors" "fmt" "github.com/argoproj/notifications-engine/pkg/util/text" @@ -29,7 +30,7 @@ type ConditionResult struct { type Service interface { // Executes given trigger name and return result of each condition - Run(triggerName string, vars map[string]interface{}) ([]ConditionResult, error) + Run(triggerName string, vars map[string]any) ([]ConditionResult, error) } type service struct { @@ -70,7 +71,7 @@ func hash(input string) string { return base64.RawURLEncoding.EncodeToString(h.Sum(nil)) } -func (svc *service) Run(triggerName string, vars map[string]interface{}) ([]ConditionResult, error) { +func (svc *service) Run(triggerName string, vars map[string]any) ([]ConditionResult, error) { t, ok := svc.triggers[triggerName] if !ok { return nil, fmt.Errorf("trigger '%s' is not configured", triggerName) @@ -83,7 +84,7 @@ func (svc *service) Run(triggerName string, vars map[string]interface{}) ([]Cond } var whenResult bool if prog, ok := svc.compiledConditions[condition.When]; !ok { - return nil, fmt.Errorf("trigger configuration has changed after initialization") + return nil, errors.New("trigger configuration has changed after initialization") } else if val, err := expr.Run(prog, vars); err == nil { boolRes, ok := val.(bool) conditionResult.Triggered = ok && boolRes diff --git a/pkg/triggers/service_test.go b/pkg/triggers/service_test.go index aa37b49c..eee71773 100644 --- a/pkg/triggers/service_test.go +++ b/pkg/triggers/service_test.go @@ -1,10 +1,10 @@ package triggers import ( - "fmt" "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRun(t *testing.T) { @@ -15,14 +15,12 @@ func TestRun(t *testing.T) { }}, }) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) - conditionKey := fmt.Sprintf("[0].%s", hash("var1 == 'abc'")) + conditionKey := "[0]." + hash("var1 == 'abc'") t.Run("Triggered", func(t *testing.T) { - res, err := svc.Run("my-trigger", map[string]interface{}{"var1": "abc"}) + res, err := svc.Run("my-trigger", map[string]any{"var1": "abc"}) if assert.NoError(t, err) { return } @@ -34,7 +32,7 @@ func TestRun(t *testing.T) { }) t.Run("NotTriggered", func(t *testing.T) { - res, err := svc.Run("my-trigger", map[string]interface{}{"var1": "bcd"}) + res, err := svc.Run("my-trigger", map[string]any{"var1": "bcd"}) if assert.NoError(t, err) { return } @@ -46,7 +44,7 @@ func TestRun(t *testing.T) { }) t.Run("Failed", func(t *testing.T) { - res, err := svc.Run("my-trigger", map[string]interface{}{}) + res, err := svc.Run("my-trigger", map[string]any{}) if assert.NoError(t, err) { return } @@ -68,17 +66,13 @@ func TestRun_OncePerSet(t *testing.T) { }}, }) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) - conditionKey := fmt.Sprintf("[0].%s", hash("var1 == 'abc'")) + conditionKey := "[0]." + hash("var1 == 'abc'") t.Run("Triggered", func(t *testing.T) { - res, err := svc.Run("my-trigger", map[string]interface{}{"var1": "abc", "revision": "123"}) - if !assert.NoError(t, err) { - t.FailNow() - } + res, err := svc.Run("my-trigger", map[string]any{"var1": "abc", "revision": "123"}) + require.NoError(t, err) assert.Equal(t, []ConditionResult{{ Key: conditionKey, Triggered: true, @@ -88,10 +82,8 @@ func TestRun_OncePerSet(t *testing.T) { }) t.Run("NotTriggered", func(t *testing.T) { - res, err := svc.Run("my-trigger", map[string]interface{}{"var1": "bcd"}) - if !assert.NoError(t, err) { - t.FailNow() - } + res, err := svc.Run("my-trigger", map[string]any{"var1": "bcd"}) + require.NoError(t, err) assert.Equal(t, []ConditionResult{{ Key: conditionKey, Triggered: false, @@ -102,12 +94,12 @@ func TestRun_OncePerSet(t *testing.T) { } func TestRun_OncePer_Evaluate(t *testing.T) { - vars := map[string]interface{}{ + vars := map[string]any{ "var1": "abc", "revision": "123", - "app": map[string]interface{}{ - "metadata": map[string]interface{}{ - "annotations": map[string]interface{}{ + "app": map[string]any{ + "metadata": map[string]any{ + "annotations": map[string]any{ "example.com/version": "v0.1", }, }, @@ -137,18 +129,12 @@ func TestRun_OncePer_Evaluate(t *testing.T) { }}, }) - if !assert.NoError(t, err) { - t.FailNow() - return - } + require.NoError(t, err) - conditionKey := fmt.Sprintf("[0].%s", hash("var1 == 'abc'")) + conditionKey := "[0]." + hash("var1 == 'abc'") res, err := svc.Run("my-trigger", vars) - if !assert.NoError(t, err) { - t.FailNow() - return - } + require.NoError(t, err) assert.Equal(t, []ConditionResult{{ Key: conditionKey, diff --git a/pkg/util/misc/misc.go b/pkg/util/misc/misc.go index e4fcf928..8a1ec980 100644 --- a/pkg/util/misc/misc.go +++ b/pkg/util/misc/misc.go @@ -10,7 +10,7 @@ import ( "sigs.k8s.io/yaml" ) -func PrintFormatted(input interface{}, output string, out io.Writer) error { +func PrintFormatted(input any, output string, out io.Writer) error { switch output { case "json": data, err := json.MarshalIndent(input, "", " ") @@ -31,7 +31,7 @@ func PrintFormatted(input interface{}, output string, out io.Writer) error { } } -func IterateStringKeyMap(val interface{}, callback func(key string)) { +func IterateStringKeyMap(val any, callback func(key string)) { keys := reflect.ValueOf(val).MapKeys() var sortedKeys []string for _, k := range keys { diff --git a/pkg/util/slack/client.go b/pkg/util/slack/client.go index ac8ecb17..c8fce3dd 100644 --- a/pkg/util/slack/client.go +++ b/pkg/util/slack/client.go @@ -60,8 +60,10 @@ type SlackClient interface { SendMessageContext(ctx context.Context, channelID string, options ...sl.MsgOption) (string, string, string, error) } -type timestampMap map[string]map[string]string -type channelMap map[string]string +type ( + timestampMap map[string]map[string]string + channelMap map[string]string +) type state struct { lock sync.Mutex @@ -129,8 +131,8 @@ func (c *threadedClient) SendMessage(ctx context.Context, recipient string, grou if ts == "" || policy == Post || policy == PostAndUpdate { newTs, channelID, err := SendMessageRateLimited( - c.Client, ctx, + c.Client, c.Limiter, recipient, sl.MsgOptionPost(), @@ -150,8 +152,8 @@ func (c *threadedClient) SendMessage(ctx context.Context, recipient string, grou if ts != "" && (policy == Update || policy == PostAndUpdate) { _, _, err := SendMessageRateLimited( - c.Client, ctx, + c.Client, c.Limiter, c.getChannelID(recipient), sl.MsgOptionUpdate(ts), @@ -174,7 +176,7 @@ func buildPostOptions(broadcast bool, options []sl.MsgOption) sl.MsgOption { return opt } -func SendMessageRateLimited(client SlackClient, ctx context.Context, limiter *rate.Limiter, recipient string, options ...sl.MsgOption) (ts, channelID string, err error) { +func SendMessageRateLimited(ctx context.Context, client SlackClient, limiter *rate.Limiter, recipient string, options ...sl.MsgOption) (ts, channelID string, err error) { for { err = limiter.Wait(ctx) if err != nil { diff --git a/pkg/util/slack/client_test.go b/pkg/util/slack/client_test.go index cb03d527..c6dc1856 100644 --- a/pkg/util/slack/client_test.go +++ b/pkg/util/slack/client_test.go @@ -11,6 +11,7 @@ import ( "github.com/golang/mock/gomock" "github.com/slack-go/slack" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "golang.org/x/time/rate" ) @@ -28,7 +29,7 @@ func TestDeliveryPolicy_MarshalJSON(t *testing.T) { for i, tc := range tests { t.Run(strconv.Itoa(i), func(t *testing.T) { bs, err := json.Marshal(tc.input) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tc.want, string(bs)) }) } @@ -49,7 +50,7 @@ func TestDeliveryPolicy_UnmarshalJSON(t *testing.T) { t.Run(strconv.Itoa(i), func(t *testing.T) { var got DeliveryPolicy err := json.Unmarshal([]byte(tc.input), &got) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tc.want, got) }) } @@ -63,7 +64,7 @@ type slackAPIMethodMatcher struct { wantAPIMethod string } -func (m slackAPIMethodMatcher) Matches(maybeMsgOption interface{}) bool { +func (m slackAPIMethodMatcher) Matches(maybeMsgOption any) bool { msgOption, ok := maybeMsgOption.(slack.MsgOption) if !ok { return false @@ -181,7 +182,7 @@ func TestThreadedClient(t *testing.T) { }, ) err := client.SendMessage(context.TODO(), channel, tc.groupingKey, false, tc.policy, []slack.MsgOption{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tc.wantthreadTSs, client.ThreadTSs) }) }