github.com/reiver/go@v0.0.0-20150109200633-1d0c7792f172/src/os/env_test.go (about)

     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  
     5  package os_test
     6  
     7  import (
     8  	. "os"
     9  	"reflect"
    10  	"strings"
    11  	"testing"
    12  )
    13  
    14  // testGetenv gives us a controlled set of variables for testing Expand.
    15  func 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  
    37  var 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  
    54  func 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  
    63  func 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  
    73  func 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  }