summaryrefslogtreecommitdiffstats
path: root/pkg/test/utils.go
blob: 47f2c11466c8c48e6b5ee01c84e7544c3f72c1a0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package test

import (
	"fmt"
	"os/exec"
	"regexp"
	"strings"
	"testing"

	"github.com/jesseduffield/lazygit/pkg/secureexec"
	"github.com/mgutz/str"
	"github.com/stretchr/testify/assert"
)

// CommandSwapper takes a command, verifies that it is what it's expected to be
// and then returns a replacement command that will actually be called by the os
type CommandSwapper struct {
	Expect  string
	Replace string
}

// SwapCommand verifies the command is what we expected, and swaps it out for a different command
func (i *CommandSwapper) SwapCommand(t *testing.T, cmd string, args []string) *exec.Cmd {
	splitCmd := str.ToArgv(i.Expect)
	assert.EqualValues(t, splitCmd[0], cmd, fmt.Sprintf("received command: %s %s", cmd, strings.Join(args, " ")))
	if len(splitCmd) > 1 {
		assert.EqualValues(t, splitCmd[1:], args, fmt.Sprintf("received command: %s %s", cmd, strings.Join(args, " ")))
	}

	splitCmd = str.ToArgv(i.Replace)
	return secureexec.Command(splitCmd[0], splitCmd[1:]...)
}

// CreateMockCommand creates a command function that will verify its receiving the right sequence of commands from lazygit
func CreateMockCommand(t *testing.T, swappers []*CommandSwapper) func(cmd string, args ...string) *exec.Cmd {
	commandIndex := 0

	return func(cmd string, args ...string) *exec.Cmd {
		var command *exec.Cmd
		if commandIndex > len(swappers)-1 {
			assert.Fail(t, fmt.Sprintf("too many commands run. This command was (%s %s)", cmd, strings.Join(args, " ")))
		}
		command = swappers[commandIndex].SwapCommand(t, cmd, args)
		commandIndex++
		return command
	}
}

func AssertContainsMatch(t *testing.T, strs []string, pattern *regexp.Regexp, message string) {
	t.Helper()

	for _, str := range strs {
		if pattern.Match([]byte(str)) {
			return
		}
	}

	assert.Fail(t, message)
}