utils_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // Copyright 2014 Manu Martinez-Almeida. All rights reserved.
  2. // Use of this source code is governed by a MIT style
  3. // license that can be found in the LICENSE file.
  4. package gin
  5. import (
  6. "fmt"
  7. "net/http"
  8. "testing"
  9. "github.com/stretchr/testify/assert"
  10. )
  11. func init() {
  12. SetMode(TestMode)
  13. }
  14. func TestWrap(t *testing.T) {
  15. router := New()
  16. router.GET("/path", Wrap(func(w http.ResponseWriter, req *http.Request) {
  17. assert.Equal(t, req.Method, "GET")
  18. assert.Equal(t, req.URL.Path, "/path")
  19. w.WriteHeader(400)
  20. fmt.Fprint(w, "hola!")
  21. }))
  22. w := performRequest(router, "GET", "/path")
  23. assert.Equal(t, w.Code, 400)
  24. assert.Equal(t, w.Body.String(), "hola!")
  25. }
  26. func TestLastChar(t *testing.T) {
  27. assert.Equal(t, lastChar("hola"), uint8('a'))
  28. assert.Equal(t, lastChar("adios"), uint8('s'))
  29. assert.Panics(t, func() { lastChar("") })
  30. }
  31. func TestParseAccept(t *testing.T) {
  32. parts := parseAccept("text/html , application/xhtml+xml,application/xml;q=0.9, */* ;q=0.8")
  33. assert.Len(t, parts, 4)
  34. assert.Equal(t, parts[0], "text/html")
  35. assert.Equal(t, parts[1], "application/xhtml+xml")
  36. assert.Equal(t, parts[2], "application/xml")
  37. assert.Equal(t, parts[3], "*/*")
  38. }
  39. func TestChooseData(t *testing.T) {
  40. A := "a"
  41. B := "b"
  42. assert.Equal(t, chooseData(A, B), A)
  43. assert.Equal(t, chooseData(nil, B), B)
  44. assert.Panics(t, func() { chooseData(nil, nil) })
  45. }
  46. func TestFilterFlags(t *testing.T) {
  47. result := filterFlags("text/html ")
  48. assert.Equal(t, result, "text/html")
  49. result = filterFlags("text/html;")
  50. assert.Equal(t, result, "text/html")
  51. }
  52. func TestFunctionName(t *testing.T) {
  53. assert.Equal(t, nameOfFunction(somefunction), "github.com/gin-gonic/gin.somefunction")
  54. }
  55. func somefunction() {
  56. // this empty function is used by TestFunctionName()
  57. }
  58. func TestJoinPaths(t *testing.T) {
  59. assert.Equal(t, joinPaths("", ""), "")
  60. assert.Equal(t, joinPaths("", "/"), "/")
  61. assert.Equal(t, joinPaths("/a", ""), "/a")
  62. assert.Equal(t, joinPaths("/a/", ""), "/a/")
  63. assert.Equal(t, joinPaths("/a/", "/"), "/a/")
  64. assert.Equal(t, joinPaths("/a", "/"), "/a/")
  65. assert.Equal(t, joinPaths("/a", "/hola"), "/a/hola")
  66. assert.Equal(t, joinPaths("/a/", "/hola"), "/a/hola")
  67. assert.Equal(t, joinPaths("/a/", "/hola/"), "/a/hola/")
  68. assert.Equal(t, joinPaths("/a/", "/hola//"), "/a/hola/")
  69. }