|
| 1 | +package fsx_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "os" |
| 6 | + "path/filepath" |
| 7 | + "testing" |
| 8 | + |
| 9 | + "github.com/cerberauth/x/fsx" |
| 10 | +) |
| 11 | + |
| 12 | +func TestReadFile_Success(t *testing.T) { |
| 13 | + dir := t.TempDir() |
| 14 | + path := filepath.Join(dir, "test.txt") |
| 15 | + if err := os.WriteFile(path, []byte("hello"), 0600); err != nil { |
| 16 | + t.Fatalf("failed to create test file: %v", err) |
| 17 | + } |
| 18 | + |
| 19 | + data, err := fsx.ReadFile(path) |
| 20 | + if err != nil { |
| 21 | + t.Fatalf("unexpected error: %v", err) |
| 22 | + } |
| 23 | + if string(data) != "hello" { |
| 24 | + t.Errorf("expected %q, got %q", "hello", string(data)) |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +func TestReadFile_NotFound(t *testing.T) { |
| 29 | + _, err := fsx.ReadFile("/nonexistent/path/file.txt") |
| 30 | + if err == nil { |
| 31 | + t.Fatal("expected error, got nil") |
| 32 | + } |
| 33 | + if errors.Is(err, fsx.ErrPermission) || errors.Is(err, fsx.ErrSnapPermission) { |
| 34 | + t.Errorf("expected a not-found error, got permission error: %v", err) |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +func TestReadFile_PermissionDenied_Generic(t *testing.T) { |
| 39 | + if os.Getuid() == 0 { |
| 40 | + t.Skip("skipping permission test: running as root") |
| 41 | + } |
| 42 | + |
| 43 | + t.Setenv("SNAP", "") |
| 44 | + t.Setenv("SNAP_NAME", "") |
| 45 | + t.Setenv("SNAP_USER_DATA", "") |
| 46 | + |
| 47 | + dir := t.TempDir() |
| 48 | + path := filepath.Join(dir, "noaccess.txt") |
| 49 | + if err := os.WriteFile(path, []byte("secret"), 0000); err != nil { |
| 50 | + t.Fatalf("failed to create test file: %v", err) |
| 51 | + } |
| 52 | + |
| 53 | + _, err := fsx.ReadFile(path) |
| 54 | + if err == nil { |
| 55 | + t.Fatal("expected error, got nil") |
| 56 | + } |
| 57 | + if !errors.Is(err, fsx.ErrPermission) { |
| 58 | + t.Errorf("expected ErrPermission, got: %v", err) |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +func TestReadFile_PermissionDenied_Snap(t *testing.T) { |
| 63 | + if os.Getuid() == 0 { |
| 64 | + t.Skip("skipping permission test: running as root") |
| 65 | + } |
| 66 | + |
| 67 | + t.Setenv("SNAP", "/snap/myapp/current") |
| 68 | + t.Setenv("SNAP_NAME", "myapp") |
| 69 | + t.Setenv("SNAP_USER_DATA", "") |
| 70 | + |
| 71 | + dir := t.TempDir() |
| 72 | + path := filepath.Join(dir, "noaccess.txt") |
| 73 | + if err := os.WriteFile(path, []byte("secret"), 0000); err != nil { |
| 74 | + t.Fatalf("failed to create test file: %v", err) |
| 75 | + } |
| 76 | + |
| 77 | + _, err := fsx.ReadFile(path) |
| 78 | + if err == nil { |
| 79 | + t.Fatal("expected error, got nil") |
| 80 | + } |
| 81 | + if !errors.Is(err, fsx.ErrSnapPermission) { |
| 82 | + t.Errorf("expected ErrSnapPermission, got: %v", err) |
| 83 | + } |
| 84 | +} |
0 commit comments