GoBlog/errors_test.go

116 lines
2.7 KiB
Go
Raw Normal View History

2021-06-19 06:37:16 +00:00
package main
import (
"io"
"net/http"
"net/http/httptest"
2021-07-24 11:41:07 +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_errors(t *testing.T) {
app := &goBlog{
cfg: &config{
2021-07-24 11:41:07 +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{},
},
}
2021-07-24 11:41:07 +00:00
_ = app.initDatabase(false)
2021-09-02 12:49:10 +00:00
app.initComponents(false)
2021-06-19 06:37:16 +00:00
t.Run("Test 404, no HTML", func(t *testing.T) {
h := http.HandlerFunc(app.serve404)
req := httptest.NewRequest(http.MethodGet, "/abc", nil)
req.Header.Set("Accept", contenttype.JSON)
rec := httptest.NewRecorder()
h(rec, req)
res := rec.Result()
resBody, _ := io.ReadAll(res.Body)
_ = res.Body.Close()
resString := string(resBody)
assert.Equal(t, http.StatusNotFound, res.StatusCode)
assert.Contains(t, resString, "not found")
assert.Contains(t, res.Header.Get("Content-Type"), "text/plain")
})
t.Run("Test 404, HTML", func(t *testing.T) {
h := http.HandlerFunc(app.serve404)
req := httptest.NewRequest(http.MethodGet, "/abc", nil)
req.Header.Set("Accept", contenttype.HTML)
rec := httptest.NewRecorder()
h(rec, req)
res := rec.Result()
resBody, _ := io.ReadAll(res.Body)
_ = res.Body.Close()
resString := string(resBody)
assert.Equal(t, http.StatusNotFound, res.StatusCode)
assert.Contains(t, resString, "not found")
assert.Contains(t, res.Header.Get("Content-Type"), contenttype.HTML)
})
t.Run("Test Method Not Allowed, no HTML", func(t *testing.T) {
h := http.HandlerFunc(app.serveNotAllowed)
req := httptest.NewRequest(http.MethodGet, "/abc", nil)
req.Header.Set("Accept", contenttype.JSON)
rec := httptest.NewRecorder()
h(rec, req)
res := rec.Result()
resBody, _ := io.ReadAll(res.Body)
_ = res.Body.Close()
resString := string(resBody)
assert.Equal(t, http.StatusMethodNotAllowed, res.StatusCode)
assert.Contains(t, resString, "Method Not Allowed")
assert.Contains(t, res.Header.Get("Content-Type"), "text/plain")
})
t.Run("Test Method Not Allowed", func(t *testing.T) {
h := http.HandlerFunc(app.serveNotAllowed)
req := httptest.NewRequest(http.MethodGet, "/abc", nil)
req.Header.Set("Accept", contenttype.HTML)
rec := httptest.NewRecorder()
h(rec, req)
res := rec.Result()
resBody, _ := io.ReadAll(res.Body)
_ = res.Body.Close()
resString := string(resBody)
assert.Equal(t, http.StatusMethodNotAllowed, res.StatusCode)
assert.Contains(t, resString, "Method Not Allowed")
assert.Contains(t, res.Header.Get("Content-Type"), contenttype.HTML)
})
}