package lib import ( "context" "net/url" "os" "strings" "testing" "time" "github.com/stretchr/testify/require" "golang.org/x/net/webdav" ) // makeListingFS builds an in-memory file system from a map of names to // contents, where a name ending in "/" is a directory. The in-memory file // system accepts names that some platforms reject (e.g. ":" or "<" on // Windows), so hostile names can be tested everywhere. func makeListingFS(t *testing.T, m map[string]string) webdav.FileSystem { ctx := context.Background() fs := webdav.NewMemFS() for name, data := range m { if strings.HasSuffix(name, "/") { require.NoError(t, fs.Mkdir(ctx, "/"+strings.TrimSuffix(name, "/"), 0o755)) continue } f, err := fs.OpenFile(ctx, "/"+name, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o644) require.NoError(t, err) _, err = f.Write([]byte(data)) require.NoError(t, err) require.NoError(t, f.Close()) } return fs } func renderListing(t *testing.T, fs webdav.FileSystem, dirPath string, sorting ListingSortOptions, listing Listing) string { html, err := RenderListing(context.Background(), fs, dirPath, sorting, listing) require.NoError(t, err) return html } var sortByNameAsc = ListingSortOptions{Field: listingSortByName, Order: listingSortAsc} func TestParseListingSortQuery(t *testing.T) { t.Run("defaults", func(t *testing.T) { got := ParseListingSortQuery(url.Values{}) if got.Field != listingSortByDate || got.Order != listingSortDesc { t.Fatalf("unexpected defaults: %+v", got) } }) t.Run("valid values", func(t *testing.T) { got := ParseListingSortQuery(url.Values{"C": {"S"}, "O": {"D"}}) if got.Field != listingSortBySize || got.Order != listingSortDesc { t.Fatalf("unexpected parsed values: %+v", got) } }) t.Run("invalid values fallback", func(t *testing.T) { got := ParseListingSortQuery(url.Values{"C": {"invalid"}, "O": {"nope"}}) if got.Field != listingSortByDate || got.Order != listingSortDesc { t.Fatalf("unexpected fallback values: %+v", got) } }) } func TestRenderDirectoryListingBasic(t *testing.T) { fs := makeListingFS(t, map[string]string{ "file1.txt": "content1", "subdir/": "", }) html := renderListing(t, fs, "/", sortByNameAsc, Listing{ShowPath: true}) if !strings.Contains(html, "") || !strings.Contains(html, `