package playground import ( "strings" "testing" ) func TestClean(t *testing.T) { cases := map[string]string{ "user:/a/../b": "user:/b", "user:": "user:/", "user:/../../x": "user:/x", "tmp:\\a\\b.txt": "tmp:/a/b.txt", "web:/App/": "web:/App", "nope:/x": "", "/x": "", } for in, want := range cases { if got := Clean(in); got != want { t.Errorf("Clean(%q) = %q, want %q", in, got, want) } } } func TestMemFSSemantics(t *testing.T) { m := newMemFS([]File{{Path: "user:/a/b.txt", Data: []byte("x")}}) if !m.IsDir("user:/a") { t.Fatal("parent folders of a loaded file must exist") } if err := m.WriteFile("user:/missing/c.txt", nil); err == nil { t.Error("WriteFile without a parent folder must fail like os.WriteFile") } if err := m.Remove("user:/a"); err == nil { t.Error("Remove of a non-empty folder must fail like os.Remove") } if err := m.Remove("user:/"); err == nil { t.Error("a root must not be removable") } if err := m.RemoveAll("user:/a"); err != nil || m.Exists("user:/a/b.txt") { t.Errorf("RemoveAll: %v", err) } if err := m.MkdirAll("user:/p/q"); err != nil || !m.IsDir("user:/p/q") { t.Errorf("MkdirAll: %v", err) } m.WriteFile("user:/p/f.txt", []byte("1")) if err := m.MkdirAll("user:/p/f.txt/z"); err == nil { t.Error("MkdirAll through a file must fail") } written, removed := m.Changes() var w []string for _, f := range written { w = append(w, f.Path) } if strings.Join(w, ",") != "user:/p,user:/p/f.txt,user:/p/q" || strings.Join(removed, ",") != "user:/a,user:/a/b.txt" { t.Errorf("changes: written %v removed %v", w, removed) } } func TestGlobAndHidden(t *testing.T) { m := newMemFS([]File{{Path: "user:/d/a.mp3"}, {Path: "user:/d/b.txt"}, {Path: "user:/d/.c.mp3"}}) list, _ := m.Glob("user:/d/*.mp3") var names []string for _, e := range list { if !isHiddenPath(e.Vpath) { names = append(names, e.Name) } } if strings.Join(names, ",") != "a.mp3" { t.Errorf("glob: %v", names) } if _, err := m.Glob("user:/d/[.mp3"); err == nil { t.Error("a bad pattern must report an error") } } func TestNaturalLess(t *testing.T) { cases := []struct { a, b string want bool }{ {"file2", "file10", true}, {"file10", "file2", false}, {"a", "b", true}, {"File1", "file02", true}, } for _, c := range cases { if got := naturalLess(c.a, c.b); got != c.want { t.Errorf("naturalLess(%q, %q) = %v", c.a, c.b, got) } } } func TestMatchers(t *testing.T) { cases := []struct { f func(string, string) bool pattern, s string want bool }{ {matchURL, "https://a.com/x", "https://a.com/x/", true}, {matchURL, "https://a.com/*", "https://a.com/x/y", true}, {matchURL, "https://a.com/*", "https://b.com/x", false}, {matchURL, "/a\\.com\\/\\d+$/", "https://a.com/12", true}, {matchText, "Capital", "what is the capital?", true}, {matchText, "/^hi/i", "Hi there", true}, {matchText, "", "anything", true}, } for _, c := range cases { if got := c.f(c.pattern, c.s); got != c.want { t.Errorf("match(%q, %q) = %v", c.pattern, c.s, got) } } }