Skip to content

Commit

Permalink
eliminate global state in handlers/http_test.go
Browse files Browse the repository at this point in the history
  • Loading branch information
cryptix committed Feb 11, 2021
1 parent 7fa52a6 commit 431e917
Show file tree
Hide file tree
Showing 5 changed files with 87 additions and 88 deletions.
15 changes: 5 additions & 10 deletions web/handlers/admin/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,24 @@ package admin
import (
"net/http"

"github.com/gorilla/mux"
"go.mindeco.de/http/render"

"github.com/ssb-ngi-pointer/go-ssb-room/roomstate"
"github.com/ssb-ngi-pointer/go-ssb-room/web/router"
)

var HTMLTemplates = []string{
"/admin/dashboard.tmpl",
}

func Handler(m *mux.Router, r *render.Renderer, roomState *roomstate.Manager) http.Handler {
if m == nil {
m = router.Admin(nil)
}
// Handler supplies the elevated access pages to known users.
// It is not registering on the mux router like other pages to clean up the authorize flow.
func Handler(r *render.Renderer, roomState *roomstate.Manager) http.Handler {

m.Get(router.AdminDashboard).HandlerFunc(r.HTML("/admin/dashboard.tmpl", func(rw http.ResponseWriter, req *http.Request) (interface{}, error) {
return r.HTML("/admin/dashboard.tmpl", func(rw http.ResponseWriter, req *http.Request) (interface{}, error) {
lst := roomState.List()
return struct {
Clients []string
Count int
}{lst, len(lst)}, nil
}))

return m
})
}
11 changes: 4 additions & 7 deletions web/handlers/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ func New(
if err != nil {
return no
}

uid, ok := v.(int64)
if !ok {
// TODO: hook up logging
Expand Down Expand Up @@ -142,15 +143,11 @@ func New(
}

// hookup handlers to the router
news.Handler(m, r)
roomsAuth.Handler(m, r, a)

adminRouter := m.PathPrefix("/admin").Subrouter()
adminRouter.Use(a.Authenticate)

// we dont strip path here because it somehow fucks with the middleware setup
adminRouter.PathPrefix("/").Handler(admin.Handler(adminRouter, r, roomState))

m.PathPrefix("/news").Handler(http.StripPrefix("/news", news.Handler(m, r)))
adminHandler := a.Authenticate(admin.Handler(r, roomState))
m.PathPrefix("/admin").Handler(adminHandler)

m.Get(router.CompleteIndex).Handler(r.StaticHTML("/landing/index.tmpl"))
m.Get(router.CompleteAbout).Handler(r.StaticHTML("/landing/about.tmpl"))
Expand Down
89 changes: 50 additions & 39 deletions web/handlers/http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,14 @@ import (
)

func TestIndex(t *testing.T) {
setup(t)
t.Cleanup(teardown)
ts := setup(t)

a := assert.New(t)
r := require.New(t)

url, err := testRouter.Get(router.CompleteIndex).URL()
url, err := ts.Router.Get(router.CompleteIndex).URL()
r.Nil(err)
html, resp := testClient.GetHTML(url.String(), nil)
html, resp := ts.Client.GetHTML(url.String(), nil)
a.Equal(http.StatusOK, resp.Code, "wrong HTTP status code")
assertLocalized(t, html, []localizedElement{
{"#welcome", "LandingWelcome"},
Expand All @@ -40,36 +39,36 @@ func TestIndex(t *testing.T) {
}

func TestAbout(t *testing.T) {
setup(t)
t.Cleanup(teardown)
ts := setup(t)

a := assert.New(t)
r := require.New(t)

url, err := testRouter.Get(router.CompleteAbout).URL()
url, err := ts.Router.Get(router.CompleteAbout).URL()
r.Nil(err)
html, resp := testClient.GetHTML(url.String(), nil)
html, resp := ts.Client.GetHTML(url.String(), nil)
a.Equal(http.StatusOK, resp.Code, "wrong HTTP status code")
found := html.Find("h1").Text()
a.Equal("The about page", found)
}

func TestNotFound(t *testing.T) {
setup(t)
t.Cleanup(teardown)
ts := setup(t)

a := assert.New(t)

html, resp := testClient.GetHTML("/some/random/ASDKLANZXC", nil)
html, resp := ts.Client.GetHTML("/some/random/ASDKLANZXC", nil)
a.Equal(http.StatusNotFound, resp.Code, "wrong HTTP status code")
found := html.Find("h1").Text()
a.Equal("Error #404 - Not Found", found)
}

func TestNewsRegisterd(t *testing.T) {
setup(t)
t.Cleanup(teardown)
ts := setup(t)

a := assert.New(t)

html, resp := testClient.GetHTML("/news/", nil)
html, resp := ts.Client.GetHTML("/news/", nil)
a.Equal(http.StatusOK, resp.Code, "wrong HTTP status code")
assertLocalized(t, html, []localizedElement{
{"#welcome", "NewsWelcome"},
Expand All @@ -78,24 +77,32 @@ func TestNewsRegisterd(t *testing.T) {
}

func TestRestricted(t *testing.T) {
setup(t)
t.Cleanup(teardown)
ts := setup(t)

a := assert.New(t)

html, resp := testClient.GetHTML("/admin/", nil)
a.Equal(http.StatusUnauthorized, resp.Code, "wrong HTTP status code")
found := html.Find("h1").Text()
a.Equal("Error #401 - Unauthorized", found)
testURLs := []string{
// "/admin/",
"/admin/admin",
"/admin/admin/",
}

for _, turl := range testURLs {
html, resp := ts.Client.GetHTML(turl, nil)
a.Equal(http.StatusUnauthorized, resp.Code, "wrong HTTP status code for %q", turl)
found := html.Find("h1").Text()
a.Equal("Error #401 - Unauthorized", found, "wrong error message code for %q", turl)
}
}

func TestLoginForm(t *testing.T) {
setup(t)
t.Cleanup(teardown)
ts := setup(t)

a, r := assert.New(t), require.New(t)

url, err := testRouter.Get(router.AuthFallbackSignInForm).URL()
url, err := ts.Router.Get(router.AuthFallbackSignInForm).URL()
r.Nil(err)
html, resp := testClient.GetHTML(url.String(), nil)
html, resp := ts.Client.GetHTML(url.String(), nil)
a.Equal(http.StatusOK, resp.Code, "wrong HTTP status code")

assertLocalized(t, html, []localizedElement{
Expand All @@ -105,25 +112,25 @@ func TestLoginForm(t *testing.T) {
}

func TestFallbackAuth(t *testing.T) {
setup(t)
t.Cleanup(teardown)
ts := setup(t)

a, r := assert.New(t), require.New(t)

loginVals := url.Values{
"user": []string{"test"},
"pass": []string{"test"},
}
testAuthFallbackDB.CheckReturns(int64(23), nil)
ts.AuthFallbackDB.CheckReturns(int64(23), nil)

url, err := testRouter.Get(router.AuthFallbackSignInForm).URL()
url, err := ts.Router.Get(router.AuthFallbackSignIn).URL()
r.Nil(err)
url.Host = "localhost"
url.Scheme = "http"

resp := testClient.PostForm(url.String(), loginVals)
a.Equal(http.StatusSeeOther, resp.Code, "wrong HTTP status code")
resp := ts.Client.PostForm(url.String(), loginVals)
a.Equal(http.StatusSeeOther, resp.Code, "wrong HTTP status code for sign in")

a.Equal(1, testAuthFallbackDB.CheckCallCount())
a.Equal(1, ts.AuthFallbackDB.CheckCallCount())

// very cheap client session
jar, err := cookiejar.New(nil)
Expand All @@ -134,7 +141,7 @@ func TestFallbackAuth(t *testing.T) {

var h = http.Header(map[string][]string{})

dashboardURL, err := testRouter.Get(router.AdminDashboard).URL()
dashboardURL, err := ts.Router.Get(router.AdminDashboard).URL()
r.Nil(err)
dashboardURL.Host = "localhost"
dashboardURL.Scheme = "http"
Expand All @@ -144,9 +151,13 @@ func TestFallbackAuth(t *testing.T) {
theCookie := cs[0].String()
a.NotEqual("", theCookie, "should have a new cookie")
h.Set("Cookie", theCookie)

html, resp := testClient.GetHTML(dashboardURL.String(), &h)
if !a.Equal(http.StatusOK, resp.Code, "wrong HTTP status code") {
// t.Log(h)
// durl := dashboardURL.String()
durl := "http://localhost/admin"
// durl := "/admin"
t.Log(durl)
html, resp := ts.Client.GetHTML(durl, &h)
if !a.Equal(http.StatusOK, resp.Code, "wrong HTTP status code for dashboard") {
t.Log(html.Find("body").Text())
}

Expand All @@ -156,9 +167,9 @@ func TestFallbackAuth(t *testing.T) {
})

testRef := refs.FeedRef{Algo: "test", ID: bytes.Repeat([]byte{0}, 16)}
testRoomState.AddEndpoint(testRef, nil)
ts.RoomState.AddEndpoint(testRef, nil)

html, resp = testClient.GetHTML(dashboardURL.String(), &h)
html, resp = ts.Client.GetHTML(durl, &h)
if !a.Equal(http.StatusOK, resp.Code, "wrong HTTP status code") {
t.Log(html.Find("body").Text())
}
Expand All @@ -170,9 +181,9 @@ func TestFallbackAuth(t *testing.T) {
})

testRef2 := refs.FeedRef{Algo: "test", ID: bytes.Repeat([]byte{1}, 16)}
testRoomState.AddEndpoint(testRef2, nil)
ts.RoomState.AddEndpoint(testRef2, nil)

html, resp = testClient.GetHTML(dashboardURL.String(), &h)
html, resp = ts.Client.GetHTML(durl, &h)
a.Equal(http.StatusOK, resp.Code, "wrong HTTP status code")

t.Log(html.Find("body").Text())
Expand Down
55 changes: 26 additions & 29 deletions web/handlers/setup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,33 +12,34 @@ import (
"path/filepath"
"testing"

"github.com/ssb-ngi-pointer/go-ssb-room/roomstate"

"github.com/BurntSushi/toml"
"github.com/gorilla/mux"
"go.mindeco.de/http/tester"
"go.mindeco.de/logging/logtest"

"github.com/ssb-ngi-pointer/go-ssb-room/admindb/mockdb"
"github.com/ssb-ngi-pointer/go-ssb-room/internal/repo"
"github.com/ssb-ngi-pointer/go-ssb-room/roomstate"
"github.com/ssb-ngi-pointer/go-ssb-room/web/i18n"
"github.com/ssb-ngi-pointer/go-ssb-room/web/router"
)

var (
testMux *http.ServeMux
testClient *tester.Tester
testRouter = router.CompleteApp()
type testSession struct {
Mux *http.ServeMux
Client *tester.Tester
Router *mux.Router

// mocked dbs
testAuthDB *mockdb.FakeAuthWithSSBService
testAuthFallbackDB *mockdb.FakeAuthFallbackService
AuthDB *mockdb.FakeAuthWithSSBService
AuthFallbackDB *mockdb.FakeAuthFallbackService

testRoomState *roomstate.Manager
RoomState *roomstate.Manager
}

testI18N = justTheKeys()
)
var testI18N = justTheKeys()

func setup(t *testing.T) {
func setup(t *testing.T) *testSession {
var ts testSession

testRepoPath := filepath.Join("testrun", t.Name())
os.RemoveAll(testRepoPath)
Expand All @@ -51,35 +52,31 @@ func setup(t *testing.T) {
t.Fatal(err)
}

testAuthDB = new(mockdb.FakeAuthWithSSBService)
testAuthFallbackDB = new(mockdb.FakeAuthFallbackService)
ts.AuthDB = new(mockdb.FakeAuthWithSSBService)
ts.AuthFallbackDB = new(mockdb.FakeAuthFallbackService)

log, _ := logtest.KitLogger("complete", t)
ctx := context.TODO()
testRoomState = roomstate.NewManager(ctx, log)
ts.RoomState = roomstate.NewManager(ctx, log)

ts.Router = router.CompleteApp()

h, err := New(
testRouter,
ts.Router,
testRepo,
testRoomState,
testAuthDB,
testAuthFallbackDB,
ts.RoomState,
ts.AuthDB,
ts.AuthFallbackDB,
)
if err != nil {
t.Fatal("setup: handler init failed:", err)
}

testMux = http.NewServeMux()
testMux.Handle("/", h)
testClient = tester.New(testMux, t)
}
ts.Mux = http.NewServeMux()
ts.Mux.Handle("/", h)
ts.Client = tester.New(ts.Mux, t)

func teardown() {
testMux = nil
testClient = nil
testAuthDB = nil
testAuthFallbackDB = nil
testRoomState = nil
return &ts
}

// auto generate from defaults a list of Label = "Label"
Expand Down
5 changes: 2 additions & 3 deletions web/router/admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,8 @@ func Admin(m *mux.Router) *mux.Router {
m = mux.NewRouter()
}

// we dont strip path here because it somehow fucks with the middleware setup
m.Path("/admin").Methods("GET").Name(AdminDashboard)
// m.Path("/admin/settings").Methods("GET").Name(AdminSettings)
m.Path("/").Methods("GET").Name(AdminDashboard)
// m.Path("/settings").Methods("GET").Name(AdminSettings)

return m
}

0 comments on commit 431e917

Please sign in to comment.