github.com/ader1990/go@v0.0.0-20140630135419-8c24447fa791/src/pkg/net/http/httptest/recorder_test.go (about)

     1  // Copyright 2012 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package httptest
     6  
     7  import (
     8  	"fmt"
     9  	"net/http"
    10  	"testing"
    11  )
    12  
    13  func TestRecorder(t *testing.T) {
    14  	type checkFunc func(*ResponseRecorder) error
    15  	check := func(fns ...checkFunc) []checkFunc { return fns }
    16  
    17  	hasStatus := func(wantCode int) checkFunc {
    18  		return func(rec *ResponseRecorder) error {
    19  			if rec.Code != wantCode {
    20  				return fmt.Errorf("Status = %d; want %d", rec.Code, wantCode)
    21  			}
    22  			return nil
    23  		}
    24  	}
    25  	hasContents := func(want string) checkFunc {
    26  		return func(rec *ResponseRecorder) error {
    27  			if rec.Body.String() != want {
    28  				return fmt.Errorf("wrote = %q; want %q", rec.Body.String(), want)
    29  			}
    30  			return nil
    31  		}
    32  	}
    33  	hasFlush := func(want bool) checkFunc {
    34  		return func(rec *ResponseRecorder) error {
    35  			if rec.Flushed != want {
    36  				return fmt.Errorf("Flushed = %v; want %v", rec.Flushed, want)
    37  			}
    38  			return nil
    39  		}
    40  	}
    41  
    42  	tests := []struct {
    43  		name   string
    44  		h      func(w http.ResponseWriter, r *http.Request)
    45  		checks []checkFunc
    46  	}{
    47  		{
    48  			"200 default",
    49  			func(w http.ResponseWriter, r *http.Request) {},
    50  			check(hasStatus(200), hasContents("")),
    51  		},
    52  		{
    53  			"first code only",
    54  			func(w http.ResponseWriter, r *http.Request) {
    55  				w.WriteHeader(201)
    56  				w.WriteHeader(202)
    57  				w.Write([]byte("hi"))
    58  			},
    59  			check(hasStatus(201), hasContents("hi")),
    60  		},
    61  		{
    62  			"write sends 200",
    63  			func(w http.ResponseWriter, r *http.Request) {
    64  				w.Write([]byte("hi first"))
    65  				w.WriteHeader(201)
    66  				w.WriteHeader(202)
    67  			},
    68  			check(hasStatus(200), hasContents("hi first"), hasFlush(false)),
    69  		},
    70  		{
    71  			"flush",
    72  			func(w http.ResponseWriter, r *http.Request) {
    73  				w.(http.Flusher).Flush() // also sends a 200
    74  				w.WriteHeader(201)
    75  			},
    76  			check(hasStatus(200), hasFlush(true)),
    77  		},
    78  	}
    79  	r, _ := http.NewRequest("GET", "http://foo.com/", nil)
    80  	for _, tt := range tests {
    81  		h := http.HandlerFunc(tt.h)
    82  		rec := NewRecorder()
    83  		h.ServeHTTP(rec, r)
    84  		for _, check := range tt.checks {
    85  			if err := check(rec); err != nil {
    86  				t.Errorf("%s: %v", tt.name, err)
    87  			}
    88  		}
    89  	}
    90  }