helpers.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package test
  2. import (
  3. "context"
  4. "flag"
  5. "io"
  6. "net"
  7. "net/http"
  8. "os"
  9. "path/filepath"
  10. "testing"
  11. "github.com/stretchr/testify/assert"
  12. "github.com/stretchr/testify/require"
  13. )
  14. // ShortTempDir returns a short private directory of the test's own, removed when the
  15. // test ends. t.TempDir embeds the test name, which on darwin routinely pushes a unix
  16. // socket path laid out under it past the 104 byte sun_path limit.
  17. func ShortTempDir(t *testing.T) string {
  18. t.Helper()
  19. dir, err := os.MkdirTemp("", "la")
  20. require.NoError(t, err)
  21. t.Cleanup(func() { _ = os.RemoveAll(dir) })
  22. return dir
  23. }
  24. // Update is the -update flag: Golden rewrites its file instead of comparing against it.
  25. var Update = flag.Bool("update", false, "rewrite golden files instead of comparing against them")
  26. // Golden compares got with the file at path, or rewrites the file when -update is set.
  27. func Golden(t *testing.T, path, got string) {
  28. t.Helper()
  29. if *Update {
  30. require.NoError(t, os.MkdirAll(filepath.Dir(path), 0755))
  31. require.NoError(t, os.WriteFile(path, []byte(got), 0644))
  32. return
  33. }
  34. want, err := os.ReadFile(path)
  35. require.NoError(t, err, "missing golden file, run with -update")
  36. assert.Equal(t, string(want), got)
  37. }
  38. // HTTPDo sends one request to the HTTP server on the unix socket at socket and returns
  39. // the status, body and headers of its answer. The host in the URL is a placeholder:
  40. // every connection goes to the socket.
  41. func HTTPDo(t *testing.T, socket, method, target string) (int, string, http.Header) {
  42. t.Helper()
  43. client := &http.Client{Transport: &http.Transport{
  44. DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
  45. return (&net.Dialer{}).DialContext(ctx, "unix", socket)
  46. },
  47. }}
  48. t.Cleanup(client.CloseIdleConnections)
  49. req, err := http.NewRequest(method, "http://nebula"+target, nil)
  50. require.NoError(t, err)
  51. res, err := client.Do(req)
  52. require.NoError(t, err)
  53. defer res.Body.Close()
  54. body, err := io.ReadAll(res.Body)
  55. require.NoError(t, err)
  56. return res.StatusCode, string(body), res.Header
  57. }
  58. // HTTPGet is HTTPDo for a GET whose headers the test does not read.
  59. func HTTPGet(t *testing.T, socket, target string) (int, string) {
  60. t.Helper()
  61. status, body, _ := HTTPDo(t, socket, http.MethodGet, target)
  62. return status, body
  63. }