github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/tools/godoc/server_test.go (about)

     1  package godoc
     2  
     3  import (
     4  	"errors"
     5  	"expvar"
     6  	"net/http"
     7  	"net/http/httptest"
     8  	"testing"
     9  	"text/template"
    10  )
    11  
    12  var (
    13  	// NOTE: with no plain-text in the template, template.Execute will not
    14  	// return an error when http.ResponseWriter.Write does return an error.
    15  	tmpl = template.Must(template.New("test").Parse("{{.Foo}}"))
    16  )
    17  
    18  type withFoo struct {
    19  	Foo int
    20  }
    21  
    22  type withoutFoo struct {
    23  }
    24  
    25  type errResponseWriter struct {
    26  }
    27  
    28  func (*errResponseWriter) Header() http.Header {
    29  	return http.Header{}
    30  }
    31  
    32  func (*errResponseWriter) WriteHeader(int) {
    33  }
    34  
    35  func (*errResponseWriter) Write(p []byte) (int, error) {
    36  	return 0, errors.New("error")
    37  }
    38  
    39  func TestApplyTemplateToResponseWriter(t *testing.T) {
    40  	for _, tc := range []struct {
    41  		desc    string
    42  		rw      http.ResponseWriter
    43  		data    interface{}
    44  		expVars int
    45  	}{
    46  		{
    47  			desc:    "no error",
    48  			rw:      &httptest.ResponseRecorder{},
    49  			data:    &withFoo{},
    50  			expVars: 0,
    51  		},
    52  		{
    53  			desc:    "template error",
    54  			rw:      &httptest.ResponseRecorder{},
    55  			data:    &withoutFoo{},
    56  			expVars: 0,
    57  		},
    58  		{
    59  			desc:    "ResponseWriter error",
    60  			rw:      &errResponseWriter{},
    61  			data:    &withFoo{},
    62  			expVars: 1,
    63  		},
    64  	} {
    65  		httpErrors.Init()
    66  		applyTemplateToResponseWriter(tc.rw, tmpl, tc.data)
    67  		gotVars := 0
    68  		httpErrors.Do(func(expvar.KeyValue) {
    69  			gotVars++
    70  		})
    71  		if gotVars != tc.expVars {
    72  			t.Errorf("applyTemplateToResponseWriter(%q): got %d vars, want %d", tc.desc, gotVars, tc.expVars)
    73  		}
    74  	}
    75  }