Thanks to visit codestin.com
Credit goes to github.com

Skip to content

chore: improve notifications tests #13863

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jul 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion coderd/database/dbauthz/dbauthz_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2493,7 +2493,8 @@ func (s *MethodTestSuite) TestSystemFunctions() {
}))
s.Run("FetchNewMessageMetadata", s.Subtest(func(db database.Store, check *expects) {
// TODO: update this test once we have a specific role for notifications
check.Args(database.FetchNewMessageMetadataParams{}).Asserts(rbac.ResourceSystem, policy.ActionRead)
u := dbgen.User(s.T(), db, database.User{})
check.Args(database.FetchNewMessageMetadataParams{UserID: u.ID}).Asserts(rbac.ResourceSystem, policy.ActionRead)
}))
s.Run("GetNotificationMessagesByStatus", s.Subtest(func(db database.Store, check *expects) {
// TODO: update this test once we have a specific role for notifications
Expand Down
21 changes: 16 additions & 5 deletions coderd/database/dbmem/dbmem.go
Original file line number Diff line number Diff line change
Expand Up @@ -1229,15 +1229,15 @@ func (*FakeQuerier) BulkMarkNotificationMessagesFailed(_ context.Context, arg da
if err != nil {
return 0, err
}
return -1, nil
return int64(len(arg.IDs)), nil
}

func (*FakeQuerier) BulkMarkNotificationMessagesSent(_ context.Context, arg database.BulkMarkNotificationMessagesSentParams) (int64, error) {
err := validateDatabaseType(arg)
if err != nil {
return 0, err
}
return -1, nil
return int64(len(arg.IDs)), nil
}

func (*FakeQuerier) CleanTailnetCoordinators(_ context.Context) error {
Expand Down Expand Up @@ -1864,20 +1864,31 @@ func (q *FakeQuerier) FavoriteWorkspace(_ context.Context, arg uuid.UUID) error
return nil
}

func (*FakeQuerier) FetchNewMessageMetadata(_ context.Context, arg database.FetchNewMessageMetadataParams) (database.FetchNewMessageMetadataRow, error) {
func (q *FakeQuerier) FetchNewMessageMetadata(_ context.Context, arg database.FetchNewMessageMetadataParams) (database.FetchNewMessageMetadataRow, error) {
err := validateDatabaseType(arg)
if err != nil {
return database.FetchNewMessageMetadataRow{}, err
}

user, err := q.getUserByIDNoLock(arg.UserID)
if err != nil {
return database.FetchNewMessageMetadataRow{}, xerrors.Errorf("fetch user: %w", err)
}

// Mimic COALESCE in query
userName := user.Name
if userName == "" {
userName = user.Username
}

actions, err := json.Marshal([]types.TemplateAction{{URL: "http://xyz.com", Label: "XYZ"}})
if err != nil {
return database.FetchNewMessageMetadataRow{}, err
}

return database.FetchNewMessageMetadataRow{
UserEmail: "[email protected]",
UserName: "Testy McTester",
UserEmail: user.Email,
UserName: userName,
NotificationName: "Some notification",
Actions: actions,
UserID: arg.UserID,
Expand Down
39 changes: 17 additions & 22 deletions coderd/notifications/manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,8 @@ import (
"github.com/stretchr/testify/require"
"golang.org/x/xerrors"

"cdr.dev/slog"
"cdr.dev/slog/sloggers/slogtest"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbgen"
"github.com/coder/coder/v2/coderd/database/dbmem"
"github.com/coder/coder/v2/coderd/database/dbtestutil"
"github.com/coder/coder/v2/coderd/notifications"
"github.com/coder/coder/v2/coderd/notifications/dispatch"
"github.com/coder/coder/v2/coderd/notifications/types"
Expand All @@ -29,17 +25,15 @@ func TestBufferedUpdates(t *testing.T) {
t.Parallel()

// setup
if !dbtestutil.WillUsePostgres() {
t.Skip("This test requires postgres")
}
ctx, logger, db := setupInMemory(t)

ctx, logger, db := setup(t)
interceptor := &bulkUpdateInterceptor{Store: db}
santa := &santaHandler{}

cfg := defaultNotificationsConfig(database.NotificationMethodSmtp)
cfg.StoreSyncInterval = serpent.Duration(time.Hour) // Ensure we don't sync the store automatically.

// GIVEN: a manager which will pass or fail notifications based on their "nice" labels
mgr, err := notifications.NewManager(cfg, interceptor, logger.Named("notifications-manager"))
require.NoError(t, err)
mgr.WithHandlers(map[database.NotificationMethod]notifications.Handler{
Expand All @@ -50,18 +44,17 @@ func TestBufferedUpdates(t *testing.T) {

user := dbgen.User(t, db, database.User{})

// given
// WHEN: notifications are enqueued which should succeed and fail
_, err = enq.Enqueue(ctx, user.ID, notifications.TemplateWorkspaceDeleted, map[string]string{"nice": "true"}, "") // Will succeed.
require.NoError(t, err)
_, err = enq.Enqueue(ctx, user.ID, notifications.TemplateWorkspaceDeleted, map[string]string{"nice": "true"}, "") // Will succeed.
require.NoError(t, err)
_, err = enq.Enqueue(ctx, user.ID, notifications.TemplateWorkspaceDeleted, map[string]string{"nice": "false"}, "") // Will fail.
require.NoError(t, err)

// when
mgr.Run(ctx)

// then
// THEN:

const (
expectedSuccess = 2
Expand Down Expand Up @@ -99,15 +92,18 @@ func TestBufferedUpdates(t *testing.T) {
func TestBuildPayload(t *testing.T) {
t.Parallel()

// given
// SETUP
ctx, logger, db := setupInMemory(t)

// GIVEN: a set of helpers to be injected into the templates
const label = "Click here!"
const url = "http://xyz.com/"
helpers := map[string]any{
"my_label": func() string { return label },
"my_url": func() string { return url },
}

db := dbmem.New()
// GIVEN: an enqueue interceptor which returns mock metadata
interceptor := newEnqueueInterceptor(db,
// Inject custom message metadata to influence the payload construction.
func() database.FetchNewMessageMetadataRow {
Expand All @@ -130,17 +126,14 @@ func TestBuildPayload(t *testing.T) {
}
})

logger := slogtest.Make(t, &slogtest.Options{IgnoreErrors: true, IgnoredErrorIs: []error{}}).Leveled(slog.LevelDebug)
enq, err := notifications.NewStoreEnqueuer(defaultNotificationsConfig(database.NotificationMethodSmtp), interceptor, helpers, logger.Named("notifications-enqueuer"))
require.NoError(t, err)

ctx := testutil.Context(t, testutil.WaitShort)

// when
// WHEN: a notification is enqueued
_, err = enq.Enqueue(ctx, uuid.New(), notifications.TemplateWorkspaceDeleted, nil, "test")
require.NoError(t, err)

// then
// THEN: expect that a payload will be constructed and have the expected values
payload := testutil.RequireRecvCtx(ctx, t, interceptor.payload)
require.Len(t, payload.Actions, 1)
require.Equal(t, label, payload.Actions[0].Label)
Expand All @@ -150,12 +143,14 @@ func TestBuildPayload(t *testing.T) {
func TestStopBeforeRun(t *testing.T) {
t.Parallel()

ctx := context.Background()
logger := slogtest.Make(t, &slogtest.Options{IgnoreErrors: true, IgnoredErrorIs: []error{}}).Leveled(slog.LevelDebug)
mgr, err := notifications.NewManager(defaultNotificationsConfig(database.NotificationMethodSmtp), dbmem.New(), logger.Named("notifications-manager"))
// SETUP
ctx, logger, db := setupInMemory(t)

// GIVEN: a standard manager
mgr, err := notifications.NewManager(defaultNotificationsConfig(database.NotificationMethodSmtp), db, logger.Named("notifications-manager"))
require.NoError(t, err)

// Call stop before notifier is started with Run().
// THEN: validate that the manager can be stopped safely without Run() having been called yet
require.Eventually(t, func() bool {
assert.NoError(t, mgr.Stop(ctx))
return true
Expand Down
Loading
Loading