Debian Codegraph @

internal/testing.go

raw
1 // Copyright (c) 2026, Daniel Martí <[email protected]>
2 // See LICENSE for licensing information
3
4 package internal
5
6 import (
7 "os"
8 "os/exec"
9 "path/filepath"
10 "strings"
11 )
12
13 // TestMainSetup is used by the integration tests running shell scripts
14 // either via our interpreter or via real shells,
15 // to ensure a reasonably clean and consistent environment.
16 func TestMainSetup() {
17 // Set the locale to computer-friendly English and UTF-8.
18 // Some systems like macOS miss C.UTF8, so fall back to the US English locale.
19 if out, _ := exec.Command("locale", "-a").Output(); strings.Contains(
20 strings.ToLower(string(out)), "c.utf",
21 ) {
22 os.Setenv("LANGUAGE", "C.UTF-8")
23 os.Setenv("LC_ALL", "C.UTF-8")
24 } else {
25 os.Setenv("LANGUAGE", "en_US.UTF-8")
26 os.Setenv("LC_ALL", "en_US.UTF-8")
27 }
28
29 // Bash prints the pwd after changing directories when CDPATH is set.
30 os.Unsetenv("CDPATH")
31
32 pathDir, err := os.MkdirTemp("", "interp-bin-")
33 if err != nil {
34 panic(err)
35 }
36
37 // These short names are commonly used as variables.
38 // Ensure they are unset as env vars.
39 // We can't easily remove names from $PATH,
40 // so do the next best thing: override each name with a failing script.
41 for _, s := range []string{
42 "a", "b", "c", "d", "e", "f", "foo", "bar",
43 } {
44 os.Unsetenv(s)
45 pathFile := filepath.Join(pathDir, s)
46 if err := os.WriteFile(pathFile, []byte("#!/bin/sh\necho NO_SUCH_COMMAND; exit 1"), 0o777); err != nil {
47 panic(err)
48 }
49 }
50
51 os.Setenv("PATH", pathDir+string(os.PathListSeparator)+os.Getenv("PATH"))
52 }