frostfs-http-gw/internal/handler/reader_test.go
Aleksey Kravchenko f0c999d9a2
All checks were successful
/ Builds (push) Successful in 54s
/ Vulncheck (push) Successful in 50s
/ OCI image (push) Successful in 1m28s
/ Lint (push) Successful in 2m3s
/ Tests (push) Successful in 55s
[#188] Improve content-type detector
Signed-off-by: Aleksey Kravchenko <al.kravchenko@yadro.com>
2025-01-21 06:52:37 +00:00

89 lines
2.3 KiB
Go

//go:build !integration
package handler
import (
"io"
"strings"
"testing"
"github.com/stretchr/testify/require"
)
const (
txtContentType = "text/plain; charset=utf-8"
cssContentType = "text/css; charset=utf-8"
htmlContentType = "text/html; charset=utf-8"
javascriptContentType = "text/javascript; charset=utf-8"
htmlBody = "<!DOCTYPE html><html ><head><meta charset=\"utf-8\"><title>Test Html</title>"
)
func TestDetector(t *testing.T) {
sb := strings.Builder{}
for i := 0; i < 10; i++ {
sb.WriteString("Some txt content. Content-Type must be detected properly by detector.")
}
for _, tc := range []struct {
Name string
ExpectedContentType string
Content string
FileName string
}{
{
Name: "less than 512b",
ExpectedContentType: txtContentType,
Content: sb.String()[:256],
FileName: "test.txt",
},
{
Name: "more than 512b",
ExpectedContentType: txtContentType,
Content: sb.String(),
FileName: "test.txt",
},
{
Name: "css content type",
ExpectedContentType: cssContentType,
Content: sb.String(),
FileName: "test.css",
},
{
Name: "javascript content type",
ExpectedContentType: javascriptContentType,
Content: sb.String(),
FileName: "test.js",
},
{
Name: "html content type by file content",
ExpectedContentType: htmlContentType,
Content: htmlBody,
FileName: "test.detect-by-content",
},
{
Name: "html content type by file extension",
ExpectedContentType: htmlContentType,
Content: sb.String(),
FileName: "test.html",
},
{
Name: "empty file extension",
ExpectedContentType: txtContentType,
Content: sb.String(),
FileName: "test",
},
} {
t.Run(tc.Name, func(t *testing.T) {
contentType, data, err := readContentType(uint64(len(tc.Content)),
func(uint64) (io.Reader, error) {
return strings.NewReader(tc.Content), nil
}, tc.FileName,
)
require.NoError(t, err)
require.Equal(t, tc.ExpectedContentType, contentType)
require.True(t, strings.HasPrefix(tc.Content, string(data)))
})
}
}