File: resolver_test.go

package info (click to toggle)
golang-gopkg-alecthomas-kingpin.v3 3.0~git20180227.b8d601d-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 420 kB
  • sloc: makefile: 6
file content (83 lines) | stat: -rw-r--r-- 2,350 bytes parent folder | download
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
71
72
73
74
75
76
77
78
79
80
81
82
83
package kingpin

import (
	"os"
	"testing"

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

func TestResolverSimple(t *testing.T) {
	app := newTestApp()
	app.Resolver(MapResolver(map[string][]string{"hello": []string{"world"}}))
	f := app.Flag("hello", "help").String()
	_, err := app.Parse([]string{})
	assert.NoError(t, err)
	assert.Equal(t, "world", *f)
}

func TestResolverSatisfiesRequired(t *testing.T) {
	app := newTestApp()
	app.Resolver(MapResolver(map[string][]string{"hello": []string{"world"}}))
	f := app.Flag("hello", "help").Required().String()
	_, err := app.Parse([]string{})
	assert.NoError(t, err)
	assert.Equal(t, "world", *f)
}

func TestResolverLowerPriorityThanFlag(t *testing.T) {
	app := newTestApp()
	app.Resolver(MapResolver(map[string][]string{"hello": []string{"world"}}))
	f := app.Flag("hello", "help").String()
	_, err := app.Parse([]string{"--hello", "there"})
	assert.NoError(t, err)
	assert.Equal(t, "there", *f)
}

func TestResolverFallbackWithMultipleResolvers(t *testing.T) {
	app := newTestApp()
	app.Resolver(MapResolver(map[string][]string{"hello": []string{"there"}, "foo": []string{"bar"}}))
	app.Resolver(MapResolver(map[string][]string{"hello": []string{"world"}}))
	f1 := app.Flag("hello", "help").String()
	f2 := app.Flag("foo", "help").String()
	_, err := app.Parse([]string{})
	assert.NoError(t, err)
	assert.Equal(t, "world", *f1)
	assert.Equal(t, "bar", *f2)
}

func TestResolverLowerPriorityThanEnvar(t *testing.T) {
	os.Setenv("TEST_RESOLVER", "foo")
	app := newTestApp()
	app.Resolver(MapResolver(map[string][]string{"hello": []string{"world"}}))
	f := app.Flag("hello", "help").Envar("TEST_RESOLVER").String()
	_, err := app.Parse([]string{})
	assert.NoError(t, err)
	assert.Equal(t, "foo", *f)
}

func TestJSONResolver(t *testing.T) {
	r, err := JSONResolver([]byte(`{
		"str": "string",
		"num": 1234,
		"bool": true,
		"array": ["a", "b"]
	}`))
	assert.NoError(t, err)

	values, err := r.Resolve("str", nil)
	assert.NoError(t, err)
	assert.Equal(t, []string{"string"}, values)

	values, err = r.Resolve("num", nil)
	assert.NoError(t, err)
	assert.Equal(t, []string{"1234"}, values)

	values, err = r.Resolve("bool", nil)
	assert.NoError(t, err)
	assert.Equal(t, []string{"true"}, values)

	values, err = r.Resolve("array", nil)
	assert.NoError(t, err)
	assert.Equal(t, []string{"a", "b"}, values)
}