terraform/command/jsonstate/state_test.go

368 lines
8.5 KiB
Go
Raw Normal View History

package jsonstate
import (
"encoding/json"
"reflect"
"testing"
"github.com/hashicorp/terraform/addrs"
"github.com/hashicorp/terraform/configs/configschema"
"github.com/hashicorp/terraform/states"
"github.com/hashicorp/terraform/terraform"
"github.com/zclconf/go-cty/cty"
)
func TestMarshalOutputs(t *testing.T) {
tests := []struct {
Outputs map[string]*states.OutputValue
Want map[string]output
Err bool
}{
{
nil,
nil,
false,
},
{
map[string]*states.OutputValue{
"test": {
Sensitive: true,
Value: cty.StringVal("sekret"),
},
},
map[string]output{
"test": {
Sensitive: true,
Value: json.RawMessage(`"sekret"`),
},
},
false,
},
{
map[string]*states.OutputValue{
"test": {
Sensitive: false,
Value: cty.StringVal("not_so_sekret"),
},
},
map[string]output{
"test": {
Sensitive: false,
Value: json.RawMessage(`"not_so_sekret"`),
},
},
false,
},
}
for _, test := range tests {
got, err := marshalOutputs(test.Outputs)
if test.Err {
if err == nil {
t.Fatal("succeeded; want error")
}
return
} else if err != nil {
t.Fatalf("unexpected error: %s", err)
}
eq := reflect.DeepEqual(got, test.Want)
if !eq {
// printing the output isn't terribly useful, but it does help indicate which test case failed
t.Fatalf("wrong result:\nGot: %#v\nWant: %#v\n", got, test.Want)
}
}
}
func TestMarshalAttributeValues(t *testing.T) {
tests := []struct {
Attr cty.Value
Schema *configschema.Block
Want attributeValues
}{
{
cty.NilVal,
&configschema.Block{
Attributes: map[string]*configschema.Attribute{
"foo": {
Type: cty.String,
Optional: true,
},
},
},
nil,
},
{
cty.NullVal(cty.String),
&configschema.Block{
Attributes: map[string]*configschema.Attribute{
"foo": {
Type: cty.String,
Optional: true,
},
},
},
nil,
},
{
cty.ObjectVal(map[string]cty.Value{
"foo": cty.StringVal("bar"),
}),
&configschema.Block{
Attributes: map[string]*configschema.Attribute{
"foo": {
Type: cty.String,
Optional: true,
},
},
},
mildwonkey/b-show-state (#20032) * command/show: properly marshal attribute values to json marshalAttributeValues in jsonstate and jsonplan packages was returning a cty.Value, which json/encoding could not marshal. These functions now convert those cty.Values into json.RawMessages. * command/jsonplan: planned values should include resources that are not changing * command/jsonplan: return a filtered list of proposed 'after' attributes Previously, proposed 'after' attributes were not being shown if the attributes were not WhollyKnown. jsonplan now iterates through all the `after` attributes, omitting those which are not wholly known. The same was roughly true for after_unknown, and that structure is now correctly populated. In the future we may choose to filter the after_unknown structure to _only_ display unknown attributes, instead of all attributes. * command/jsonconfig: use a unique key for providers so that aliased providers don't get munged together This now uses the same "provider" key from configs.Module, e.g. `providername.provideralias`. * command/jsonplan: unknownAsBool needs to iterate through objects that are not wholly known * command/jsonplan: properly display actions as strings according to the RFC, instead of a plans.Action string. For example: a plans.Action string DeleteThenCreate should be displayed as ["delete", "create"] Tests have been updated to reflect this. * command/jsonplan: return "null" for unknown list items. The length of a list could be meaningful on its own, so we will turn unknowns into "null". The same is less likely true for maps and objects, so we will continue to omit unknown values from those.
2019-01-23 20:46:53 +01:00
attributeValues{"foo": json.RawMessage(`"bar"`)},
},
{
cty.ObjectVal(map[string]cty.Value{
"foo": cty.NullVal(cty.String),
}),
&configschema.Block{
Attributes: map[string]*configschema.Attribute{
"foo": {
Type: cty.String,
Optional: true,
},
},
},
mildwonkey/b-show-state (#20032) * command/show: properly marshal attribute values to json marshalAttributeValues in jsonstate and jsonplan packages was returning a cty.Value, which json/encoding could not marshal. These functions now convert those cty.Values into json.RawMessages. * command/jsonplan: planned values should include resources that are not changing * command/jsonplan: return a filtered list of proposed 'after' attributes Previously, proposed 'after' attributes were not being shown if the attributes were not WhollyKnown. jsonplan now iterates through all the `after` attributes, omitting those which are not wholly known. The same was roughly true for after_unknown, and that structure is now correctly populated. In the future we may choose to filter the after_unknown structure to _only_ display unknown attributes, instead of all attributes. * command/jsonconfig: use a unique key for providers so that aliased providers don't get munged together This now uses the same "provider" key from configs.Module, e.g. `providername.provideralias`. * command/jsonplan: unknownAsBool needs to iterate through objects that are not wholly known * command/jsonplan: properly display actions as strings according to the RFC, instead of a plans.Action string. For example: a plans.Action string DeleteThenCreate should be displayed as ["delete", "create"] Tests have been updated to reflect this. * command/jsonplan: return "null" for unknown list items. The length of a list could be meaningful on its own, so we will turn unknowns into "null". The same is less likely true for maps and objects, so we will continue to omit unknown values from those.
2019-01-23 20:46:53 +01:00
attributeValues{"foo": json.RawMessage(`null`)},
},
{
cty.ObjectVal(map[string]cty.Value{
"bar": cty.MapVal(map[string]cty.Value{
"hello": cty.StringVal("world"),
}),
"baz": cty.ListVal([]cty.Value{
cty.StringVal("goodnight"),
cty.StringVal("moon"),
}),
}),
&configschema.Block{
Attributes: map[string]*configschema.Attribute{
"bar": {
Type: cty.Map(cty.String),
Required: true,
},
"baz": {
Type: cty.List(cty.String),
Optional: true,
},
},
},
attributeValues{
mildwonkey/b-show-state (#20032) * command/show: properly marshal attribute values to json marshalAttributeValues in jsonstate and jsonplan packages was returning a cty.Value, which json/encoding could not marshal. These functions now convert those cty.Values into json.RawMessages. * command/jsonplan: planned values should include resources that are not changing * command/jsonplan: return a filtered list of proposed 'after' attributes Previously, proposed 'after' attributes were not being shown if the attributes were not WhollyKnown. jsonplan now iterates through all the `after` attributes, omitting those which are not wholly known. The same was roughly true for after_unknown, and that structure is now correctly populated. In the future we may choose to filter the after_unknown structure to _only_ display unknown attributes, instead of all attributes. * command/jsonconfig: use a unique key for providers so that aliased providers don't get munged together This now uses the same "provider" key from configs.Module, e.g. `providername.provideralias`. * command/jsonplan: unknownAsBool needs to iterate through objects that are not wholly known * command/jsonplan: properly display actions as strings according to the RFC, instead of a plans.Action string. For example: a plans.Action string DeleteThenCreate should be displayed as ["delete", "create"] Tests have been updated to reflect this. * command/jsonplan: return "null" for unknown list items. The length of a list could be meaningful on its own, so we will turn unknowns into "null". The same is less likely true for maps and objects, so we will continue to omit unknown values from those.
2019-01-23 20:46:53 +01:00
"bar": json.RawMessage(`{"hello":"world"}`),
"baz": json.RawMessage(`["goodnight","moon"]`),
},
},
}
for _, test := range tests {
got := marshalAttributeValues(test.Attr, test.Schema)
eq := reflect.DeepEqual(got, test.Want)
if !eq {
mildwonkey/b-show-state (#20032) * command/show: properly marshal attribute values to json marshalAttributeValues in jsonstate and jsonplan packages was returning a cty.Value, which json/encoding could not marshal. These functions now convert those cty.Values into json.RawMessages. * command/jsonplan: planned values should include resources that are not changing * command/jsonplan: return a filtered list of proposed 'after' attributes Previously, proposed 'after' attributes were not being shown if the attributes were not WhollyKnown. jsonplan now iterates through all the `after` attributes, omitting those which are not wholly known. The same was roughly true for after_unknown, and that structure is now correctly populated. In the future we may choose to filter the after_unknown structure to _only_ display unknown attributes, instead of all attributes. * command/jsonconfig: use a unique key for providers so that aliased providers don't get munged together This now uses the same "provider" key from configs.Module, e.g. `providername.provideralias`. * command/jsonplan: unknownAsBool needs to iterate through objects that are not wholly known * command/jsonplan: properly display actions as strings according to the RFC, instead of a plans.Action string. For example: a plans.Action string DeleteThenCreate should be displayed as ["delete", "create"] Tests have been updated to reflect this. * command/jsonplan: return "null" for unknown list items. The length of a list could be meaningful on its own, so we will turn unknowns into "null". The same is less likely true for maps and objects, so we will continue to omit unknown values from those.
2019-01-23 20:46:53 +01:00
t.Fatalf("wrong result:\nGot: %#v\nWant: %#v\n", got, test.Want)
}
}
}
func TestMarshalResources(t *testing.T) {
deposedKey := states.NewDeposedKey()
tests := map[string]struct {
Resources map[string]*states.Resource
Schemas *terraform.Schemas
Want []resource
Err bool
}{
"nil": {
nil,
nil,
nil,
false,
},
"single resource": {
map[string]*states.Resource{
"test_thing.baz": {
Addr: addrs.Resource{
Mode: addrs.ManagedResourceMode,
Type: "test_thing",
Name: "bar",
},
EachMode: states.EachList,
Instances: map[addrs.InstanceKey]*states.ResourceInstance{
addrs.IntKey(0): {
Current: &states.ResourceInstanceObjectSrc{
SchemaVersion: 1,
Status: states.ObjectReady,
AttrsJSON: []byte(`{"woozles":"confuzles"}`),
},
},
},
Initial steps towards AbsProviderConfig/LocalProviderConfig separation (#23978) * Introduce "Local" terminology for non-absolute provider config addresses In a future change AbsProviderConfig and LocalProviderConfig are going to become two entirely distinct types, rather than Abs embedding Local as written here. This naming change is in preparation for that subsequent work, which will also include introducing a new "ProviderConfig" type that is an interface that AbsProviderConfig and LocalProviderConfig both implement. This is intended to be largely just a naming change to get started, so we can deal with all of the messy renaming. However, this did also require a slight change in modeling where the Resource.DefaultProviderConfig method has become Resource.DefaultProvider returning a Provider address directly, because this method doesn't have enough information to construct a true and accurate LocalProviderConfig -- it would need to refer to the configuration to know what this module is calling the provider it has selected. In order to leave a trail to follow for subsequent work, all of the changes here are intended to ensure that remaining work will become obvious via compile-time errors when all of the following changes happen: - The concept of "legacy" provider addresses is removed from the addrs package, including removing addrs.NewLegacyProvider and addrs.Provider.LegacyString. - addrs.AbsProviderConfig stops having addrs.LocalProviderConfig embedded in it and has an addrs.Provider and a string alias directly instead. - The provider-schema-handling parts of Terraform core are updated to work with addrs.Provider to identify providers, rather than legacy strings. In particular, there are still several codepaths here making legacy provider address assumptions (in order to limit the scope of this change) but I've made sure each one is doing something that relies on at least one of the above changes not having been made yet. * addrs: ProviderConfig interface In a (very) few special situations in the main "terraform" package we need to make runtime decisions about whether a provider config is absolute or local. We currently do that by exploiting the fact that AbsProviderConfig has LocalProviderConfig nested inside of it and so in the local case we can just ignore the wrapping AbsProviderConfig and use the embedded value. In a future change we'll be moving away from that embedding and making these two types distinct in order to represent that mapping between them requires consulting a lookup table in the configuration, and so here we introduce a new interface type ProviderConfig that can represent either AbsProviderConfig or LocalProviderConfig decided dynamically at runtime. This also includes the Config.ResolveAbsProviderAddr method that will eventually be responsible for that local-to-absolute translation, so that callers with access to the configuration can normalize to an addrs.AbsProviderConfig given a non-nil addrs.ProviderConfig. That's currently unused because existing callers are still relying on the simplistic structural transform, but we'll switch them over in a later commit. * rename LocalType to LocalName Co-authored-by: Kristin Laemmert <mildwonkey@users.noreply.github.com>
2020-01-31 14:23:07 +01:00
ProviderConfig: addrs.LocalProviderConfig{
LocalName: "test",
}.Absolute(addrs.RootModuleInstance),
},
},
testSchemas(),
[]resource{
resource{
Address: "test_thing.bar",
Mode: "managed",
Type: "test_thing",
Name: "bar",
Index: addrs.IntKey(0),
ProviderName: "test",
SchemaVersion: 1,
AttributeValues: attributeValues{
"foozles": json.RawMessage(`null`),
"woozles": json.RawMessage(`"confuzles"`),
},
},
},
false,
},
"deposed resource": {
map[string]*states.Resource{
"test_thing.baz": {
Addr: addrs.Resource{
Mode: addrs.ManagedResourceMode,
Type: "test_thing",
Name: "bar",
},
EachMode: states.EachList,
Instances: map[addrs.InstanceKey]*states.ResourceInstance{
addrs.IntKey(0): {
Deposed: map[states.DeposedKey]*states.ResourceInstanceObjectSrc{
states.DeposedKey(deposedKey): &states.ResourceInstanceObjectSrc{
SchemaVersion: 1,
Status: states.ObjectReady,
AttrsJSON: []byte(`{"woozles":"confuzles"}`),
},
},
},
},
Initial steps towards AbsProviderConfig/LocalProviderConfig separation (#23978) * Introduce "Local" terminology for non-absolute provider config addresses In a future change AbsProviderConfig and LocalProviderConfig are going to become two entirely distinct types, rather than Abs embedding Local as written here. This naming change is in preparation for that subsequent work, which will also include introducing a new "ProviderConfig" type that is an interface that AbsProviderConfig and LocalProviderConfig both implement. This is intended to be largely just a naming change to get started, so we can deal with all of the messy renaming. However, this did also require a slight change in modeling where the Resource.DefaultProviderConfig method has become Resource.DefaultProvider returning a Provider address directly, because this method doesn't have enough information to construct a true and accurate LocalProviderConfig -- it would need to refer to the configuration to know what this module is calling the provider it has selected. In order to leave a trail to follow for subsequent work, all of the changes here are intended to ensure that remaining work will become obvious via compile-time errors when all of the following changes happen: - The concept of "legacy" provider addresses is removed from the addrs package, including removing addrs.NewLegacyProvider and addrs.Provider.LegacyString. - addrs.AbsProviderConfig stops having addrs.LocalProviderConfig embedded in it and has an addrs.Provider and a string alias directly instead. - The provider-schema-handling parts of Terraform core are updated to work with addrs.Provider to identify providers, rather than legacy strings. In particular, there are still several codepaths here making legacy provider address assumptions (in order to limit the scope of this change) but I've made sure each one is doing something that relies on at least one of the above changes not having been made yet. * addrs: ProviderConfig interface In a (very) few special situations in the main "terraform" package we need to make runtime decisions about whether a provider config is absolute or local. We currently do that by exploiting the fact that AbsProviderConfig has LocalProviderConfig nested inside of it and so in the local case we can just ignore the wrapping AbsProviderConfig and use the embedded value. In a future change we'll be moving away from that embedding and making these two types distinct in order to represent that mapping between them requires consulting a lookup table in the configuration, and so here we introduce a new interface type ProviderConfig that can represent either AbsProviderConfig or LocalProviderConfig decided dynamically at runtime. This also includes the Config.ResolveAbsProviderAddr method that will eventually be responsible for that local-to-absolute translation, so that callers with access to the configuration can normalize to an addrs.AbsProviderConfig given a non-nil addrs.ProviderConfig. That's currently unused because existing callers are still relying on the simplistic structural transform, but we'll switch them over in a later commit. * rename LocalType to LocalName Co-authored-by: Kristin Laemmert <mildwonkey@users.noreply.github.com>
2020-01-31 14:23:07 +01:00
ProviderConfig: addrs.LocalProviderConfig{
LocalName: "test",
}.Absolute(addrs.RootModuleInstance),
},
},
testSchemas(),
[]resource{
resource{
Address: "test_thing.bar",
Mode: "managed",
Type: "test_thing",
Name: "bar",
Index: addrs.IntKey(0),
ProviderName: "test",
DeposedKey: deposedKey.String(),
AttributeValues: attributeValues{
"foozles": json.RawMessage(`null`),
"woozles": json.RawMessage(`"confuzles"`),
},
},
},
false,
},
"deposed and current resource": {
map[string]*states.Resource{
"test_thing.baz": {
Addr: addrs.Resource{
Mode: addrs.ManagedResourceMode,
Type: "test_thing",
Name: "bar",
},
EachMode: states.EachList,
Instances: map[addrs.InstanceKey]*states.ResourceInstance{
addrs.IntKey(0): {
Deposed: map[states.DeposedKey]*states.ResourceInstanceObjectSrc{
states.DeposedKey(deposedKey): &states.ResourceInstanceObjectSrc{
SchemaVersion: 1,
Status: states.ObjectReady,
AttrsJSON: []byte(`{"woozles":"confuzles"}`),
},
},
Current: &states.ResourceInstanceObjectSrc{
SchemaVersion: 1,
Status: states.ObjectReady,
AttrsJSON: []byte(`{"woozles":"confuzles"}`),
},
},
},
Initial steps towards AbsProviderConfig/LocalProviderConfig separation (#23978) * Introduce "Local" terminology for non-absolute provider config addresses In a future change AbsProviderConfig and LocalProviderConfig are going to become two entirely distinct types, rather than Abs embedding Local as written here. This naming change is in preparation for that subsequent work, which will also include introducing a new "ProviderConfig" type that is an interface that AbsProviderConfig and LocalProviderConfig both implement. This is intended to be largely just a naming change to get started, so we can deal with all of the messy renaming. However, this did also require a slight change in modeling where the Resource.DefaultProviderConfig method has become Resource.DefaultProvider returning a Provider address directly, because this method doesn't have enough information to construct a true and accurate LocalProviderConfig -- it would need to refer to the configuration to know what this module is calling the provider it has selected. In order to leave a trail to follow for subsequent work, all of the changes here are intended to ensure that remaining work will become obvious via compile-time errors when all of the following changes happen: - The concept of "legacy" provider addresses is removed from the addrs package, including removing addrs.NewLegacyProvider and addrs.Provider.LegacyString. - addrs.AbsProviderConfig stops having addrs.LocalProviderConfig embedded in it and has an addrs.Provider and a string alias directly instead. - The provider-schema-handling parts of Terraform core are updated to work with addrs.Provider to identify providers, rather than legacy strings. In particular, there are still several codepaths here making legacy provider address assumptions (in order to limit the scope of this change) but I've made sure each one is doing something that relies on at least one of the above changes not having been made yet. * addrs: ProviderConfig interface In a (very) few special situations in the main "terraform" package we need to make runtime decisions about whether a provider config is absolute or local. We currently do that by exploiting the fact that AbsProviderConfig has LocalProviderConfig nested inside of it and so in the local case we can just ignore the wrapping AbsProviderConfig and use the embedded value. In a future change we'll be moving away from that embedding and making these two types distinct in order to represent that mapping between them requires consulting a lookup table in the configuration, and so here we introduce a new interface type ProviderConfig that can represent either AbsProviderConfig or LocalProviderConfig decided dynamically at runtime. This also includes the Config.ResolveAbsProviderAddr method that will eventually be responsible for that local-to-absolute translation, so that callers with access to the configuration can normalize to an addrs.AbsProviderConfig given a non-nil addrs.ProviderConfig. That's currently unused because existing callers are still relying on the simplistic structural transform, but we'll switch them over in a later commit. * rename LocalType to LocalName Co-authored-by: Kristin Laemmert <mildwonkey@users.noreply.github.com>
2020-01-31 14:23:07 +01:00
ProviderConfig: addrs.LocalProviderConfig{
LocalName: "test",
}.Absolute(addrs.RootModuleInstance),
},
},
testSchemas(),
[]resource{
resource{
Address: "test_thing.bar",
Mode: "managed",
Type: "test_thing",
Name: "bar",
Index: addrs.IntKey(0),
ProviderName: "test",
SchemaVersion: 1,
AttributeValues: attributeValues{
mildwonkey/b-show-state (#20032) * command/show: properly marshal attribute values to json marshalAttributeValues in jsonstate and jsonplan packages was returning a cty.Value, which json/encoding could not marshal. These functions now convert those cty.Values into json.RawMessages. * command/jsonplan: planned values should include resources that are not changing * command/jsonplan: return a filtered list of proposed 'after' attributes Previously, proposed 'after' attributes were not being shown if the attributes were not WhollyKnown. jsonplan now iterates through all the `after` attributes, omitting those which are not wholly known. The same was roughly true for after_unknown, and that structure is now correctly populated. In the future we may choose to filter the after_unknown structure to _only_ display unknown attributes, instead of all attributes. * command/jsonconfig: use a unique key for providers so that aliased providers don't get munged together This now uses the same "provider" key from configs.Module, e.g. `providername.provideralias`. * command/jsonplan: unknownAsBool needs to iterate through objects that are not wholly known * command/jsonplan: properly display actions as strings according to the RFC, instead of a plans.Action string. For example: a plans.Action string DeleteThenCreate should be displayed as ["delete", "create"] Tests have been updated to reflect this. * command/jsonplan: return "null" for unknown list items. The length of a list could be meaningful on its own, so we will turn unknowns into "null". The same is less likely true for maps and objects, so we will continue to omit unknown values from those.
2019-01-23 20:46:53 +01:00
"foozles": json.RawMessage(`null`),
"woozles": json.RawMessage(`"confuzles"`),
},
},
resource{
Address: "test_thing.bar",
Mode: "managed",
Type: "test_thing",
Name: "bar",
Index: addrs.IntKey(0),
ProviderName: "test",
DeposedKey: deposedKey.String(),
AttributeValues: attributeValues{
"foozles": json.RawMessage(`null`),
"woozles": json.RawMessage(`"confuzles"`),
},
},
},
false,
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
got, err := marshalResources(test.Resources, test.Schemas)
if test.Err {
if err == nil {
t.Fatal("succeeded; want error")
}
return
} else if err != nil {
t.Fatalf("unexpected error: %s", err)
}
eq := reflect.DeepEqual(got, test.Want)
if !eq {
t.Fatalf("wrong result:\nGot: %#v\nWant: %#v\n", got, test.Want)
}
})
}
}
func testSchemas() *terraform.Schemas {
return &terraform.Schemas{
Providers: map[addrs.Provider]*terraform.ProviderSchema{
addrs.NewLegacyProvider("test"): &terraform.ProviderSchema{
ResourceTypes: map[string]*configschema.Block{
"test_thing": {
Attributes: map[string]*configschema.Attribute{
"woozles": {Type: cty.String, Optional: true, Computed: true},
"foozles": {Type: cty.String, Optional: true},
},
},
},
},
},
}
}