|
| 1 | +// Copyright 2026 The go-python 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 | +package bind |
| 6 | + |
| 7 | +import ( |
| 8 | + "os" |
| 9 | + "os/exec" |
| 10 | + "path/filepath" |
| 11 | + "testing" |
| 12 | +) |
| 13 | + |
| 14 | +var makeShellArgTests = []struct { |
| 15 | + arg, want string |
| 16 | +}{ |
| 17 | + {"", "''"}, |
| 18 | + {"-O2", "-O2"}, |
| 19 | + {"-I/usr/include/python3.12", "-I/usr/include/python3.12"}, |
| 20 | + {"$(CXXLIBFLAGS)", "$(CXXLIBFLAGS)"}, // a make variable, left for make |
| 21 | + {"-Wl,-rpath,$ORIGIN", "'-Wl,-rpath,$$ORIGIN'"}, |
| 22 | + {"a$b", "'a$$b'"}, |
| 23 | + {"-I/opt/My Python/include", "'-I/opt/My Python/include'"}, |
| 24 | + {`C:\hostedtoolcache\Python\include`, `'C:\hostedtoolcache\Python\include'`}, |
| 25 | + {"it's", `'it'\''s'`}, |
| 26 | + {`say "hi"`, `'say "hi"'`}, |
| 27 | + {"*.cpp", "'*.cpp'"}, |
| 28 | + {"a;b", "'a;b'"}, |
| 29 | + {"#x", "'#x'"}, |
| 30 | +} |
| 31 | + |
| 32 | +func TestMakeShellArg(t *testing.T) { |
| 33 | + for _, tt := range makeShellArgTests { |
| 34 | + if got := makeShellArg(tt.arg); got != tt.want { |
| 35 | + t.Errorf("makeShellArg(%q) = %q, want %q", tt.arg, got, tt.want) |
| 36 | + } |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +// TestMakeShellArgRoundTrip checks makeShellArg's actual contract: written |
| 41 | +// into a recipe line, the shell that make runs it with receives arg itself. |
| 42 | +func TestMakeShellArgRoundTrip(t *testing.T) { |
| 43 | + if _, err := exec.LookPath("make"); err != nil { |
| 44 | + t.Skip("make not found") |
| 45 | + } |
| 46 | + for _, tt := range makeShellArgTests { |
| 47 | + if tt.arg == "$(CXXLIBFLAGS)" { |
| 48 | + continue // expanded by make, by design |
| 49 | + } |
| 50 | + dir := t.TempDir() |
| 51 | + mk := "all:\n\t@printf '%s' " + makeShellArg(tt.arg) + "\n" |
| 52 | + if err := os.WriteFile(filepath.Join(dir, "Makefile"), []byte(mk), 0644); err != nil { |
| 53 | + t.Fatal(err) |
| 54 | + } |
| 55 | + cmd := exec.Command("make", "-s") |
| 56 | + cmd.Dir = dir |
| 57 | + out, err := cmd.CombinedOutput() |
| 58 | + if err != nil { |
| 59 | + t.Errorf("make for %q: %v\n%s", tt.arg, err, out) |
| 60 | + continue |
| 61 | + } |
| 62 | + if string(out) != tt.arg { |
| 63 | + t.Errorf("make passed %q to the shell as %q", tt.arg, out) |
| 64 | + } |
| 65 | + } |
| 66 | +} |
0 commit comments