github.com/segakazzz/buffalo@v0.16.22-0.20210119082501-1f52048d3feb/render/download_test.go (about) 1 package render 2 3 import ( 4 "bytes" 5 "context" 6 "io" 7 "net/http" 8 "net/http/httptest" 9 "strconv" 10 "testing" 11 12 "github.com/stretchr/testify/require" 13 ) 14 15 type dlRenderer func(context.Context, string, io.Reader) Renderer 16 17 type dlContext struct { 18 context.Context 19 rw http.ResponseWriter 20 } 21 22 func (c dlContext) Response() http.ResponseWriter { 23 return c.rw 24 } 25 26 var data = []byte("data") 27 28 func Test_Download_KnownExtension(t *testing.T) { 29 r := require.New(t) 30 31 table := []dlRenderer{ 32 Download, 33 New(Options{}).Download, 34 } 35 36 for _, dl := range table { 37 ctx := dlContext{rw: httptest.NewRecorder()} 38 39 re := dl(ctx, "filename.pdf", bytes.NewReader(data)) 40 41 bb := &bytes.Buffer{} 42 r.NoError(re.Render(bb, nil)) 43 44 r.Equal(data, bb.Bytes()) 45 r.Equal(strconv.Itoa(len(data)), ctx.Response().Header().Get("Content-Length")) 46 r.Equal("attachment; filename=filename.pdf", ctx.Response().Header().Get("Content-Disposition")) 47 r.Equal("application/pdf", re.ContentType()) 48 } 49 } 50 51 func Test_Download_UnknownExtension(t *testing.T) { 52 r := require.New(t) 53 54 table := []dlRenderer{ 55 Download, 56 New(Options{}).Download, 57 } 58 59 for _, dl := range table { 60 ctx := dlContext{rw: httptest.NewRecorder()} 61 re := dl(ctx, "filename", bytes.NewReader(data)) 62 63 bb := &bytes.Buffer{} 64 r.NoError(re.Render(bb, nil)) 65 66 r.Equal(data, bb.Bytes()) 67 r.Equal(strconv.Itoa(len(data)), ctx.Response().Header().Get("Content-Length")) 68 r.Equal("attachment; filename=filename", ctx.Response().Header().Get("Content-Disposition")) 69 r.Equal("application/octet-stream", re.ContentType()) 70 } 71 } 72 73 func Test_InvalidContext(t *testing.T) { 74 r := require.New(t) 75 76 table := []dlRenderer{ 77 Download, 78 New(Options{}).Download, 79 } 80 81 for _, dl := range table { 82 re := dl(context.TODO(), "filename", bytes.NewReader(data)) 83 84 bb := &bytes.Buffer{} 85 r.Error(re.Render(bb, nil)) 86 } 87 }