Fast and extensible multi-platform HTTP/1-2-3 web server with automatic HTTPS
Mirrored from https://github.com/Slazee/caddy.git
Synced Nov 11, 01:00 UTC
| 1 | package filesystems |
| 2 | |
| 3 | import ( |
| 4 | "io/fs" |
| 5 | "os" |
| 6 | "path/filepath" |
| 7 | "runtime" |
| 8 | "testing" |
| 9 | "testing/fstest" |
| 10 | ) |
| 11 | |
| 12 | type openCountingFS struct { |
| 13 | fstest.MapFS |
| 14 | opens int |
| 15 | } |
| 16 | |
| 17 | func (o *openCountingFS) Open(name string) (fs.File, error) { |
| 18 | o.opens++ |
| 19 | return o.MapFS.Open(name) |
| 20 | } |
| 21 | |
| 22 | func TestWrapperFsStat(t *testing.T) { |
| 23 | for i, tc := range []struct { |
| 24 | hideStatFS bool |
| 25 | wantOpens int |
| 26 | }{ |
| 27 | {hideStatFS: false, wantOpens: 0}, |
| 28 | {hideStatFS: true, wantOpens: 1}, |
| 29 | } { |
| 30 | inner := &openCountingFS{MapFS: fstest.MapFS{"file": {Data: []byte("data")}}} |
| 31 | var fsys fs.FS = inner |
| 32 | if tc.hideStatFS { |
| 33 | fsys = struct{ fs.FS }{inner} |
| 34 | } |
| 35 | var m FileSystemMap |
| 36 | m.Register("test", fsys) |
| 37 | wrapped, _ := m.Get("test") |
| 38 | |
| 39 | info, err := fs.Stat(wrapped, "file") |
| 40 | if err != nil { |
| 41 | t.Fatalf("Test %d: unexpected error: %v", i, err) |
| 42 | } |
| 43 | if info.Size() != 4 { |
| 44 | t.Errorf("Test %d: expected size 4, got %d", i, info.Size()) |
| 45 | } |
| 46 | if inner.opens != tc.wantOpens { |
| 47 | t.Errorf("Test %d: expected %d opens, got %d", i, tc.wantOpens, inner.opens) |
| 48 | } |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | func TestDefaultFileSystemStatDoesNotOpen(t *testing.T) { |
| 53 | if runtime.GOOS == "windows" || os.Geteuid() == 0 { |
| 54 | t.Skip("needs a file that cannot be opened") |
| 55 | } |
| 56 | name := filepath.Join(t.TempDir(), "unreadable") |
| 57 | if err := os.WriteFile(name, []byte("data"), 0o000); err != nil { |
| 58 | t.Fatal(err) |
| 59 | } |
| 60 | if _, err := DefaultFileSystem.Open(name); err == nil { |
| 61 | t.Fatal("expected open to fail") |
| 62 | } |
| 63 | |
| 64 | info, err := fs.Stat(DefaultFileSystem, name) |
| 65 | if err != nil { |
| 66 | t.Fatalf("unexpected error: %v", err) |
| 67 | } |
| 68 | if info.Size() != 4 { |
| 69 | t.Errorf("expected size 4, got %d", info.Size()) |
| 70 | } |
| 71 | } |