serve_test.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package cmd
  2. import (
  3. "fmt"
  4. "github.com/gorilla/websocket"
  5. "github.com/stretchr/testify/require"
  6. "heckel.io/ntfy/client"
  7. "heckel.io/ntfy/test"
  8. "heckel.io/ntfy/util"
  9. "math/rand"
  10. "os"
  11. "os/exec"
  12. "path/filepath"
  13. "testing"
  14. "time"
  15. )
  16. func init() {
  17. rand.Seed(time.Now().UnixMilli())
  18. }
  19. func TestCLI_Serve_Unix_Curl(t *testing.T) {
  20. sockFile := filepath.Join(t.TempDir(), "ntfy.sock")
  21. configFile := newEmptyFile(t) // Avoid issues with existing server.yml file on system
  22. go func() {
  23. app, _, _, _ := newTestApp()
  24. err := app.Run([]string{"ntfy", "serve", "--config=" + configFile, "--listen-http=-", "--listen-unix=" + sockFile})
  25. require.Nil(t, err)
  26. }()
  27. for i := 0; i < 40 && !util.FileExists(sockFile); i++ {
  28. time.Sleep(50 * time.Millisecond)
  29. }
  30. require.True(t, util.FileExists(sockFile))
  31. cmd := exec.Command("curl", "-s", "--unix-socket", sockFile, "-d", "this is a message", "localhost/mytopic")
  32. out, err := cmd.Output()
  33. require.Nil(t, err)
  34. m := toMessage(t, string(out))
  35. require.Equal(t, "this is a message", m.Message)
  36. }
  37. func TestCLI_Serve_WebSocket(t *testing.T) {
  38. port := 10000 + rand.Intn(20000)
  39. go func() {
  40. configFile := newEmptyFile(t) // Avoid issues with existing server.yml file on system
  41. app, _, _, _ := newTestApp()
  42. err := app.Run([]string{"ntfy", "serve", "--config=" + configFile, fmt.Sprintf("--listen-http=:%d", port)})
  43. require.Nil(t, err)
  44. }()
  45. test.WaitForPortUp(t, port)
  46. ws, _, err := websocket.DefaultDialer.Dial(fmt.Sprintf("ws://127.0.0.1:%d/mytopic/ws", port), nil)
  47. require.Nil(t, err)
  48. messageType, data, err := ws.ReadMessage()
  49. require.Nil(t, err)
  50. require.Equal(t, websocket.TextMessage, messageType)
  51. require.Equal(t, "open", toMessage(t, string(data)).Event)
  52. c := client.New(client.NewConfig())
  53. _, err = c.Publish(fmt.Sprintf("http://127.0.0.1:%d/mytopic", port), "my message")
  54. require.Nil(t, err)
  55. messageType, data, err = ws.ReadMessage()
  56. require.Nil(t, err)
  57. require.Equal(t, websocket.TextMessage, messageType)
  58. m := toMessage(t, string(data))
  59. require.Equal(t, "my message", m.Message)
  60. require.Equal(t, "mytopic", m.Topic)
  61. }
  62. func newEmptyFile(t *testing.T) string {
  63. filename := filepath.Join(t.TempDir(), "empty")
  64. require.Nil(t, os.WriteFile(filename, []byte{}, 0600))
  65. return filename
  66. }