Skip to content

Commit

Permalink
testscript: add *TestScript.Setenv method (#25)
Browse files Browse the repository at this point in the history
Allows environment variables to be set by Run-Param commands.
  • Loading branch information
myitcv authored and rogpeppe committed Nov 26, 2018
1 parent 9bd3ae4 commit 9b2bd7c
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 2 deletions.
3 changes: 1 addition & 2 deletions testscript/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -194,8 +194,7 @@ func (ts *TestScript) cmdEnv(neg bool, args []string) {
ts.Logf("%s=%s\n", env, ts.envMap[env])
continue
}
ts.env = append(ts.env, env)
ts.envMap[env[:i]] = env[i+1:]
ts.Setenv(env[:i], env[i+1:])
}
}

Expand Down
6 changes: 6 additions & 0 deletions testscript/scripts/setenv.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
setSpecialVal
exists $SPECIALVAL.txt
ensureSpecialVal

-- 42.txt --
Douglas Adams
11 changes: 11 additions & 0 deletions testscript/testscript.go
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,17 @@ func (ts *TestScript) MkAbs(file string) string {
return filepath.Join(ts.cd, file)
}

// Setenv sets the value of the environment variable named by the key.
func (ts *TestScript) Setenv(key, value string) {
ts.env = append(ts.env, key+"="+value)
ts.envMap[key] = value
}

// Getenv gets the value of the environment variable named by the key.
func (ts *TestScript) Getenv(key string) string {
return ts.envMap[key]
}

// parse parses a single line as a list of space-separated arguments
// subject to environment variable expansion (but not resplitting).
// Single quotes around text disable splitting and expansion.
Expand Down
15 changes: 15 additions & 0 deletions testscript/testscript_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,25 @@ func TestSimple(t *testing.T) {
// TODO set temp directory.
Run(t, Params{
Dir: "scripts",
Cmds: map[string]func(ts *TestScript, neg bool, args []string){
"setSpecialVal": setSpecialVal,
"ensureSpecialVal": ensureSpecialVal,
},
})
// TODO check that the temp directory has been removed.
}

func setSpecialVal(ts *TestScript, neg bool, args []string) {
ts.Setenv("SPECIALVAL", "42")
}

func ensureSpecialVal(ts *TestScript, neg bool, args []string) {
want := "42"
if got := ts.Getenv("SPECIALVAL"); got != want {
ts.Fatalf("expected SPECIALVAL to be %q; got %q", want, got)
}
}

var diffTests = []struct {
text1 string
text2 string
Expand Down

0 comments on commit 9b2bd7c

Please sign in to comment.