More tests

This commit is contained in:
Jan-Lukas Else 2021-09-02 14:49:10 +02:00
parent 33e9d53a93
commit d48f4f556a
9 changed files with 225 additions and 10 deletions

View File

@ -44,7 +44,7 @@ func Test_authMiddleware(t *testing.T) {
}
_ = app.initDatabase(false)
app.initComponents()
app.initComponents(false)
app.d = http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
_, _ = rw.Write([]byte("ABC Test"))

View File

@ -43,7 +43,7 @@ func Test_blogStats(t *testing.T) {
}
_ = app.initDatabase(false)
app.initComponents()
app.initComponents(false)
// Insert post

View File

@ -32,7 +32,7 @@ func Test_captchaMiddleware(t *testing.T) {
}
_ = app.initDatabase(false)
app.initComponents()
app.initComponents(false)
h := app.captchaMiddleware(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
_, _ = rw.Write([]byte("ABC Test"))

View File

@ -37,7 +37,7 @@ func Test_comments(t *testing.T) {
}
_ = app.initDatabase(false)
app.initComponents()
app.initComponents(false)
t.Run("Successful comment", func(t *testing.T) {

View File

@ -31,7 +31,7 @@ func Test_errors(t *testing.T) {
}
_ = app.initDatabase(false)
app.initComponents()
app.initComponents(false)
t.Run("Test 404, no HTML", func(t *testing.T) {
h := http.HandlerFunc(app.serve404)

105
httpLogs_test.go Normal file
View File

@ -0,0 +1,105 @@
package main
import (
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func initTestHttpLogs(logFile string) (http.Handler, error) {
app := &goBlog{
cfg: &config{
Server: &configServer{
Logging: true,
LogFile: logFile,
},
},
}
err := app.initHTTPLog()
if err != nil {
return nil, err
}
return app.logMiddleware(testHttpHandler()), nil
}
func testHttpHandler() http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
_, _ = rw.Write([]byte("Test"))
})
}
func Test_httpLogs(t *testing.T) {
// Init
logFile := filepath.Join(t.TempDir(), "access.log")
handler, err := initTestHttpLogs(logFile)
require.NoError(t, err)
// Do fake request
req := httptest.NewRequest(http.MethodGet, "/testpath", nil)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
// Check response
res := rec.Result()
resBody, _ := io.ReadAll(res.Body)
resBodyStr := string(resBody)
assert.Equal(t, http.StatusOK, res.StatusCode)
assert.Contains(t, resBodyStr, "Test")
// Check log
logBytes, err := os.ReadFile(logFile)
require.NoError(t, err)
logString := string(logBytes)
assert.Contains(t, logString, "GET /testpath")
}
func Benchmark_httpLogs(b *testing.B) {
// Init
logFile := filepath.Join(b.TempDir(), "access.log")
logHandler, err := initTestHttpLogs(logFile)
require.NoError(b, err)
noLogHandler := testHttpHandler()
// Run benchmarks
b.Run("With logging", func(b *testing.B) {
b.RunParallel(func(p *testing.PB) {
for p.Next() {
logHandler.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/testpath", nil))
}
})
})
b.Run("Without logging", func(b *testing.B) {
b.RunParallel(func(p *testing.PB) {
for p.Next() {
noLogHandler.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/testpath", nil))
}
})
})
}

View File

@ -116,7 +116,7 @@ func main() {
}
// Initialize components
app.initComponents()
app.initComponents(true)
// Start cron hooks
app.startHourlyHooks()
@ -132,10 +132,12 @@ func main() {
app.shutdown.Wait()
}
func (app *goBlog) initComponents() {
func (app *goBlog) initComponents(logging bool) {
var err error
// Log start
if logging {
log.Println("Initialize components...")
}
app.initMarkdown()
if err = app.initTemplateAssets(); err != nil { // Needs minify
app.logErrAndQuit("Failed to init template assets:", err.Error())
@ -170,8 +172,10 @@ func (app *goBlog) initComponents() {
app.initBlogStats()
app.initSessions()
// Log finish
if logging {
log.Println("Initialized components")
}
}
func (a *goBlog) logErrAndQuit(v ...interface{}) {
log.Println(v...)

106
privateMode_test.go Normal file
View File

@ -0,0 +1,106 @@
package main
import (
"io"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
"github.com/go-chi/chi/v5/middleware"
"github.com/justinas/alice"
"github.com/stretchr/testify/assert"
)
func Test_privateMode(t *testing.T) {
// Init
app := &goBlog{
cfg: &config{
Db: &configDb{
File: filepath.Join(t.TempDir(), "db.db"),
},
Server: &configServer{},
PrivateMode: &configPrivateMode{
Enabled: true,
},
User: &configUser{
Name: "Test",
Nick: "test",
Password: "testpw",
AppPasswords: []*configAppPassword{
{
Username: "testapp",
Password: "pw",
},
},
},
DefaultBlog: "en",
Blogs: map[string]*configBlog{
"en": {
Lang: "en",
},
},
},
}
_ = app.initDatabase(false)
app.initComponents(false)
handler := alice.New(middleware.WithValue(blogKey, "en"), app.privateModeHandler).ThenFunc(func(rw http.ResponseWriter, r *http.Request) {
_, _ = rw.Write([]byte("Awesome"))
})
// Test check
assert.True(t, app.isPrivate())
// Test successful request
req := httptest.NewRequest(http.MethodGet, "/test", nil)
req.SetBasicAuth("testapp", "pw")
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
res := rec.Result()
resBody, _ := io.ReadAll(res.Body)
resBodyStr := string(resBody)
assert.Equal(t, http.StatusOK, res.StatusCode)
assert.Equal(t, "Awesome", resBodyStr)
// Test unauthenticated request
req = httptest.NewRequest(http.MethodGet, "/test", nil)
rec = httptest.NewRecorder()
handler.ServeHTTP(rec, req)
res = rec.Result()
resBody, _ = io.ReadAll(res.Body)
resBodyStr = string(resBody)
assert.Equal(t, http.StatusOK, res.StatusCode) // Not 401, to be compatible with some apps
assert.NotEqual(t, "Awesome", resBodyStr)
assert.NotContains(t, resBodyStr, "Awesome")
assert.Contains(t, resBodyStr, "Login")
// Disable private mode
app.cfg.PrivateMode.Enabled = false
req = httptest.NewRequest(http.MethodGet, "/test", nil)
rec = httptest.NewRecorder()
handler.ServeHTTP(rec, req)
res = rec.Result()
resBody, _ = io.ReadAll(res.Body)
resBodyStr = string(resBody)
assert.Equal(t, http.StatusOK, res.StatusCode)
assert.Equal(t, "Awesome", resBodyStr)
}

View File

@ -29,7 +29,7 @@ func Test_webmentions(t *testing.T) {
}
_ = app.initDatabase(false)
app.initComponents()
app.initComponents(false)
_ = app.db.insertWebmention(&mention{
Source: "https://example.net/test",