Skip to content

Commit

Permalink
add test
Browse files Browse the repository at this point in the history
  • Loading branch information
jerome-quere committed Oct 7, 2019
1 parent f3a36ca commit 5e65885
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 9 deletions.
14 changes: 5 additions & 9 deletions scw/custom_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package scw

import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io"
Expand Down Expand Up @@ -40,23 +39,20 @@ type File struct {
}

func (f *File) UnmarshalJSON(b []byte) error {
type file File
var tmpFile struct {
File
Content string `json:"content"`
file
Content []byte `json:"content"`
}

err := json.Unmarshal(b, &tmpFile)
if err != nil {
return err
}

content, err := base64.StdEncoding.DecodeString(tmpFile.Content)
if err != nil {
return err
}
tmpFile.File.Content = bytes.NewReader(content)
tmpFile.file.Content = bytes.NewReader(tmpFile.Content)

*f = tmpFile.File
*f = File(tmpFile.file)
return nil
}

Expand Down
43 changes: 43 additions & 0 deletions scw/custom_types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package scw

import (
"encoding/json"
"io/ioutil"
"testing"
"time"

Expand Down Expand Up @@ -123,3 +124,45 @@ func TestTimeSeries_UnmarshallJSON(t *testing.T) {
})
}
}

func TestFile_UnmarshalJSON(t *testing.T) {

type testCase struct {
json string
name string
contentType string
content []byte
}

run := func(c *testCase) func(t *testing.T) {
return func(t *testing.T) {
f := File{}
err := json.Unmarshal([]byte(c.json), &f)
testhelpers.AssertNoError(t, err)
testhelpers.Equals(t, c.name, f.Name)
testhelpers.Equals(t, c.contentType, f.ContentType)
s, err := ioutil.ReadAll(f.Content)
testhelpers.AssertNoError(t, err)
testhelpers.Equals(t, c.content, s)
}
}

t.Run("empty", run(&testCase{
json: `{}`,
content: []byte{},
}))

t.Run("strint_content", run(&testCase{
json: `{"name": "test", "content_type":"text/plain", "content": "dGVzdDQyCg=="}`,
name: "test",
contentType: "text/plain",
content: []byte("test42\n"),
}))

t.Run("binary_content", run(&testCase{
json: `{"name": "test", "content_type":"text/plain", "content": "AAAACg=="}`,
name: "test",
contentType: "text/plain",
content: []byte("\x00\x00\x00\n"),
}))
}

0 comments on commit 5e65885

Please sign in to comment.