Added controller testing.

This commit is contained in:
mikestefanello 2021-12-05 20:22:45 -05:00
parent 7f93fa7f6c
commit 5e384c8a4e
7 changed files with 105 additions and 16 deletions

17
controllers/about_test.go Normal file
View file

@ -0,0 +1,17 @@
package controllers
import (
"net/http"
"testing"
"github.com/stretchr/testify/assert"
)
func TestAbout_Get(t *testing.T) {
resp := GetRequest(t, "about")
assert.Equal(t, http.StatusOK, resp.StatusCode)
doc := GetGoqueryDoc(t, resp)
h1 := doc.Find("h1.title")
assert.Len(t, h1.Nodes, 1)
assert.Equal(t, "About", h1.Text())
}

View file

@ -5,6 +5,9 @@ import (
"fmt"
"html/template"
"net/http"
"path"
"path/filepath"
"runtime"
"sync"
"goweb/config"
@ -25,6 +28,8 @@ var (
// Template function map
funcMap = funcmap.GetFuncMap()
templatePath = getTemplatesDirectoryPath()
)
type Controller struct {
@ -74,15 +79,15 @@ func (t *Controller) parsePageTemplates(p Page) error {
template.New(p.Layout+TemplateExt).
Funcs(funcMap).
ParseFiles(
fmt.Sprintf("%s/layouts/%s%s", TemplateDir, p.Layout, TemplateExt),
fmt.Sprintf("%s/pages/%s%s", TemplateDir, p.Name, TemplateExt),
fmt.Sprintf("%s/layouts/%s%s", templatePath, p.Layout, TemplateExt),
fmt.Sprintf("%s/pages/%s%s", templatePath, p.Name, TemplateExt),
)
if err != nil {
return err
}
parsed, err = parsed.ParseGlob(fmt.Sprintf("%s/components/*%s", TemplateDir, TemplateExt))
parsed, err = parsed.ParseGlob(fmt.Sprintf("%s/components/*%s", templatePath, TemplateExt))
if err != nil {
return err
@ -98,3 +103,12 @@ func (t *Controller) parsePageTemplates(p Page) error {
func (t *Controller) Redirect(c echo.Context, route string, routeParams ...interface{}) error {
return c.Redirect(http.StatusFound, c.Echo().Reverse(route, routeParams))
}
// getTemplatesDirectoryPath gets the templates directory path
// This is needed incase this is called from a package outside of main,
// such as testing
func getTemplatesDirectoryPath() string {
_, b, _, _ := runtime.Caller(0)
d := path.Join(path.Dir(b))
return filepath.Join(filepath.Dir(d), TemplateDir)
}

View file

@ -0,0 +1,48 @@
package controllers
import (
"net/http"
"net/http/httptest"
"os"
"testing"
"goweb/container"
"github.com/PuerkitoBio/goquery"
"github.com/stretchr/testify/assert"
"github.com/labstack/gommon/log"
"github.com/stretchr/testify/require"
)
var (
srv *httptest.Server
c *container.Container
)
func TestMain(m *testing.M) {
// Start a test HTTP server
c = container.NewContainer()
BuildRouter(c)
c.Web.Logger.SetLevel(log.DEBUG)
srv = httptest.NewServer(c.Web)
exitVal := m.Run()
srv.Close()
os.Exit(exitVal)
}
func GetRequest(t *testing.T, route string, routeParams ...interface{}) *http.Response {
cli := http.Client{}
resp, err := cli.Get(srv.URL + c.Web.Reverse(route, routeParams))
require.NoError(t, err)
return resp
}
func GetGoqueryDoc(t *testing.T, resp *http.Response) *goquery.Document {
doc, err := goquery.NewDocumentFromReader(resp.Body)
require.NoError(t, err)
err = resp.Body.Close()
assert.NoError(t, err)
return doc
}

70
controllers/router.go Normal file
View file

@ -0,0 +1,70 @@
package controllers
import (
"net/http"
"goweb/middleware"
"github.com/gorilla/sessions"
"github.com/labstack/echo-contrib/session"
"github.com/labstack/echo/v4"
echomw "github.com/labstack/echo/v4/middleware"
"goweb/container"
)
const StaticDir = "static"
func BuildRouter(c *container.Container) {
// Middleware
c.Web.Use(echomw.RemoveTrailingSlashWithConfig(echomw.TrailingSlashConfig{
RedirectCode: http.StatusMovedPermanently,
}))
c.Web.Use(echomw.RequestID())
c.Web.Use(echomw.Recover())
c.Web.Use(echomw.Gzip())
c.Web.Use(echomw.Logger())
c.Web.Use(session.Middleware(sessions.NewCookieStore([]byte(c.Config.App.EncryptionKey))))
c.Web.Use(echomw.CSRFWithConfig(echomw.CSRFConfig{
TokenLookup: "form:csrf",
}))
// Static files with proper cache control
// funcmap.File() should be used in templates to append a cache key to the URL in order to break cache
// after each server restart
c.Web.Group("", middleware.CacheControl(15552000)).
Static("/", StaticDir)
// Base controller
ctr := NewController(c)
// Error handler
err := Error{Controller: ctr}
c.Web.HTTPErrorHandler = err.Get
// Routes
navRoutes(c.Web, ctr)
userRoutes(c.Web, ctr)
}
func navRoutes(e *echo.Echo, ctr Controller) {
home := Home{Controller: ctr}
e.GET("/", home.Get).Name = "home"
about := About{Controller: ctr}
e.GET("/about", about.Get).Name = "about"
contact := Contact{Controller: ctr}
e.GET("/contact", contact.Get).Name = "contact"
e.POST("/contact", contact.Post).Name = "contact.post"
}
func userRoutes(e *echo.Echo, ctr Controller) {
login := Login{Controller: ctr}
e.GET("/user/login", login.Get).Name = "login"
e.POST("/user/login", login.Post).Name = "login.post"
register := Register{Controller: ctr}
e.GET("/user/register", register.Get).Name = "register"
e.POST("/user/register", register.Post).Name = "register.post"
}