File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -265,7 +265,28 @@ func (r *Resource) InternalValidate(topSchemaMap schemaMap) error {
265265 return schemaMap (r .Schema ).InternalValidate (tsm )
266266}
267267
268+ // Data returns a ResourceData struct for this Resource. Each return value
269+ // is a separate copy and can be safely modified differently.
270+ //
271+ // The data returned from this function has no actual affect on the Resource
272+ // itself (including the state given to this function).
273+ //
274+ // This function is useful for unit tests and ResourceImporter functions.
275+ func (r * Resource ) Data (s * terraform.InstanceState ) * ResourceData {
276+ result , err := schemaMap (r .Schema ).Data (s , nil )
277+ if err != nil {
278+ // At the time of writing, this isn't possible (Data never returns
279+ // non-nil errors). We panic to find this in the future if we have to.
280+ // I don't see a reason for Data to ever return an error.
281+ panic (err )
282+ }
283+
284+ return result
285+ }
286+
268287// TestResourceData Yields a ResourceData filled with this resource's schema for use in unit testing
288+ //
289+ // TODO: May be able to be removed with the above ResourceData function.
269290func (r * Resource ) TestResourceData () * ResourceData {
270291 return & ResourceData {
271292 schema : r .Schema ,
Original file line number Diff line number Diff line change @@ -846,3 +846,51 @@ func TestResourceRefresh_migrateStateErr(t *testing.T) {
846846 t .Fatal ("expected error, but got none!" )
847847 }
848848}
849+
850+ func TestResourceData (t * testing.T ) {
851+ r := & Resource {
852+ SchemaVersion : 2 ,
853+ Schema : map [string ]* Schema {
854+ "foo" : & Schema {
855+ Type : TypeInt ,
856+ Optional : true ,
857+ },
858+ },
859+ }
860+
861+ state := & terraform.InstanceState {
862+ ID : "foo" ,
863+ Attributes : map [string ]string {
864+ "id" : "foo" ,
865+ "foo" : "42" ,
866+ },
867+ }
868+
869+ data := r .Data (state )
870+ if data .Id () != "foo" {
871+ t .Fatalf ("err: %s" , data .Id ())
872+ }
873+ if v := data .Get ("foo" ); v != 42 {
874+ t .Fatalf ("bad: %#v" , v )
875+ }
876+ }
877+
878+ func TestResourceData_blank (t * testing.T ) {
879+ r := & Resource {
880+ SchemaVersion : 2 ,
881+ Schema : map [string ]* Schema {
882+ "foo" : & Schema {
883+ Type : TypeInt ,
884+ Optional : true ,
885+ },
886+ },
887+ }
888+
889+ data := r .Data (nil )
890+ if data .Id () != "" {
891+ t .Fatalf ("err: %s" , data .Id ())
892+ }
893+ if v := data .Get ("foo" ); v != 0 {
894+ t .Fatalf ("bad: %#v" , v )
895+ }
896+ }
You can’t perform that action at this time.
0 commit comments