dndex/view/files_test.go

61 lines
1.3 KiB
Go

package view
import (
"fmt"
"io/ioutil"
"local/dndex/config"
"local/dndex/storage"
"net/http"
"net/http/httptest"
"os"
"path"
"testing"
)
func TestFiles(t *testing.T) {
os.Args = os.Args[:1]
f, err := ioutil.TempFile(os.TempDir(), "pattern*")
if err != nil {
t.Fatal(err)
}
f.Close()
defer os.Remove(f.Name())
os.Setenv("DBURI", f.Name())
d, err := ioutil.TempDir(os.TempDir(), "pattern*")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(d)
os.Setenv("FILEROOT", d)
t.Logf("config: %+v", config.New())
handler := jsonHandler(storage.Graph{})
t.Run("get fake file 404", func(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, fmt.Sprintf("%s/fake", config.New().FilePrefix), nil)
w := httptest.NewRecorder()
handler.ServeHTTP(w, r)
if w.Code != http.StatusNotFound {
t.Fatalf("%d: %s", w.Code, w.Body.Bytes())
}
})
t.Run("get text file", func(t *testing.T) {
f, err := ioutil.TempFile(d, "*.txt")
t.Logf("tempFile(%q, *.txt) = %q", d, f.Name())
if err != nil {
t.Fatal(err)
}
f.Write([]byte("hello, world"))
f.Close()
r := httptest.NewRequest(http.MethodGet, path.Join(config.New().FilePrefix, path.Base(f.Name())), nil)
w := httptest.NewRecorder()
t.Logf("URL = %q", r.URL.String())
handler.ServeHTTP(w, r)
if w.Code != http.StatusOK {
t.Fatalf("%d: %s", w.Code, w.Body.Bytes())
}
})
}