Skip to content

Commit 7c99a5a

Browse files
authored
fix(scw.File): add unmarshal (#201)
1 parent 2b0ce7d commit 7c99a5a

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

scw/custom_types.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package scw
22

33
import (
4+
"bytes"
45
"encoding/json"
56
"fmt"
67
"io"
@@ -37,6 +38,24 @@ type File struct {
3738
Content io.Reader `json:"content"`
3839
}
3940

41+
func (f *File) UnmarshalJSON(b []byte) error {
42+
type file File
43+
var tmpFile struct {
44+
file
45+
Content []byte `json:"content"`
46+
}
47+
48+
err := json.Unmarshal(b, &tmpFile)
49+
if err != nil {
50+
return err
51+
}
52+
53+
tmpFile.file.Content = bytes.NewReader(tmpFile.Content)
54+
55+
*f = File(tmpFile.file)
56+
return nil
57+
}
58+
4059
// Money represents an amount of money with its currency type.
4160
type Money struct {
4261
// CurrencyCode is the 3-letter currency code defined in ISO 4217.

scw/custom_types_test.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package scw
22

33
import (
44
"encoding/json"
5+
"io/ioutil"
56
"testing"
67
"time"
78

@@ -123,3 +124,45 @@ func TestTimeSeries_UnmarshallJSON(t *testing.T) {
123124
})
124125
}
125126
}
127+
128+
func TestFile_UnmarshalJSON(t *testing.T) {
129+
130+
type testCase struct {
131+
json string
132+
name string
133+
contentType string
134+
content []byte
135+
}
136+
137+
run := func(c *testCase) func(t *testing.T) {
138+
return func(t *testing.T) {
139+
f := File{}
140+
err := json.Unmarshal([]byte(c.json), &f)
141+
testhelpers.AssertNoError(t, err)
142+
testhelpers.Equals(t, c.name, f.Name)
143+
testhelpers.Equals(t, c.contentType, f.ContentType)
144+
s, err := ioutil.ReadAll(f.Content)
145+
testhelpers.AssertNoError(t, err)
146+
testhelpers.Equals(t, c.content, s)
147+
}
148+
}
149+
150+
t.Run("empty", run(&testCase{
151+
json: `{}`,
152+
content: []byte{},
153+
}))
154+
155+
t.Run("strint_content", run(&testCase{
156+
json: `{"name": "test", "content_type":"text/plain", "content": "dGVzdDQyCg=="}`,
157+
name: "test",
158+
contentType: "text/plain",
159+
content: []byte("test42\n"),
160+
}))
161+
162+
t.Run("binary_content", run(&testCase{
163+
json: `{"name": "test", "content_type":"text/plain", "content": "AAAACg=="}`,
164+
name: "test",
165+
contentType: "text/plain",
166+
content: []byte("\x00\x00\x00\n"),
167+
}))
168+
}

0 commit comments

Comments
 (0)