Skip to content

Commit

Permalink
fix
Browse files Browse the repository at this point in the history
  • Loading branch information
artemvang committed Jun 10, 2024
1 parent 3b6bab2 commit 5d73594
Show file tree
Hide file tree
Showing 4 changed files with 8 additions and 106 deletions.
2 changes: 0 additions & 2 deletions configuration_version.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,6 @@ type ConfigurationVersion struct {
Status ConfigurationStatus `jsonapi:"attr,status"`
// Relations
Workspace *Workspace `jsonapi:"relation,workspace"`
// Links
Links map[string]string
}

// ConfigurationVersionCreateOptions represents the options for creating a
Expand Down
29 changes: 1 addition & 28 deletions configuration_version_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"context"
"fmt"
"testing"
"time"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
Expand All @@ -22,17 +21,11 @@ func TestConfigurationVersionsCreate(t *testing.T) {
ConfigurationVersionCreateOptions{Workspace: wsTest},
)
require.NoError(t, err)
assert.Equal(t, ConfigurationPending, cv.Status)
assert.Contains(t, cv.Links["upload"], "blobs/")

// Get a refreshed view of the configuration version.
refreshed, err := client.ConfigurationVersions.Read(ctx, cv.ID)
require.NoError(t, err)
assert.Equal(t, cv.ID, refreshed.ID)
assert.Equal(t, ConfigurationPending, refreshed.Status)
assert.Equal(t, cv.Workspace, refreshed.Workspace)
assert.Equal(t, cv.Links["self"], refreshed.Links["self"])
assert.Equal(t, "", refreshed.Links["upload"])
assert.Equal(t, cv, refreshed)
})
t.Run("when no workspace is provided", func(t *testing.T) {
_, err := client.ConfigurationVersions.Create(ctx, ConfigurationVersionCreateOptions{})
Expand All @@ -47,26 +40,6 @@ func TestConfigurationVersionsCreate(t *testing.T) {
assert.Nil(t, cv)
assert.EqualError(t, err, "invalid value for workspace ID")
})

t.Run("with uploaded blob", func(t *testing.T) {
cv, err := client.ConfigurationVersions.Create(ctx,
ConfigurationVersionCreateOptions{Workspace: wsTest},
)
require.NoError(t, err)
uploadBlob(cv.Links["upload"])

i := 1
for ; i <= 10; i++ {
refreshed, err := client.ConfigurationVersions.Read(ctx, cv.ID)
require.NoError(t, err)
assert.Equal(t, cv.ID, refreshed.ID)
if refreshed.Status == ConfigurationUploaded {
return
}
time.Sleep(time.Second)
}
assert.NotEqual(t, 10, i)
})
}

func TestConfigurationVersionsRead(t *testing.T) {
Expand Down
34 changes: 0 additions & 34 deletions helper_test.go
Original file line number Diff line number Diff line change
@@ -1,19 +1,14 @@
package scalr

import (
"bytes"
"context"
"encoding/base64"
"fmt"
"net/http"
"os"
"strings"
"testing"

"github.com/hashicorp/go-uuid"
)

const tfArchiveBase64 = "H4sIAECmYWYAA+2STQrCMBCFu84phh5AJ/8rD5NFKgVbpZ10I97dpj9ShHYjRcR8mwfhTZiXF/ItHbN9QUSrNQxqRkWhRp0AroxEKSRaC8gltzwDvfNeA6El1/SruIZ81bn6vOLrbUWxcc+U46U/AsX+K1fWB9pK9xH9exil1vvn0sz9C2t5379SGjPAvRZa8uf9XwPdAkEe/wHP4c4AOncJHk7zGXswtnSJ0dX6ui2p7KKTmuDfB0Uc/Ha6RCKRSKzxBOV743QACgAA"
const defaultAccountID = "acc-svrcncgh453bi8g"
const defaultAccountName = "mainiacp"
const defaultModuleID = "mod-svsmkkjo8sju4o0"
Expand Down Expand Up @@ -527,32 +522,3 @@ func createSlackIntegration(
}
}
}

func uploadBlob(blobURL string) error {
data, _ := base64.StdEncoding.DecodeString(tfArchiveBase64)
req, err := http.NewRequest("PUT", blobURL, bytes.NewBuffer(data))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/octet-stream")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if err != nil {
return err
} else {
body := &bytes.Buffer{}
_, err := body.ReadFrom(resp.Body)
if err != nil {
return err
}
if resp.StatusCode >= 300 {
return fmt.Errorf("Bad status code on blob upload")
}
}

return nil
}
49 changes: 7 additions & 42 deletions scalr.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,6 @@ func DefaultConfig() *Config {

// Set the default user agent.
config.Headers.Set("User-Agent", userAgent)
// Set the default API Profile.
config.Headers.Set("Prefer", "profile=preview")

return config
}
Expand Down Expand Up @@ -354,6 +352,7 @@ func (c *Client) newJsonRequest(method, path string, v interface{}) (*retryableh
}

func (c *Client) createRequest(method, url string, rawBody interface{}, reqHeaders http.Header) (*retryablehttp.Request, error) {

req, err := retryablehttp.NewRequest(method, url, rawBody)
if err != nil {
return nil, err
Expand Down Expand Up @@ -423,27 +422,14 @@ func (c *Client) do(ctx context.Context, req *retryablehttp.Request, v interface
return fmt.Errorf("v must be a struct or an io.Writer")
}

response, err := io.ReadAll(resp.Body)
if err != nil {
return err
}

// Try to get the Items and Pagination struct fields.
items := dst.FieldByName("Items")
pagination := dst.FieldByName("Pagination")
links := dst.FieldByName("Links")

if links.IsValid() {
if links.Type().Kind() != reflect.Map {
return fmt.Errorf("v.Links must be a map")
}
unmarshalLinks(bytes.NewReader(response), links)
}

// Unmarshal a single value if v does not contain the
// Items and Pagination struct fields.
if !items.IsValid() || !pagination.IsValid() {
return jsonapi.UnmarshalPayload(bytes.NewReader(response), v)
return jsonapi.UnmarshalPayload(resp.Body, v)
}

// Return an error if v.Items is not a slice.
Expand All @@ -452,8 +438,11 @@ func (c *Client) do(ctx context.Context, req *retryablehttp.Request, v interface
}

// Create a temporary buffer and copy all the read data into it.
body := bytes.NewBuffer(nil)
reader := io.TeeReader(resp.Body, body)

// Unmarshal as a list of values as v.Items is a slice.
raw, err := jsonapi.UnmarshalManyPayload(bytes.NewReader(response), items.Type().Elem())
raw, err := jsonapi.UnmarshalManyPayload(reader, items.Type().Elem())
if err != nil {
return err
}
Expand All @@ -472,7 +461,7 @@ func (c *Client) do(ctx context.Context, req *retryablehttp.Request, v interface

// As we are getting a list of values, we need to decode
// the pagination details out of the response body.
p, err := parsePagination(bytes.NewReader(response))
p, err := parsePagination(body)
if err != nil {
return err
}
Expand Down Expand Up @@ -517,30 +506,6 @@ func parsePagination(body io.Reader) (*Pagination, error) {
return &raw.Meta.Pagination, nil
}

func unmarshalLinks(body io.Reader, links reflect.Value) error {
var raw struct {
Data struct {
Links map[string]string `json:"links"`
} `json:"data"`
}

// JSON decode the raw response.
if err := json.NewDecoder(body).Decode(&raw); err != nil {
return err
}

links.Set(reflect.MakeMap(reflect.ValueOf(raw.Data.Links).Type()))

// Add all of the results to the new map.
for k, v := range raw.Data.Links {
targetKey := reflect.ValueOf(k)
targetValue := reflect.ValueOf(v)
links.SetMapIndex(targetKey, targetValue)
}

return nil
}

// checkResponseCode can be used to check the status code of an HTTP request.
func checkResponseCode(r *http.Response) error {
if r.StatusCode >= 200 && r.StatusCode <= 299 {
Expand Down

0 comments on commit 5d73594

Please sign in to comment.