From d48f4f556a3981bd9f0c17dfd8646a5bccb8a72b Mon Sep 17 00:00:00 2001 From: Jan-Lukas Else Date: Thu, 2 Sep 2021 14:49:10 +0200 Subject: [PATCH] More tests --- authentication_test.go | 2 +- blogstats_test.go | 2 +- captcha_test.go | 2 +- comments_test.go | 2 +- errors_test.go | 2 +- httpLogs_test.go | 105 ++++++++++++++++++++++++++++++++++++++++ main.go | 12 +++-- privateMode_test.go | 106 +++++++++++++++++++++++++++++++++++++++++ webmention_test.go | 2 +- 9 files changed, 225 insertions(+), 10 deletions(-) create mode 100644 httpLogs_test.go create mode 100644 privateMode_test.go diff --git a/authentication_test.go b/authentication_test.go index 43416df..a932e2e 100644 --- a/authentication_test.go +++ b/authentication_test.go @@ -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")) diff --git a/blogstats_test.go b/blogstats_test.go index d0db3a4..3cd36a1 100644 --- a/blogstats_test.go +++ b/blogstats_test.go @@ -43,7 +43,7 @@ func Test_blogStats(t *testing.T) { } _ = app.initDatabase(false) - app.initComponents() + app.initComponents(false) // Insert post diff --git a/captcha_test.go b/captcha_test.go index cbadc84..5cd855f 100644 --- a/captcha_test.go +++ b/captcha_test.go @@ -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")) diff --git a/comments_test.go b/comments_test.go index 2108675..4729567 100644 --- a/comments_test.go +++ b/comments_test.go @@ -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) { diff --git a/errors_test.go b/errors_test.go index 6e711c0..257667f 100644 --- a/errors_test.go +++ b/errors_test.go @@ -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) diff --git a/httpLogs_test.go b/httpLogs_test.go new file mode 100644 index 0000000..48f8f33 --- /dev/null +++ b/httpLogs_test.go @@ -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)) + } + }) + }) + +} diff --git a/main.go b/main.go index ed3cd72..33e0a55 100644 --- a/main.go +++ b/main.go @@ -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 - log.Println("Initialize components...") + 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,7 +172,9 @@ func (app *goBlog) initComponents() { app.initBlogStats() app.initSessions() // Log finish - log.Println("Initialized components") + if logging { + log.Println("Initialized components") + } } func (a *goBlog) logErrAndQuit(v ...interface{}) { diff --git a/privateMode_test.go b/privateMode_test.go new file mode 100644 index 0000000..4b3c5a6 --- /dev/null +++ b/privateMode_test.go @@ -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) + +} diff --git a/webmention_test.go b/webmention_test.go index 5cecdf6..ae52bed 100644 --- a/webmention_test.go +++ b/webmention_test.go @@ -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",