github.com/NeowayLabs/nash@v0.2.2-0.20200127205349-a227041ffd50/nash_test.go (about) 1 package nash 2 3 import ( 4 "bytes" 5 "io/ioutil" 6 "os" 7 "testing" 8 9 "github.com/madlambda/nash/sh" 10 "github.com/madlambda/nash/tests" 11 ) 12 13 // only testing the public API 14 // bypass to internal sh.Shell 15 16 func TestExecuteFile(t *testing.T) { 17 testfile := tests.Testdir + "/ex1.sh" 18 19 var out bytes.Buffer 20 shell, cleanup := newTestShell(t) 21 defer cleanup() 22 23 shell.SetNashdPath(tests.Nashcmd) 24 shell.SetStdout(&out) 25 shell.SetStderr(os.Stderr) 26 shell.SetStdin(os.Stdin) 27 28 err := shell.ExecuteFile(testfile) 29 if err != nil { 30 t.Error(err) 31 return 32 } 33 34 if string(out.Bytes()) != "hello world\n" { 35 t.Errorf("Wrong command output: '%s'", string(out.Bytes())) 36 return 37 } 38 } 39 40 func TestExecuteString(t *testing.T) { 41 shell, cleanup := newTestShell(t) 42 defer cleanup() 43 44 var out bytes.Buffer 45 46 shell.SetStdout(&out) 47 48 err := shell.ExecuteString("-ínput-", "echo -n AAA") 49 if err != nil { 50 t.Error(err) 51 return 52 } 53 54 if string(out.Bytes()) != "AAA" { 55 t.Errorf("Unexpected '%s'", string(out.Bytes())) 56 return 57 } 58 59 out.Reset() 60 61 err = shell.ExecuteString("-input-", ` 62 PROMPT="humpback> " 63 setenv PROMPT 64 `) 65 if err != nil { 66 t.Error(err) 67 return 68 } 69 70 prompt := shell.Prompt() 71 if prompt != "humpback> " { 72 t.Errorf("Invalid prompt = %s", prompt) 73 return 74 } 75 76 } 77 78 func TestSetvar(t *testing.T) { 79 shell, cleanup := newTestShell(t) 80 defer cleanup() 81 82 shell.Newvar("__TEST__", sh.NewStrObj("something")) 83 84 var out bytes.Buffer 85 shell.SetStdout(&out) 86 87 err := shell.Exec("TestSetvar", `echo -n $__TEST__`) 88 89 if err != nil { 90 t.Error(err) 91 return 92 } 93 94 if string(out.Bytes()) != "something" { 95 t.Errorf("Value differ: '%s' != '%s'", string(out.Bytes()), "something") 96 return 97 } 98 99 val, ok := shell.Getvar("__TEST__") 100 101 if !ok || val.String() != "something" { 102 t.Errorf("Getvar doesn't work: '%s' != '%s'", val, "something") 103 return 104 } 105 } 106 107 func newTestShell(t *testing.T) (*Shell, func()) { 108 t.Helper() 109 110 nashpath, pathclean := tmpdir(t) 111 nashroot, rootclean := tmpdir(t) 112 113 s, err := NewAbort(nashpath, nashroot) 114 if err != nil { 115 t.Fatal(err) 116 } 117 118 return s, func() { 119 pathclean() 120 rootclean() 121 } 122 } 123 124 func tmpdir(t *testing.T) (string, func()) { 125 t.Helper() 126 127 dir, err := ioutil.TempDir("", "nash-tests") 128 if err != nil { 129 t.Fatal(err) 130 } 131 132 return dir, func() { 133 err := os.RemoveAll(dir) 134 if err != nil { 135 t.Fatal(err) 136 } 137 } 138 }