setup.go 2.3 KB

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