Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Test setup

Neeraj Gupta11d9744187b3
diff --git a/server/internal/testutil/testutil.go b/server/internal/testutil/testutil.go
new file mode 100644
index 0000000000..f74d27adaf
--- /dev/null
+++ b/server/internal/testutil/testutil.go
@@ -0,0 +1,299 @@
+package testutil
+
+import (
+ "database/sql"
+ "fmt"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/ente-io/museum/ente"
+ "github.com/ente-io/museum/pkg/utils/crypto"
+ "github.com/golang-migrate/migrate/v4"
+ "github.com/golang-migrate/migrate/v4/database/postgres"
+ _ "github.com/golang-migrate/migrate/v4/source/file"
+ _ "github.com/lib/pq"
+)
+
+const testDBDSN = "user=test_user password=test_pass host=localhost dbname=ente_test_db sslmode=disable"
+
+var (
+ testDBInitOnce sync.Once
+ testDB *sql.DB
+ testDBErr error
+ serverRootOnce sync.Once
+ serverRoot string
+ serverRootErr error
+ serverRootMu sync.Mutex
+)
+
+var (
+ testSecretEncryptionKey = []byte("0123456789abcdef0123456789abcdef")
+ testHashingKey = []byte("abcdef0123456789abcdef0123456789")
+)
+
+type UserFixture struct {
+ UserID int64
+ Email string
+ CreationTime int64
+ FamilyAdminID *int64
+}
+
+type SubscriptionFixture struct {
+ UserID int64
+ Storage int64
+ OriginalTransactionID string
+ ExpiryTime int64
+ ProductID string
+ PaymentProvider ente.PaymentProvider
+ Attributes string
+}
+
+type NotificationHistoryFixture struct {
+ UserID int64
+ TemplateID string
+ SentTime int64
+ NotificationGroup string
+}
+
+func RequireTestDB(t *testing.T) *sql.DB {
+ t.Helper()
+ if os.Getenv("ENV") != "test" {
+ t.Skip("requires ENV=test")
+ }
+
+ testDBInitOnce.Do(func() {
+ testDB, testDBErr = sql.Open("postgres", testDBDSN)
+ if testDBErr != nil {
+ return
+ }
+ if err := testDB.Ping(); err != nil {
+ testDBErr = err
+ return
+ }
+
+ driver, err := postgres.WithInstance(testDB, &postgres.Config{})
+ if err != nil {
+ testDBErr = err
+ return
+ }
+
+ migrationPath := "file://" + filepath.Join(serverRootPath())
+ migrationPath = migrationPath + "/migrations"
+ mig, err := migrate.NewWithDatabaseInstance(migrationPath, "ente_test_db", driver)
+ if err != nil {
+ testDBErr = err
+ return
+ }
+ if err := mig.Up(); err != nil && err != migrate.ErrNoChange {
+ testDBErr = err
+ return
+ }
+ })
+
+ if testDBErr != nil {
+ t.Fatalf("test database setup failed: %v", testDBErr)
+ }
+ return testDB
+}
+
+func ResetTables(t *testing.T, db *sql.DB) {
+ t.Helper()
+ _, err := db.Exec(`
+ TRUNCATE TABLE
+ notification_history,
+ task_lock,
+ storage_bonus,
+ subscriptions,
+ usage,
+ families,
+ tokens,
+ authenticator_entity,
+ collections,
+ users
+ RESTART IDENTITY CASCADE`)
+ if err != nil {
+ t.Fatalf("failed to reset test tables: %v", err)
+ }
+}
+
+func WithServerRoot(t *testing.T) {
+ t.Helper()
+ serverRootMu.Lock()
+
+ originalWD, err := os.Getwd()
+ if err != nil {
+ serverRootMu.Unlock()
+ t.Fatalf("failed to get cwd: %v", err)
+ }
+ if err := os.Chdir(serverRootPath()); err != nil {
+ serverRootMu.Unlock()
+ t.Fatalf("failed to chdir to server root: %v", err)
+ }
+
+ t.Cleanup(func() {
+ if err := os.Chdir(originalWD); err != nil {
+ t.Errorf("failed to restore cwd: %v", err)
+ }
+ serverRootMu.Unlock()
+ })
+}
+
+func SecretEncryptionKey() []byte {
+ return append([]byte(nil), testSecretEncryptionKey...)
+}
+
+func HashingKey() []byte {
+ return append([]byte(nil), testHashingKey...)
+}
+
+func InsertUser(t *testing.T, db *sql.DB, fixture UserFixture) int64 {
+ t.Helper()
+ if fixture.Email == "" {
+ t.Fatal("user fixture email is required")
+ }
+ if fixture.CreationTime == 0 {
+ t.Fatal("user fixture creation_time is required")
+ }
+
+ normalizedEmail := strings.ToLower(strings.TrimSpace(fixture.Email))
+ encryptedEmail, err := crypto.Encrypt(normalizedEmail, testSecretEncryptionKey)
+ if err != nil {
+ t.Fatalf("failed to encrypt email %q: %v", fixture.Email, err)
+ }
+ emailHash, err := crypto.GetHash(normalizedEmail, testHashingKey)
+ if err != nil {
+ t.Fatalf("failed to hash email %q: %v", fixture.Email, err)
+ }
+
+ if fixture.UserID > 0 {
+ _, err = db.Exec(
+ `INSERT INTO users(user_id, encrypted_email, email_decryption_nonce, email_hash, creation_time, family_admin_id)
+ OVERRIDING SYSTEM VALUE
+ VALUES($1, $2, $3, $4, $5, $6)`,
+ fixture.UserID,
+ encryptedEmail.Cipher,
+ encryptedEmail.Nonce,
+ emailHash,
+ fixture.CreationTime,
+ fixture.FamilyAdminID,
+ )
+ if err != nil {
+ t.Fatalf("failed to insert user %q: %v", fixture.Email, err)
+ }
+ return fixture.UserID
+ }
+
+ var userID int64
+ err = db.QueryRow(
+ `INSERT INTO users(encrypted_email, email_decryption_nonce, email_hash, creation_time, family_admin_id)
+ VALUES($1, $2, $3, $4, $5)
+ RETURNING user_id`,
+ encryptedEmail.Cipher,
+ encryptedEmail.Nonce,
+ emailHash,
+ fixture.CreationTime,
+ fixture.FamilyAdminID,
+ ).Scan(&userID)
+ if err != nil {
+ t.Fatalf("failed to insert user %q: %v", fixture.Email, err)
+ }
+ return userID
+}
+
+func InsertUsage(t *testing.T, db *sql.DB, userID int64, storageConsumed int64) {
+ t.Helper()
+ _, err := db.Exec(`INSERT INTO usage(user_id, storage_consumed) VALUES($1, $2)`, userID, storageConsumed)
+ if err != nil {
+ t.Fatalf("failed to insert usage for user %d: %v", userID, err)
+ }
+}
+
+func InsertSubscription(t *testing.T, db *sql.DB, fixture SubscriptionFixture) {
+ t.Helper()
+ if fixture.UserID == 0 {
+ t.Fatal("subscription fixture user_id is required")
+ }
+ if fixture.Storage == 0 {
+ t.Fatal("subscription fixture storage is required")
+ }
+ if fixture.OriginalTransactionID == "" {
+ fixture.OriginalTransactionID = fmt.Sprintf("txn-%d", fixture.UserID)
+ }
+ if fixture.ProductID == "" {
+ fixture.ProductID = "photos_yearly"
+ }
+ if fixture.PaymentProvider == "" {
+ fixture.PaymentProvider = ente.Stripe
+ }
+ if fixture.Attributes == "" {
+ fixture.Attributes = "{}"
+ }
+
+ _, err := db.Exec(
+ `INSERT INTO subscriptions(user_id, storage, original_transaction_id, expiry_time, product_id, payment_provider, latest_verification_data, attributes)
+ VALUES($1, $2, $3, $4, $5, $6, $7, $8::jsonb)`,
+ fixture.UserID,
+ fixture.Storage,
+ fixture.OriginalTransactionID,
+ fixture.ExpiryTime,
+ fixture.ProductID,
+ fixture.PaymentProvider,
+ "",
+ fixture.Attributes,
+ )
+ if err != nil {
+ t.Fatalf("failed to insert subscription for user %d: %v", fixture.UserID, err)
+ }
+}
+
+func InsertNotificationHistory(t *testing.T, db *sql.DB, fixture NotificationHistoryFixture) {
+ t.Helper()
+ if fixture.UserID == 0 {
+ t.Fatal("notification history fixture user_id is required")
+ }
+ if fixture.TemplateID == "" {
+ t.Fatal("notification history fixture template_id is required")
+ }
+ if fixture.SentTime == 0 {
+ t.Fatal("notification history fixture sent_time is required")
+ }
+
+ var notificationGroup sql.NullString
+ if fixture.NotificationGroup != "" {
+ notificationGroup = sql.NullString{
+ String: fixture.NotificationGroup,
+ Valid: true,
+ }
+ }
+
+ _, err := db.Exec(
+ `INSERT INTO notification_history(user_id, template_id, sent_time, notification_group)
+ VALUES($1, $2, $3, $4)`,
+ fixture.UserID,
+ fixture.TemplateID,
+ fixture.SentTime,
+ notificationGroup,
+ )
+ if err != nil {
+ t.Fatalf("failed to insert notification history for user %d: %v", fixture.UserID, err)
+ }
+}
+
+func serverRootPath() string {
+ serverRootOnce.Do(func() {
+ _, file, _, ok := runtime.Caller(0)
+ if !ok {
+ serverRootErr = fmt.Errorf("failed to resolve runtime caller for testutil")
+ return
+ }
+ serverRoot = filepath.Clean(filepath.Join(filepath.Dir(file), "..", ".."))
+ })
+ if serverRootErr != nil {
+ panic(serverRootErr)
+ }
+ return serverRoot
+}
diff --git a/server/pkg/controller/email/storage_warning_integration_test.go b/server/pkg/controller/email/storage_warning_integration_test.go
new file mode 100644
index 0000000000..f2d5d24ce7
--- /dev/null
+++ b/server/pkg/controller/email/storage_warning_integration_test.go
@@ -0,0 +1,112 @@
+package email
+
+import (
+ "database/sql"
+ "testing"
+
+ "github.com/ente-io/museum/ente"
+ "github.com/ente-io/museum/internal/testutil"
+ "github.com/ente-io/museum/pkg/controller/lock"
+ "github.com/ente-io/museum/pkg/repo"
+ storageBonusRepo "github.com/ente-io/museum/pkg/repo/storagebonus"
+ timeutil "github.com/ente-io/museum/pkg/utils/time"
+)
+
+const storageWarningIntegrationTestGiB = int64(1 << 30)
+
+func TestSendStorageWarningMailsActiveOverageIntegration(t *testing.T) {
+ testutil.WithServerRoot(t)
+
+ db := testutil.RequireTestDB(t)
+ testutil.ResetTables(t, db)
+ t.Cleanup(func() {
+ testutil.ResetTables(t, db)
+ })
+
+ now := timeutil.Microseconds()
+ userID := testutil.InsertUser(t, db, testutil.UserFixture{
+ Email: "[email protected]",
+ CreationTime: now - timeutil.MicroSecondsInOneHour,
+ })
+ testutil.InsertUsage(t, db, userID, 36*storageWarningIntegrationTestGiB)
+ testutil.InsertSubscription(t, db, testutil.SubscriptionFixture{
+ UserID: userID,
+ Storage: 10 * storageWarningIntegrationTestGiB,
+ ExpiryTime: now + 24*timeutil.MicroSecondsInOneHour,
+ ProductID: "photos_yearly",
+ PaymentProvider: ente.Stripe,
+ })
+
+ controller := newStorageWarningIntegrationController(db)
+ controller.SendStorageWarningMails()
+
+ assertStorageWarningNotificationCount(t, db, userID, StorageWarningActiveOverageAnchorTemplateID, 1)
+}
+
+func TestSendStorageWarningMailsExpiredIntegration(t *testing.T) {
+ testutil.WithServerRoot(t)
+
+ db := testutil.RequireTestDB(t)
+ testutil.ResetTables(t, db)
+ t.Cleanup(func() {
+ testutil.ResetTables(t, db)
+ })
+
+ now := timeutil.Microseconds()
+ userID := testutil.InsertUser(t, db, testutil.UserFixture{
+ Email: "[email protected]",
+ CreationTime: now - timeutil.MicroSecondsInOneHour,
+ })
+ testutil.InsertUsage(t, db, userID, 26*storageWarningIntegrationTestGiB)
+ testutil.InsertSubscription(t, db, testutil.SubscriptionFixture{
+ UserID: userID,
+ Storage: 10 * storageWarningIntegrationTestGiB,
+ ExpiryTime: now - storageWarningExpiredAnchorDelay - (10 * 24 * timeutil.MicroSecondsInOneHour),
+ ProductID: "photos_yearly",
+ PaymentProvider: ente.Stripe,
+ })
+
+ controller := newStorageWarningIntegrationController(db)
+ controller.SendStorageWarningMails()
+
+ assertStorageWarningNotificationCount(t, db, userID, storageWarningExpired0TemplateID, 1)
+}
+
+func newStorageWarningIntegrationController(db *sql.DB) *EmailNotificationController {
+ userRepo := &repo.UserRepository{
+ DB: db,
+ SecretEncryptionKey: testutil.SecretEncryptionKey(),
+ HashingKey: testutil.HashingKey(),
+ }
+
+ return &EmailNotificationController{
+ UserRepo: userRepo,
+ UsageRepo: &repo.UsageRepository{DB: db, UserRepo: userRepo},
+ BillingRepo: &repo.BillingRepository{DB: db},
+ StorageBonusRepo: &storageBonusRepo.Repository{DB: db},
+ LockController: &lock.LockController{
+ TaskLockingRepo: &repo.TaskLockRepository{DB: db},
+ HostName: "storage-warning-test-host",
+ },
+ NotificationHistoryRepo: &repo.NotificationHistoryRepository{DB: db},
+ }
+}
+
+func assertStorageWarningNotificationCount(t *testing.T, db *sql.DB, userID int64, templateID string, want int) {
+ t.Helper()
+
+ var got int
+ err := db.QueryRow(
+ `SELECT COUNT(*)
+ FROM notification_history
+ WHERE user_id = $1 AND template_id = $2`,
+ userID,
+ templateID,
+ ).Scan(&got)
+ if err != nil {
+ t.Fatalf("failed to count notification history for user %d template %q: %v", userID, templateID, err)
+ }
+ if got != want {
+ t.Fatalf("unexpected notification count for user %d template %q: got %d want %d", userID, templateID, got, want)
+ }
+}
diff --git a/server/pkg/controller/user/inactive_user_orchestrator_integration_test.go b/server/pkg/controller/user/inactive_user_orchestrator_integration_test.go
new file mode 100644
index 0000000000..708d4c9fab
--- /dev/null
+++ b/server/pkg/controller/user/inactive_user_orchestrator_integration_test.go
@@ -0,0 +1,76 @@
+package user
+
+import (
+ "database/sql"
+ "testing"
+
+ "github.com/ente-io/museum/internal/testutil"
+ museumController "github.com/ente-io/museum/pkg/controller"
+ "github.com/ente-io/museum/pkg/controller/lock"
+ "github.com/ente-io/museum/pkg/repo"
+ storageBonusRepo "github.com/ente-io/museum/pkg/repo/storagebonus"
+ timeutil "github.com/ente-io/museum/pkg/utils/time"
+)
+
+func TestProcessInactiveUsersWarn2mIntegration(t *testing.T) {
+ testutil.WithServerRoot(t)
+
+ db := testutil.RequireTestDB(t)
+ testutil.ResetTables(t, db)
+ t.Cleanup(func() {
+ testutil.ResetTables(t, db)
+ })
+
+ now := timeutil.Microseconds()
+ userID := testutil.InsertUser(t, db, testutil.UserFixture{
+ Email: "[email protected]",
+ CreationTime: now - inactiveUserWarn2MonthsInMicroSeconds - inactiveUserOneDayInMicroSeconds,
+ })
+
+ userRepo := &repo.UserRepository{
+ DB: db,
+ SecretEncryptionKey: testutil.SecretEncryptionKey(),
+ HashingKey: testutil.HashingKey(),
+ }
+ storageBonusRepo := &storageBonusRepo.Repository{DB: db}
+ billingRepo := &repo.BillingRepository{DB: db}
+ billingController := &museumController.BillingController{
+ BillingRepo: billingRepo,
+ UserRepo: userRepo,
+ StorageBonusRepo: storageBonusRepo,
+ }
+ orchestrator := &InactiveUserOrchestrator{
+ UserRepo: userRepo,
+ NotificationHistoryRepo: &repo.NotificationHistoryRepository{DB: db},
+ LockController: &lock.LockController{
+ TaskLockingRepo: &repo.TaskLockRepository{DB: db},
+ HostName: "inactive-user-test-host",
+ },
+ UserController: &UserController{
+ BillingController: billingController,
+ },
+ }
+
+ orchestrator.ProcessInactiveUsers()
+
+ assertNotificationHistoryCount(t, db, userID, InactiveUserDeletionWarn2mTemplateID, 1)
+}
+
+func assertNotificationHistoryCount(t *testing.T, db *sql.DB, userID int64, templateID string, want int) {
+ t.Helper()
+
+ var got int
+ err := db.QueryRow(
+ `SELECT COUNT(*)
+ FROM notification_history
+ WHERE user_id = $1 AND template_id = $2`,
+ userID,
+ templateID,
+ ).Scan(&got)
+ if err != nil {
+ t.Fatalf("failed to count notification history for user %d template %q: %v", userID, templateID, err)
+ }
+ if got != want {
+ t.Fatalf("unexpected notification count for user %d template %q: got %d want %d", userID, templateID, got, want)
+ }
+}
diff --git a/server/pkg/repo/usage_storage_warning_test.go b/server/pkg/repo/usage_storage_warning_test.go
index e4e3c37393..b7f3e57b4c 100644
--- a/server/pkg/repo/usage_storage_warning_test.go
+++ b/server/pkg/repo/usage_storage_warning_test.go
@@ -4,103 +4,37 @@ import (
"context"
"database/sql"
"fmt"
- "os"
- "path/filepath"
- "strings"
- "sync"
"testing"
- "github.com/golang-migrate/migrate/v4"
- "github.com/golang-migrate/migrate/v4/database/postgres"
+ "github.com/ente-io/museum/internal/testutil"
"github.com/google/uuid"
)
const testGiB = int64(1 << 30)
-var (
- storageWarningRepoTestDB *sql.DB
- storageWarningRepoTestDBErr error
- storageWarningRepoTestDBOnce sync.Once
-)
-
func getStorageWarningRepoTestDB(t *testing.T) *sql.DB {
t.Helper()
- if os.Getenv("ENV") != "test" {
- t.Skip("requires ENV=test")
- }
-
- storageWarningRepoTestDBOnce.Do(func() {
- storageWarningRepoTestDB, storageWarningRepoTestDBErr = sql.Open("postgres", "user=test_user password=test_pass host=localhost dbname=ente_test_db sslmode=disable")
- if storageWarningRepoTestDBErr != nil {
- return
- }
-
- driver, err := postgres.WithInstance(storageWarningRepoTestDB, &postgres.Config{})
- if err != nil {
- storageWarningRepoTestDBErr = err
- return
- }
-
- cwd, err := os.Getwd()
- if err != nil {
- storageWarningRepoTestDBErr = err
- return
- }
- cwd = strings.Split(cwd, "/pkg/")[0]
- migrationPath := "file://" + filepath.Join(cwd, "migrations")
- mig, err := migrate.NewWithDatabaseInstance(migrationPath, "ente_test_db", driver)
- if err != nil {
- storageWarningRepoTestDBErr = err
- return
- }
- if err := mig.Up(); err != nil && err != migrate.ErrNoChange {
- storageWarningRepoTestDBErr = err
- return
- }
- })
-
- if storageWarningRepoTestDBErr != nil {
- t.Skipf("repo storage warning integration tests require local postgres: %v", storageWarningRepoTestDBErr)
- }
-
- resetStorageWarningRepoTestTables(t, storageWarningRepoTestDB)
+ db := testutil.RequireTestDB(t)
+ resetStorageWarningRepoTestTables(t, db)
t.Cleanup(func() {
- resetStorageWarningRepoTestTables(t, storageWarningRepoTestDB)
+ resetStorageWarningRepoTestTables(t, db)
})
- return storageWarningRepoTestDB
+ return db
}
func resetStorageWarningRepoTestTables(t *testing.T, db *sql.DB) {
t.Helper()
- for _, table := range []string{
- "notification_history",
- "storage_bonus",
- "subscriptions",
- "usage",
- "families",
- "users",
- } {
- if _, err := db.Exec("DELETE FROM " + table); err != nil {
- t.Fatalf("failed to clear %s: %v", table, err)
- }
- }
+ testutil.ResetTables(t, db)
}
func insertStorageWarningTestUser(t *testing.T, db *sql.DB, userID int64, familyAdminID *int64) {
t.Helper()
- _, err := db.Exec(
- `INSERT INTO users(user_id, encrypted_email, email_decryption_nonce, email_hash, creation_time, family_admin_id)
- VALUES($1, $2, $3, $4, $5, $6)`,
- userID,
- []byte{byte(userID), 1},
- []byte{byte(userID), 2},
- fmt.Sprintf("user-%[email protected]", userID),
- int64(1),
- familyAdminID,
- )
- if err != nil {
- t.Fatalf("failed to insert user %d: %v", userID, err)
- }
+ testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: userID,
+ Email: fmt.Sprintf("user-%[email protected]", userID),
+ CreationTime: 1,
+ FamilyAdminID: familyAdminID,
+ })
}
func insertStorageWarningTestUsage(t *testing.T, db *sql.DB, userID int64, usage int64) {
diff --git a/server/pkg/utils/email/email_test.go b/server/pkg/utils/email/email_test.go
index ed35ed6305..dd5681fab6 100644
--- a/server/pkg/utils/email/email_test.go
+++ b/server/pkg/utils/email/email_test.go
@@ -1,9 +1,9 @@
package email
import (
- "os"
"testing"
+ "github.com/ente-io/museum/internal/testutil"
"github.com/stretchr/testify/assert"
)
@@ -99,12 +99,7 @@ func TestGetMaskedEmailForPublic(t *testing.T) {
}
func TestInactiveUserDeletionTemplatesIncludeAccountEmail(t *testing.T) {
- originalWD, err := os.Getwd()
- assert.NoError(t, err)
- assert.NoError(t, os.Chdir("../../.."))
- defer func() {
- assert.NoError(t, os.Chdir(originalWD))
- }()
+ testutil.WithServerRoot(t)
templateData := map[string]interface{}{
"Email": "[email protected]",
diff --git a/server/pkg/utils/email/storage_warning_template_test.go b/server/pkg/utils/email/storage_warning_template_test.go
new file mode 100644
index 0000000000..c4f89904a5
--- /dev/null
+++ b/server/pkg/utils/email/storage_warning_template_test.go
@@ -0,0 +1,30 @@
+package email
+
+import (
+ "testing"
+
+ "github.com/ente-io/museum/internal/testutil"
+ "github.com/stretchr/testify/assert"
+)
+
+func TestStorageWarningTemplatesIncludeAccountEmail(t *testing.T) {
+ testutil.WithServerRoot(t)
+
+ templateData := map[string]interface{}{
+ "AccountEmail": "[email protected]",
+ "AutoDeleteDate": "April 1, 2026",
+ "ExpiryDate": "March 1, 2026",
+ }
+ templateNames := []string{
+ "storage-warning/storage_warning_active_overage.html",
+ "storage-warning/storage_warning_expired.html",
+ }
+
+ for _, templateName := range templateNames {
+ t.Run(templateName, func(t *testing.T) {
+ body, err := getMailBodyWithBase("base.html", templateName, templateData)
+ assert.NoError(t, err)
+ assert.Contains(t, body, "[email protected]")
+ })
+ }
+}
diff --git a/server/scripts/setup-test-db.sh b/server/scripts/setup-test-db.sh
new file mode 100755
index 0000000000..e9934b206a
--- /dev/null
+++ b/server/scripts/setup-test-db.sh
@@ -0,0 +1,36 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+server_dir="$(cd "${script_dir}/.." && pwd)"
+
+cd "${server_dir}"
+
+psql_base_args=(-v ON_ERROR_STOP=1)
+
+psql "${psql_base_args[@]}" -d postgres <<'SQL'
+DO $$
+BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'test_user') THEN
+ CREATE ROLE test_user LOGIN PASSWORD 'test_pass';
+ ELSE
+ ALTER ROLE test_user WITH LOGIN PASSWORD 'test_pass';
+ END IF;
+END
+$$;
+
+SELECT 'CREATE DATABASE ente_test_db OWNER test_user'
+WHERE NOT EXISTS (SELECT 1 FROM pg_database WHERE datname = 'ente_test_db')\gexec
+
+ALTER DATABASE ente_test_db OWNER TO test_user;
+GRANT ALL PRIVILEGES ON DATABASE ente_test_db TO test_user;
+SQL
+
+psql "${psql_base_args[@]}" -d ente_test_db <<'SQL'
+ALTER SCHEMA public OWNER TO test_user;
+GRANT ALL PRIVILEGES ON SCHEMA public TO test_user;
+GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO test_user;
+GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO test_user;
+ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO test_user;
+ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO test_user;
+SQL
diff --git a/server/scripts/test-email-notifications.sh b/server/scripts/test-email-notifications.sh
new file mode 100755
index 0000000000..2d2085f5f1
--- /dev/null
+++ b/server/scripts/test-email-notifications.sh
@@ -0,0 +1,82 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+server_dir="$(cd "${script_dir}/.." && pwd)"
+
+cd "${server_dir}"
+
+mode="${1:-all}"
+
+user_unit_pattern='TestNextInactivityEmailStage|TestHasAnyStageSuccess|TestBuildInactiveUserRunSummary|TestIsInInactiveUserRollout|TestProcessCandidateBatchRecoversPanics'
+user_full_pattern="${user_unit_pattern}|TestProcessInactiveUsersWarn2mIntegration"
+email_unit_pattern='TestBucketStorageWarning|TestComputeStorageWarningMetrics|TestResolveExpiredWarningStage|TestResolveActiveOverageWarningStage|TestStorageWarning|TestBuildStorageWarningRunSummary'
+email_full_pattern="${email_unit_pattern}|TestSendStorageWarningMailsActiveOverageIntegration|TestSendStorageWarningMailsExpiredIntegration"
+template_pattern='TestInactiveUserDeletionTemplatesIncludeAccountEmail|TestStorageWarningTemplatesIncludeAccountEmail'
+
+run_cmd() {
+ printf '\n==> %s\n' "$*"
+ "$@"
+}
+
+run_and_assert_no_skips() {
+ local skip_fragments=()
+ while [[ "$1" != "--" ]]; do
+ skip_fragments+=("$1")
+ shift
+ done
+ shift
+
+ local output
+ printf '\n==> %s\n' "$*"
+ if ! output="$("$@" 2>&1)"; then
+ printf '%s\n' "${output}"
+ return 1
+ fi
+ printf '%s\n' "${output}"
+ for skip_fragment in "${skip_fragments[@]}"; do
+ if grep -Fq -- "${skip_fragment}" <<<"${output}"; then
+ printf 'unexpected skipped test detected: %s\n' "${skip_fragment}" >&2
+ return 1
+ fi
+ done
+}
+
+run_unit_suites() {
+ run_cmd go test -count=1 -v ./pkg/controller/user -run "${user_unit_pattern}"
+ run_cmd go test -count=1 -v ./pkg/controller/email -run "${email_unit_pattern}"
+ run_cmd go test -count=1 -v ./pkg/utils/email -run "${template_pattern}"
+}
+
+run_integration_suites() {
+ export ENV=test
+ "${script_dir}/setup-test-db.sh"
+
+ run_and_assert_no_skips '--- SKIP: TestProcessInactiveUsersWarn2mIntegration' -- \
+ go test -count=1 -v ./pkg/controller/user -run "${user_full_pattern}"
+ run_and_assert_no_skips \
+ '--- SKIP: TestSendStorageWarningMailsActiveOverageIntegration' \
+ '--- SKIP: TestSendStorageWarningMailsExpiredIntegration' \
+ -- \
+ go test -count=1 -v ./pkg/controller/email -run "${email_full_pattern}"
+ run_and_assert_no_skips '--- SKIP: TestGetStorageWarningCandidates' -- \
+ go test -count=1 -v ./pkg/repo -run 'TestGetStorageWarningCandidates'
+ run_cmd go test -count=1 -v ./pkg/utils/email -run "${template_pattern}"
+}
+
+case "${mode}" in
+ unit)
+ run_unit_suites
+ ;;
+ integration)
+ run_integration_suites
+ ;;
+ all)
+ run_unit_suites
+ run_integration_suites
+ ;;
+ *)
+ printf 'usage: %s [unit|integration|all]\n' "$0" >&2
+ exit 1
+ ;;
+esac