File: interpreter_test.go

package info (click to toggle)
singularity-container 4.0.3%2Bds1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 21,672 kB
  • sloc: asm: 3,857; sh: 2,125; ansic: 1,677; awk: 414; makefile: 110; python: 99
file content (327 lines) | stat: -rw-r--r-- 7,871 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
// Copyright (c) 2020, Sylabs, Inc. All rights reserved.
// This software is licensed under a 3-clause BSD license.  Please
// consult LICENSE.md file distributed with the sources of this project regarding
// your rights to use or distribute this software.

package interpreter

import (
	"bytes"
	"context"
	"fmt"
	"io"
	"os"
	"reflect"
	"sort"
	"strings"
	"testing"

	"mvdan.cc/sh/v3/interp"
)

func newIOStream() (io.Reader, io.ReadWriter, io.ReadWriter) {
	var stdin bytes.Buffer
	var stdout bytes.Buffer
	var stderr bytes.Buffer
	return &stdin, &stdout, &stderr
}

type bufferCloser struct {
	bytes.Buffer
}

func (*bufferCloser) Close() error {
	return nil
}

type testShellBuiltin struct {
	builtin string
	fn      func(*Shell) ShellBuiltin
}

type testOpenHandler struct {
	path string
	fn   func(*Shell) OpenHandler
}

func TestInterpreter(t *testing.T) {
	var err error
	var shell *Shell

	_, err = New(nil, "empty_reader", nil, nil, interp.StdIO(newIOStream()))
	if err == nil {
		t.Fatalf("unexpected error with empty reader: %s", err)
	}

	tests := []struct {
		name         string
		argv         []string
		env          []string
		script       string
		expectOut    string
		expectErr    string
		shellBuiltin *testShellBuiltin
		openHandler  *testOpenHandler
		expectExit   uint8
	}{
		{
			name:      "hello stdout",
			script:    "echo 'hello'",
			expectOut: "hello",
		},
		{
			name:      "hello stderr",
			script:    "echo 'hello' 1>&2",
			expectErr: "hello",
		},
		{
			name:   "exit 0",
			script: "exit 0",
		},
		{
			name:       "exit 1",
			script:     "exit 1",
			expectExit: 1,
		},
		{
			name:      "echo arg one",
			script:    "echo ${1}",
			argv:      []string{"arg1"},
			expectOut: "arg1",
		},
		{
			name:      "echo env",
			script:    "echo $PATH",
			env:       []string{"PATH=/bin"},
			expectOut: "/bin",
		},
		{
			name:   "spawn true",
			script: "/bin/true",
		},
		{
			name:       "spawn false",
			script:     "/bin/false",
			expectExit: 1,
		},
		{
			name:      "exec builtin",
			script:    "exec true && echo 'hello'",
			env:       []string{"PATH=/bin"},
			expectOut: "/bin/true",
			shellBuiltin: &testShellBuiltin{
				builtin: "exec",
				fn: func(shell *Shell) ShellBuiltin {
					return func(ctx context.Context, args []string) error {
						hc := interp.HandlerCtx(ctx)
						cmd, err := shell.LookPath(ctx, args[0])
						if err != nil {
							return err
						}
						fmt.Fprintf(hc.Stdout, "%s\n", cmd)
						return nil
					}
				},
			},
		},
		{
			name:      "testing builtin",
			script:    "testing argument",
			expectOut: "argument",
			shellBuiltin: &testShellBuiltin{
				builtin: "testing",
				fn: func(shell *Shell) ShellBuiltin {
					return func(ctx context.Context, args []string) error {
						hc := interp.HandlerCtx(ctx)
						fmt.Fprintf(hc.Stdout, "%s\n", args[0])
						return nil
					}
				},
			},
		},
		{
			name:   "export env",
			script: "export FOO=bar && exec /bin/true",
			shellBuiltin: &testShellBuiltin{
				builtin: "exec",
				fn: func(shell *Shell) ShellBuiltin {
					return func(ctx context.Context, args []string) error {
						hc := interp.HandlerCtx(ctx)
						for _, env := range GetEnv(hc) {
							if env == "FOO=bar" {
								return nil
							}
						}
						return fmt.Errorf("no FOO environment variable")
					}
				},
			},
		},
		{
			name:      "source handler",
			script:    ". /virtual/file",
			expectOut: "a virtual file",
			openHandler: &testOpenHandler{
				path: "/virtual/file",
				fn: func(shell *Shell) OpenHandler {
					return func(path string, flag int, perm os.FileMode) (io.ReadWriteCloser, error) {
						bc := new(bufferCloser)
						bc.WriteString("echo 'a virtual file'\n")
						return bc, nil
					}
				},
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			var scriptBuf bytes.Buffer
			var stdin bytes.Buffer
			var stdout bytes.Buffer
			var stderr bytes.Buffer

			scriptBuf.WriteString(tt.script)

			shell, err = New(&scriptBuf, "buffer", tt.argv, tt.env, interp.StdIO(&stdin, &stdout, &stderr))
			if err != nil {
				t.Fatalf("unexpected error: %s", err)
			}
			if tt.shellBuiltin != nil {
				shell.RegisterShellBuiltin(tt.shellBuiltin.builtin, tt.shellBuiltin.fn(shell))
			}
			if tt.openHandler != nil {
				shell.RegisterOpenHandler(tt.openHandler.path, tt.openHandler.fn(shell))
			}
			if err := shell.Run(context.Background()); err != nil {
				if tt.expectExit != 0 && shell.Status() != tt.expectExit {
					t.Fatalf("unexpected exit status for %s: got %d instead of %d", tt.name, shell.Status(), tt.expectExit)
				} else if tt.expectExit == 0 {
					t.Fatalf("unexpected error: %s", err)
				}
			}

			errStr := strings.TrimSpace(stderr.String())
			outStr := strings.TrimSpace(stdout.String())

			if tt.expectErr != "" && errStr != tt.expectErr {
				t.Fatalf("unexpected stderr: %s instead of %s", errStr, tt.expectErr)
			}
			if tt.expectOut != "" && outStr != tt.expectOut {
				t.Fatalf("unexpected stdout: %s instead of %s", outStr, tt.expectOut)
			}
		})
	}
}

func TestEvaluateEnv(t *testing.T) {
	tests := []struct {
		name      string
		script    string
		argv      []string
		env       []string
		resultEnv []string
		expectErr bool
	}{
		{
			name:      "EmptyScript",
			script:    "",
			resultEnv: []string{},
		},
		{
			name:      "SingleEnv",
			script:    "FOO=bar",
			resultEnv: []string{"FOO=bar"},
		},
		{
			name:      "ExternalEnv",
			env:       []string{"FOO=bar"},
			script:    "BAR=$FOO",
			resultEnv: []string{"BAR=bar"},
		},
		{
			name:      "ExternalEnvExport",
			env:       []string{"FOO=bar"},
			script:    "BAR=foo && export FOO",
			resultEnv: []string{"FOO=bar", "BAR=foo"},
		},
		{
			name:      "ExternalEnvOverwrite",
			env:       []string{"FOO=bar"},
			script:    "FOO=overwrite",
			resultEnv: []string{"FOO=overwrite"},
		},
		{
			name:      "ExecFailure",
			script:    "/bin/true",
			resultEnv: []string{},
			expectErr: true,
		},
		{
			name:      "OpenFailure",
			script:    "echo hello > /tmp/hello",
			resultEnv: []string{},
			expectErr: true,
		},
		{
			name:      "NonExistentVar",
			script:    "FOO=$FAKE",
			resultEnv: []string{"FOO="},
		},
		{
			name:      "ArgZeroVar",
			script:    "FOO=$0",
			resultEnv: []string{"FOO=singularity"},
		},
		{
			name:      "ArgOneVar",
			argv:      []string{"bar"},
			script:    "FOO=$1",
			resultEnv: []string{"FOO=bar"},
		},
		{
			name:      "AllArgVar",
			argv:      []string{"bar", "-a", "foo"},
			script:    "FOO=\"$@\"",
			resultEnv: []string{"FOO=bar -a foo"},
		},
	}

	// Since mvdan.cc/sh/v3@v3.4.0 some default vars will be set:
	//    HOME IFS OPTIND PWD UID GID EUID
	// These don't adversely impact our downstream container environment, but
	// must be accounted for here.
	// https://github.com/mvdan/sh/commit/f4c774aa15046ef006508e182fde10c4b56876fa
	// https://github.com/mvdan/sh/commit/d48a421feafd08247e3b19a6f26b31008ab858c7
	pwd, err := os.Getwd()
	if err != nil {
		t.Fatal(err)
	}
	shDefaults := []string{
		fmt.Sprintf("HOME=%s", os.Getenv("HOME")),
		"IFS= \t\n",
		"OPTIND=1",
		fmt.Sprintf("PWD=%s", pwd),
		fmt.Sprintf("UID=%d", os.Getuid()),
		fmt.Sprintf("EUID=%d", os.Geteuid()),
		fmt.Sprintf("GID=%d", os.Getgid()),
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			env, err := EvaluateEnv(context.Background(), []byte(tt.script), tt.argv, tt.env)
			if !tt.expectErr && err != nil {
				t.Fatalf("unexpected error: %s", err)
			} else if tt.expectErr && err == nil {
				t.Fatalf("unexpected success")
			} else if !tt.expectErr {
				tt.resultEnv = append(tt.resultEnv, shDefaults...)
				sort.Strings(tt.resultEnv)
				sort.Strings(env)
				if !reflect.DeepEqual(tt.resultEnv, env) {
					t.Fatalf("unexpected variables:\nwant %v\ngot %v", tt.resultEnv, env)
				}
			}
		})
	}
}