Skip to content

Commit

Permalink
config: Reduce code duplication in tests
Browse files Browse the repository at this point in the history
  • Loading branch information
lippserd committed Oct 31, 2024
1 parent 069e535 commit 79829da
Showing 1 changed file with 11 additions and 9 deletions.
20 changes: 11 additions & 9 deletions config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -194,9 +194,7 @@ default-key: overridden-value`,
func TestFromEnv(t *testing.T) {
for _, tc := range configTests {
t.Run(tc.Name, tc.F(func(data testutils.ConfigTestData) (Validator, error) {
// Since our test cases only define the expected configuration,
// we need to create a new instance of that type for FromEnv to parse the configuration into.
actual := reflect.New(reflect.TypeOf(tc.Expected).Elem()).Interface().(Validator)
actual := createValidatorInstance(tc.Expected)

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

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

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

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

var err error
if data.Yaml != "" {
Expand Down Expand Up @@ -528,3 +522,11 @@ func TestParseFlags(t *testing.T) {
require.Contains(t, string(out), "-h, --help")
})
}

// createValidatorInstance creates a new instance of the same type as the provided value.
//
// Since our test cases only define the expected configuration,
// we need to create a new instance of that type for our functions to parse the configuration into.
func createValidatorInstance(v Validator) Validator {
return reflect.New(reflect.TypeOf(v).Elem()).Interface().(Validator)
}

0 comments on commit 79829da

Please sign in to comment.