Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion cmd/download.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package cmd

import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
netURL "net/url"
"os"
Expand Down Expand Up @@ -185,7 +187,10 @@ func newDownload(flags *pflag.FlagSet, usrCfg *viper.Viper) (*download, error) {
}
defer res.Body.Close()

if err := json.NewDecoder(res.Body).Decode(&d.payload); err != nil {
body, err := ioutil.ReadAll(res.Body)
res.Body = ioutil.NopCloser(bytes.NewReader(body))

if err := json.Unmarshal(body, &d.payload); err != nil || res.StatusCode < 200 || res.StatusCode > 299 {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The decodedAPIError already unmarshals the error, right? Can we move all the error handling logic into that method?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The response body can only be read once. If we unmarshal or decode the body before saving a copy we wouldn't have a way to decode the JSON into the error struct.

return nil, decodedAPIError(res)
}

Expand Down
36 changes: 36 additions & 0 deletions cmd/download_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,42 @@ func assertDownloadedCorrectFiles(t *testing.T, targetDir string) {
assert.True(t, os.IsNotExist(err), "It should not write the file if empty.")
}

func TestDownloadError(t *testing.T) {
Comment thread
Jrank2013 marked this conversation as resolved.
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, `{"error": {"type": "error", "message": "test error"}}`)
})

ts := httptest.NewServer(handler)
defer ts.Close()

tmpDir, err := ioutil.TempDir("", "submit-err-tmp-dir")
defer os.RemoveAll(tmpDir)
assert.NoError(t, err)

v := viper.New()
v.Set("token", "abc123")
v.Set("workspace", tmpDir)
v.Set("apibaseurl", ts.URL)

cfg := config.Config{
Persister: config.InMemoryPersister{},
UserViperConfig: v,
DefaultBaseURL: "http://example.com",
}

flags := pflag.NewFlagSet("fake", pflag.PanicOnError)
setupDownloadFlags(flags)
flags.Set("uuid", "value")

err = runDownload(cfg, flags, []string{})

fmt.Println(err)
Comment thread
Jrank2013 marked this conversation as resolved.
Outdated

assert.Regexp(t, "test error", err.Error())
Comment thread
Jrank2013 marked this conversation as resolved.
Outdated

}

const payloadTemplate = `
{
"solution": {
Expand Down