user_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package handler
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/go-nunu/nunu-layout-advanced/cmd/server/wire"
  7. "github.com/go-nunu/nunu-layout-advanced/pkg/config"
  8. "github.com/go-nunu/nunu-layout-advanced/pkg/log"
  9. "github.com/stretchr/testify/assert"
  10. "io"
  11. "net/http"
  12. "net/http/httptest"
  13. "os"
  14. "strings"
  15. "testing"
  16. )
  17. var headers = map[string]string{
  18. "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySW5mbyI6eyJ1c2VyU2lkIjoiOHpsdGxQRzhXSCIsIm5pY2tuYW1lIjoi55CD55CDIiwidXNlcklkIjowfSwiZXhwIjoxNjg3NzcwMzYzLCJqdGkiOiI4emx0bFBHOFdIIiwiaXNzIjoiaHR0cHM6Ly90ZWh1Yi5jb20vYXBpIiwibmJmIjoxNjcyMjE3NzYzLCJzdWIiOiI4emx0bFBHOFdIIn0.G0sSUzj3GBANqj6dU7rSMsr44SARgYwH1ERwKUCaxsM",
  19. }
  20. func TestMain(m *testing.M) {
  21. fmt.Println("begin")
  22. code := m.Run()
  23. fmt.Println("test end")
  24. os.Exit(code)
  25. }
  26. type Response struct {
  27. Code int `json:"code"`
  28. Message string `json:"message"`
  29. Data interface{} `json:"data"`
  30. }
  31. func NewRequest(method, path string, header map[string]string, body io.Reader) (*Response, error) {
  32. // 测试时需要定义好 gin 的路由定义函数
  33. os.Setenv("APP_CONF", "../../../config/local.yml")
  34. conf := config.NewConfig()
  35. logger := log.NewLog(conf)
  36. logger.Info("start")
  37. app, _, err := wire.NewApp(conf, logger)
  38. if err != nil {
  39. return nil, err
  40. }
  41. req, _ := http.NewRequest(method, path, body)
  42. for k, v := range header {
  43. req.Header.Set(k, v)
  44. }
  45. if strings.ToUpper(method) != "GET" && body != nil {
  46. req.Header.Set("Content-Type", "application/json")
  47. }
  48. w := httptest.NewRecorder()
  49. app.ServeHTTP(w, req)
  50. response := new(Response)
  51. err = json.Unmarshal([]byte(w.Body.String()), response)
  52. if err != nil {
  53. return nil, err
  54. }
  55. return response, nil
  56. }
  57. func TestGetUserById(t *testing.T) {
  58. response, err := NewRequest("GET",
  59. fmt.Sprintf("/user?id=%s", "-1"),
  60. headers,
  61. nil,
  62. )
  63. t.Log("response")
  64. assert.Nil(t, err)
  65. assert.Equal(t, 1, response.Code)
  66. }
  67. func TestCreateUser(t *testing.T) {
  68. params, err := json.Marshal(map[string]interface{}{
  69. "email": "5303221@gmail.com",
  70. "username": "test",
  71. })
  72. assert.Nil(t, err)
  73. response, err := NewRequest("POST",
  74. "/user",
  75. headers,
  76. bytes.NewBuffer(params),
  77. )
  78. t.Log("响应结果")
  79. assert.Nil(t, err)
  80. //assert.NotEmpty(t, response.Data)
  81. assert.Equal(t, 0, response.Code)
  82. //tsms.SendSMS2("MotokApp", "18502100065", "1234")
  83. }