auth_test.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package testserver
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "testing"
  7. "github.com/pkg/errors"
  8. "github.com/stretchr/testify/require"
  9. "github.com/usememos/memos/api"
  10. )
  11. func TestAuthServer(t *testing.T) {
  12. ctx := context.Background()
  13. s, err := NewTestingServer(ctx, t)
  14. require.NoError(t, err)
  15. defer s.Shutdown(ctx)
  16. signup := &api.SignUp{
  17. Username: "testuser",
  18. Password: "testpassword",
  19. }
  20. user, err := s.postAuthSignup(signup)
  21. require.NoError(t, err)
  22. require.Equal(t, signup.Username, user.Username)
  23. }
  24. func (s *TestingServer) postAuthSignup(signup *api.SignUp) (*api.User, error) {
  25. rawData, err := json.Marshal(&signup)
  26. if err != nil {
  27. return nil, errors.Wrap(err, "failed to marshal signup")
  28. }
  29. reader := bytes.NewReader(rawData)
  30. body, err := s.post("/api/auth/signup", reader, nil)
  31. if err != nil {
  32. return nil, err
  33. }
  34. buf := &bytes.Buffer{}
  35. _, err = buf.ReadFrom(body)
  36. if err != nil {
  37. return nil, errors.Wrap(err, "fail to read response body")
  38. }
  39. type AuthSignupResponse struct {
  40. Data *api.User `json:"data"`
  41. }
  42. res := new(AuthSignupResponse)
  43. if err = json.Unmarshal(buf.Bytes(), res); err != nil {
  44. return nil, errors.Wrap(err, "fail to unmarshal post signup response")
  45. }
  46. return res.Data, nil
  47. }