user_test.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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.eyJVc2VySWQiOiJ5aHM2SGVzZmdGIiwiZXhwIjoxNjkzOTE0ODgwLCJuYmYiOjE2ODYxMzg4ODAsImlhdCI6MTY4NjEzODg4MH0.NnFrZFgc_333a9PXqaoongmIDksNvQoHzgM_IhJM4MQ",
  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 TestGetProfile(t *testing.T) {
  58. response, err := NewRequest("GET",
  59. fmt.Sprintf("/user"),
  60. headers,
  61. nil,
  62. )
  63. t.Log("response")
  64. assert.Nil(t, err)
  65. assert.Equal(t, 1, response.Code)
  66. }
  67. func TestUpdateProfile(t *testing.T) {
  68. params, err := json.Marshal(map[string]interface{}{
  69. "email": "5303221@gmail.com",
  70. "username": "user1",
  71. "nickname": "8888",
  72. })
  73. assert.Nil(t, err)
  74. response, err := NewRequest("PUT",
  75. "/user",
  76. headers,
  77. bytes.NewBuffer(params),
  78. )
  79. t.Log("响应结果")
  80. assert.Nil(t, err)
  81. //assert.NotEmpty(t, response.Data)
  82. assert.Equal(t, 0, response.Code)
  83. //tsms.SendSMS2("MotokApp", "18502100065", "1234")
  84. }