From 6d360e6473917ca6742167a36ab2617b5bf394f9 Mon Sep 17 00:00:00 2001 From: Derek Nola Date: Mon, 31 Jul 2023 10:22:34 -0700 Subject: [PATCH] Unit test for MustFindString (#8013) Signed-off-by: Derek Nola --- pkg/configfilearg/defaultparser_test.go | 55 +++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/pkg/configfilearg/defaultparser_test.go b/pkg/configfilearg/defaultparser_test.go index b7c09308ef..8ae8decc26 100644 --- a/pkg/configfilearg/defaultparser_test.go +++ b/pkg/configfilearg/defaultparser_test.go @@ -1,6 +1,7 @@ package configfilearg import ( + "os" "reflect" "testing" ) @@ -72,3 +73,57 @@ func Test_UnitMustParse(t *testing.T) { }) } } + +func Test_UnitMustFindString(t *testing.T) { + tests := []struct { + name string + args []string + target string + setup func() error // Optional, delete if unused + teardown func() error // Optional, delete if unused + want string + }{ + { + name: "Target not found in config file", + args: []string{"--foo", "bar"}, + target: "token", + + want: "", + + setup: func() error { return os.Setenv("K3S_CONFIG_FILE", "./testdata/data.yaml") }, + teardown: func() error { return os.Unsetenv("K3S_CONFIG_FILE") }, + }, + { + name: "Target found in config file", + args: []string{"--foo", "bar"}, + target: "token", + + want: "12345", + + setup: func() error { return os.Setenv("K3S_CONFIG_FILE", "./testdata/defaultdata.yaml") }, + teardown: func() error { return os.Unsetenv("K3S_CONFIG_FILE") }, + }, + { + name: "Override flag found, function is short-circuited", + args: []string{"--foo", "bar", "-h"}, + target: "token", + + want: "-h", + + setup: func() error { return os.Setenv("K3S_CONFIG_FILE", "./testdata/defaultdata.yaml") }, + teardown: func() error { return os.Unsetenv("K3S_CONFIG_FILE") }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + defer tt.teardown() + if err := tt.setup(); err != nil { + t.Errorf("Setup for MustFindString() failed = %v", err) + return + } + if got := MustFindString(tt.args, tt.target); got != tt.want { + t.Errorf("MustFindString() = %+v\nWant = %+v", got, tt.want) + } + }) + } +}