1// Copyright 2010 The Go 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
5package os_test
6
7import (
8	. "os"
9	"reflect"
10	"strings"
11	"testing"
12)
13
14// testGetenv gives us a controlled set of variables for testing Expand.
15func testGetenv(s string) string {
16	switch s {
17	case "*":
18		return "all the args"
19	case "#":
20		return "NARGS"
21	case "$":
22		return "PID"
23	case "1":
24		return "ARGUMENT1"
25	case "HOME":
26		return "/usr/gopher"
27	case "H":
28		return "(Value of H)"
29	case "home_1":
30		return "/usr/foo"
31	case "_":
32		return "underscore"
33	}
34	return ""
35}
36
37var expandTests = []struct {
38	in, out string
39}{
40	{"", ""},
41	{"$*", "all the args"},
42	{"$$", "PID"},
43	{"${*}", "all the args"},
44	{"$1", "ARGUMENT1"},
45	{"${1}", "ARGUMENT1"},
46	{"now is the time", "now is the time"},
47	{"$HOME", "/usr/gopher"},
48	{"$home_1", "/usr/foo"},
49	{"${HOME}", "/usr/gopher"},
50	{"${H}OME", "(Value of H)OME"},
51	{"A$$$#$1$H$home_1*B", "APIDNARGSARGUMENT1(Value of H)/usr/foo*B"},
52}
53
54func TestExpand(t *testing.T) {
55	for _, test := range expandTests {
56		result := Expand(test.in, testGetenv)
57		if result != test.out {
58			t.Errorf("Expand(%q)=%q; expected %q", test.in, result, test.out)
59		}
60	}
61}
62
63func TestConsistentEnviron(t *testing.T) {
64	e0 := Environ()
65	for i := 0; i < 10; i++ {
66		e1 := Environ()
67		if !reflect.DeepEqual(e0, e1) {
68			t.Fatalf("environment changed")
69		}
70	}
71}
72
73func TestUnsetenv(t *testing.T) {
74	const testKey = "GO_TEST_UNSETENV"
75	set := func() bool {
76		prefix := testKey + "="
77		for _, key := range Environ() {
78			if strings.HasPrefix(key, prefix) {
79				return true
80			}
81		}
82		return false
83	}
84	if err := Setenv(testKey, "1"); err != nil {
85		t.Fatalf("Setenv: %v", err)
86	}
87	if !set() {
88		t.Error("Setenv didn't set TestUnsetenv")
89	}
90	if err := Unsetenv(testKey); err != nil {
91		t.Fatalf("Unsetenv: %v", err)
92	}
93	if set() {
94		t.Fatal("Unsetenv didn't clear TestUnsetenv")
95	}
96}
97
98func TestLookupEnv(t *testing.T) {
99	const smallpox = "SMALLPOX"      // No one has smallpox.
100	value, ok := LookupEnv(smallpox) // Should not exist.
101	if ok || value != "" {
102		t.Fatalf("%s=%q", smallpox, value)
103	}
104	defer Unsetenv(smallpox)
105	err := Setenv(smallpox, "virus")
106	if err != nil {
107		t.Fatalf("failed to release smallpox virus")
108	}
109	value, ok = LookupEnv(smallpox)
110	if !ok {
111		t.Errorf("smallpox release failed; world remains safe but LookupEnv is broken")
112	}
113}
114