summaryrefslogtreecommitdiffstats
path: root/modules/git/command_test.go
blob: d3b8338d02f89af63889e5e5ed766004026503e3 (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
60
61
62
63
64
65
66
67
68
69
70
// Copyright 2022 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package git

import (
	"context"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestRunWithContextStd(t *testing.T) {
	cmd := NewCommand(context.Background(), "--version")
	stdout, stderr, err := cmd.RunStdString(&RunOpts{})
	require.NoError(t, err)
	assert.Empty(t, stderr)
	assert.Contains(t, stdout, "git version")

	cmd = NewCommand(context.Background(), "--no-such-arg")
	stdout, stderr, err = cmd.RunStdString(&RunOpts{})
	if assert.Error(t, err) {
		assert.Equal(t, stderr, err.Stderr())
		assert.Contains(t, err.Stderr(), "unknown option:")
		assert.Contains(t, err.Error(), "exit status 129 - unknown option:")
		assert.Empty(t, stdout)
	}

	cmd = NewCommand(context.Background())
	cmd.AddDynamicArguments("-test")
	require.ErrorIs(t, cmd.Run(&RunOpts{}), ErrBrokenCommand)

	cmd = NewCommand(context.Background())
	cmd.AddDynamicArguments("--test")
	require.ErrorIs(t, cmd.Run(&RunOpts{}), ErrBrokenCommand)

	subCmd := "version"
	cmd = NewCommand(context.Background()).AddDynamicArguments(subCmd) // for test purpose only, the sub-command should never be dynamic for production
	stdout, stderr, err = cmd.RunStdString(&RunOpts{})
	require.NoError(t, err)
	assert.Empty(t, stderr)
	assert.Contains(t, stdout, "git version")
}

func TestGitArgument(t *testing.T) {
	assert.True(t, isValidArgumentOption("-x"))
	assert.True(t, isValidArgumentOption("--xx"))
	assert.False(t, isValidArgumentOption(""))
	assert.False(t, isValidArgumentOption("x"))

	assert.True(t, isSafeArgumentValue(""))
	assert.True(t, isSafeArgumentValue("x"))
	assert.False(t, isSafeArgumentValue("-x"))
}

func TestCommandString(t *testing.T) {
	cmd := NewCommandContextNoGlobals(context.Background(), "a", "-m msg", "it's a test", `say "hello"`)
	assert.EqualValues(t, cmd.prog+` a "-m msg" "it's a test" "say \"hello\""`, cmd.String())

	cmd = NewCommandContextNoGlobals(context.Background(), "url: https://a:b@c/")
	assert.EqualValues(t, cmd.prog+` "url: https://sanitized-credential@c/"`, cmd.toString(true))
}

func TestGrepOnlyFunction(t *testing.T) {
	cmd := NewCommand(context.Background(), "anything-but-grep")
	assert.Panics(t, func() {
		cmd.AddGitGrepExpression("whatever")
	})
}