gin_integration_test.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package gin
  2. import (
  3. "bufio"
  4. "bytes"
  5. "fmt"
  6. "io/ioutil"
  7. "net"
  8. "net/http"
  9. "testing"
  10. "time"
  11. "github.com/stretchr/testify/assert"
  12. )
  13. func TestRun(t *testing.T) {
  14. buffer := new(bytes.Buffer)
  15. router := New()
  16. go func() {
  17. router.Use(LoggerWithWriter(buffer))
  18. router.GET("/example", func(c *Context) { c.String(http.StatusOK, "it worked") })
  19. router.Run(":5150")
  20. }()
  21. // have to wait for the goroutine to start and run the server
  22. // otherwise the main thread will complete
  23. time.Sleep(5 * time.Millisecond)
  24. resp, err := http.Get("http://localhost:5150/example")
  25. if err != nil {
  26. t.FailNow()
  27. }
  28. defer resp.Body.Close()
  29. body, ioerr := ioutil.ReadAll(resp.Body)
  30. if ioerr != nil {
  31. t.FailNow()
  32. }
  33. assert.Equal(t, "it worked", body, "resp body should match")
  34. assert.Equal(t, "200 OK", resp.Status, "should get a 200")
  35. }
  36. func TestUnixSocket(t *testing.T) {
  37. buffer := new(bytes.Buffer)
  38. router := New()
  39. go func() {
  40. router.Use(LoggerWithWriter(buffer))
  41. router.GET("/example", func(c *Context) { c.String(http.StatusOK, "it worked") })
  42. router.RunUnix("/tmp/unix_unit_test")
  43. }()
  44. // have to wait for the goroutine to start and run the server
  45. // otherwise the main thread will complete
  46. time.Sleep(5 * time.Millisecond)
  47. c, err := net.Dial("unix", "/tmp/unix_unit_test")
  48. if err != nil {
  49. println(err)
  50. t.FailNow()
  51. }
  52. fmt.Fprintf(c, "GET /example HTTP/1.0\r\n\r\n")
  53. scanner := bufio.NewScanner(c)
  54. var response string
  55. for scanner.Scan() {
  56. response += scanner.Text()
  57. }
  58. assert.Contains(t, response, "HTTP/1.0 200", "should get a 200")
  59. assert.Contains(t, response, "it worked", "resp body should match")
  60. }