getdirentries_test.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright 2019 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. // +build darwin dragonfly freebsd openbsd netbsd
  5. package unix_test
  6. import (
  7. "fmt"
  8. "io/ioutil"
  9. "os"
  10. "path/filepath"
  11. "sort"
  12. "strings"
  13. "testing"
  14. "golang.org/x/sys/unix"
  15. )
  16. func TestGetdirentries(t *testing.T) {
  17. for _, count := range []int{10, 1000} {
  18. t.Run(fmt.Sprintf("n=%d", count), func(t *testing.T) {
  19. testGetdirentries(t, count)
  20. })
  21. }
  22. }
  23. func testGetdirentries(t *testing.T, count int) {
  24. if count > 100 && testing.Short() && os.Getenv("GO_BUILDER_NAME") == "" {
  25. t.Skip("skipping in -short mode")
  26. }
  27. d, err := ioutil.TempDir("", "getdirentries-test")
  28. if err != nil {
  29. t.Fatalf("Tempdir: %v", err)
  30. }
  31. defer os.RemoveAll(d)
  32. var names []string
  33. for i := 0; i < count; i++ {
  34. names = append(names, fmt.Sprintf("file%03d", i))
  35. }
  36. // Make files in the temp directory
  37. for _, name := range names {
  38. err := ioutil.WriteFile(filepath.Join(d, name), []byte("data"), 0)
  39. if err != nil {
  40. t.Fatalf("WriteFile: %v", err)
  41. }
  42. }
  43. // Read files using Getdirentries
  44. fd, err := unix.Open(d, unix.O_RDONLY, 0)
  45. if err != nil {
  46. t.Fatalf("Open: %v", err)
  47. }
  48. defer unix.Close(fd)
  49. var base uintptr
  50. var buf [2048]byte
  51. names2 := make([]string, 0, count)
  52. for {
  53. n, err := unix.Getdirentries(fd, buf[:], &base)
  54. if err != nil {
  55. t.Fatalf("Getdirentries: %v", err)
  56. }
  57. if n == 0 {
  58. break
  59. }
  60. data := buf[:n]
  61. for len(data) > 0 {
  62. var bc int
  63. bc, _, names2 = unix.ParseDirent(data, -1, names2)
  64. if bc == 0 && len(data) > 0 {
  65. t.Fatal("no progress")
  66. }
  67. data = data[bc:]
  68. }
  69. }
  70. sort.Strings(names)
  71. sort.Strings(names2)
  72. if strings.Join(names, ":") != strings.Join(names2, ":") {
  73. t.Errorf("names don't match\n names: %q\nnames2: %q", names, names2)
  74. }
  75. }