Skip to content

Commit

Permalink
Add some tests for modified Static.
Browse files Browse the repository at this point in the history
  • Loading branch information
apghero committed Mar 27, 2019
1 parent f08d548 commit df5afa7
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
4 changes: 4 additions & 0 deletions handler/misc.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,10 @@ func Ready(ms storage.MetricStore) http.Handler {
//
// The returned handler is already instrumented for Prometheus.
func Static(root http.FileSystem, prefix string) http.Handler {
if prefix == "/" {
prefix = ""
}

handler := http.FileServer(root)
return promhttp.InstrumentHandlerCounter(
httpCnt.MustCurryWith(prometheus.Labels{"handler": "static"}),
Expand Down
62 changes: 62 additions & 0 deletions handler/misc_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package handler

import (
"fmt"
"log"
"net/http"
"net/http/httptest"
"os"
"testing"
)

type fakeFileSystem struct {
files map[string]struct{}
}

// Open implements the http.FileSystem interface
//
// If a file is present, no error will be returned.
// This implementation always returns a nil File.
func (f *fakeFileSystem) Open(name string) (http.File, error) {
log.Println("requesting" + name)

if _, ok := f.files[name]; !ok {
return nil, os.ErrNotExist
}
return os.Open("misc_test.go")
// return nil, nil
}

func TestRoutePrefixForStatic(t *testing.T) {
fs := &fakeFileSystem{map[string]struct{}{
"/index.js": struct{}{},
}}

for _, test := range []struct {
prefix string
path string
code int
}{
{"/", "/index.js", 200},
{"/", "/missing.js", 404},
{"/route-prefix", "/index.js", 200},
{"/route-prefix", "/missing.js", 404},
} {
test := test
t.Run(fmt.Sprintf("%v", test), func(t *testing.T) {
t.Parallel()
req, err := http.NewRequest(
http.MethodGet, "http://example.com"+test.prefix+test.path, nil,
)
if err != nil {
t.Fatal(err)
}
w := httptest.NewRecorder()
static := Static(fs, test.prefix)
static.ServeHTTP(w, req)
if test.code != w.Code {
t.Errorf("Wanted %d, got %d.", test.code, w.Code)
}
})
}
}

0 comments on commit df5afa7

Please sign in to comment.