tests for http package

This commit is contained in:
Julien Neuhart
2018-04-04 18:10:18 +02:00
parent 3d8247ec50
commit 15916e80e6
2 changed files with 43 additions and 1 deletions

View File

@@ -33,7 +33,7 @@ func (e *notAuthorizedContentTypeError) Error() string {
// FindAuthorizedContentType tries to return a content type according to a request header.
// If no authorized content type found, throws an error.
func FindAuthorizedContentType(h http.Header) (ContentType, error) {
ct := findContentType(h.Get("Content-Type"), HTMLContentType, OctetStreamContentType, MultipartFormDataContentType)
ct := findContentType(h.Get("Content-Type"), OctetStreamContentType, MultipartFormDataContentType)
if ct == "" {
return "", &notAuthorizedContentTypeError{}
}

42
app/http/http_test.go Normal file
View File

@@ -0,0 +1,42 @@
package http
import (
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
)
func TestFindAuthorizedContentType(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/", nil)
// case 1: uses a request without a content type entry in its header.
if _, err := FindAuthorizedContentType(req.Header); err == nil {
t.Error("It should not have been able to retrieve an authorized content type from header!")
}
// case 2: uses a request with a content type entry in its header.
req.Header.Set("Content-Type", string(MultipartFormDataContentType))
if _, err := FindAuthorizedContentType(req.Header); err != nil {
t.Error("It should have been able to retrieve an authorized content type from header!")
}
}
func TestSniffContentType(t *testing.T) {
// case 1: uses a file with a wrong content type.
path, _ := filepath.Abs("../../_tests/configurations/gotenberg.yml")
f, _ := os.Open(path)
defer f.Close()
if _, err := SniffContentType(f); err == nil {
t.Error("It should not have been able to retrieve an authorized content type from an YAML file!")
}
// case 2: uses a file with a correct content type.
path, _ = filepath.Abs("../../_tests/file.pdf")
f, _ = os.Open(path)
defer f.Close()
if _, err := SniffContentType(f); err != nil {
t.Error("It should have been able to retrieve an authorized content type from a PDF file!")
}
}