Skip to content

armgit / ente

Public Imported from GitHub
0

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

[server] Simplify Postgres-backed test runner

Manav Rathi435ff8df9557
diff --git a/.github/workflows/server-test.yml b/.github/workflows/server-test.yml
index bef7a20118..330d69edc9 100644
--- a/.github/workflows/server-test.yml
+++ b/.github/workflows/server-test.yml
@@ -24,5 +24,12 @@ jobs:
- name: Checkout
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
- - name: Run server tests in Docker
- run: ./scripts/test-in-docker.sh
+ - name: Setup go
+ uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0
+ with:
+ go-version-file: server/go.mod
+ cache-dependency-path: server/go.sum
+ cache: true
+
+ - name: Run server tests
+ run: ./scripts/test-with-postgres.sh
diff --git a/server/Dockerfile.test b/server/Dockerfile.test
deleted file mode 100644
index 97e713f70e..0000000000
--- a/server/Dockerfile.test
+++ /dev/null
@@ -1,19 +0,0 @@
-FROM golang:1.26.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 356f40db74..c81e5bf59d 100644
--- a/server/RUNNING.md
+++ b/server/RUNNING.md
@@ -227,28 +227,16 @@ air
### Testing
-Set up a local database for testing. This is not required for running the server. Create a test database with the following name and credentials:
+For quick local iteration without Postgres-backed tests, run `go test ./...` or a narrower package like `go test ./pkg/controller/email`. Tests that require Postgres skip unless the test environment is explicitly enabled.
-```sql
-$ psql -U postgres
-CREATE DATABASE ente_test_db;
-CREATE USER test_user WITH PASSWORD 'test_pass';
-GRANT ALL PRIVILEGES ON DATABASE ente_test_db TO test_user;
-```
-
-For running the tests, you can use the following command:
+To run the full `server/` Go test suite, including Postgres-backed tests, use:
```sh
-ENV="test" go test -v ./pkg/...
-go clean -testcache && ENV="test" go test -v ./pkg/...
+./scripts/test-with-postgres.sh
+./scripts/test-with-postgres.sh -v
```
-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
-```
+The script creates a temporary `ente_test_*` database, runs the tests, and drops the database when it exits. By default it starts a disposable Docker Postgres if Docker is available. To use an existing local Postgres instead, set `ENTE_TEST_POSTGRES=local`.
## Configuration
diff --git a/server/compose.test.yaml b/server/compose.test.yaml
deleted file mode 100644
index 0582724f23..0000000000
--- a/server/compose.test.yaml
+++ /dev/null
@@ -1,40 +0,0 @@
-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 06cd6392b7..74455290c2 100644
--- a/server/internal/testutil/testutil.go
+++ b/server/internal/testutil/testutil.go
@@ -18,11 +18,8 @@ import (
_ "github.com/lib/pq"
)
-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"
+const testDBDSN = "sslmode=disable"
+const testDBNamePrefix = "ente_test_"
var (
testDBInitOnce sync.Once
@@ -70,6 +67,11 @@ func RequireTestDB(t *testing.T) *sql.DB {
}
testDBInitOnce.Do(func() {
+ testDBName, err := expectedTestDBName()
+ if err != nil {
+ testDBErr = err
+ return
+ }
testDB, testDBErr = sql.Open("postgres", testDBDSN)
if testDBErr != nil {
return
@@ -91,7 +93,7 @@ func RequireTestDB(t *testing.T) *sql.DB {
migrationPath := "file://" + filepath.Join(serverRootPath())
migrationPath = migrationPath + "/migrations"
- mig, err := migrate.NewWithDatabaseInstance(migrationPath, "ente_test_db", driver)
+ mig, err := migrate.NewWithDatabaseInstance(migrationPath, testDBName, driver)
if err != nil {
testDBErr = err
return
@@ -138,26 +140,44 @@ 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)
+ expectedDBName, err := expectedTestDBName()
+ if err != nil {
+ return err
+ }
+
+ var currentDBName string
+ err = db.QueryRow(`SELECT current_database()`).Scan(&currentDBName)
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 currentDBName != expectedDBName {
+ return fmt.Errorf("expected test database %q, connected to %q", expectedDBName, currentDBName)
+ }
+ return nil
+}
+
+func expectedTestDBName() (string, error) {
+ dbName := os.Getenv("PGDATABASE")
+ if dbName == "" {
+ return "", fmt.Errorf("PGDATABASE must be set when ENV=test")
}
- if currentDBUser != testDBUser {
- return fmt.Errorf("expected test database user %q, connected as %q", testDBUser, currentDBUser)
+ if !isTemporaryTestDBName(dbName) {
+ return "", fmt.Errorf("refusing to use non-temporary test database %q", dbName)
}
- 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)
+ return dbName, nil
+}
+
+func isTemporaryTestDBName(dbName string) bool {
+ if dbName == "ente_test_db" || !strings.HasPrefix(dbName, testDBNamePrefix) || len(dbName) == len(testDBNamePrefix) {
+ return false
}
- if marker != testDBSentinelMarker {
- return fmt.Errorf("unexpected test database sentinel marker %q", marker)
+ for _, r := range dbName {
+ if r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '_' {
+ continue
+ }
+ return false
}
- return nil
+ return true
}
func WithServerRoot(t *testing.T) {
diff --git a/server/scripts/run-go-tests-in-container.sh b/server/scripts/run-go-tests-in-container.sh
deleted file mode 100755
index a9fca51fd2..0000000000
--- a/server/scripts/run-go-tests-in-container.sh
+++ /dev/null
@@ -1,31 +0,0 @@
-#!/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
deleted file mode 100755
index 0122ee8c94..0000000000
--- a/server/scripts/setup-test-db.sh
+++ /dev/null
@@ -1,91 +0,0 @@
-#!/usr/bin/env bash
-set -euo pipefail
-
-script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-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 $$
-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;
-
-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
deleted file mode 100755
index abab8f86d9..0000000000
--- a/server/scripts/test-in-docker.sh
+++ /dev/null
@@ -1,18 +0,0 @@
-#!/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 "$@"
diff --git a/server/scripts/test-with-postgres.sh b/server/scripts/test-with-postgres.sh
new file mode 100755
index 0000000000..322736ea84
--- /dev/null
+++ b/server/scripts/test-with-postgres.sh
@@ -0,0 +1,112 @@
+#!/bin/sh
+
+set -eu
+
+script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
+server_dir=$(CDPATH= cd -- "$script_dir/.." && pwd)
+test_db="ente_test_$(date +%Y%m%d%H%M%S)_$$"
+pg_port="${ENTE_TEST_PGPORT:-45432}"
+postgres_mode="${ENTE_TEST_POSTGRES:-auto}"
+container_name="ente-server-test-postgres-$$"
+
+is_local_target() {
+ case "${1:-}" in
+ ""|localhost|127.0.0.1|::1|/var/run/postgresql|/tmp)
+ return 0
+ ;;
+ *)
+ return 1
+ ;;
+ esac
+}
+
+cleanup() {
+ if [ "$postgres_mode" = "docker" ]; then
+ docker rm -f "$container_name" >/dev/null 2>&1 || true
+ return
+ fi
+
+ psql -v ON_ERROR_STOP=1 -d postgres >/dev/null 2>&1 <<SQL || true
+SELECT pg_terminate_backend(pid)
+FROM pg_stat_activity
+WHERE datname = '$test_db';
+
+DROP DATABASE IF EXISTS "$test_db";
+SQL
+}
+
+start_docker_postgres() {
+ docker run --detach --rm \
+ --name "$container_name" \
+ --env POSTGRES_DB="$test_db" \
+ --env POSTGRES_PASSWORD=test_pass \
+ --publish "127.0.0.1:$pg_port:5432" \
+ postgres:15 >/dev/null
+
+ attempts=30
+ while [ "$attempts" -gt 0 ]; do
+ if docker exec "$container_name" pg_isready -q -h localhost -p 5432 -d "$test_db" -U postgres; then
+ return
+ fi
+ attempts=$((attempts - 1))
+ sleep 1
+ done
+ echo "Postgres did not become ready after 30 seconds." >&2
+ exit 1
+}
+
+create_local_db() {
+ if ! command -v psql >/dev/null 2>&1; then
+ echo "psql is required when using local Postgres." >&2
+ exit 1
+ fi
+ if [ -n "${DATABASE_URL:-}" ] || [ -n "${PGSERVICE:-}" ] || [ -n "${PGSERVICEFILE:-}" ]; then
+ echo "Refusing DATABASE_URL/PGSERVICE/PGSERVICEFILE; they can redirect psql to another database." >&2
+ exit 1
+ fi
+ if [ "${ALLOW_NONLOCAL_TEST_DB:-0}" != "1" ]; then
+ if ! is_local_target "${PGHOST:-}"; then
+ echo "Refusing non-local PGHOST=${PGHOST}. Set ALLOW_NONLOCAL_TEST_DB=1 to override." >&2
+ exit 1
+ fi
+ if ! is_local_target "${PGHOSTADDR:-}"; then
+ echo "Refusing non-local PGHOSTADDR=${PGHOSTADDR}. Set ALLOW_NONLOCAL_TEST_DB=1 to override." >&2
+ exit 1
+ fi
+ fi
+
+ if [ -z "${PGHOST:-}" ] && [ -z "${PGHOSTADDR:-}" ]; then
+ export PGHOST=localhost
+ fi
+ psql -v ON_ERROR_STOP=1 -d postgres <<SQL
+CREATE DATABASE "$test_db";
+SQL
+}
+
+cd "$server_dir"
+
+case "$postgres_mode" in
+ auto)
+ if command -v docker >/dev/null 2>&1 && docker info >/dev/null 2>&1; then
+ postgres_mode=docker
+ else
+ postgres_mode=local
+ fi
+ ;;
+ docker|local)
+ ;;
+ *)
+ echo "Unsupported ENTE_TEST_POSTGRES=$postgres_mode. Use auto, docker, or local." >&2
+ exit 1
+ ;;
+esac
+
+if [ "$postgres_mode" = "docker" ]; then
+ trap cleanup EXIT INT TERM
+ start_docker_postgres
+ ENV=test PGHOST=localhost PGPORT="$pg_port" PGUSER=postgres PGPASSWORD=test_pass PGDATABASE="$test_db" go test -p 1 -count=1 "$@" ./...
+else
+ create_local_db
+ trap cleanup EXIT INT TERM
+ ENV=test PGDATABASE="$test_db" go test -p 1 -count=1 "$@" ./...
+fi