测试Go http.Request.FormFile吗? [英] Testing Go http.Request.FormFile?
问题描述
尝试测试端点时如何设置Request.FormFile?
How do I set the Request.FormFile when trying to test an endpoint?
部分代码:
func (a *EP) Endpoint(w http.ResponseWriter, r *http.Request) {
...
x, err := strconv.Atoi(r.FormValue("x"))
if err != nil {
a.ren.Text(w, http.StatusInternalServerError, err.Error())
return
}
f, fh, err := r.FormFile("y")
if err != nil {
a.ren.Text(w, http.StatusInternalServerError, err.Error())
return
}
defer f.Close()
...
}
如何使用httptest库生成具有可以在FormFile中获得的值的帖子请求?
How do I use the httptest lib to generate a post request that has value that I can get in FormFile?
推荐答案
如果您查看 FormFile
函数的实现,您会发现它读取了公开的 MultipartForm
字段.
If you have a look at the implementation of the FormFile
function you'll see that it reads the exposed MultipartForm
field.
https://golang.org/src/净/http/request.go?s=39022:39107#L1249
// FormFile returns the first file for the provided form key.
1258 // FormFile calls ParseMultipartForm and ParseForm if necessary.
1259 func (r *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error) {
1260 if r.MultipartForm == multipartByReader {
1261 return nil, nil, errors.New("http: multipart handled by MultipartReader")
1262 }
1263 if r.MultipartForm == nil {
1264 err := r.ParseMultipartForm(defaultMaxMemory)
1265 if err != nil {
1266 return nil, nil, err
1267 }
1268 }
1269 if r.MultipartForm != nil && r.MultipartForm.File != nil {
1270 if fhs := r.MultipartForm.File[key]; len(fhs) > 0 {
1271 f, err := fhs[0].Open()
1272 return f, fhs[0], err
1273 }
1274 }
1275 return nil, nil, ErrMissingFile
1276 }
在测试中,您应该能够创建 multipart.Form
的测试实例并将其分配给您的请求对象-
In your test you should be able to create a test instance of multipart.Form
and assign it to your request object - https://golang.org/pkg/mime/multipart/#Form
type Form struct {
Value map[string][]string
File map[string][]*FileHeader
}
当然,这需要您使用真实的文件路径,从测试的角度来看,这不是很好.为了解决这个问题,您可以定义一个接口来从请求对象中读取 FormFile
,并将模拟实现传递到您的 EP
结构中.
Of course this will require that you use a real filepath which isn't great from a testing perspective. To get around this you could define an interface to read FormFile
from a request object and pass a mock implementation into your EP
struct.
Here is a good post with a few examples on how to do this: https://husobee.github.io/golang/testing/unit-test/2015/06/08/golang-unit-testing.html
这篇关于测试Go http.Request.FormFile吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!