diff --git a/CHANGELOG.md b/CHANGELOG.md index 8fa5364414..2a81155a97 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,6 +66,7 @@ BUG FIXES: * Skip imports blocks logic on `tofu destroy` ([#2214](https://github.com/opentofu/opentofu/pull/2214)) * Updated github.com/golang-jwt/jwt/v4 from 4.4.2 to 4.5.1 to make security scanners happy (no vulnerability, see [#2179](https://github.com/opentofu/opentofu/pull/2179)) * `tofu test` is now setting `null`s for dynamic type when generating mock values. ([#2245](https://github.com/opentofu/opentofu/pull/2245)) +* Variables declared in test files are now taking into account type default values. ([#2244](https://github.com/opentofu/opentofu/pull/2244)) INTERNAL CHANGES: diff --git a/internal/command/test.go b/internal/command/test.go index c20bf647a3..7be349f0b3 100644 --- a/internal/command/test.go +++ b/internal/command/test.go @@ -1148,6 +1148,13 @@ func parseAndApplyDefaultValues(unparsedVariables map[string]backend.UnparsedVar for name, variable := range unparsedVariables { value, valueDiags := variable.ParseVariableValue(configs.VariableParseLiteral) diags = diags.Append(valueDiags) + + // Even so the variable is declared, some of the fields could + // be empty and filled in via type default values. + if confVariable, ok := configVariables[name]; ok && confVariable.TypeDefaults != nil { + value.Value = confVariable.TypeDefaults.Apply(value.Value) + } + inputs[name] = value } diff --git a/internal/command/testdata/test/default_variables/main.tf b/internal/command/testdata/test/default_variables/main.tf index ce7d9e83d8..8b49cafa8f 100644 --- a/internal/command/testdata/test/default_variables/main.tf +++ b/internal/command/testdata/test/default_variables/main.tf @@ -3,3 +3,10 @@ variable "input" { type = string default = "Hello, world!" } + +variable "another_input" { + type = object({ + optional_string = optional(string, "type_default") + optional_number = optional(number, 42) + }) +} diff --git a/internal/command/testdata/test/default_variables/main.tftest.hcl b/internal/command/testdata/test/default_variables/main.tftest.hcl index a6292d0923..caf95220c5 100644 --- a/internal/command/testdata/test/default_variables/main.tftest.hcl +++ b/internal/command/testdata/test/default_variables/main.tftest.hcl @@ -4,4 +4,20 @@ run "applies_defaults" { condition = var.input == "Hello, world!" error_message = "should have applied default value" } + + variables { + another_input = { + optional_string = "Hello, world!" + } + } + + assert { + condition = var.another_input.optional_string == "Hello, world!" + error_message = "should have used custom value from test file" + } + + assert { + condition = var.another_input.optional_number == 42 + error_message = "should have used default type value" + } }