github.com/JimmyHuang454/JLS-go@v0.0.0-20230831150107-90d536585ba0/internal/safefilepath/path_test.go (about) 1 // Copyright 2022 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package safefilepath_test 6 7 import ( 8 "internal/safefilepath" 9 "os" 10 "path/filepath" 11 "runtime" 12 "testing" 13 ) 14 15 type PathTest struct { 16 path, result string 17 } 18 19 const invalid = "" 20 21 var fspathtests = []PathTest{ 22 {".", "."}, 23 {"/a/b/c", "/a/b/c"}, 24 {"a\x00b", invalid}, 25 } 26 27 var winreservedpathtests = []PathTest{ 28 {`a\b`, `a\b`}, 29 {`a:b`, `a:b`}, 30 {`a/b:c`, `a/b:c`}, 31 {`NUL`, `NUL`}, 32 {`./com1`, `./com1`}, 33 {`a/nul/b`, `a/nul/b`}, 34 } 35 36 // Whether a reserved name with an extension is reserved or not varies by 37 // Windows version. 38 var winreservedextpathtests = []PathTest{ 39 {"nul.txt", "nul.txt"}, 40 {"a/nul.txt/b", "a/nul.txt/b"}, 41 } 42 43 var plan9reservedpathtests = []PathTest{ 44 {`#c`, `#c`}, 45 } 46 47 func TestFromFS(t *testing.T) { 48 switch runtime.GOOS { 49 case "windows": 50 if canWriteFile(t, "NUL") { 51 t.Errorf("can unexpectedly write a file named NUL on Windows") 52 } 53 if canWriteFile(t, "nul.txt") { 54 fspathtests = append(fspathtests, winreservedextpathtests...) 55 } else { 56 winreservedpathtests = append(winreservedpathtests, winreservedextpathtests...) 57 } 58 for i := range winreservedpathtests { 59 winreservedpathtests[i].result = invalid 60 } 61 for i := range fspathtests { 62 fspathtests[i].result = filepath.FromSlash(fspathtests[i].result) 63 } 64 case "plan9": 65 for i := range plan9reservedpathtests { 66 plan9reservedpathtests[i].result = invalid 67 } 68 } 69 tests := fspathtests 70 tests = append(tests, winreservedpathtests...) 71 tests = append(tests, plan9reservedpathtests...) 72 for _, test := range tests { 73 got, err := safefilepath.FromFS(test.path) 74 if (got == "") != (err != nil) { 75 t.Errorf(`FromFS(%q) = %q, %v; want "" only if err != nil`, test.path, got, err) 76 } 77 if got != test.result { 78 t.Errorf("FromFS(%q) = %q, %v; want %q", test.path, got, err, test.result) 79 } 80 } 81 } 82 83 func canWriteFile(t *testing.T, name string) bool { 84 path := filepath.Join(t.TempDir(), name) 85 os.WriteFile(path, []byte("ok"), 0666) 86 b, _ := os.ReadFile(path) 87 return string(b) == "ok" 88 }