Debian Codegraph @

unix/getdirentries_test.go

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