forked from pocketbase/pocketbase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.go
63 lines (55 loc) · 1.18 KB
/
request.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
package tests
import (
"bytes"
"io"
"mime/multipart"
"os"
)
// MockMultipartData creates a mocked multipart/form-data payload.
//
// Example
//
// data, mp, err := tests.MockMultipartData(
// map[string]string{"title": "new"},
// "file1",
// "file2",
// ...
// )
func MockMultipartData(data map[string]string, fileFields ...string) (*bytes.Buffer, *multipart.Writer, error) {
body := new(bytes.Buffer)
mp := multipart.NewWriter(body)
defer mp.Close()
// write data fields
for k, v := range data {
mp.WriteField(k, v)
}
// write file fields
for _, fileField := range fileFields {
// create a test temporary file
err := func() error {
tmpFile, err := os.CreateTemp(os.TempDir(), "tmpfile-*.txt")
if err != nil {
return err
}
if _, err := tmpFile.Write([]byte("test")); err != nil {
return err
}
tmpFile.Seek(0, 0)
defer tmpFile.Close()
defer os.Remove(tmpFile.Name())
// stub uploaded file
w, err := mp.CreateFormFile(fileField, tmpFile.Name())
if err != nil {
return err
}
if _, err := io.Copy(w, tmpFile); err != nil {
return err
}
return nil
}()
if err != nil {
return nil, nil, err
}
}
return body, mp, nil
}