Ejemplo n.º 1
0
func TestMuxContextMakerError(t *testing.T) {
	givenErr := errors.New("")
	var actualErr error
	mux, err := ctxmux.New(
		ctxmux.MuxContextMaker(func(r *http.Request) (context.Context, error) {
			return nil, givenErr
		}),
		ctxmux.MuxErrorHandler(
			func(ctx context.Context, w http.ResponseWriter, r *http.Request, err error) {
				ensure.DeepEqual(t, ctx, context.Background())
				actualErr = err
			}),
	)
	ensure.Nil(t, err)
	hw := httptest.NewRecorder()
	hr := &http.Request{
		Method: "GET",
		URL: &url.URL{
			Path: "/",
		},
	}
	mux.GET(hr.URL.Path, func(context.Context, http.ResponseWriter, *http.Request) error {
		panic("not reached")
	})
	mux.ServeHTTP(hw, hr)
	ensure.DeepEqual(t, actualErr, givenErr)
}
Ejemplo n.º 2
0
func TestServeCombinedURLWithExt(t *testing.T) {
	contents := [][]byte{
		[]byte("foo"),
		[]byte("bar"),
	}
	var count int
	h := Handler{
		Path: "/",
		Box: funcBox(func(name string) ([]byte, error) {
			defer func() { count++ }()
			return contents[count], nil
		}),
	}
	v, err := h.URL("n1.js", "n2")
	ensure.Nil(t, err)
	ensure.DeepEqual(t, v, "/W1sibjEuanMiLCJhY2JkMThkYiJdLFsibjIiLCIzN2I1MWQxOSJdXQ.js")
	w := httptest.NewRecorder()
	r := &http.Request{
		URL: &url.URL{
			Path: v,
		},
	}
	h.ServeHTTP(w, r)
	ensure.DeepEqual(t, w.Code, http.StatusOK)
	ensure.DeepEqual(t, w.Body.String(), "foobar")
	ensure.DeepEqual(t, w.Header(), http.Header{
		"Content-Length": []string{"6"},
		"Cache-Control":  []string{cacheControl},
		"Content-Type":   []string{"application/javascript"},
	})
}
Ejemplo n.º 3
0
func TestWrapExistingMultiStackError(t *testing.T) {
	err := &multiStackError{
		multiStack: new(stack.Multi),
	}
	we := Wrap(context.Background(), err)
	ensure.DeepEqual(t, we, err)
	ensure.DeepEqual(t, len(err.multiStack.Stacks()), 1)
}
Ejemplo n.º 4
0
func TestWrapNewSingleFrame(t *testing.T) {
	err := errors.New("")
	config := Config{StackMode: StackModeSingleFrame}
	ctx := WithConfig(context.Background(), config)
	we := Wrap(ctx, err).(*singleFrameError)
	ensure.DeepEqual(t, we.config, config)
	ensure.DeepEqual(t, we.underlying, err)
	ensure.DeepEqual(t, we.frame.Name, "TestWrapNewSingleFrame")
}
Ejemplo n.º 5
0
func TestWrapNewMultiStackError(t *testing.T) {
	err := errors.New("")
	config := Config{StackMode: StackModeMultiStack}
	ctx := WithConfig(context.Background(), config)
	we := Wrap(ctx, err).(*multiStackError)
	ensure.DeepEqual(t, we.config, config)
	ensure.DeepEqual(t, we.underlying, err)
	ensure.DeepEqual(t, we.multiStack.Stacks()[0][0].Name, "TestWrapNewMultiStackError")
}
Ejemplo n.º 6
0
func TestSimple(t *testing.T) {
	t.Parallel()
	var out bytes.Buffer
	w := htmlwriter.New(&out)
	const original = "hello & world"
	n, err := w.Write([]byte(original))
	ensure.Nil(t, err)
	ensure.DeepEqual(t, n, 17)
	ensure.DeepEqual(t, out.String(), html.EscapeString(original))
}
Ejemplo n.º 7
0
func TestPrefixClient(t *testing.T) {
	const (
		prefix1      = "prefix1"
		prefix2      = "prefix2"
		avgKey       = "avg"
		avgVal       = float64(1)
		sumKey       = "sum"
		sumVal       = float64(2)
		histogramKey = "histogram"
		histogramVal = float64(3)
		timeKey      = "time"
	)

	var keys []string
	hc := &stats.HookClient{
		BumpAvgHook: func(key string, val float64) {
			keys = append(keys, key)
			ensure.DeepEqual(t, val, avgVal)
		},
		BumpSumHook: func(key string, val float64) {
			keys = append(keys, key)
			ensure.DeepEqual(t, val, sumVal)
		},
		BumpHistogramHook: func(key string, val float64) {
			keys = append(keys, key)
			ensure.DeepEqual(t, val, histogramVal)
		},
		BumpTimeHook: func(key string) interface {
			End()
		} {
			return multiEnderTest{
				EndHook: func() {
					keys = append(keys, key)
				},
			}
		},
	}

	pc := stats.PrefixClient([]string{prefix1, prefix2}, hc)
	pc.BumpAvg(avgKey, avgVal)
	pc.BumpSum(sumKey, sumVal)
	pc.BumpHistogram(histogramKey, histogramVal)
	pc.BumpTime(timeKey).End()

	ensure.SameElements(t, keys, []string{
		prefix1 + avgKey,
		prefix1 + sumKey,
		prefix1 + histogramKey,
		prefix1 + timeKey,
		prefix2 + avgKey,
		prefix2 + sumKey,
		prefix2 + histogramKey,
		prefix2 + timeKey,
	})
}
Ejemplo n.º 8
0
func TestRestAPIKeyModify(t *testing.T) {
	t.Parallel()
	var req http.Request
	k := parse.RestAPIKey{
		ApplicationID: defaultApplicationID,
		RestAPIKey:    "42",
	}
	ensure.Nil(t, k.Modify(&req))
	ensure.DeepEqual(t, req.Header.Get("X-Parse-Application-ID"), k.ApplicationID)
	ensure.DeepEqual(t, req.Header.Get("X-Parse-REST-API-Key"), k.RestAPIKey)
}
Ejemplo n.º 9
0
func TestHTTPHandlerFunc(t *testing.T) {
	w := httptest.NewRecorder()
	r := &http.Request{}
	var actualW http.ResponseWriter
	var actualR *http.Request
	h := ctxmux.HTTPHandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		actualW = w
		actualR = r
	})
	ensure.Nil(t, h(nil, w, r))
	ensure.DeepEqual(t, actualW, w)
	ensure.DeepEqual(t, actualR, r)
}
Ejemplo n.º 10
0
func TestSessionTokenModify(t *testing.T) {
	t.Parallel()
	st := parse.SessionToken{
		ApplicationID: defaultApplicationID,
		RestAPIKey:    "42",
		SessionToken:  "43",
	}
	var req http.Request
	ensure.Nil(t, st.Modify(&req))
	ensure.DeepEqual(t, req.Header.Get("X-Parse-Application-ID"), st.ApplicationID)
	ensure.DeepEqual(t, req.Header.Get("X-Parse-REST-API-Key"), st.RestAPIKey)
	ensure.DeepEqual(t, req.Header.Get("X-Parse-Session-Token"), st.SessionToken)
}
Ejemplo n.º 11
0
func TestServeInvalidData(t *testing.T) {
	h := Handler{Path: "/"}
	w := httptest.NewRecorder()
	r := &http.Request{
		URL: &url.URL{
			Path: "/bar",
		},
	}
	h.ServeHTTP(w, r)
	ensure.DeepEqual(t, w.Code, http.StatusBadRequest)
	ensureDisableCaching(t, w.Header())
	ensure.DeepEqual(t, w.Body.String(), http.StatusText(http.StatusBadRequest))
}
Ejemplo n.º 12
0
func TestAFewFlags(t *testing.T) {
	const name = "TestAFewFlags"
	s := flag.NewFlagSet(name, flag.PanicOnError)
	const foo = "42"
	const bar = int(43)
	fooActual := s.String("foo", "", "")
	barActual := s.Int("bar", 0, "")
	os.Setenv(named(name, "foo"), foo)
	os.Setenv(named(name, "bar"), fmt.Sprint(bar))
	ensure.Nil(t, flagenv.ParseSet(name, s))
	ensure.DeepEqual(t, *fooActual, foo)
	ensure.DeepEqual(t, *barActual, bar)
}
Ejemplo n.º 13
0
func TestHTTPStopWithFinishedRequest(t *testing.T) {
	t.Parallel()
	hello := []byte("hello")
	fin := make(chan struct{})
	okHandler := func(w http.ResponseWriter, r *http.Request) {
		defer close(fin)
		w.Write(hello)
	}

	listener, err := net.Listen("tcp", "127.0.0.1:0")
	ensure.Nil(t, err)
	server := &http.Server{Handler: http.HandlerFunc(okHandler)}
	transport := &http.Transport{}
	client := &http.Client{Transport: transport}
	down := &httpdown.HTTP{}
	s := down.Serve(server, listener)
	res, err := client.Get(fmt.Sprintf("http://%s/", listener.Addr().String()))
	ensure.Nil(t, err)
	actualBody, err := ioutil.ReadAll(res.Body)
	ensure.Nil(t, err)
	ensure.DeepEqual(t, actualBody, hello)
	ensure.Nil(t, res.Body.Close())

	// At this point the request is finished, and the connection should be alive
	// but idle (because we have keep alive enabled by default in our Transport).
	ensure.Nil(t, s.Stop())
	<-fin

	ensure.Nil(t, s.Wait())
}
Ejemplo n.º 14
0
func TestLoadFromBox(t *testing.T) {
	const magic = "foo"
	h := Handler{
		Box: funcBox(func(name string) ([]byte, error) {
			ensure.DeepEqual(t, name, magic)
			return []byte(magic), nil
		}),
	}
	f, err := h.load(magic)
	ensure.Nil(t, err)
	ensure.DeepEqual(t, f, file{
		Name:    magic,
		Content: []byte(magic),
		Hash:    "acbd18db",
	})
}
Ejemplo n.º 15
0
func TestMultiStackSingleStack(t *testing.T) {
	frame := stack.Frame{Name: "42"}
	s := stack.Stack{frame}
	var multi stack.Multi
	multi.Add(s)
	ensure.DeepEqual(t, MultiStack(&singleStackError{stack: s}), &multi)
}
Ejemplo n.º 16
0
func TestStackMultiStack(t *testing.T) {
	frame := stack.Frame{Name: "42"}
	s := stack.Stack{frame}
	var multi stack.Multi
	multi.Add(s)
	ensure.DeepEqual(t, Stack(&multiStackError{multiStack: &multi}), s)
}
Ejemplo n.º 17
0
func TestCustomAppID(t *testing.T) {
	t.Parallel()
	values := url.Values{}
	values.Add("appid", "123")
	_, ctx := fromValues(t, values)
	ensure.DeepEqual(t, rellenv.FbApp(ctx).ID(), uint64(123))
}
Ejemplo n.º 18
0
func TestExistingConnState(t *testing.T) {
	t.Parallel()
	hello := []byte("hello")
	fin := make(chan struct{})
	okHandler := func(w http.ResponseWriter, r *http.Request) {
		defer close(fin)
		w.Write(hello)
	}

	var called int32
	listener, err := net.Listen("tcp", "127.0.0.1:0")
	ensure.Nil(t, err)
	server := &http.Server{
		Handler: http.HandlerFunc(okHandler),
		ConnState: func(c net.Conn, s http.ConnState) {
			atomic.AddInt32(&called, 1)
		},
	}
	transport := &http.Transport{}
	client := &http.Client{Transport: transport}
	down := &httpdown.HTTP{}
	s := down.Serve(server, listener)
	res, err := client.Get(fmt.Sprintf("http://%s/", listener.Addr().String()))
	ensure.Nil(t, err)
	actualBody, err := ioutil.ReadAll(res.Body)
	ensure.Nil(t, err)
	ensure.DeepEqual(t, actualBody, hello)
	ensure.Nil(t, res.Body.Close())

	ensure.Nil(t, s.Stop())
	<-fin

	ensure.True(t, atomic.LoadInt32(&called) > 0)
}
Ejemplo n.º 19
0
func TestHTTPWithinStopTimeout(t *testing.T) {
	t.Parallel()
	hello := []byte("hello")
	finOkHandler := make(chan struct{})
	okHandler := func(w http.ResponseWriter, r *http.Request) {
		defer close(finOkHandler)
		w.WriteHeader(200)
		w.Write(hello)
	}

	listener, err := net.Listen("tcp", "127.0.0.1:0")
	ensure.Nil(t, err)
	server := &http.Server{Handler: http.HandlerFunc(okHandler)}
	transport := &http.Transport{}
	client := &http.Client{Transport: transport}
	down := &httpdown.HTTP{StopTimeout: time.Minute}
	s := down.Serve(server, listener)
	res, err := client.Get(fmt.Sprintf("http://%s/", listener.Addr().String()))
	ensure.Nil(t, err)

	finStop := make(chan struct{})
	go func() {
		defer close(finStop)
		ensure.Nil(t, s.Stop())
	}()

	actualBody, err := ioutil.ReadAll(res.Body)
	ensure.Nil(t, err)
	ensure.DeepEqual(t, actualBody, hello)
	ensure.Nil(t, res.Body.Close())
	<-finOkHandler
	<-finStop
}
Ejemplo n.º 20
0
func TestDecodeMultiple(t *testing.T) {
	value, err := decode("W1siZm9vMSIsImJhcjEiXSxbImZvbzIiLCJiYXIyIl1d")
	ensure.Nil(t, err)
	ensure.DeepEqual(t, value, []file{
		{Name: "foo1", Hash: "bar1"},
		{Name: "foo2", Hash: "bar2"},
	})
}
Ejemplo n.º 21
0
func TestRedirectTrailingSlash(t *testing.T) {
	mux, err := ctxmux.New(ctxmux.MuxRedirectTrailingSlash())
	ensure.Nil(t, err)
	hw := httptest.NewRecorder()
	hr := &http.Request{
		Method: "GET",
		URL: &url.URL{
			Path: "/foo",
		},
	}
	mux.GET(hr.URL.Path+"/", func(context.Context, http.ResponseWriter, *http.Request) error {
		return nil
	})
	mux.ServeHTTP(hw, hr)
	ensure.DeepEqual(t, hw.Header().Get("Location"), hr.URL.Path)
	ensure.DeepEqual(t, hw.Code, http.StatusMovedPermanently)
}
Ejemplo n.º 22
0
func TestNewRequestAfterStop(t *testing.T) {
	t.Parallel()
	const count = 10000
	hello := []byte("hello")
	finOkHandler := make(chan struct{})
	unblockOkHandler := make(chan struct{})
	okHandler := func(w http.ResponseWriter, r *http.Request) {
		defer close(finOkHandler)
		w.WriteHeader(200)
		const diff = 500
		for i := 0; i < count-diff; i++ {
			w.Write(hello)
		}
		<-unblockOkHandler
		for i := 0; i < diff; i++ {
			w.Write(hello)
		}
	}

	listener, err := net.Listen("tcp", "127.0.0.1:0")
	listener, onClose := NewOnCloseListener(listener)
	ensure.Nil(t, err)
	server := &http.Server{Handler: http.HandlerFunc(okHandler)}
	transport := &http.Transport{}
	client := &http.Client{Transport: transport}
	down := &httpdown.HTTP{}
	s := down.Serve(server, listener)
	res, err := client.Get(fmt.Sprintf("http://%s/", listener.Addr().String()))
	ensure.Nil(t, err)

	finStop := make(chan struct{})
	go func() {
		defer close(finStop)
		ensure.Nil(t, s.Stop())
	}()

	// Wait until the listener is closed.
	<-onClose

	// Now the next request should not be able to connect as the listener is
	// now closed.
	_, err = client.Get(fmt.Sprintf("http://%s/", listener.Addr().String()))

	// We should just get "connection refused" here, but sometimes, very rarely,
	// we get a "connection reset" instead. Unclear why this happens.
	ensure.Err(t, err, regexp.MustCompile("(connection refused|connection reset by peer)$"))

	// Unblock the handler and ensure we finish writing the rest of the body
	// successfully.
	close(unblockOkHandler)
	actualBody, err := ioutil.ReadAll(res.Body)
	ensure.Nil(t, err)
	ensure.DeepEqual(t, actualBody, bytes.Repeat(hello, count))
	ensure.Nil(t, res.Body.Close())
	<-finOkHandler
	<-finStop
}
Ejemplo n.º 23
0
func TestServeLoadError(t *testing.T) {
	h := Handler{
		Path: "/",
		Box: funcBox(func(name string) ([]byte, error) {
			return nil, errors.New("")
		}),
	}
	w := httptest.NewRecorder()
	r := &http.Request{
		URL: &url.URL{
			Path: "/W1sibjEuanMiLCJhY2JkMThkYiJdLFsibjIiLCIzN2I1MWQxOSJdXQ.js",
		},
	}
	h.ServeHTTP(w, r)
	ensure.DeepEqual(t, w.Code, http.StatusNotFound)
	ensureDisableCaching(t, w.Header())
	ensure.DeepEqual(t, w.Body.String(), http.StatusText(http.StatusNotFound))
}
Ejemplo n.º 24
0
func TestServeHashMismatch(t *testing.T) {
	h := Handler{
		Path: "/",
		Box: funcBox(func(name string) ([]byte, error) {
			return []byte("foo"), nil
		}),
	}
	w := httptest.NewRecorder()
	r := &http.Request{
		URL: &url.URL{
			Path: "/W1siZm9vIiwiYmFyIl1d",
		},
	}
	h.ServeHTTP(w, r)
	ensure.DeepEqual(t, w.Code, http.StatusNotFound)
	ensureDisableCaching(t, w.Header())
	ensure.DeepEqual(t, w.Body.String(), http.StatusText(http.StatusNotFound))
}
Ejemplo n.º 25
0
func TestEncodeMultiple(t *testing.T) {
	files := []file{
		{Name: "foo1", Hash: "bar1"},
		{Name: "foo2", Hash: "bar2"},
	}
	value, err := encode(files)
	ensure.Nil(t, err)
	ensure.DeepEqual(t, value, "W1siZm9vMSIsImJhcjEiXSxbImZvbzIiLCJiYXIyIl1d")
}
Ejemplo n.º 26
0
func TestPublicGet(t *testing.T) {
	t.Parallel()
	user := struct {
		Username string `json:"username"`
	}{}
	res, err := defaultFbClient.Do(
		&http.Request{
			Method: "GET",
			URL: &url.URL{
				Path: "5526183",
			},
		},
		&user,
	)
	ensure.Nil(t, err)
	ensure.DeepEqual(t, res.StatusCode, 200)
	ensure.DeepEqual(t, user.Username, "naitik")
}
Ejemplo n.º 27
0
func TestNewError(t *testing.T) {
	givenErr := errors.New("")
	mux, err := ctxmux.New(
		func(*ctxmux.Mux) error {
			return givenErr
		},
	)
	ensure.True(t, mux == nil)
	ensure.DeepEqual(t, err, givenErr)
}
Ejemplo n.º 28
0
func TestExplicitAreIgnored(t *testing.T) {
	const name = "TestExplicitAreIgnored"
	s := flag.NewFlagSet(name, flag.PanicOnError)
	const bar = int(43)
	barActual := s.Int("bar", 0, "")
	s.Parse([]string{"-bar", fmt.Sprint(bar)})
	os.Setenv(named(name, "bar"), "44")
	ensure.Nil(t, flagenv.ParseSet(name, s))
	ensure.DeepEqual(t, *barActual, bar)
}
Ejemplo n.º 29
0
func TestDeepEqualString(t *testing.T) {
	var c capture
	ensure.DeepEqual(&c, "foo", "bar")
	c.Equal(t, `ensure_test.go:79: expected these to be equal:
ACTUAL:
(string) (len=3) "foo"

EXPECTED:
(string) (len=3) "bar"`)
}
Ejemplo n.º 30
0
func TestHTTPListenerCloseError(t *testing.T) {
	t.Parallel()
	expectedError := errors.New("foo")
	listener, err := net.Listen("tcp", "127.0.0.1:0")
	listener = &closeErrListener{Listener: listener, err: expectedError}
	ensure.Nil(t, err)
	server := &http.Server{}
	down := &httpdown.HTTP{}
	s := down.Serve(server, listener)
	ensure.DeepEqual(t, s.Stop(), expectedError)
}