test.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package test
  2. import (
  3. "fmt"
  4. "net"
  5. "os"
  6. "testing"
  7. "github.com/joho/godotenv"
  8. "github.com/usememos/memos/server/profile"
  9. "github.com/usememos/memos/server/version"
  10. )
  11. func getUnusedPort() int {
  12. // Get a random unused port
  13. listener, err := net.Listen("tcp", "localhost:0")
  14. if err != nil {
  15. panic(err)
  16. }
  17. defer listener.Close()
  18. // Get the port number
  19. port := listener.Addr().(*net.TCPAddr).Port
  20. return port
  21. }
  22. func GetTestingProfile(t *testing.T) *profile.Profile {
  23. if err := godotenv.Load(".env"); err != nil {
  24. t.Log("failed to load .env file, but it's ok")
  25. }
  26. // Get a temporary directory for the test data.
  27. dir := t.TempDir()
  28. mode := "dev"
  29. port := getUnusedPort()
  30. driver := getDriverFromEnv()
  31. dsn := os.Getenv("DSN")
  32. if driver == "sqlite" {
  33. dsn = fmt.Sprintf("%s/memos_%s.db", dir, mode)
  34. }
  35. return &profile.Profile{
  36. Mode: mode,
  37. Port: port,
  38. Data: dir,
  39. DSN: dsn,
  40. Driver: driver,
  41. Version: version.GetCurrentVersion(mode),
  42. }
  43. }
  44. func getDriverFromEnv() string {
  45. driver := os.Getenv("DRIVER")
  46. if driver == "" {
  47. driver = "sqlite"
  48. }
  49. return driver
  50. }