server.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. // Package servertest runs an in-process Miniflux server for integration tests.
  4. package servertest // import "miniflux.app/v2/internal/http/server/servertest"
  5. import (
  6. "database/sql"
  7. "fmt"
  8. "log/slog"
  9. "math/rand/v2"
  10. "net/http/httptest"
  11. "os"
  12. "testing"
  13. "miniflux.app/v2/internal/cli"
  14. "miniflux.app/v2/internal/config"
  15. "miniflux.app/v2/internal/database"
  16. "miniflux.app/v2/internal/http/server"
  17. "miniflux.app/v2/internal/model"
  18. "miniflux.app/v2/internal/storage"
  19. "miniflux.app/v2/internal/worker"
  20. )
  21. const skipIntegrationTestsMessage = `Set TEST_DATABASE_URL to a PostgreSQL database to run the integration tests`
  22. // testServer is the server started by Main, or nil when TEST_DATABASE_URL is not set.
  23. var testServer *Server
  24. // Server serves all Miniflux routes from an httptest server backed by a PostgreSQL database.
  25. type Server struct {
  26. // URL is the base URL of the server, without a trailing slash.
  27. URL string
  28. // Store gives the tests direct access to the database, for setup that no API offers.
  29. Store *storage.Storage
  30. db *sql.DB
  31. pool *worker.Pool
  32. httpServer *httptest.Server
  33. }
  34. // Main runs the tests of a package and exits. When TEST_DATABASE_URL is set, it first starts
  35. // the server that Require returns, and prepares it with setup unless setup is nil.
  36. func Main(m *testing.M, setup func(*Server) error) {
  37. os.Exit(runTests(m, setup))
  38. }
  39. func runTests(m *testing.M, setup func(*Server) error) int {
  40. databaseURL := os.Getenv("TEST_DATABASE_URL")
  41. if databaseURL == "" {
  42. return m.Run()
  43. }
  44. server, err := newServer(databaseURL)
  45. if err != nil {
  46. fmt.Fprintf(os.Stderr, "Unable to start the integration test server: %v\n", err)
  47. return 1
  48. }
  49. defer server.stop()
  50. if setup != nil {
  51. if err := setup(server); err != nil {
  52. fmt.Fprintf(os.Stderr, "Unable to set up the integration test server: %v\n", err)
  53. return 1
  54. }
  55. }
  56. testServer = server
  57. return m.Run()
  58. }
  59. // Require returns the server started by Main, or skips the test when TEST_DATABASE_URL is not set.
  60. func Require(t testing.TB) *Server {
  61. t.Helper()
  62. if testServer == nil {
  63. t.Skip(skipIntegrationTestsMessage)
  64. }
  65. return testServer
  66. }
  67. // NewUser creates a regular user with the given password, removed when the test ends.
  68. func (s *Server) NewUser(t testing.TB, password string) *model.User {
  69. t.Helper()
  70. user, err := s.Store.CreateUser(&model.UserCreationRequest{
  71. Username: fmt.Sprintf("test_user_%d", rand.Int()),
  72. Password: password,
  73. })
  74. if err != nil {
  75. t.Fatal(err)
  76. }
  77. t.Cleanup(func() {
  78. if err := s.Store.RemoveUser(user.ID); err != nil {
  79. t.Errorf(`Unable to remove user %d: %v`, user.ID, err)
  80. }
  81. })
  82. return user
  83. }
  84. // newServer migrates the database and starts a server that uses it.
  85. func newServer(databaseURL string) (*Server, error) {
  86. // The tests serve their feeds from httptest servers listening on 127.0.0.1.
  87. os.Setenv("FETCHER_ALLOW_PRIVATE_NETWORKS", "1")
  88. os.Setenv("INTEGRATION_ALLOW_PRIVATE_NETWORKS", "1")
  89. opts, err := config.NewConfigParser().ParseEnvironmentVariables()
  90. if err != nil {
  91. return nil, err
  92. }
  93. config.Opts = opts
  94. // Keep the server logs out of the test output unless LOG_LEVEL is set.
  95. if os.Getenv("LOG_LEVEL") == "" {
  96. slog.SetDefault(slog.New(slog.DiscardHandler))
  97. } else if err := cli.InitializeDefaultLogger(opts.LogLevel(), os.Stderr, opts.LogFormat(), opts.LogDateTime()); err != nil {
  98. return nil, err
  99. }
  100. db, err := database.NewConnectionPool(databaseURL, opts.DatabaseMinConns(), opts.DatabaseMaxConns(), opts.DatabaseConnectionLifetime())
  101. if err != nil {
  102. return nil, err
  103. }
  104. if err := database.Migrate(db); err != nil {
  105. db.Close()
  106. return nil, err
  107. }
  108. store := storage.NewStorage(db)
  109. pool := worker.NewPool(store, opts.WorkerPoolSize())
  110. httpServer := httptest.NewServer(server.NewRouter(store, pool))
  111. return &Server{
  112. URL: httpServer.URL,
  113. Store: store,
  114. db: db,
  115. pool: pool,
  116. httpServer: httpServer,
  117. }, nil
  118. }
  119. // stop stops the server and closes the database.
  120. func (s *Server) stop() {
  121. s.httpServer.Close()
  122. s.pool.Shutdown()
  123. s.db.Close()
  124. }