gin_integration_test.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. assert.Error(t, router.Run(":5150"))
  25. resp, err := http.Get("http://localhost:5150/example")
  26. defer resp.Body.Close()
  27. assert.NoError(t, err)
  28. body, ioerr := ioutil.ReadAll(resp.Body)
  29. assert.NoError(t, ioerr)
  30. assert.Equal(t, "it worked", string(body[:]), "resp body should match")
  31. assert.Equal(t, "200 OK", resp.Status, "should get a 200")
  32. }
  33. func TestUnixSocket(t *testing.T) {
  34. buffer := new(bytes.Buffer)
  35. router := New()
  36. go func() {
  37. router.Use(LoggerWithWriter(buffer))
  38. router.GET("/example", func(c *Context) { c.String(http.StatusOK, "it worked") })
  39. router.RunUnix("/tmp/unix_unit_test")
  40. }()
  41. // have to wait for the goroutine to start and run the server
  42. // otherwise the main thread will complete
  43. time.Sleep(5 * time.Millisecond)
  44. c, err := net.Dial("unix", "/tmp/unix_unit_test")
  45. assert.NoError(t, err)
  46. fmt.Fprintf(c, "GET /example HTTP/1.0\r\n\r\n")
  47. scanner := bufio.NewScanner(c)
  48. var response string
  49. for scanner.Scan() {
  50. response += scanner.Text()
  51. }
  52. assert.Contains(t, response, "HTTP/1.0 200", "should get a 200")
  53. assert.Contains(t, response, "it worked", "resp body should match")
  54. }
  55. func TestBadUnixSocket(t *testing.T) {
  56. router := New()
  57. assert.Error(t, router.RunUnix("#/tmp/unix_unit_test"))
  58. }