setup.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package test
  2. import (
  3. "fmt"
  4. "io"
  5. "log/slog"
  6. "net/http"
  7. "time"
  8. "github.com/browsh-org/browsh/interfacer/src/browsh"
  9. ginkgo "github.com/onsi/ginkgo"
  10. "github.com/spf13/viper"
  11. )
  12. var (
  13. staticFileServerPort = "4444"
  14. rootDir = browsh.Shell("git rev-parse --show-toplevel")
  15. )
  16. func startStaticFileServer() {
  17. serverMux := http.NewServeMux()
  18. serverMux.Handle("/", http.FileServer(http.Dir(rootDir+"/interfacer/test/sites")))
  19. http.ListenAndServe(":"+staticFileServerPort, serverMux)
  20. }
  21. func initBrowsh() {
  22. browsh.IsTesting = true
  23. browsh.Initialise()
  24. viper.Set("http-server-mode", true)
  25. }
  26. func waitUntilConnectedToWebExtension(maxTime time.Duration) {
  27. start := time.Now()
  28. for time.Since(start) < maxTime {
  29. if browsh.IsConnectedToWebExtension {
  30. return
  31. }
  32. time.Sleep(50 * time.Millisecond)
  33. }
  34. panic("Didn't connect to webextension in time")
  35. }
  36. func getBrowshServiceBase() string {
  37. return "http://localhost:" + viper.GetString("http-server.port")
  38. }
  39. func getPath(path string, mode string) string {
  40. browshServiceBase := getBrowshServiceBase()
  41. staticFileServerBase := "http://localhost:" + staticFileServerPort
  42. fullBase := browshServiceBase + "/" + staticFileServerBase
  43. client := &http.Client{}
  44. request, err := http.NewRequest("GET", fullBase+path, nil)
  45. if mode == "plain" {
  46. request.Header.Add("X-Browsh-Raw-Mode", "PLAIN")
  47. }
  48. if mode == "dom" {
  49. request.Header.Add("X-Browsh-Raw-Mode", "DOM")
  50. }
  51. response, err := client.Do(request)
  52. if err != nil {
  53. panic(fmt.Sprintf("%s", err))
  54. } else {
  55. defer response.Body.Close()
  56. contents, err := io.ReadAll(response.Body)
  57. if err != nil {
  58. fmt.Printf("%s", err)
  59. panic(fmt.Sprintf("%s", err))
  60. }
  61. return string(contents)
  62. }
  63. }
  64. func stopFirefox() {
  65. browsh.IsConnectedToWebExtension = false
  66. browsh.Shell(rootDir + "/webext/contrib/firefoxheadless.sh kill")
  67. time.Sleep(500 * time.Millisecond)
  68. }
  69. var _ = ginkgo.BeforeEach(func() {
  70. browsh.ResetTabs()
  71. waitUntilConnectedToWebExtension(15 * time.Second)
  72. browsh.IsMonochromeMode = false
  73. slog.Info("\n---------")
  74. slog.Info(ginkgo.CurrentGinkgoTestDescription().FullTestText)
  75. slog.Info("---------")
  76. })
  77. var _ = ginkgo.BeforeSuite(func() {
  78. initBrowsh()
  79. stopFirefox()
  80. go startStaticFileServer()
  81. go browsh.HTTPServerStart()
  82. time.Sleep(1 * time.Second)
  83. })
  84. var _ = ginkgo.AfterSuite(func() {
  85. stopFirefox()
  86. })