Skip to content

Commit 37ce192

Browse files
committed
config: Reduce code duplication in tests
1 parent 2ee29d0 commit 37ce192

File tree

1 file changed

+11
-9
lines changed

1 file changed

+11
-9
lines changed

config/config_test.go

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -194,9 +194,7 @@ default-key: overridden-value`,
194194
func TestFromEnv(t *testing.T) {
195195
for _, tc := range configTests {
196196
t.Run(tc.Name, tc.F(func(data testutils.ConfigTestData) (Validator, error) {
197-
// Since our test cases only define the expected configuration,
198-
// we need to create a new instance of that type for FromEnv to parse the configuration into.
199-
actual := reflect.New(reflect.TypeOf(tc.Expected).Elem()).Interface().(Validator)
197+
actual := createValidatorInstance(tc.Expected)
200198

201199
err := FromEnv(actual, EnvOptions{Environment: data.Env})
202200

@@ -227,9 +225,7 @@ func TestFromEnv(t *testing.T) {
227225
func TestFromYAMLFile(t *testing.T) {
228226
for _, tc := range configTests {
229227
t.Run(tc.Name, tc.F(func(data testutils.ConfigTestData) (Validator, error) {
230-
// Since our test cases only define the expected configuration,
231-
// we need to create a new instance of that type for FromYAMLFile to parse the configuration into.
232-
actual := reflect.New(reflect.TypeOf(tc.Expected).Elem()).Interface().(Validator)
228+
actual := createValidatorInstance(tc.Expected)
233229

234230
var err error
235231
testutils.WithYAMLFile(t, data.Yaml, func(file *os.File) {
@@ -405,9 +401,7 @@ func TestLoad(t *testing.T) {
405401

406402
for _, tc := range loadTests {
407403
t.Run(tc.Name, tc.F(func(data testutils.ConfigTestData) (Validator, error) {
408-
// Since our test cases only define the expected configuration,
409-
// we need to create a new instance of that type for Load to parse the configuration into.
410-
actual := reflect.New(reflect.TypeOf(tc.Expected).Elem()).Interface().(Validator)
404+
actual := createValidatorInstance(tc.Expected)
411405

412406
var err error
413407
if data.Yaml != "" {
@@ -528,3 +522,11 @@ func TestParseFlags(t *testing.T) {
528522
require.Contains(t, string(out), "-h, --help")
529523
})
530524
}
525+
526+
// createValidatorInstance creates a new instance of the same type as the provided value.
527+
//
528+
// Since our test cases only define the expected configuration,
529+
// we need to create a new instance of that type for our functions to parse the configuration into.
530+
func createValidatorInstance(v Validator) Validator {
531+
return reflect.New(reflect.TypeOf(v).Elem()).Interface().(Validator)
532+
}

0 commit comments

Comments
 (0)