blob: 5671bcfb5b0f2306ed892025257ce1921a99085c [file] [log] [blame]
Colin Cross7cdad452020-06-29 23:01:52 -07001// Copyright 2020 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package fs
16
17import (
18 "os"
19 "testing"
20)
21
22func TestMockFs_LstatStatSymlinks(t *testing.T) {
Colin Cross323dc602020-09-18 14:25:31 -070023 t.Parallel()
Colin Cross7cdad452020-06-29 23:01:52 -070024 // setup filesystem
25 filesystem := NewMockFs(nil)
26 Create(t, "/tmp/realdir/hi.txt", filesystem)
27 Create(t, "/tmp/realdir/ignoreme.txt", filesystem)
28
29 Link(t, "/tmp/links/dir", "../realdir", filesystem)
30 Link(t, "/tmp/links/file", "../realdir/hi.txt", filesystem)
31 Link(t, "/tmp/links/broken", "nothingHere", filesystem)
32 Link(t, "/tmp/links/recursive", "recursive", filesystem)
33
34 assertStat := func(t *testing.T, stat os.FileInfo, err error, wantName string, wantMode os.FileMode) {
35 t.Helper()
36 if err != nil {
37 t.Error(err)
38 return
39 }
40 if g, w := stat.Name(), wantName; g != w {
41 t.Errorf("want name %q, got %q", w, g)
42 }
43 if g, w := stat.Mode(), wantMode; g != w {
44 t.Errorf("%s: want mode %q, got %q", wantName, w, g)
45 }
46 }
47
48 assertErr := func(t *testing.T, err error, wantErr string) {
49 if err == nil || err.Error() != wantErr {
50 t.Errorf("want error %q, got %q", wantErr, err)
51 }
52 }
53
54 stat, err := filesystem.Lstat("/tmp/links/dir")
55 assertStat(t, stat, err, "dir", os.ModeSymlink)
56
57 stat, err = filesystem.Stat("/tmp/links/dir")
58 assertStat(t, stat, err, "realdir", os.ModeDir)
59
60 stat, err = filesystem.Lstat("/tmp/links/file")
61 assertStat(t, stat, err, "file", os.ModeSymlink)
62
63 stat, err = filesystem.Stat("/tmp/links/file")
64 assertStat(t, stat, err, "hi.txt", 0)
65
66 stat, err = filesystem.Lstat("/tmp/links/broken")
67 assertStat(t, stat, err, "broken", os.ModeSymlink)
68
69 stat, err = filesystem.Stat("/tmp/links/broken")
70 assertErr(t, err, "stat /tmp/links/nothingHere: file does not exist")
71
72 stat, err = filesystem.Lstat("/tmp/links/recursive")
73 assertStat(t, stat, err, "recursive", os.ModeSymlink)
74
75 stat, err = filesystem.Stat("/tmp/links/recursive")
76 assertErr(t, err, "read /tmp/links/recursive: too many levels of symbolic links")
77}