Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

63 lines
1.5KB

  1. package form
  2. import (
  3. "bytes"
  4. "errors"
  5. "io"
  6. "net/http"
  7. "net/http/httptest"
  8. "net/url"
  9. "testing"
  10. . "github.com/smartystreets/goconvey/convey"
  11. )
  12. type user struct {
  13. Username string `schema:"username"`
  14. Password string `schema:"password"`
  15. }
  16. func (self *user) Validate() error {
  17. if self.Username == "" || self.Password == "" {
  18. return errors.New("username/password can not be empty")
  19. }
  20. if len(self.Password) < 8 {
  21. return errors.New("password must be greater than 8bits")
  22. }
  23. return nil
  24. }
  25. func TestParse(t *testing.T) {
  26. app := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  27. var form user
  28. if err := parse(r, &form); err == nil {
  29. w.WriteHeader(http.StatusAccepted)
  30. io.WriteString(w, "uid")
  31. } else {
  32. w.WriteHeader(http.StatusBadRequest)
  33. io.WriteString(w, err.Error())
  34. }
  35. })
  36. Convey("rex.form.Parse", t, func() {
  37. values := url.Values{}
  38. values.Set("username", "username")
  39. values.Set("password", "password")
  40. request, _ := http.NewRequest("POST", "/", bytes.NewBufferString(values.Encode()))
  41. request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  42. response := httptest.NewRecorder()
  43. app.ServeHTTP(response, request)
  44. So(response.Code, ShouldEqual, http.StatusAccepted)
  45. values.Set("password", "7")
  46. request, _ = http.NewRequest("POST", "/", bytes.NewBufferString(values.Encode()))
  47. response = httptest.NewRecorder()
  48. app.ServeHTTP(response, request)
  49. So(response.Code, ShouldEqual, http.StatusBadRequest)
  50. })
  51. }