GoBlog/captcha_test.go

83 lines
1.8 KiB
Go
Raw Normal View History

2021-06-19 06:37:16 +00:00
package main
import (
"context"
2021-06-19 06:37:16 +00:00
"io"
"net/http"
"net/http/httptest"
2021-07-03 10:11:57 +00:00
"path/filepath"
2021-06-19 06:37:16 +00:00
"testing"
"github.com/stretchr/testify/assert"
"go.goblog.app/app/pkgs/contenttype"
2021-06-19 06:37:16 +00:00
)
func Test_captchaMiddleware(t *testing.T) {
app := &goBlog{
cfg: &config{
2021-07-03 10:11:57 +00:00
Db: &configDb{
File: filepath.Join(t.TempDir(), "test.db"),
},
2021-06-19 06:37:16 +00:00
Server: &configServer{
PublicAddress: "https://example.com",
},
Blogs: map[string]*configBlog{
"en": {
Lang: "en",
},
},
DefaultBlog: "en",
User: &configUser{},
},
}
_ = app.initDatabase(false)
2021-09-02 12:49:10 +00:00
app.initComponents(false)
2021-06-19 06:37:16 +00:00
h := app.captchaMiddleware(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
2021-06-23 17:20:50 +00:00
_, _ = rw.Write([]byte("ABC Test"))
2021-06-19 06:37:16 +00:00
}))
t.Run("Default", func(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/abc", nil)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req.WithContext(context.WithValue(req.Context(), blogKey, "en")))
2021-06-19 06:37:16 +00:00
res := rec.Result()
resBody, _ := io.ReadAll(res.Body)
_ = res.Body.Close()
resString := string(resBody)
assert.Equal(t, http.StatusUnauthorized, res.StatusCode)
assert.Contains(t, res.Header.Get("Content-Type"), contenttype.HTML)
assert.Contains(t, resString, "name=captchamethod value=POST")
})
t.Run("Captcha session", func(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/abc", nil)
rec1 := httptest.NewRecorder()
session, _ := app.captchaSessions.Get(req, "c")
session.Values["captcha"] = true
2021-06-23 17:20:50 +00:00
_ = session.Save(req, rec1)
2021-06-19 06:37:16 +00:00
for _, cookie := range rec1.Result().Cookies() {
req.AddCookie(cookie)
}
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req)
res := rec2.Result()
resBody, _ := io.ReadAll(res.Body)
_ = res.Body.Close()
resString := string(resBody)
assert.Equal(t, http.StatusOK, res.StatusCode)
assert.Contains(t, resString, "ABC Test")
})
}