watcher_test.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. //go:build !nowatcher
  2. package frankenphp_test
  3. import (
  4. "net/http"
  5. "net/http/httptest"
  6. "os"
  7. "path/filepath"
  8. "testing"
  9. "time"
  10. "github.com/stretchr/testify/assert"
  11. )
  12. // we have to wait a few milliseconds for the watcher debounce to take effect
  13. const pollingTime = 250
  14. // in tests checking for no reload: we will poll 3x250ms = 0.75s
  15. const minTimesToPollForChanges = 3
  16. // in tests checking for a reload: we will poll a maximum of 60x250ms = 15s
  17. const maxTimesToPollForChanges = 60
  18. func TestWorkersShouldReloadOnMatchingPattern(t *testing.T) {
  19. watch := []string{"./testdata/**/*.txt"}
  20. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  21. requestBodyHasReset := pollForWorkerReset(t, handler, maxTimesToPollForChanges)
  22. assert.True(t, requestBodyHasReset)
  23. }, &testOptions{nbParallelRequests: 1, nbWorkers: 1, workerScript: "worker-with-counter.php", watch: watch})
  24. }
  25. func TestWorkersShouldNotReloadOnExcludingPattern(t *testing.T) {
  26. watch := []string{"./testdata/**/*.php"}
  27. runTest(t, func(handler func(http.ResponseWriter, *http.Request), _ *httptest.Server, i int) {
  28. requestBodyHasReset := pollForWorkerReset(t, handler, minTimesToPollForChanges)
  29. assert.False(t, requestBodyHasReset)
  30. }, &testOptions{nbParallelRequests: 1, nbWorkers: 1, workerScript: "worker-with-counter.php", watch: watch})
  31. }
  32. func pollForWorkerReset(t *testing.T, handler func(http.ResponseWriter, *http.Request), limit int) bool {
  33. // first we make an initial request to start the request counter
  34. body := fetchBody("GET", "http://example.com/worker-with-counter.php", handler)
  35. assert.Equal(t, "requests:1", body)
  36. // now we spam file updates and check if the request counter resets
  37. for i := 0; i < limit; i++ {
  38. updateTestFile("./testdata/files/test.txt", "updated", t)
  39. time.Sleep(pollingTime * time.Millisecond)
  40. body := fetchBody("GET", "http://example.com/worker-with-counter.php", handler)
  41. if body == "requests:1" {
  42. return true
  43. }
  44. }
  45. return false
  46. }
  47. func updateTestFile(fileName string, content string, t *testing.T) {
  48. absFileName, err := filepath.Abs(fileName)
  49. assert.NoError(t, err)
  50. dirName := filepath.Dir(absFileName)
  51. if _, err := os.Stat(dirName); os.IsNotExist(err) {
  52. err = os.MkdirAll(dirName, 0700)
  53. assert.NoError(t, err)
  54. }
  55. bytes := []byte(content)
  56. err = os.WriteFile(absFileName, bytes, 0644)
  57. assert.NoError(t, err)
  58. }