git » gofer » commit c66f205

fileserver: Add tests for helper functions

author Alberto Bertogli
2022-10-06 00:14:44 UTC
committer Alberto Bertogli
2022-10-09 11:34:34 UTC
parent c8fa1c94f159abbab1af3c9908e8485d36084edb

fileserver: Add tests for helper functions

This patch adds tests for the fileserver's helper functions.

server/fileserver.go +3 -3
server/fileserver_test.go +61 -0

diff --git a/server/fileserver.go b/server/fileserver.go
index 3ebfc1b..0be02f5 100644
--- a/server/fileserver.go
+++ b/server/fileserver.go
@@ -50,14 +50,14 @@ func (fsrv *fileServer) ServeHTTP(w http.ResponseWriter, req *http.Request) {
 	// Open and stat the path.
 	f, err := fsrv.root.Open(cleanPath)
 	if err != nil {
-		toHTTPErrror(w, err)
+		toHTTPError(w, err)
 		return
 	}
 	defer f.Close()
 
 	fi, err := f.Stat()
 	if err != nil {
-		toHTTPErrror(w, err)
+		toHTTPError(w, err)
 		return
 	}
 
@@ -108,7 +108,7 @@ func localRedirect(w http.ResponseWriter, req *http.Request, dst string) {
 	w.WriteHeader(http.StatusMovedPermanently)
 }
 
-func toHTTPErrror(w http.ResponseWriter, err error) {
+func toHTTPError(w http.ResponseWriter, err error) {
 	if os.IsNotExist(err) {
 		http.Error(w, "404 Not found", http.StatusNotFound)
 		return
diff --git a/server/fileserver_test.go b/server/fileserver_test.go
new file mode 100644
index 0000000..477ab10
--- /dev/null
+++ b/server/fileserver_test.go
@@ -0,0 +1,61 @@
+package server
+
+import (
+	"io/fs"
+	"net/http"
+	"net/http/httptest"
+	"testing"
+)
+
+func TestDirListError(t *testing.T) {
+	// Use this file as a "directory" for dirList.
+	// We expect it to return a 500 error.
+	d := http.Dir(".")
+	f, _ := d.Open("fileserver_test.go")
+	req := httptest.NewRequest("GET", "http://unused/", nil)
+	w := httptest.NewRecorder()
+	dirList(w, req, f)
+	resp := w.Result()
+	if resp.StatusCode != http.StatusInternalServerError {
+		t.Errorf("expected internal server error, got %v", resp)
+	}
+}
+
+func TestToHTTPError(t *testing.T) {
+	cases := []struct {
+		err       error
+		expStatus int
+	}{
+		{fs.ErrNotExist, http.StatusNotFound},
+		{fs.ErrPermission, http.StatusForbidden},
+		{fs.ErrInvalid, http.StatusInternalServerError},
+	}
+	for _, c := range cases {
+		w := httptest.NewRecorder()
+		toHTTPError(w, c.err)
+		resp := w.Result()
+		if resp.StatusCode != c.expStatus {
+			t.Errorf("for error %v: expected %v, got %v",
+				c.err, c.expStatus, resp.StatusCode)
+		}
+	}
+}
+
+func TestHumanizeInt(t *testing.T) {
+	cases := []struct {
+		i int64
+		e string
+	}{
+		{10, "10"},
+		{1025, "1K"},
+		{2 * 1024, "2K"},
+		{2 * 1024 * 1024, "2M"},
+		{2 * 1024 * 1024 * 1024, "2G"},
+	}
+	for _, c := range cases {
+		s := humanizeInt(c.i)
+		if s != c.e {
+			t.Errorf("%v: expected %q, got %q", c.i, c.e, s)
+		}
+	}
+}