-
Notifications
You must be signed in to change notification settings - Fork 1
/
builder_test.go
109 lines (74 loc) · 2.39 KB
/
builder_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package multipartbuilder_test
import (
"io"
"mime"
"mime/multipart"
"strings"
. "github.com/mxmCherry/multipartbuilder"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Builder", func() {
var subject *Builder
BeforeEach(func() {
subject = New()
})
Context("fields", func() {
It("should add single field", func() {
subject.AddField("field_name", "FIELD_VALUE")
form := readForm(subject.Build())
Expect(form.Value).To(Equal(map[string][]string{
"field_name": {"FIELD_VALUE"},
}))
})
}) // fields context
Context("readers", func() {
It("should add reader", func() {
subject.AddReader("field_name", "file.bin", strings.NewReader("READER_CONTENTS"))
form := readForm(subject.Build())
Expect(form.File).To(HaveKey("field_name"))
Expect(form.File["field_name"]).To(HaveLen(1))
fileHeader := form.File["field_name"][0]
Expect(fileHeader).NotTo(BeNil())
Expect(fileHeader.Filename).To(Equal("file.bin"))
Expect(read(fileHeader)).To(Equal("READER_CONTENTS"))
})
}) // readers context
Context("files", func() {
It("should add file", func() {
subject.AddFile("field_name", "testdata/file.txt")
form := readForm(subject.Build())
Expect(form.File).To(HaveKey("field_name"))
Expect(form.File["field_name"]).To(HaveLen(1))
fileHeader := form.File["field_name"][0]
Expect(fileHeader).NotTo(BeNil())
Expect(fileHeader.Filename).To(Equal("file.txt"))
Expect(read(fileHeader)).To(Equal("FILE_TXT_CONTENTS\n"))
})
}) // files context
Context("errors", func() {
It("should report errors", func() {
subject.AddFile("file1", "testdata/inexisting.txt")
_, reader := subject.Build()
_, err := io.ReadAll(reader)
Expect(err.Error()).To(ContainSubstring("multipartbuilder: failed to open file file1 (testdata/inexisting.txt)"))
})
}) // errors context
})
func readForm(ctype string, r io.Reader) *multipart.Form {
const maxMemory = 1024 * 1024
mediaType, params, err := mime.ParseMediaType(ctype)
Expect(err).NotTo(HaveOccurred())
Expect(strings.HasPrefix(mediaType, "multipart/"))
mr := multipart.NewReader(r, params["boundary"])
form, err := mr.ReadForm(maxMemory)
Expect(err).NotTo(HaveOccurred())
return form
}
func read(fh *multipart.FileHeader) string {
r, err := fh.Open()
Expect(err).NotTo(HaveOccurred())
b, err := io.ReadAll(r)
Expect(err).NotTo(HaveOccurred())
return string(b)
}