Debian Codegraph @

ulimit_linux_test.go

raw symbols SCIP
1 // Copyright (c) 2019, Daniel Martí <[email protected]>
2 // See LICENSE for licensing information
3
4 package main
5
6 import (
7 "bytes"
8 "fmt"
9 "os"
10 "os/exec"
11 "path/filepath"
12 "strconv"
13 "testing"
14
15 qt "github.com/frankban/quicktest"
16 "golang.org/x/sys/unix"
17 )
18
19 func init() {
20 // Here rather than in TestMain, to reuse the unix build tag.
21 if limit := os.Getenv("TEST_WITH_FILE_LIMIT"); limit != "" {
22 n, err := strconv.ParseUint(limit, 10, 64)
23 if err != nil {
24 panic(err)
25 }
26 rlimit := unix.Rlimit{Cur: n, Max: n}
27 if err := unix.Setrlimit(unix.RLIMIT_NOFILE, &rlimit); err != nil {
28 panic(err)
29 }
30 os.Exit(main1())
31 }
32 }
33
34 func TestWithLowOpenFileLimit(t *testing.T) {
35 // Safe to run in parallel, as we only change the limit for child processes.
36 t.Parallel()
37
38 tempDir := t.TempDir()
39 testBinary, err := os.Executable()
40 qt.Assert(t, err, qt.IsNil)
41
42 const (
43 // Enough directories to run into the ulimit.
44 // Enough number of files in total to run into the ulimit.
45 numberDirs = 500
46 numberFilesPerDir = 20
47 numberFilesTotal = numberDirs * numberFilesPerDir
48 )
49 t.Logf("writing %d tiny Go files", numberFilesTotal)
50 var allGoFiles []string
51 for i := 0; i < numberDirs; i++ {
52 // Prefix "p", so the package name is a valid identifier.
53 // Add one go.mod file per directory as well,
54 // which will help catch data races when loading module info.
55 dirName := fmt.Sprintf("p%03d", i)
56 dirPath := filepath.Join(tempDir, dirName)
57 err := os.MkdirAll(dirPath, 0o777)
58 qt.Assert(t, err, qt.IsNil)
59
60 err = os.WriteFile(filepath.Join(dirPath, "go.mod"),
61 []byte(fmt.Sprintf("module %s\n\ngo 1.16", dirName)), 0o666)
62 qt.Assert(t, err, qt.IsNil)
63
64 for j := 0; j < numberFilesPerDir; j++ {
65 filePath := filepath.Join(dirPath, fmt.Sprintf("%03d.go", j))
66 err := os.WriteFile(filePath,
67 // Extra newlines so that "-l" prints all paths.
68 []byte(fmt.Sprintf("package %s\n\n\n", dirName)), 0o666)
69 qt.Assert(t, err, qt.IsNil)
70 allGoFiles = append(allGoFiles, filePath)
71 }
72 }
73 if len(allGoFiles) != numberFilesTotal {
74 panic("allGoFiles doesn't have the expected number of files?")
75 }
76 runGofmt := func(paths ...string) {
77 t.Logf("running with %d paths", len(paths))
78 cmd := exec.Command(testBinary, append([]string{"-l"}, paths...)...)
79 // 256 is a relatively common low limit, e.g. on Mac.
80 cmd.Env = append(os.Environ(), "TEST_WITH_FILE_LIMIT=256")
81 out, err := cmd.Output()
82 var stderr []byte
83 if err, _ := err.(*exec.ExitError); err != nil {
84 stderr = err.Stderr
85 }
86 qt.Assert(t, err, qt.IsNil, qt.Commentf("stderr:\n%s", stderr))
87 qt.Assert(t, bytes.Count(out, []byte("\n")), qt.Equals, len(allGoFiles))
88 }
89 runGofmt(tempDir)
90 runGofmt(allGoFiles...)
91 }