Debian Codegraph @

util/content_type_writer_test.go

raw
1 package util
2
3 import (
4 "crypto/rand"
5 "github.com/stretchr/testify/require"
6 "net/http/httptest"
7 "testing"
8 )
9
10 func TestSniffWriter_WriteHTML(t *testing.T) {
11 rr := httptest.NewRecorder()
12 sw := NewContentTypeWriter(rr, "")
13 sw.Write([]byte("<script>alert('hi')</script>"))
14 require.Equal(t, "text/plain; charset=utf-8", rr.Header().Get("Content-Type"))
15 }
16
17 func TestSniffWriter_WriteTwoWriteCalls(t *testing.T) {
18 rr := httptest.NewRecorder()
19 sw := NewContentTypeWriter(rr, "")
20 sw.Write([]byte{0x25, 0x50, 0x44, 0x46, 0x2d, 0x11, 0x22, 0x33})
21 sw.Write([]byte("<script>alert('hi')</script>"))
22 require.Equal(t, "application/pdf", rr.Header().Get("Content-Type"))
23 }
24
25 func TestSniffWriter_NoSniffWriterWriteHTML(t *testing.T) {
26 // This test just makes sure that without the sniff-w, we would get text/html
27
28 rr := httptest.NewRecorder()
29 rr.Write([]byte("<script>alert('hi')</script>"))
30 require.Equal(t, "text/html; charset=utf-8", rr.Header().Get("Content-Type"))
31 }
32
33 func TestSniffWriter_WriteHTMLSplitIntoTwoWrites(t *testing.T) {
34 // This test shows how splitting the HTML into two Write() calls will still yield text/plain
35
36 rr := httptest.NewRecorder()
37 sw := NewContentTypeWriter(rr, "")
38 sw.Write([]byte("<scr"))
39 sw.Write([]byte("ipt>alert('hi')</script>"))
40 require.Equal(t, "text/plain; charset=utf-8", rr.Header().Get("Content-Type"))
41 }
42
43 func TestSniffWriter_WriteUnknownMimeType(t *testing.T) {
44 rr := httptest.NewRecorder()
45 sw := NewContentTypeWriter(rr, "")
46 randomBytes := make([]byte, 199)
47 rand.Read(randomBytes[5:]) // Start at an offset; the test kept failing randomly because it hit random magic strings
48 sw.Write(randomBytes)
49 require.Equal(t, "application/octet-stream", rr.Header().Get("Content-Type"))
50 }
51
52 func TestSniffWriter_WriteWithFilenameAPK(t *testing.T) {
53 rr := httptest.NewRecorder()
54 sw := NewContentTypeWriter(rr, "https://example.com/ntfy.apk")
55 sw.Write([]byte{0x50, 0x4B, 0x03, 0x04})
56 require.Equal(t, "application/vnd.android.package-archive", rr.Header().Get("Content-Type"))
57 }