open-vault/http/testing.go

62 lines
1.3 KiB
Go
Raw Normal View History

2015-03-13 18:13:33 +00:00
package http
import (
"fmt"
2015-03-13 18:13:33 +00:00
"net"
"net/http"
"testing"
"golang.org/x/net/http2"
2015-03-13 18:13:33 +00:00
"github.com/hashicorp/vault/vault"
)
2015-04-19 20:17:25 +00:00
func TestListener(t *testing.T) (net.Listener, string) {
fail := func(format string, args ...interface{}) {
panic(fmt.Sprintf(format, args...))
}
if t != nil {
fail = t.Fatalf
}
2015-03-13 18:13:33 +00:00
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
fail("err: %s", err)
2015-03-13 18:13:33 +00:00
}
addr := "http://" + ln.Addr().String()
2015-04-19 20:17:25 +00:00
return ln, addr
}
2015-03-13 18:13:33 +00:00
2015-04-19 20:17:25 +00:00
func TestServerWithListener(t *testing.T, ln net.Listener, addr string, core *vault.Core) {
2015-03-29 23:14:54 +00:00
// Create a muxer to handle our requests so that we can authenticate
// for tests.
mux := http.NewServeMux()
mux.Handle("/_test/auth", http.HandlerFunc(testHandleAuth))
mux.Handle("/", Handler(core))
2015-03-13 18:13:33 +00:00
server := &http.Server{
Addr: ln.Addr().String(),
2015-03-29 23:14:54 +00:00
Handler: mux,
2015-03-13 18:13:33 +00:00
}
if err := http2.ConfigureServer(server, nil); err != nil {
t.Fatal(err)
}
2015-03-13 18:13:33 +00:00
go server.Serve(ln)
2015-04-19 20:17:25 +00:00
}
2015-03-13 18:13:33 +00:00
2015-04-19 20:17:25 +00:00
func TestServer(t *testing.T, core *vault.Core) (net.Listener, string) {
ln, addr := TestListener(t)
TestServerWithListener(t, ln, addr, core)
2015-03-13 18:13:33 +00:00
return ln, addr
}
2015-03-29 23:14:54 +00:00
func TestServerAuth(t *testing.T, addr string, token string) {
if _, err := http.Get(addr + "/_test/auth?token=" + token); err != nil {
t.Fatalf("error authenticating: %s", err)
}
}
func testHandleAuth(w http.ResponseWriter, req *http.Request) {
respondOk(w, nil)
}