github.com/nilium/gitlab-runner@v12.5.0+incompatible/shells/shell_writer_test.go (about) 1 package shells_test 2 3 import ( 4 "io/ioutil" 5 "os" 6 "os/exec" 7 "path" 8 "path/filepath" 9 "testing" 10 11 "github.com/stretchr/testify/assert" 12 "github.com/stretchr/testify/require" 13 14 "gitlab.com/gitlab-org/gitlab-runner/shells" 15 "gitlab.com/gitlab-org/gitlab-runner/shells/shellstest" 16 ) 17 18 func runShell(t *testing.T, shell, cwd string, writer shells.ShellWriter) { 19 var extension string 20 var cmdArgs []string 21 22 switch shell { 23 case "bash": 24 extension = "sh" 25 26 case "cmd": 27 extension = "cmd" 28 cmdArgs = append(cmdArgs, "/Q", "/C") 29 30 case "powershell": 31 extension = "ps1" 32 cmdArgs = append(cmdArgs, "-noprofile", "-noninteractive", "-executionpolicy", "Bypass", "-command") 33 34 default: 35 require.FailNow(t, "unknown shell %q", shell) 36 } 37 38 script := writer.Finish(false) 39 scriptFile := filepath.Join(cwd, shell+"-test-script."+extension) 40 err := ioutil.WriteFile(scriptFile, []byte(script), 0700) 41 require.NoError(t, err) 42 defer os.Remove(scriptFile) 43 44 cmdArgs = append(cmdArgs, scriptFile) 45 cmd := exec.Command(shell, cmdArgs...) 46 cmd.Dir = cwd 47 48 output, err := cmd.CombinedOutput() 49 require.NoError(t, err, "output: %s", string(output)) 50 } 51 52 func TestMkDir(t *testing.T) { 53 const TestPath = "test-path" 54 55 tmpDir, err := ioutil.TempDir("", "runner-test") 56 require.NoError(t, err) 57 defer os.RemoveAll(tmpDir) 58 59 shellstest.OnEachShellWithWriter(t, func(t *testing.T, shell string, writer shells.ShellWriter) { 60 testTmpDir := writer.MkTmpDir(shell + "-mkdir-test") 61 writer.Cd(testTmpDir) 62 writer.MkDir(TestPath) 63 writer.MkDir(TestPath) 64 65 runShell(t, shell, tmpDir, writer) 66 67 createdPath := filepath.Join(tmpDir, testTmpDir, TestPath) 68 _, err := ioutil.ReadDir(createdPath) 69 assert.NoError(t, err) 70 }) 71 } 72 73 func TestRmFile(t *testing.T) { 74 const TestPath = "test-path" 75 76 tmpDir, err := ioutil.TempDir("", "runner-test") 77 require.NoError(t, err) 78 defer os.RemoveAll(tmpDir) 79 80 shellstest.OnEachShellWithWriter(t, func(t *testing.T, shell string, writer shells.ShellWriter) { 81 tmpFile := path.Join(tmpDir, TestPath) 82 err = ioutil.WriteFile(tmpFile, []byte{}, 0600) 83 require.NoError(t, err) 84 85 writer.RmFile(TestPath) 86 87 runShell(t, shell, tmpDir, writer) 88 89 _, err = os.Stat(tmpFile) 90 require.True(t, os.IsNotExist(err), "tmpFile not deleted") 91 92 // check if the file do not exist 93 runShell(t, shell, tmpDir, writer) 94 }) 95 }