Skip to content

armgit / ente

Public Imported from GitHub
0

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

Dockerize server tests and harden test DB setup

Neeraj Gupta460bdccbca0d
diff --git a/.github/workflows/server-test.yml b/.github/workflows/server-test.yml
new file mode 100644
index 0000000000..2680b9e661
--- /dev/null
+++ b/.github/workflows/server-test.yml
@@ -0,0 +1,29 @@
+name: "Test (server)"
+
+on:
+ pull_request:
+ paths:
+ - "server/**"
+ - ".github/workflows/server-test.yml"
+
+permissions:
+ contents: read
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ test:
+ runs-on: ubuntu-latest
+ defaults:
+ run:
+ working-directory: server
+
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v4
+
+ - name: Run server tests in Docker
+ run: ./scripts/test-in-docker.sh
+
diff --git a/server/Dockerfile.test b/server/Dockerfile.test
new file mode 100644
index 0000000000..bfe4797d69
--- /dev/null
+++ b/server/Dockerfile.test
@@ -0,0 +1,20 @@
+FROM golang:1.23.4-bookworm
+
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ build-essential \
+ ca-certificates \
+ git \
+ libsodium-dev \
+ pkg-config \
+ postgresql-client \
+ socat \
+ && rm -rf /var/lib/apt/lists/*
+
+WORKDIR /work/server
+
+COPY go.mod .
+COPY go.sum .
+RUN go mod download
+
+COPY . .
+
diff --git a/server/RUNNING.md b/server/RUNNING.md
index 226ae5c6ef..52d8458ba3 100644
--- a/server/RUNNING.md
+++ b/server/RUNNING.md
@@ -209,6 +209,14 @@ ENV="test" go test -v ./pkg/...
go clean -testcache && ENV="test" go test -v ./pkg/...
```
+To run the full `server/` Go test suite inside Docker instead of relying on a
+host Postgres setup, use:
+
+```sh
+./scripts/test-in-docker.sh
+./scripts/test-in-docker.sh -v
+```
+
## Configuration
Now that you have museum running (either inside Docker or standalone), we can
diff --git a/server/compose.test.yaml b/server/compose.test.yaml
new file mode 100644
index 0000000000..0582724f23
--- /dev/null
+++ b/server/compose.test.yaml
@@ -0,0 +1,40 @@
+services:
+ postgres-test:
+ image: postgres:15
+ environment:
+ POSTGRES_DB: ente_test_db
+ POSTGRES_USER: test_user
+ POSTGRES_PASSWORD: test_pass
+ healthcheck:
+ test: ["CMD-SHELL", "pg_isready -q -d ente_test_db -U test_user"]
+ interval: 2s
+ timeout: 5s
+ retries: 30
+ volumes:
+ - postgres-test-data:/var/lib/postgresql/data
+
+ server-test:
+ build:
+ context: .
+ dockerfile: Dockerfile.test
+ depends_on:
+ postgres-test:
+ condition: service_healthy
+ environment:
+ ENV: test
+ PGPASSWORD: test_pass
+ command:
+ - /bin/sh
+ - -lc
+ - |
+ export PATH="/usr/local/go/bin:/go/bin:$$PATH"
+ socat TCP-LISTEN:5432,fork,reuseaddr TCP:postgres-test:5432 &
+ socat_pid=$$!
+ trap 'kill "$$socat_pid"' EXIT
+ until pg_isready -h localhost -p 5432 -U test_user -d ente_test_db; do
+ sleep 1
+ done
+ go test -p 1 -count=1 ./...
+
+volumes:
+ postgres-test-data:
diff --git a/server/internal/testutil/testutil.go b/server/internal/testutil/testutil.go
index f74d27adaf..858cd1b859 100644
--- a/server/internal/testutil/testutil.go
+++ b/server/internal/testutil/testutil.go
@@ -19,6 +19,10 @@ import (
)
const testDBDSN = "user=test_user password=test_pass host=localhost dbname=ente_test_db sslmode=disable"
+const testDBName = "ente_test_db"
+const testDBUser = "test_user"
+const testDBSentinelTable = "ente_test_db_sentinel"
+const testDBSentinelMarker = "ente-server-test-db-v1"
var (
testDBInitOnce sync.Once
@@ -74,6 +78,10 @@ func RequireTestDB(t *testing.T) *sql.DB {
testDBErr = err
return
}
+ if err := verifySafeTestDB(testDB); err != nil {
+ testDBErr = err
+ return
+ }
driver, err := postgres.WithInstance(testDB, &postgres.Config{})
if err != nil {
@@ -102,11 +110,15 @@ func RequireTestDB(t *testing.T) *sql.DB {
func ResetTables(t *testing.T, db *sql.DB) {
t.Helper()
+ if err := verifySafeTestDB(db); err != nil {
+ t.Fatalf("refusing to reset tables on unsafe database connection: %v", err)
+ }
_, err := db.Exec(`
TRUNCATE TABLE
notification_history,
task_lock,
storage_bonus,
+ referral_codes,
subscriptions,
usage,
families,
@@ -120,6 +132,29 @@ func ResetTables(t *testing.T, db *sql.DB) {
}
}
+func verifySafeTestDB(db *sql.DB) error {
+ var currentDBName, currentDBUser string
+ err := db.QueryRow(`SELECT current_database(), current_user`).Scan(&currentDBName, &currentDBUser)
+ if err != nil {
+ return fmt.Errorf("failed to verify test database identity: %w", err)
+ }
+ if currentDBName != testDBName {
+ return fmt.Errorf("expected test database %q, connected to %q", testDBName, currentDBName)
+ }
+ if currentDBUser != testDBUser {
+ return fmt.Errorf("expected test database user %q, connected as %q", testDBUser, currentDBUser)
+ }
+ var marker string
+ err = db.QueryRow(fmt.Sprintf(`SELECT marker FROM public.%s WHERE id = 1`, testDBSentinelTable)).Scan(&marker)
+ if err != nil {
+ return fmt.Errorf("missing test database sentinel in %q: run ./scripts/setup-test-db.sh or use the docker test runner: %w", testDBName, err)
+ }
+ if marker != testDBSentinelMarker {
+ return fmt.Errorf("unexpected test database sentinel marker %q", marker)
+ }
+ return nil
+}
+
func WithServerRoot(t *testing.T) {
t.Helper()
serverRootMu.Lock()
diff --git a/server/pkg/controller/access/access_test.go b/server/pkg/controller/access/access_test.go
new file mode 100644
index 0000000000..0d0ca0bbc9
--- /dev/null
+++ b/server/pkg/controller/access/access_test.go
@@ -0,0 +1,453 @@
+package access
+
+import (
+ "database/sql"
+ "errors"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/ente-io/museum/ente"
+ "github.com/ente-io/museum/internal/testutil"
+ "github.com/ente-io/museum/pkg/repo"
+ publicRepo "github.com/ente-io/museum/pkg/repo/public"
+ "github.com/gin-gonic/gin"
+)
+
+func setupAccessControllerTest(t *testing.T) (Controller, *sql.DB, *gin.Context) {
+ t.Helper()
+
+ testutil.WithServerRoot(t)
+ db := testutil.RequireTestDB(t)
+ testutil.ResetTables(t, db)
+ t.Cleanup(func() {
+ testutil.ResetTables(t, db)
+ })
+
+ gin.SetMode(gin.TestMode)
+ recorder := httptest.NewRecorder()
+ ctx, _ := gin.CreateTestContext(recorder)
+
+ return NewAccessController(
+ &repo.CollectionRepository{
+ DB: db,
+ CollectionLinkRepo: publicRepo.NewCollectionLinkRepository(db, ""),
+ },
+ &repo.FileRepository{DB: db},
+ ), db, ctx
+}
+
+func insertAccessTestCollection(t *testing.T, db *sql.DB, ownerID int64, isDeleted bool) int64 {
+ t.Helper()
+
+ var collectionID int64
+ err := db.QueryRow(
+ `INSERT INTO collections(owner_id, encrypted_key, key_decryption_nonce, name, type, attributes, updation_time, is_deleted, app)
+ VALUES($1, $2, $3, $4, $5, $6::jsonb, $7, $8, $9)
+ RETURNING collection_id`,
+ ownerID,
+ "encrypted-key",
+ "key-nonce",
+ "Test collection",
+ "album",
+ "{}",
+ int64(1),
+ isDeleted,
+ string(ente.Photos),
+ ).Scan(&collectionID)
+ if err != nil {
+ t.Fatalf("failed to insert collection for owner %d: %v", ownerID, err)
+ }
+ return collectionID
+}
+
+func insertAccessTestCollectionShare(t *testing.T, db *sql.DB, collectionID, fromUserID, toUserID int64, role ente.CollectionParticipantRole) {
+ t.Helper()
+
+ _, err := db.Exec(
+ `INSERT INTO collection_shares(collection_id, from_user_id, to_user_id, encrypted_key, updation_time, role_type, shared_at)
+ VALUES($1, $2, $3, $4, $5, $6, $7)`,
+ collectionID,
+ fromUserID,
+ toUserID,
+ "share-key",
+ int64(1),
+ string(role),
+ int64(1),
+ )
+ if err != nil {
+ t.Fatalf("failed to insert collection share for collection %d: %v", collectionID, err)
+ }
+}
+
+func insertAccessTestFile(t *testing.T, db *sql.DB, ownerID int64) int64 {
+ t.Helper()
+
+ var fileID int64
+ err := db.QueryRow(
+ `INSERT INTO files(owner_id, file_decryption_header, thumbnail_decryption_header, metadata_decryption_header, encrypted_metadata, updation_time, info)
+ VALUES($1, $2, $3, $4, $5, $6, $7::jsonb)
+ RETURNING file_id`,
+ ownerID,
+ "file-header",
+ "thumbnail-header",
+ "metadata-header",
+ "encrypted-metadata",
+ int64(1),
+ "{}",
+ ).Scan(&fileID)
+ if err != nil {
+ t.Fatalf("failed to insert file for owner %d: %v", ownerID, err)
+ }
+ return fileID
+}
+
+func linkAccessTestFileToCollection(t *testing.T, db *sql.DB, collectionID, fileID, ownerID int64) {
+ t.Helper()
+
+ _, err := db.Exec(
+ `INSERT INTO collection_files(collection_id, file_id, encrypted_key, key_decryption_nonce, updation_time, c_owner_id, f_owner_id)
+ VALUES($1, $2, $3, $4, $5, $6, $7)`,
+ collectionID,
+ fileID,
+ "collection-file-key",
+ "collection-file-nonce",
+ int64(1),
+ ownerID,
+ ownerID,
+ )
+ if err != nil {
+ t.Fatalf("failed to link file %d to collection %d: %v", fileID, collectionID, err)
+ }
+}
+
+func TestGetCollectionReturnsOwnerRole(t *testing.T) {
+ controller, db, ctx := setupAccessControllerTest(t)
+
+ ownerID := testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: 1,
+ Email: "[email protected]",
+ CreationTime: 1,
+ })
+ collectionID := insertAccessTestCollection(t, db, ownerID, false)
+
+ resp, err := controller.GetCollection(ctx, &GetCollectionParams{
+ CollectionID: collectionID,
+ ActorUserID: ownerID,
+ })
+ if err != nil {
+ t.Fatalf("GetCollection() error = %v", err)
+ }
+ if resp.Collection.ID != collectionID {
+ t.Fatalf("unexpected collection id: got %d want %d", resp.Collection.ID, collectionID)
+ }
+ if resp.Role == nil || *resp.Role != ente.OWNER {
+ t.Fatalf("unexpected role: got %v want %v", resp.Role, ente.OWNER)
+ }
+}
+
+func TestGetCollectionReturnsShareeRole(t *testing.T) {
+ controller, db, ctx := setupAccessControllerTest(t)
+
+ ownerID := testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: 1,
+ Email: "[email protected]",
+ CreationTime: 1,
+ })
+ shareeID := testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: 2,
+ Email: "[email protected]",
+ CreationTime: 1,
+ })
+ collectionID := insertAccessTestCollection(t, db, ownerID, false)
+ insertAccessTestCollectionShare(t, db, collectionID, ownerID, shareeID, ente.COLLABORATOR)
+
+ resp, err := controller.GetCollection(ctx, &GetCollectionParams{
+ CollectionID: collectionID,
+ ActorUserID: shareeID,
+ })
+ if err != nil {
+ t.Fatalf("GetCollection() error = %v", err)
+ }
+ if resp.Role == nil || *resp.Role != ente.COLLABORATOR {
+ t.Fatalf("unexpected role: got %v want %v", resp.Role, ente.COLLABORATOR)
+ }
+}
+
+func TestGetCollectionVerifyOwnerRejectsSharee(t *testing.T) {
+ controller, db, ctx := setupAccessControllerTest(t)
+
+ ownerID := testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: 1,
+ Email: "[email protected]",
+ CreationTime: 1,
+ })
+ shareeID := testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: 2,
+ Email: "[email protected]",
+ CreationTime: 1,
+ })
+ collectionID := insertAccessTestCollection(t, db, ownerID, false)
+ insertAccessTestCollectionShare(t, db, collectionID, ownerID, shareeID, ente.VIEWER)
+
+ _, err := controller.GetCollection(ctx, &GetCollectionParams{
+ CollectionID: collectionID,
+ ActorUserID: shareeID,
+ VerifyOwner: true,
+ })
+ if !errors.Is(err, ente.ErrPermissionDenied) {
+ t.Fatalf("expected permission denied, got %v", err)
+ }
+}
+
+func TestGetCollectionRejectsDeletedCollectionByDefault(t *testing.T) {
+ controller, db, ctx := setupAccessControllerTest(t)
+
+ ownerID := testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: 1,
+ Email: "[email protected]",
+ CreationTime: 1,
+ })
+ collectionID := insertAccessTestCollection(t, db, ownerID, true)
+
+ _, err := controller.GetCollection(ctx, &GetCollectionParams{
+ CollectionID: collectionID,
+ ActorUserID: ownerID,
+ })
+ if !errors.Is(err, ente.ErrNotFound) {
+ t.Fatalf("expected not found, got %v", err)
+ }
+}
+
+func TestGetCollectionIncludesDeletedWhenRequested(t *testing.T) {
+ controller, db, ctx := setupAccessControllerTest(t)
+
+ ownerID := testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: 1,
+ Email: "[email protected]",
+ CreationTime: 1,
+ })
+ collectionID := insertAccessTestCollection(t, db, ownerID, true)
+
+ resp, err := controller.GetCollection(ctx, &GetCollectionParams{
+ CollectionID: collectionID,
+ ActorUserID: ownerID,
+ IncludeDeleted: true,
+ })
+ if err != nil {
+ t.Fatalf("GetCollection() error = %v", err)
+ }
+ if !resp.Collection.IsDeleted {
+ t.Fatal("expected deleted collection to be returned")
+ }
+}
+
+func TestVerifyFileOwnershipRejectsDuplicateFileIDs(t *testing.T) {
+ controller, _, ctx := setupAccessControllerTest(t)
+
+ err := controller.VerifyFileOwnership(ctx, &VerifyFileOwnershipParams{
+ ActorUserId: 1,
+ FileIDs: []int64{10, 10},
+ })
+ if !errors.Is(err, ente.ErrBadRequest) {
+ t.Fatalf("expected bad request, got %v", err)
+ }
+}
+
+func TestVerifyFileOwnershipSucceedsForOwner(t *testing.T) {
+ controller, db, ctx := setupAccessControllerTest(t)
+
+ ownerID := testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: 1,
+ Email: "[email protected]",
+ CreationTime: 1,
+ })
+ fileIDOne := insertAccessTestFile(t, db, ownerID)
+ fileIDTwo := insertAccessTestFile(t, db, ownerID)
+
+ err := controller.VerifyFileOwnership(ctx, &VerifyFileOwnershipParams{
+ ActorUserId: ownerID,
+ FileIDs: []int64{fileIDOne, fileIDTwo},
+ })
+ if err != nil {
+ t.Fatalf("VerifyFileOwnership() error = %v", err)
+ }
+}
+
+func TestVerifyFileOwnershipRejectsNonOwner(t *testing.T) {
+ controller, db, ctx := setupAccessControllerTest(t)
+
+ ownerID := testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: 1,
+ Email: "[email protected]",
+ CreationTime: 1,
+ })
+ otherUserID := testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: 2,
+ Email: "[email protected]",
+ CreationTime: 1,
+ })
+ fileID := insertAccessTestFile(t, db, ownerID)
+
+ err := controller.VerifyFileOwnership(ctx, &VerifyFileOwnershipParams{
+ ActorUserId: otherUserID,
+ FileIDs: []int64{fileID},
+ })
+ if !errors.Is(err, ente.ErrPermissionDenied) {
+ t.Fatalf("expected permission denied, got %v", err)
+ }
+}
+
+func TestVerifyFileOwnershipRejectsInvalidFileIDs(t *testing.T) {
+ controller, db, ctx := setupAccessControllerTest(t)
+
+ ownerID := testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: 1,
+ Email: "[email protected]",
+ CreationTime: 1,
+ })
+ fileID := insertAccessTestFile(t, db, ownerID)
+
+ err := controller.VerifyFileOwnership(ctx, &VerifyFileOwnershipParams{
+ ActorUserId: ownerID,
+ FileIDs: []int64{fileID, 9999},
+ })
+ if !errors.Is(err, ente.ErrBadRequest) {
+ t.Fatalf("expected bad request, got %v", err)
+ }
+}
+
+func TestVerifyFileOwnershipRejectsMixedOwners(t *testing.T) {
+ controller, db, ctx := setupAccessControllerTest(t)
+
+ ownerOneID := testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: 1,
+ Email: "[email protected]",
+ CreationTime: 1,
+ })
+ ownerTwoID := testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: 2,
+ Email: "[email protected]",
+ CreationTime: 1,
+ })
+ fileIDOne := insertAccessTestFile(t, db, ownerOneID)
+ fileIDTwo := insertAccessTestFile(t, db, ownerTwoID)
+
+ err := controller.VerifyFileOwnership(ctx, &VerifyFileOwnershipParams{
+ ActorUserId: ownerOneID,
+ FileIDs: []int64{fileIDOne, fileIDTwo},
+ })
+ if !errors.Is(err, ente.ErrPermissionDenied) {
+ t.Fatalf("expected permission denied, got %v", err)
+ }
+}
+
+func TestCanAccessFileRejectsDuplicateFileIDs(t *testing.T) {
+ controller, _, ctx := setupAccessControllerTest(t)
+
+ err := controller.CanAccessFile(ctx, &CanAccessFileParams{
+ ActorUserID: 1,
+ FileIDs: []int64{10, 10},
+ })
+ if !errors.Is(err, ente.ErrBadRequest) {
+ t.Fatalf("expected bad request, got %v", err)
+ }
+}
+
+func TestCanAccessFileAllowsOwnerFiles(t *testing.T) {
+ controller, db, ctx := setupAccessControllerTest(t)
+
+ ownerID := testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: 1,
+ Email: "[email protected]",
+ CreationTime: 1,
+ })
+ fileIDOne := insertAccessTestFile(t, db, ownerID)
+ fileIDTwo := insertAccessTestFile(t, db, ownerID)
+
+ err := controller.CanAccessFile(ctx, &CanAccessFileParams{
+ ActorUserID: ownerID,
+ FileIDs: []int64{fileIDOne, fileIDTwo},
+ })
+ if err != nil {
+ t.Fatalf("CanAccessFile() error = %v", err)
+ }
+}
+
+func TestCanAccessFileAllowsSharedFiles(t *testing.T) {
+ controller, db, ctx := setupAccessControllerTest(t)
+
+ ownerID := testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: 1,
+ Email: "[email protected]",
+ CreationTime: 1,
+ })
+ actorID := testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: 2,
+ Email: "[email protected]",
+ CreationTime: 1,
+ })
+ collectionID := insertAccessTestCollection(t, db, ownerID, false)
+ insertAccessTestCollectionShare(t, db, collectionID, ownerID, actorID, ente.VIEWER)
+ fileID := insertAccessTestFile(t, db, ownerID)
+ linkAccessTestFileToCollection(t, db, collectionID, fileID, ownerID)
+
+ err := controller.CanAccessFile(ctx, &CanAccessFileParams{
+ ActorUserID: actorID,
+ FileIDs: []int64{fileID},
+ })
+ if err != nil {
+ t.Fatalf("CanAccessFile() error = %v", err)
+ }
+}
+
+func TestCanAccessFileAllowsOwnedAndSharedFilesTogether(t *testing.T) {
+ controller, db, ctx := setupAccessControllerTest(t)
+
+ ownerID := testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: 1,
+ Email: "[email protected]",
+ CreationTime: 1,
+ })
+ actorID := testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: 2,
+ Email: "[email protected]",
+ CreationTime: 1,
+ })
+ ownedFileID := insertAccessTestFile(t, db, actorID)
+ sharedCollectionID := insertAccessTestCollection(t, db, ownerID, false)
+ insertAccessTestCollectionShare(t, db, sharedCollectionID, ownerID, actorID, ente.VIEWER)
+ sharedFileID := insertAccessTestFile(t, db, ownerID)
+ linkAccessTestFileToCollection(t, db, sharedCollectionID, sharedFileID, ownerID)
+
+ err := controller.CanAccessFile(ctx, &CanAccessFileParams{
+ ActorUserID: actorID,
+ FileIDs: []int64{ownedFileID, sharedFileID},
+ })
+ if err != nil {
+ t.Fatalf("CanAccessFile() error = %v", err)
+ }
+}
+
+func TestCanAccessFileRejectsUnsharedForeignFiles(t *testing.T) {
+ controller, db, ctx := setupAccessControllerTest(t)
+
+ ownerID := testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: 1,
+ Email: "[email protected]",
+ CreationTime: 1,
+ })
+ actorID := testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: 2,
+ Email: "[email protected]",
+ CreationTime: 1,
+ })
+ fileID := insertAccessTestFile(t, db, ownerID)
+
+ err := controller.CanAccessFile(ctx, &CanAccessFileParams{
+ ActorUserID: actorID,
+ FileIDs: []int64{fileID},
+ })
+ if !errors.Is(err, ente.ErrPermissionDenied) {
+ t.Fatalf("expected permission denied, got %v", err)
+ }
+}
diff --git a/server/pkg/controller/email/storage_warning_integration_test.go b/server/pkg/controller/email/storage_warning_integration_test.go
index f2d5d24ce7..f9f7bc669f 100644
--- a/server/pkg/controller/email/storage_warning_integration_test.go
+++ b/server/pkg/controller/email/storage_warning_integration_test.go
@@ -13,6 +13,7 @@ import (
)
const storageWarningIntegrationTestGiB = int64(1 << 30)
+const storageWarningIntegrationTestUserID int64 = 1
func TestSendStorageWarningMailsActiveOverageIntegration(t *testing.T) {
testutil.WithServerRoot(t)
@@ -25,6 +26,7 @@ func TestSendStorageWarningMailsActiveOverageIntegration(t *testing.T) {
now := timeutil.Microseconds()
userID := testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: storageWarningIntegrationTestUserID,
CreationTime: now - timeutil.MicroSecondsInOneHour,
})
@@ -54,6 +56,7 @@ func TestSendStorageWarningMailsExpiredIntegration(t *testing.T) {
now := timeutil.Microseconds()
userID := testutil.InsertUser(t, db, testutil.UserFixture{
+ UserID: storageWarningIntegrationTestUserID,
CreationTime: now - timeutil.MicroSecondsInOneHour,
})
diff --git a/server/pkg/repo/storagebonus/referral_codes_test.go b/server/pkg/repo/storagebonus/referral_codes_test.go
index 117dfb1352..d93f179415 100644
--- a/server/pkg/repo/storagebonus/referral_codes_test.go
+++ b/server/pkg/repo/storagebonus/referral_codes_test.go
@@ -9,20 +9,34 @@ import (
"testing"
entity "github.com/ente-io/museum/ente/storagebonus"
+ "github.com/ente-io/museum/internal/testutil"
_ "github.com/golang-migrate/migrate/v4/source/file"
"github.com/stretchr/testify/assert"
)
+func newStorageBonusTestRepository(t *testing.T) *Repository {
+ t.Helper()
+
+ testutil.WithServerRoot(t)
+ db := testutil.RequireTestDB(t)
+ testutil.ResetTables(t, db)
+ t.Cleanup(func() {
+ testutil.ResetTables(t, db)
+ })
+
+ return NewRepository(db)
+}
+
// TestGetReferralCode tests the GetCode method
func TestGetReferralCode(t *testing.T) {
ctx := context.Background()
- repo := NewRepository(db)
+ repo := newStorageBonusTestRepository(t)
// Test for a user that doesn't have a storagebonus code
userID := int64(1)
code, err := repo.GetCode(ctx, userID)
assert.Nil(t, code)
- assert.Equal(t, sql.ErrNoRows, errors.Unwrap(err))
+ assert.ErrorIs(t, err, sql.ErrNoRows)
// Insert a storagebonus code
newCode := "AABBCC"
@@ -39,12 +53,13 @@ func TestGetReferralCode(t *testing.T) {
// Test for a user that has a storagebonus code
code, err = repo.GetCode(ctx, userID)
assert.Nil(t, err)
- assert.Equal(t, code, code)
+ assert.NotNil(t, code)
+ assert.Equal(t, newCode, *code)
}
// TestInsertReferralCode tests the InsertCode method
func TestInsertReferralCode(t *testing.T) {
- repo := NewRepository(db)
+ repo := newStorageBonusTestRepository(t)
// Insert a referral code
userID := int64(2)
code := "AAEEDD"
@@ -58,7 +73,7 @@ func TestInsertReferralCode(t *testing.T) {
// TestAddNewReferralCode tests the AddNewCode method
func TestAddNewReferralCode(t *testing.T) {
- repo := NewRepository(db)
+ repo := newStorageBonusTestRepository(t)
userID := int64(3)
code := "B22222"
err := repo.InsertCode(context.Background(), userID, code)
diff --git a/server/pkg/repo/storagebonus/repo_test.go b/server/pkg/repo/storagebonus/repo_test.go
deleted file mode 100644
index 2316bef1a4..0000000000
--- a/server/pkg/repo/storagebonus/repo_test.go
+++ /dev/null
@@ -1,67 +0,0 @@
-package storagebonus
-
-import (
- "database/sql"
- "os"
- "path/filepath"
- "strings"
- "testing"
-
- "github.com/golang-migrate/migrate/v4"
- "github.com/golang-migrate/migrate/v4/database/postgres"
- log "github.com/sirupsen/logrus"
-)
-
-var db *sql.DB
-
-func TestMain(m *testing.M) {
- if os.Getenv("ENV") != "test" {
- log.Fatalf("Not running tests in non-test environment")
- os.Exit(0)
- }
- err := setupDatabase()
- if err != nil {
- log.Fatalf("error setting up test database: %v", err)
- }
- db.QueryRow("DELETE FROM referral_codes")
- db.QueryRow("DELETE FROM storage_bonus")
- // Run the tests
- exitCode := m.Run()
- db.QueryRow("DELETE FROM referral_codes")
- db.QueryRow("DELETE FROM storage_bonus")
- // Close the test database connection
- err = db.Close()
- if err != nil {
- log.Fatalf("error closing test database connection: %v", err)
- }
- // Exit with the result of the tests
- os.Exit(exitCode)
-}
-
-func setupDatabase() error {
- var err error
- // Connect to the test database
- db, err = sql.Open("postgres", "user=test_user password=test_pass host=localhost dbname=ente_test_db sslmode=disable")
- if err != nil {
- log.Fatalf("error connecting to test database: %v", err)
- }
- driver, err := postgres.WithInstance(db, &postgres.Config{})
- if err != nil {
- log.Fatalf("error creating postgres driver: %v", err)
- }
- // Get the current working directory, find the path before "/pkg", and append "/migrations"
- cwd, _ := os.Getwd()
- cwd = strings.Split(cwd, "/pkg/")[0]
- configFilePath := "file://" + filepath.Join(cwd, "migrations")
- mig, err := migrate.NewWithDatabaseInstance(
- configFilePath, "ente_test_db", driver)
- if err != nil {
- log.Fatalf("error creating migrations: %v", err)
- } else {
- //log.Println("Loaded migration scripts")
- if err := mig.Up(); err != nil && err != migrate.ErrNoChange {
- log.Fatalf("error running migrations: %v", err)
- }
- }
- return err
-}
diff --git a/server/scripts/run-go-tests-in-container.sh b/server/scripts/run-go-tests-in-container.sh
new file mode 100755
index 0000000000..a9fca51fd2
--- /dev/null
+++ b/server/scripts/run-go-tests-in-container.sh
@@ -0,0 +1,31 @@
+#!/bin/sh
+
+set -eu
+
+export PATH="/usr/local/go/bin:/go/bin:$PATH"
+
+socat TCP-LISTEN:5432,fork,reuseaddr TCP:postgres-test:5432 &
+socat_pid=$!
+
+cleanup() {
+ kill "$socat_pid" >/dev/null 2>&1 || true
+}
+
+trap cleanup EXIT INT TERM
+
+until pg_isready -h localhost -p 5432 -U test_user -d ente_test_db >/dev/null 2>&1; do
+ sleep 1
+done
+
+psql -h localhost -U test_user -d ente_test_db <<'SQL'
+CREATE TABLE IF NOT EXISTS public.ente_test_db_sentinel (
+ id integer PRIMARY KEY,
+ marker text NOT NULL
+);
+
+INSERT INTO public.ente_test_db_sentinel (id, marker)
+VALUES (1, 'ente-server-test-db-v1')
+ON CONFLICT (id) DO UPDATE SET marker = EXCLUDED.marker;
+SQL
+
+exec go test -p 1 -count=1 "$@" ./...
diff --git a/server/scripts/setup-test-db.sh b/server/scripts/setup-test-db.sh
index e9934b206a..0122ee8c94 100755
--- a/server/scripts/setup-test-db.sh
+++ b/server/scripts/setup-test-db.sh
@@ -6,7 +6,53 @@ server_dir="$(cd "${script_dir}/.." && pwd)"
cd "${server_dir}"
+if [[ -n "${DATABASE_URL:-}" || -n "${PGSERVICE:-}" || -n "${PGSERVICEFILE:-}" ]]; then
+ echo "Refusing to run setup-test-db.sh with DATABASE_URL/PGSERVICE/PGSERVICEFILE set." >&2
+ echo "These can redirect psql to a non-local database cluster." >&2
+ exit 1
+fi
+
+is_local_target() {
+ case "${1:-}" in
+ ""|localhost|127.0.0.1|::1|/var/run/postgresql|/tmp)
+ return 0
+ ;;
+ *)
+ return 1
+ ;;
+ esac
+}
+
+if [[ "${ALLOW_NONLOCAL_TEST_DB_SETUP:-0}" != "1" ]]; then
+ if ! is_local_target "${PGHOST:-}"; then
+ echo "Refusing to run setup-test-db.sh against non-local PGHOST=${PGHOST}." >&2
+ echo "Set ALLOW_NONLOCAL_TEST_DB_SETUP=1 only if you are intentionally targeting a safe non-production cluster." >&2
+ exit 1
+ fi
+ if ! is_local_target "${PGHOSTADDR:-}"; then
+ echo "Refusing to run setup-test-db.sh against non-local PGHOSTADDR=${PGHOSTADDR}." >&2
+ echo "Set ALLOW_NONLOCAL_TEST_DB_SETUP=1 only if you are intentionally targeting a safe non-production cluster." >&2
+ exit 1
+ fi
+fi
+
psql_base_args=(-v ON_ERROR_STOP=1)
+sentinel_table="ente_test_db_sentinel"
+sentinel_marker="ente-server-test-db-v1"
+
+db_exists="$(psql "${psql_base_args[@]}" -d postgres -Atqc "SELECT 1 FROM pg_database WHERE datname = 'ente_test_db'")"
+if [[ "${db_exists}" == "1" ]]; then
+ existing_marker="$(psql "${psql_base_args[@]}" -d ente_test_db -Atqc "SELECT marker FROM public.${sentinel_table} WHERE id = 1" 2>/dev/null || true)"
+ if [[ -z "${existing_marker}" && "${ALLOW_UNMARKED_EXISTING_TEST_DB:-0}" != "1" ]]; then
+ echo "Refusing to operate on existing ente_test_db without the expected test sentinel." >&2
+ echo "If this is your known local test DB and you want to bootstrap the sentinel once, rerun with ALLOW_UNMARKED_EXISTING_TEST_DB=1." >&2
+ exit 1
+ fi
+ if [[ -n "${existing_marker}" && "${existing_marker}" != "${sentinel_marker}" ]]; then
+ echo "Refusing to operate on ente_test_db with unexpected sentinel marker: ${existing_marker}" >&2
+ exit 1
+ fi
+fi
psql "${psql_base_args[@]}" -d postgres <<'SQL'
DO $$
@@ -33,4 +79,13 @@ 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;
+
+CREATE TABLE IF NOT EXISTS public.ente_test_db_sentinel (
+ id integer PRIMARY KEY,
+ marker text NOT NULL
+);
+
+INSERT INTO public.ente_test_db_sentinel (id, marker)
+VALUES (1, 'ente-server-test-db-v1')
+ON CONFLICT (id) DO UPDATE SET marker = EXCLUDED.marker;
SQL
diff --git a/server/scripts/test-in-docker.sh b/server/scripts/test-in-docker.sh
new file mode 100755
index 0000000000..abab8f86d9
--- /dev/null
+++ b/server/scripts/test-in-docker.sh
@@ -0,0 +1,18 @@
+#!/bin/sh
+
+set -eu
+
+script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
+server_dir=$(CDPATH= cd -- "$script_dir/.." && pwd)
+compose_file="$server_dir/compose.test.yaml"
+
+cleanup() {
+ docker compose -f "$compose_file" down -v --remove-orphans >/dev/null 2>&1 || true
+}
+
+trap cleanup EXIT INT TERM
+
+cd "$server_dir"
+docker compose -f "$compose_file" build server-test
+docker compose -f "$compose_file" up -d postgres-test
+docker compose -f "$compose_file" run --rm server-test ./scripts/run-go-tests-in-container.sh "$@"