Skip to content

Commit

Permalink
add read support for data source instance
Browse files Browse the repository at this point in the history
- added corresponding test coverage
  • Loading branch information
dikhan committed Oct 1, 2019
1 parent d4fdfbc commit 9afcba7
Show file tree
Hide file tree
Showing 2 changed files with 132 additions and 1 deletion.
28 changes: 27 additions & 1 deletion openapi/data_source_instance_factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package openapi

import (
"fmt"
"net/http"

"github.com/hashicorp/terraform/helper/schema"
)
Expand Down Expand Up @@ -29,7 +30,7 @@ func (d dataSourceInstanceFactory) createTerraformInstanceDataSource() (*schema.
}
return &schema.Resource{
Schema: s,
//Read: d.read,
Read: d.read,
}, nil
}

Expand All @@ -49,3 +50,28 @@ func (d dataSourceInstanceFactory) dataSourceInstanceSchema() *schema.Schema {
Required: true,
}
}

func (d dataSourceInstanceFactory) read(data *schema.ResourceData, i interface{}) error {
openAPIClient := i.(ClientOpenAPI)
parentIDs, resourcePath, err := getParentIDsAndResourcePath(d.openAPIResource, data)
if err != nil {
return err
}
id := data.Get(dataSourceInstanceIDProperty)
if id == nil || id == "" {
return fmt.Errorf("data source 'id' property value must be populated")
}
responsePayload := map[string]interface{}{}
resp, err := openAPIClient.Get(d.openAPIResource, id.(string), &responsePayload, parentIDs...)
if err != nil {
return err
}
if err := checkHTTPStatusCode(d.openAPIResource, resp, []int{http.StatusOK}); err != nil {
return fmt.Errorf("[data source instance='%s'] GET %s failed: %s", d.openAPIResource.getResourceName(), resourcePath, err)
}
err = setStateID(d.openAPIResource, data, responsePayload)
if err != nil {
return err
}
return updateStateWithPayloadData(d.openAPIResource, responsePayload, data)
}
105 changes: 105 additions & 0 deletions openapi/data_source_instance_factory_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"errors"
"github.com/hashicorp/terraform/helper/schema"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"net/http"
"testing"
)

Expand Down Expand Up @@ -114,3 +116,106 @@ func TestCreateTerraformDataSourceInstance(t *testing.T) {
}
}
}

func TestDataSourceInstanceRead(t *testing.T) {

testCases := []struct {
name string
inputID string
client *clientOpenAPIStub
expectedResult map[string]interface{}
expectedError error
}{
{
name: "fetch selected data source as per input ID",
inputID: "ID",
client: &clientOpenAPIStub{
responsePayload: map[string]interface{}{
"id": "someID",
"label": "someLabel",
"owners": []string{"someOwner"},
},
},
expectedError: nil,
},
{
name: "input ID is empty",
inputID: "",
client: &clientOpenAPIStub{
responsePayload: map[string]interface{}{
"id": "someID",
"label": "someLabel",
"owners": []string{"someOwner"},
},
},
expectedError: errors.New("data source 'id' property value must be populated"),
},
{
name: "empty response from API",
inputID: "ID",
client: &clientOpenAPIStub{
responsePayload: map[string]interface{}{},
},
expectedError: errors.New("response object returned from the API is missing mandatory identifier property 'id'"),
},
{
name: "api returns a non expected code 404",
inputID: "ID",
client: &clientOpenAPIStub{
responsePayload: map[string]interface{}{},
returnHTTPCode: http.StatusNotFound,
},
expectedError: errors.New("[data source instance=''] GET failed: HTTP Reponse Status Code 404 - Not Found. Could not find resource instance: "),
},
{
name: "get operation returns an error",
inputID: "ID",
client: &clientOpenAPIStub{
error: errors.New("some api error in the get operation"),
},
expectedError: errors.New("some api error in the get operation"),
},
}

dataSourceFactory := dataSourceInstanceFactory{
openAPIResource: &specStubResource{
schemaDefinition: &specSchemaDefinition{
Properties: specSchemaDefinitionProperties{
newStringSchemaDefinitionPropertyWithDefaults("id", "", false, true, nil),
newStringSchemaDefinitionPropertyWithDefaults("label", "", false, false, nil),
newListSchemaDefinitionPropertyWithDefaults("owners", "", true, false, false, []string{"value1"}, typeString, nil),
},
},
},
}

for _, tc := range testCases {
resourceSchema, err := dataSourceFactory.createTerraformDataSourceInstanceSchema()
require.NoError(t, err)

dataSourceUserInput := map[string]interface{}{
dataSourceInstanceIDProperty: tc.inputID,
}
resourceData := schema.TestResourceDataRaw(t, resourceSchema, dataSourceUserInput)
// When
err = dataSourceFactory.read(resourceData, tc.client)
// Then
if tc.expectedError == nil {
assert.Nil(t, err, tc.name)
assert.Equal(t, tc.client.responsePayload["id"], resourceData.Id(), tc.name)
assert.Equal(t, tc.client.responsePayload["label"], resourceData.Get("label"), tc.name)
expectedOwners := tc.client.responsePayload["owners"].([]string)
owners := resourceData.Get("owners").([]interface{})
assert.NotNil(t, owners, tc.name)
assert.NotNil(t, len(expectedOwners), len(owners), tc.name)
assert.Equal(t, expectedOwners[0], owners[0], tc.name)
} else {
assert.Equal(t, tc.expectedError.Error(), err.Error(), tc.name)
}
}
}

func TestDataSourceInstanceRead_Fails_Because_Cannot_extract_ParentsID(t *testing.T) {
err := dataSourceInstanceFactory{}.read(nil, &clientOpenAPIStub{})
assert.EqualError(t, err, "can't get parent ids from a resourceFactory with no openAPIResource")
}

0 comments on commit 9afcba7

Please sign in to comment.