1// +build !integration
2
3package shells
4
5import (
6	"fmt"
7	"strings"
8	"testing"
9
10	"github.com/stretchr/testify/assert"
11
12	"gitlab.com/gitlab-org/gitlab-runner/common"
13)
14
15func TestPwshTrapScriptGeneration(t *testing.T) {
16	shellInfo := common.ShellScriptInfo{
17		Shell:         SNPwsh,
18		Type:          common.NormalShell,
19		RunnerCommand: "/usr/bin/gitlab-runner-helper",
20		Build: &common.Build{
21			Runner: &common.RunnerConfig{},
22		},
23	}
24	shellInfo.Build.Runner.Executor = "kubernetes"
25	shellInfo.Build.Hostname = "Test Hostname"
26
27	pwshTrap := &PwshTrapShell{
28		PowerShell: common.GetShell(SNPwsh).(*PowerShell),
29		LogFile:    "/path/to/logfile",
30	}
31
32	tests := map[string]struct {
33		stage                common.BuildStage
34		info                 common.ShellScriptInfo
35		expectedError        error
36		assertExpectedScript func(*testing.T, string)
37	}{
38		"prepare script": {
39			stage: common.BuildStagePrepare,
40			info:  shellInfo,
41			assertExpectedScript: func(t *testing.T, s string) {
42				assert.Contains(t, s, "#!/usr/bin/env pwsh")
43				assert.Contains(t, s, fmt.Sprintf(
44					strings.ReplaceAll(pwshTrapShellScript, "\n", pwshTrap.EOL),
45					pwshTrap.LogFile,
46				))
47				assert.Contains(t, s, `echo "Running on $([Environment]::MachineName) via "Test Hostname"..."`)
48				assert.Contains(t, s, `trap {runner_script_trap} runner_script_trap`)
49				assert.Contains(t, s, `exit 0`)
50			},
51		},
52		"cleanup variables": {
53			stage: common.BuildStageCleanupFileVariables,
54			info:  shellInfo,
55			assertExpectedScript: func(t *testing.T, s string) {
56				assert.Empty(t, s)
57			},
58		},
59		"no script": {
60			stage:         "no_script",
61			info:          shellInfo,
62			expectedError: common.ErrSkipBuildStage,
63		},
64	}
65
66	for tn, tc := range tests {
67		t.Run(tn, func(t *testing.T) {
68			script, err := pwshTrap.GenerateScript(tc.stage, tc.info)
69			if tc.expectedError != nil {
70				assert.ErrorIs(t, err, tc.expectedError)
71				return
72			}
73
74			tc.assertExpectedScript(t, script)
75		})
76	}
77}
78