-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparam_formdata_test.go
More file actions
101 lines (80 loc) · 2.23 KB
/
param_formdata_test.go
File metadata and controls
101 lines (80 loc) · 2.23 KB
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
package restgo
import (
"bytes"
"strings"
"testing"
)
// TestNewFormBody 测试 NewFormBody 函数
func TestNewFormBody(t *testing.T) {
fields := map[string]string{
"name": "John Doe",
"email": "john@example.com",
}
files := map[string][]byte{
"avatar": []byte("fake image data"),
}
body, err := NewFormBody(fields, files)
if err != nil {
t.Fatalf("NewFormBody failed: %v", err)
}
if body == nil {
t.Fatal("body should not be nil")
}
if body.ContentType == "" {
t.Fatal("ContentType should not be empty")
}
if !strings.Contains(body.ContentType, "multipart/form-data") {
t.Fatalf("ContentType should contain 'multipart/form-data', got: %s", body.ContentType)
}
// 读取 body 内容
buf := new(bytes.Buffer)
_, err = buf.ReadFrom(body.Value)
if err != nil {
t.Fatalf("Failed to read body: %v", err)
}
bodyStr := buf.String()
if !strings.Contains(bodyStr, "name") ||
!strings.Contains(bodyStr, "John Doe") {
t.Fatal("body should contain form fields")
}
if !strings.Contains(bodyStr, "avatar") {
t.Fatal("body should contain file field")
}
t.Log("TestNewFormBody passed")
}
// TestFormDataBuilder 测试 FormDataBuilder
func TestFormDataBuilder(t *testing.T) {
builder := NewFormDataBuilder().
AddField("username", "alice").
AddField("password", "secret123").
AddFile("profile", []byte("profile image data"))
body, err := NewFormBodyBuilder(builder)
if err != nil {
t.Fatalf("NewFormBodyBuilder failed: %v", err)
}
if body == nil {
t.Fatal("body should not be nil")
}
if !strings.Contains(body.ContentType, "multipart/form-data") {
t.Fatalf("ContentType should contain 'multipart/form-data'")
}
t.Log("TestFormDataBuilder passed")
}
// TestRequestSetFormBody 测试 Request.SetFormBody 方法
func TestRequestSetFormBody(t *testing.T) {
req := NewRequest("POST", "/upload")
fields := map[string]string{
"title": "My Document",
}
files := map[string][]byte{
"document": []byte("PDF content here"),
}
req.SetFormBody(fields, files)
if req.Body == nil {
t.Fatal("Body should not be nil after SetFormBody")
}
if !strings.Contains(req.Body.ContentType, "multipart/form-data") {
t.Fatalf("Body ContentType should be multipart/form-data")
}
t.Log("TestRequestSetFormBody passed")
}