Преглед изворни кода

test(api): run integration tests against an in-process server

The API integration tests needed a separately started Miniflux server,
and the Makefile had to build it, wait for it on port 8080, and track
it with pid and log files in /tmp.

When TEST_DATABASE_URL is set, TestMain now migrates the database,
creates the admin user, and serves the full router from httptest. The
black-box tests move to the api_test package so they can import the
exported server.NewRouter. Server logs are discarded unless LOG_LEVEL
is set, and the TEST_MINIFLUX_* variables are removed.

The Makefile also runs the built binary instead of `go run .`, which
macOS kills because the executable is named miniflux.app.
Fred пре 5 часа
родитељ
комит
ed96088163

+ 5 - 30
Makefile

@@ -89,8 +89,8 @@ openbsd-amd64:
 
 build: linux-amd64 linux-arm64 linux-armv7 linux-armv6 linux-armv5 linux-riscv64 darwin-amd64 darwin-arm64 freebsd-amd64 freebsd-arm64 openbsd-amd64
 
-run:
-	@ LOG_DATE_TIME=1 LOG_LEVEL=debug RUN_MIGRATIONS=1 CREATE_ADMIN=1 ADMIN_USERNAME=admin ADMIN_PASSWORD=test123 go run .
+run: miniflux
+	@ LOG_DATE_TIME=1 LOG_LEVEL=debug RUN_MIGRATIONS=1 CREATE_ADMIN=1 ADMIN_USERNAME=admin ADMIN_PASSWORD=test123 ./$(APP)
 
 clean:
 	@ rm -f $(APP)-* $(APP) $(APP)*.rpm $(APP)*.deb
@@ -113,41 +113,16 @@ lint:
 	gofmt -d -e .
 	golangci-lint run
 
-integration-test:
+integration-test: miniflux
 	psql -U postgres -c 'drop database if exists miniflux_test;'
 	psql -U postgres -c 'create database miniflux_test;'
 
-	DATABASE_URL=$(DB_URL) \
-	ADMIN_USERNAME=admin \
-	ADMIN_PASSWORD=test123 \
-	CREATE_ADMIN=1 \
-	RUN_MIGRATIONS=1 \
-	LOG_LEVEL=debug \
-	FETCHER_ALLOW_PRIVATE_NETWORKS=1 \
-	INTEGRATION_ALLOW_PRIVATE_NETWORKS=1 \
-	go run . >/tmp/miniflux.log 2>&1 & echo "$$!" > "/tmp/miniflux.pid"
-
-	for attempt in $$(seq 1 120); do \
-		curl -fs -o /dev/null http://127.0.0.1:8080/healthcheck && break; \
-		if [ "$$attempt" = 120 ]; then echo "Miniflux did not start:"; cat /tmp/miniflux.log; exit 1; fi; \
-		sleep 1; \
-	done
+	DATABASE_URL=$(DB_URL) ./$(APP) -migrate
 
 	TEST_DATABASE_URL=$(DB_URL) go test -v -count=1 ./internal/storage
-
-	TEST_DATABASE_URL=$(DB_URL) \
-	TEST_MINIFLUX_BASE_URL=http://127.0.0.1:8080 \
-	TEST_MINIFLUX_ADMIN_USERNAME=admin \
-	TEST_MINIFLUX_ADMIN_PASSWORD=test123 \
-	go test -v -count=1 ./internal/api
+	TEST_DATABASE_URL=$(DB_URL) go test -v -count=1 ./internal/api
 
 clean-integration-test:
-	@ go_run_pid=$$(cat /tmp/miniflux.pid 2>/dev/null); \
-	  if [ -n "$$go_run_pid" ]; then \
-	    pkill -P "$$go_run_pid"; \
-	    for attempt in $$(seq 1 30); do kill -0 "$$go_run_pid" 2>/dev/null || break; sleep 1; done; \
-	  fi
-	@ rm -f /tmp/miniflux.pid /tmp/miniflux.log
 	@ psql -U postgres -c 'drop database if exists miniflux_test;'
 
 docker-image:

+ 1 - 82
internal/api/api_integration_test.go

@@ -1,16 +1,13 @@
 // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
 // SPDX-License-Identifier: Apache-2.0
 
-package api // import "miniflux.app/v2/internal/api"
+package api_test
 
 import (
 	"bytes"
 	"errors"
-	"fmt"
 	"io"
 	"math"
-	"math/rand/v2"
-	"os"
 	"strings"
 	"testing"
 
@@ -18,84 +15,6 @@ import (
 	"miniflux.app/v2/internal/model"
 )
 
-const skipIntegrationTestsMessage = `Set TEST_MINIFLUX_* environment variables to run the API integration tests`
-
-type integrationTestConfig struct {
-	testBaseURL         string
-	testAdminUsername   string
-	testAdminPassword   string
-	testRegularUsername string
-	testRegularPassword string
-}
-
-func newIntegrationTestConfig() *integrationTestConfig {
-	getDefaultEnvValues := func(key, defaultValue string) string {
-		value := os.Getenv(key)
-		if value == "" {
-			return defaultValue
-		}
-		return value
-	}
-
-	return &integrationTestConfig{
-		testBaseURL:         getDefaultEnvValues("TEST_MINIFLUX_BASE_URL", ""),
-		testAdminUsername:   getDefaultEnvValues("TEST_MINIFLUX_ADMIN_USERNAME", ""),
-		testAdminPassword:   getDefaultEnvValues("TEST_MINIFLUX_ADMIN_PASSWORD", ""),
-		testRegularUsername: getDefaultEnvValues("TEST_MINIFLUX_REGULAR_USERNAME_PREFIX", "regular_test_user"),
-		testRegularPassword: getDefaultEnvValues("TEST_MINIFLUX_REGULAR_PASSWORD", "regular_test_user_password"),
-	}
-}
-
-func (c *integrationTestConfig) isConfigured() bool {
-	return c.testBaseURL != "" && c.testAdminUsername != "" && c.testAdminPassword != ""
-}
-
-func (c *integrationTestConfig) genRandomUsername() string {
-	return fmt.Sprintf("%s_%10d", c.testRegularUsername, rand.Int())
-}
-
-// requireIntegrationTestConfig returns the integration test configuration,
-// or skips the test when the TEST_MINIFLUX_* environment variables are not set.
-func requireIntegrationTestConfig(t *testing.T) *integrationTestConfig {
-	t.Helper()
-
-	testConfig := newIntegrationTestConfig()
-	if !testConfig.isConfigured() {
-		t.Skip(skipIntegrationTestsMessage)
-	}
-	return testConfig
-}
-
-func (c *integrationTestConfig) newAdminClient() *miniflux.Client {
-	return miniflux.NewClient(c.testBaseURL, c.testAdminUsername, c.testAdminPassword)
-}
-
-// deleteUserOnCleanup removes the user when the test and its subtests finish,
-// and fails the test if the user cannot be removed.
-func (c *integrationTestConfig) deleteUserOnCleanup(t *testing.T, userID int64) {
-	t.Helper()
-
-	t.Cleanup(func() {
-		if err := c.newAdminClient().DeleteUser(userID); err != nil {
-			t.Errorf(`Unable to delete user %d: %v`, userID, err)
-		}
-	})
-}
-
-// newRegularUser creates a regular user that is removed when the test ends,
-// and returns a client authenticated as that user.
-func (c *integrationTestConfig) newRegularUser(t *testing.T) (*miniflux.Client, *miniflux.User) {
-	t.Helper()
-
-	user, err := c.newAdminClient().CreateUser(c.genRandomUsername(), c.testRegularPassword, false)
-	if err != nil {
-		t.Fatal(err)
-	}
-	c.deleteUserOnCleanup(t, user.ID)
-
-	return miniflux.NewClient(c.testBaseURL, user.Username, c.testRegularPassword), user
-}
-
 func TestIncorrectEndpoint(t *testing.T) {
 	t.Parallel()
 

+ 1 - 1
internal/api/entry_pagination_integration_test.go

@@ -1,7 +1,7 @@
 // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
 // SPDX-License-Identifier: Apache-2.0
 
-package api
+package api_test
 
 import (
 	"fmt"

+ 1 - 1
internal/api/integration_fixture_test.go

@@ -1,7 +1,7 @@
 // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
 // SPDX-License-Identifier: Apache-2.0
 
-package api // import "miniflux.app/v2/internal/api"
+package api_test
 
 import (
 	"bytes"

+ 162 - 0
internal/api/integration_server_test.go

@@ -0,0 +1,162 @@
+// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+package api_test
+
+import (
+	"fmt"
+	"log/slog"
+	"math/rand/v2"
+	"net/http/httptest"
+	"os"
+	"testing"
+
+	miniflux "miniflux.app/v2/client"
+	"miniflux.app/v2/internal/cli"
+	"miniflux.app/v2/internal/config"
+	"miniflux.app/v2/internal/database"
+	"miniflux.app/v2/internal/http/server"
+	"miniflux.app/v2/internal/model"
+	"miniflux.app/v2/internal/storage"
+	"miniflux.app/v2/internal/worker"
+)
+
+const skipIntegrationTestsMessage = `Set TEST_DATABASE_URL to a PostgreSQL database to run the API integration tests`
+
+// integrationConfig describes the Miniflux server started by TestMain.
+// It is nil when TEST_DATABASE_URL is not set.
+var integrationConfig *integrationTestConfig
+
+type integrationTestConfig struct {
+	testBaseURL         string
+	testAdminUsername   string
+	testAdminPassword   string
+	testRegularUsername string
+	testRegularPassword string
+}
+
+func TestMain(m *testing.M) {
+	os.Exit(runTests(m))
+}
+
+func runTests(m *testing.M) int {
+	databaseURL := os.Getenv("TEST_DATABASE_URL")
+	if databaseURL == "" {
+		return m.Run()
+	}
+
+	stopServer, err := startIntegrationTestServer(databaseURL)
+	if err != nil {
+		fmt.Fprintf(os.Stderr, "Unable to start the integration test server: %v\n", err)
+		return 1
+	}
+	defer stopServer()
+
+	return m.Run()
+}
+
+// startIntegrationTestServer serves all Miniflux routes from an in-process HTTP server
+// backed by the given database, which is migrated and given an admin user.
+func startIntegrationTestServer(databaseURL string) (func(), error) {
+	// The tests serve their feeds from httptest servers listening on 127.0.0.1.
+	os.Setenv("FETCHER_ALLOW_PRIVATE_NETWORKS", "1")
+	os.Setenv("INTEGRATION_ALLOW_PRIVATE_NETWORKS", "1")
+
+	opts, err := config.NewConfigParser().ParseEnvironmentVariables()
+	if err != nil {
+		return nil, err
+	}
+	config.Opts = opts
+
+	// Keep the server logs out of the test output unless LOG_LEVEL is set.
+	if os.Getenv("LOG_LEVEL") == "" {
+		slog.SetDefault(slog.New(slog.DiscardHandler))
+	} else if err := cli.InitializeDefaultLogger(opts.LogLevel(), os.Stderr, opts.LogFormat(), opts.LogDateTime()); err != nil {
+		return nil, err
+	}
+
+	db, err := database.NewConnectionPool(databaseURL, opts.DatabaseMinConns(), opts.DatabaseMaxConns(), opts.DatabaseConnectionLifetime())
+	if err != nil {
+		return nil, err
+	}
+
+	if err := database.Migrate(db); err != nil {
+		db.Close()
+		return nil, err
+	}
+
+	testConfig := &integrationTestConfig{
+		testAdminUsername:   "admin",
+		testAdminPassword:   "test123",
+		testRegularUsername: "regular_test_user",
+		testRegularPassword: "regular_test_user_password",
+	}
+
+	store := storage.NewStorage(db)
+	if !store.UserExists(testConfig.testAdminUsername) {
+		if _, err := store.CreateUser(&model.UserCreationRequest{
+			Username: testConfig.testAdminUsername,
+			Password: testConfig.testAdminPassword,
+			IsAdmin:  true,
+		}); err != nil {
+			db.Close()
+			return nil, err
+		}
+	}
+
+	pool := worker.NewPool(store, opts.WorkerPoolSize())
+	httpServer := httptest.NewServer(server.NewRouter(store, pool))
+	testConfig.testBaseURL = httpServer.URL
+	integrationConfig = testConfig
+
+	return func() {
+		httpServer.Close()
+		pool.Shutdown()
+		db.Close()
+	}, nil
+}
+
+// requireIntegrationTestConfig returns the configuration of the integration test server,
+// or skips the test when TEST_DATABASE_URL is not set.
+func requireIntegrationTestConfig(t *testing.T) *integrationTestConfig {
+	t.Helper()
+
+	if integrationConfig == nil {
+		t.Skip(skipIntegrationTestsMessage)
+	}
+	return integrationConfig
+}
+
+func (c *integrationTestConfig) genRandomUsername() string {
+	return fmt.Sprintf("%s_%10d", c.testRegularUsername, rand.Int())
+}
+
+func (c *integrationTestConfig) newAdminClient() *miniflux.Client {
+	return miniflux.NewClient(c.testBaseURL, c.testAdminUsername, c.testAdminPassword)
+}
+
+// deleteUserOnCleanup removes the user when the test and its subtests finish,
+// and fails the test if the user cannot be removed.
+func (c *integrationTestConfig) deleteUserOnCleanup(t *testing.T, userID int64) {
+	t.Helper()
+
+	t.Cleanup(func() {
+		if err := c.newAdminClient().DeleteUser(userID); err != nil {
+			t.Errorf(`Unable to delete user %d: %v`, userID, err)
+		}
+	})
+}
+
+// newRegularUser creates a regular user that is removed when the test ends,
+// and returns a client authenticated as that user.
+func (c *integrationTestConfig) newRegularUser(t *testing.T) (*miniflux.Client, *miniflux.User) {
+	t.Helper()
+
+	user, err := c.newAdminClient().CreateUser(c.genRandomUsername(), c.testRegularPassword, false)
+	if err != nil {
+		t.Fatal(err)
+	}
+	c.deleteUserOnCleanup(t, user.ID)
+
+	return miniflux.NewClient(c.testBaseURL, user.Username, c.testRegularPassword), user
+}

+ 2 - 1
internal/http/server/routes.go

@@ -15,7 +15,8 @@ import (
 	"miniflux.app/v2/internal/worker"
 )
 
-func newRouter(store *storage.Storage, pool *worker.Pool) http.Handler {
+// NewRouter returns the HTTP handler that serves all Miniflux routes.
+func NewRouter(store *storage.Storage, pool *worker.Pool) http.Handler {
 	readinessProbe := newReadinessProbe(store)
 
 	// Application routes served under the base path.

+ 1 - 1
internal/http/server/server.go

@@ -60,7 +60,7 @@ func StartWebServer(store *storage.Storage, pool *worker.Pool) ([]*http.Server,
 	}
 
 	for _, t := range targets {
-		srv := newHTTPServer(t.address, newRouter(store, pool))
+		srv := newHTTPServer(t.address, NewRouter(store, pool))
 
 		switch t.mode {
 		case modeSystemd: