Skip to content

Commit

Permalink
refactor: Bring presetalert resources calls to new style
Browse files Browse the repository at this point in the history
  • Loading branch information
darinspivey committed Jun 1, 2021
1 parent 4553236 commit dfb1590
Show file tree
Hide file tree
Showing 11 changed files with 345 additions and 265 deletions.
4 changes: 2 additions & 2 deletions logdna/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (

type providerConfig struct {
serviceKey string
baseURL string
baseURL string
httpClient *http.Client
}

Expand Down Expand Up @@ -41,7 +41,7 @@ func providerConfigure(d *schema.ResourceData) (interface{}, error) {

return &providerConfig{
serviceKey: servicekey,
baseURL: url,
baseURL: url,
httpClient: &http.Client{Timeout: 15 * time.Second},
}, nil
}
8 changes: 8 additions & 0 deletions logdna/provider_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,11 @@ func TestProvider(t *testing.T) {
func TestProvider_impl(t *testing.T) {
var _ *schema.Provider = Provider()
}

// testAccPreCheck validates the necessary test API keys exist
// in the testing environment
func testAccPreCheck(t *testing.T) {
if servicekey == "" {
t.Fatal("'servicekey' environment variable must be set for acceptance tests")
}
}
61 changes: 2 additions & 59 deletions logdna/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package logdna
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
Expand All @@ -30,14 +29,6 @@ type requestConfig struct {
jsonMarshal jsonMarshal
}

// AlertResponsePayload contains the keys/vals used in alert API responses
type AlertResponsePayload struct {
Channels []channelResponse `json:"channels,omitempty"`
Error string `json:"error,omitempty"`
Name string `json:"name,omitempty"`
PresetID string `json:"presetid,omitempty"`
}

// newRequestConfig abstracts the struct creation to allow for mocking
func newRequestConfig(pc *providerConfig, method string, uri string, body interface{}, mutators ...func(*requestConfig)) *requestConfig {
rc := &requestConfig{
Expand Down Expand Up @@ -76,64 +67,16 @@ func (c *requestConfig) MakeRequest() ([]byte, error) {
req.Header.Set("servicekey", c.serviceKey)
res, err := c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("Error during HTTP request: %s, %+v", err, c)
return nil, fmt.Errorf("Error during HTTP request: %s", err)
}
defer res.Body.Close()

body, err := c.bodyReader(res.Body)
if err != nil {
return nil, fmt.Errorf("Error parsing HTTP response: %s, %+v", err, c)
return nil, fmt.Errorf("Error parsing HTTP response: %s, %s", err, string(body))
}
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s %s, status %d NOT OK! %s", c.method, c.apiURL, res.StatusCode, string(body))
}
return body, err
}

// MakeRequestAlert makes a HTTP request to the config-api with alert payload data and parses and returns the response
func MakeRequestAlert(c *requestConfig, url string, urlsuffix string, method string, payload viewRequest) (string, error) {
pbytes, err := json.Marshal(payload)
if err != nil {
return "", err
}
req, err := http.NewRequest(method, url+urlsuffix, bytes.NewBuffer(pbytes))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("servicekey", c.serviceKey)
resp, err := c.httpClient.Do(req)
if err != nil {
return "", fmt.Errorf(`Error with alert: %s`, err)
}
defer resp.Body.Close()
var result AlertResponsePayload
err = json.NewDecoder(resp.Body).Decode(&result)
if err != nil {
return "", err
}

if resp.StatusCode != 200 {
return "", errors.New(result.Error)
}

return result.PresetID, nil
}

// CreateAlert creates a Preset Alert with the provided payload
func (c *requestConfig) CreateAlert(url string, payload viewRequest) (string, error) {
result, err := MakeRequestAlert(c, url, "/v1/config/presetalert", "POST", payload)
return result, err
}

// UpdateAlert updates a Preset Alert with the provided presetID and payload
func (c *requestConfig) UpdateAlert(url string, presetID string, payload viewRequest) error {
_, err := MakeRequestAlert(c, url, "/v1/config/presetalert/"+presetID, "PUT", payload)
return err
}

// DeleteAlert deletes an alert with the provided presetID
func (c *requestConfig) DeleteAlert(url, presetID string) error {
_, err := MakeRequestAlert(c, url, "/v1/config/presetalert/"+presetID, "DELETE", viewRequest{})
return err
}
5 changes: 3 additions & 2 deletions logdna/request_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,9 +131,10 @@ func iterateIntegrationType(
var prepared interface{}
channelRequests := []channelRequest{}

if listEntries == nil {
return nil
if len(listEntries) == 0 {
return &channelRequests
}

for _, entry := range listEntries {
e := entry.(map[string]interface{})
prepared = nil
Expand Down
31 changes: 31 additions & 0 deletions logdna/request_types_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package logdna

import (
"testing"

"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/stretchr/testify/assert"
)

func TestRequestTypes_iterateIntegrationType(t *testing.T) {
assert := assert.New(t)

t.Run("Inserts a Diagnostics error for an unknown integration type", func(t *testing.T) {
var diags diag.Diagnostics
nonEmptyEntry := []interface{}{
map[string]interface{}{
"nah": "will not work",
},
}

channelRequests := iterateIntegrationType(nonEmptyEntry, "NOPE", &diags)

assert.Empty(*channelRequests, "Nothing was returned")
assert.Len(diags, 1, "There was 1 error")
assert.True(diags.HasError(), "The message is of type `Error`")

err := diags[0]
assert.Equal("Cannot format integration channel for outbound request", err.Summary, "Summary")
assert.Equal("Unrecognized integration: NOPE", err.Detail, "Detail")
})
}
Loading

0 comments on commit dfb1590

Please sign in to comment.