env_test.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. package os_test
  5. import (
  6. . "os"
  7. "reflect"
  8. "strings"
  9. "testing"
  10. )
  11. // testGetenv gives us a controlled set of variables for testing Expand.
  12. func testGetenv(s string) string {
  13. switch s {
  14. case "*":
  15. return "all the args"
  16. case "#":
  17. return "NARGS"
  18. case "$":
  19. return "PID"
  20. case "1":
  21. return "ARGUMENT1"
  22. case "HOME":
  23. return "/usr/gopher"
  24. case "H":
  25. return "(Value of H)"
  26. case "home_1":
  27. return "/usr/foo"
  28. case "_":
  29. return "underscore"
  30. }
  31. return ""
  32. }
  33. var expandTests = []struct {
  34. in, out string
  35. }{
  36. {"", ""},
  37. {"$*", "all the args"},
  38. {"$$", "PID"},
  39. {"${*}", "all the args"},
  40. {"$1", "ARGUMENT1"},
  41. {"${1}", "ARGUMENT1"},
  42. {"now is the time", "now is the time"},
  43. {"$HOME", "/usr/gopher"},
  44. {"$home_1", "/usr/foo"},
  45. {"${HOME}", "/usr/gopher"},
  46. {"${H}OME", "(Value of H)OME"},
  47. {"A$$$#$1$H$home_1*B", "APIDNARGSARGUMENT1(Value of H)/usr/foo*B"},
  48. }
  49. func TestExpand(t *testing.T) {
  50. for _, test := range expandTests {
  51. result := Expand(test.in, testGetenv)
  52. if result != test.out {
  53. t.Errorf("Expand(%q)=%q; expected %q", test.in, result, test.out)
  54. }
  55. }
  56. }
  57. func TestConsistentEnviron(t *testing.T) {
  58. e0 := Environ()
  59. for i := 0; i < 10; i++ {
  60. e1 := Environ()
  61. if !reflect.DeepEqual(e0, e1) {
  62. t.Fatalf("environment changed")
  63. }
  64. }
  65. }
  66. func TestUnsetenv(t *testing.T) {
  67. const testKey = "GO_TEST_UNSETENV"
  68. set := func() bool {
  69. prefix := testKey + "="
  70. for _, key := range Environ() {
  71. if strings.HasPrefix(key, prefix) {
  72. return true
  73. }
  74. }
  75. return false
  76. }
  77. if err := Setenv(testKey, "1"); err != nil {
  78. t.Fatalf("Setenv: %v", err)
  79. }
  80. if !set() {
  81. t.Error("Setenv didn't set TestUnsetenv")
  82. }
  83. if err := Unsetenv(testKey); err != nil {
  84. t.Fatalf("Unsetenv: %v", err)
  85. }
  86. if set() {
  87. t.Fatal("Unsetenv didn't clear TestUnsetenv")
  88. }
  89. }