github.com/ice-blockchain/go/src@v0.0.0-20240403114104-1564d284e521/net/http/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  	"os"
     9  	"path/filepath"
    10  	"runtime"
    11  	"testing"
    12  
    13  	"internal/safefilepath"
    14  )
    15  
    16  type PathTest struct {
    17  	path, result string
    18  }
    19  
    20  const invalid = ""
    21  
    22  var fspathtests = []PathTest{
    23  	{".", "."},
    24  	{"/a/b/c", "/a/b/c"},
    25  	{"a\x00b", invalid},
    26  }
    27  
    28  var winreservedpathtests = []PathTest{
    29  	{`a\b`, `a\b`},
    30  	{`a:b`, `a:b`},
    31  	{`a/b:c`, `a/b:c`},
    32  	{`NUL`, `NUL`},
    33  	{`./com1`, `./com1`},
    34  	{`a/nul/b`, `a/nul/b`},
    35  }
    36  
    37  // Whether a reserved name with an extension is reserved or not varies by
    38  // Windows version.
    39  var winreservedextpathtests = []PathTest{
    40  	{"nul.txt", "nul.txt"},
    41  	{"a/nul.txt/b", "a/nul.txt/b"},
    42  }
    43  
    44  var plan9reservedpathtests = []PathTest{
    45  	{`#c`, `#c`},
    46  }
    47  
    48  func TestFromFS(t *testing.T) {
    49  	switch runtime.GOOS {
    50  	case "windows":
    51  		if canWriteFile(t, "NUL") {
    52  			t.Errorf("can unexpectedly write a file named NUL on Windows")
    53  		}
    54  		if canWriteFile(t, "nul.txt") {
    55  			fspathtests = append(fspathtests, winreservedextpathtests...)
    56  		} else {
    57  			winreservedpathtests = append(winreservedpathtests, winreservedextpathtests...)
    58  		}
    59  		for i := range winreservedpathtests {
    60  			winreservedpathtests[i].result = invalid
    61  		}
    62  		for i := range fspathtests {
    63  			fspathtests[i].result = filepath.FromSlash(fspathtests[i].result)
    64  		}
    65  	case "plan9":
    66  		for i := range plan9reservedpathtests {
    67  			plan9reservedpathtests[i].result = invalid
    68  		}
    69  	}
    70  	tests := fspathtests
    71  	tests = append(tests, winreservedpathtests...)
    72  	tests = append(tests, plan9reservedpathtests...)
    73  	for _, test := range tests {
    74  		got, err := safefilepath.FromFS(test.path)
    75  		if (got == "") != (err != nil) {
    76  			t.Errorf(`FromFS(%q) = %q, %v; want "" only if err != nil`, test.path, got, err)
    77  		}
    78  		if got != test.result {
    79  			t.Errorf("FromFS(%q) = %q, %v; want %q", test.path, got, err, test.result)
    80  		}
    81  	}
    82  }
    83  
    84  func canWriteFile(t *testing.T, name string) bool {
    85  	path := filepath.Join(t.TempDir(), name)
    86  	os.WriteFile(path, []byte("ok"), 0666)
    87  	b, _ := os.ReadFile(path)
    88  	return string(b) == "ok"
    89  }