dirwalk_test.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. package dirwalk
  4. import (
  5. "fmt"
  6. "os"
  7. "path/filepath"
  8. "reflect"
  9. "runtime"
  10. "sort"
  11. "testing"
  12. "go4.org/mem"
  13. "tailscale.com/tstest"
  14. )
  15. func TestWalkShallowOSSpecific(t *testing.T) {
  16. if osWalkShallow == nil {
  17. t.Skip("no OS-specific implementation")
  18. }
  19. testWalkShallow(t, false)
  20. }
  21. func TestWalkShallowPortable(t *testing.T) {
  22. testWalkShallow(t, true)
  23. }
  24. func testWalkShallow(t *testing.T, portable bool) {
  25. if portable {
  26. tstest.Replace(t, &osWalkShallow, nil)
  27. }
  28. d := t.TempDir()
  29. t.Run("basics", func(t *testing.T) {
  30. if err := os.WriteFile(filepath.Join(d, "foo"), []byte("1"), 0600); err != nil {
  31. t.Fatal(err)
  32. }
  33. if err := os.WriteFile(filepath.Join(d, "bar"), []byte("22"), 0400); err != nil {
  34. t.Fatal(err)
  35. }
  36. if err := os.Mkdir(filepath.Join(d, "baz"), 0777); err != nil {
  37. t.Fatal(err)
  38. }
  39. var got []string
  40. if err := WalkShallow(mem.S(d), func(name mem.RO, de os.DirEntry) error {
  41. var size int64
  42. if fi, err := de.Info(); err != nil {
  43. t.Errorf("Info stat error on %q: %v", de.Name(), err)
  44. } else if !fi.IsDir() {
  45. size = fi.Size()
  46. }
  47. got = append(got, fmt.Sprintf("%q %q dir=%v type=%d size=%v", name.StringCopy(), de.Name(), de.IsDir(), de.Type(), size))
  48. return nil
  49. }); err != nil {
  50. t.Fatal(err)
  51. }
  52. sort.Strings(got)
  53. want := []string{
  54. `"bar" "bar" dir=false type=0 size=2`,
  55. `"baz" "baz" dir=true type=2147483648 size=0`,
  56. `"foo" "foo" dir=false type=0 size=1`,
  57. }
  58. if !reflect.DeepEqual(got, want) {
  59. t.Errorf("mismatch:\n got %#q\nwant %#q", got, want)
  60. }
  61. })
  62. t.Run("err_not_exist", func(t *testing.T) {
  63. err := WalkShallow(mem.S(filepath.Join(d, "not_exist")), func(name mem.RO, de os.DirEntry) error {
  64. return nil
  65. })
  66. if !os.IsNotExist(err) {
  67. t.Errorf("unexpected error: %v", err)
  68. }
  69. })
  70. t.Run("allocs", func(t *testing.T) {
  71. allocs := int(testing.AllocsPerRun(1000, func() {
  72. if err := WalkShallow(mem.S(d), func(name mem.RO, de os.DirEntry) error { return nil }); err != nil {
  73. t.Fatal(err)
  74. }
  75. }))
  76. t.Logf("allocs = %v", allocs)
  77. if !portable && runtime.GOOS == "linux" && allocs != 0 {
  78. t.Errorf("unexpected allocs: got %v, want 0", allocs)
  79. }
  80. })
  81. }