Add unit test for themes

This commit is contained in:
Neale Pickett 2019-12-05 22:25:03 -07:00
parent 3eac94c70d
commit 430e44ce87
3 changed files with 50 additions and 13 deletions

View File

@ -4,6 +4,8 @@ import (
"github.com/namsral/flag" "github.com/namsral/flag"
"github.com/spf13/afero" "github.com/spf13/afero"
"log" "log"
"mime"
"net/http"
"time" "time"
) )
@ -37,17 +39,22 @@ func main() {
) )
stateFs := afero.NewBasePathFs(afero.NewOsFs(), *statePath) stateFs := afero.NewBasePathFs(afero.NewOsFs(), *statePath)
themeFs := afero.NewBasePathFs(afero.NewOsFs(), *themePath)
theme := NewTheme(*themePath) theme := NewTheme(themeFs)
state := NewState(stateFs) state := NewState(stateFs)
puzzles := NewMothballs(*puzzlePath) puzzles := NewMothballs(*puzzlePath)
go theme.Run(*refreshInterval)
go state.Run(*refreshInterval) go state.Run(*refreshInterval)
go puzzles.Run(*refreshInterval) go puzzles.Run(*refreshInterval)
log.Println("I would be binding to", *bindStr) // Add some MIME extensions
time.Sleep(1 * time.Second) // Doing this avoids decompressing a mothball entry twice per request
log.Print(state.Export("")) mime.AddExtensionType(".json", "application/json")
time.Sleep(19 * time.Second) mime.AddExtensionType(".zip", "application/zip")
http.HandleFunc("/", theme.staticHandler)
log.Printf("Listening on %s", *bindStr)
log.Fatal(http.ListenAndServe(*bindStr, nil))
} }

View File

@ -1,20 +1,18 @@
package main package main
import ( import (
"github.com/spf13/afero"
"net/http" "net/http"
"os"
"strings" "strings"
) )
type Theme struct { type Theme struct {
Component fs afero.Fs
} }
func NewTheme(baseDir string) *Theme { func NewTheme(fs afero.Fs) *Theme {
return &Theme{ return &Theme{
Component: Component{ fs: fs,
baseDir: baseDir,
},
} }
} }
@ -28,7 +26,7 @@ func (t *Theme) staticHandler(w http.ResponseWriter, req *http.Request) {
path = "/index.html" path = "/index.html"
} }
f, err := os.Open(t.path(path)) f, err := t.fs.Open(path)
if err != nil { if err != nil {
http.NotFound(w, req) http.NotFound(w, req)
return return

32
cmd/mothd/theme_test.go Normal file
View File

@ -0,0 +1,32 @@
package main
import (
"github.com/spf13/afero"
"net/http"
"net/http/httptest"
"testing"
)
func TestTheme(t *testing.T) {
fs := new(afero.MemMapFs)
afero.WriteFile(fs, "/index.html", []byte("index"), 0644)
afero.WriteFile(fs, "/moo.html", []byte("moo"), 0644)
s := NewTheme(fs)
req, err := http.NewRequest("GET", "/", nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
handler := http.HandlerFunc(s.staticHandler)
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Errorf("Handler returned wrong code: %v", rr.Code)
}
if rr.Body.String() != "index" {
t.Errorf("Handler returned wrong content: %v", rr.Body.String())
}
}