测试从函数返回的Cookie
问题描述:
我试图测试一个从Go中的请求中检索Cookie的函数,但即使它们具有相同的值,比较失败。测试从函数返回的Cookie
package main
import (
"fmt"
"log"
"net/http"
"net/http/httptest"
"reflect"
)
func GetCookie(url string) *http.Cookie {
req, err := http.NewRequest("GET", url, nil)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
client := http.DefaultClient
res, err := client.Do(req)
if err != nil {
panic(err)
}
defer res.Body.Close()
cookies := res.Cookies()
var mycookie *http.Cookie
for _, c := range cookies {
if c.Name == "mycookie" {
mycookie = c
}
}
return mycookie
}
func main() {
validCookie := &http.Cookie{
Name: "mycookie",
Value: "SomeValue",
Path: "/mysite",
HttpOnly: true,
Secure: true,
}
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.SetCookie(w, validCookie)
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(200)
}))
defer ts.Close()
fmt.Printf("EqualL Cookies: %t\n", reflect.DeepEqual(validCookie, validCookie))
if got := GetCookie(ts.URL); !reflect.DeepEqual(got, validCookie) {
log.Fatalf("NOT THE SAME\n got = '%v'\nwant = '%v'", got, validCookie)
}
}
游乐场链接:https://play.golang.org/p/T4dbZycMuT
我已经检查了DeepEqual函数的文档,从我能看到2个结构/指针应该是相同的(特别是考虑到cookie没有不导出字段)。
我可以更改函数来比较Cookie字符串,但是我想知道是否有简单的解释为什么这不起作用或者是由于文档指定的“不一致性”。 也有任何方法来测试结构,而不是在这个情况下的字符串表示(或者我犯了一个错误,也许)?
答
与reflect.DeepEquals
比较饼干是一个非常糟糕的主意。 http.Cookie type包含的组件不会转换成cookie的文字标题表示,具体取决于它如何被解析和/或操作。
如果你改变你的代码使用%#v
:
if got := GetCookie(ts.URL); !reflect.DeepEqual(got, validCookie) {
log.Fatalf("NOT THE SAME\n got = '%#v'\nwant = '%#v'", got, validCookie)
}
...你会看到其中的差别:
EqualL Cookies: true
2009/11/10 23:00:00 NOT THE SAME
got = '&http.Cookie{Name:"mycookie", Value:"SomeValue", Path:"/mysite", Domain:"", Expires:time.Time{wall:0x0, ext:0, loc:(*time.Location)(nil)}, RawExpires:"", MaxAge:0, Secure:true, HttpOnly:true, Raw:"mycookie=SomeValue; Path=/mysite; HttpOnly; Secure", Unparsed:[]string(nil)}'
want = '&http.Cookie{Name:"mycookie", Value:"SomeValue", Path:"/mysite", Domain:"", Expires:time.Time{wall:0x0, ext:0, loc:(*time.Location)(nil)}, RawExpires:"", MaxAge:0, Secure:true, HttpOnly:true, Raw:"", Unparsed:[]string(nil)}'
相反,只是直接比较URL字符串:
if got := GetCookie(ts.URL); got.String() == validCookie.String() {
答
使用fmt.Printf("%#v")
显示问题:
got= &http.Cookie{Name:"mycookie", Value:"SomeValue", Path:"/mysite", Domain:"", Expires:time.Time{wall:0x0, ext:0, loc:(*time.Location)(nil)}, RawExpires:"", MaxAge:0, Secure:true, HttpOnly:true, Raw:"mycookie=SomeValue; Path=/mysite; HttpOnly; Secure", Unparsed:[]string(nil)}
validCookie=&http.Cookie{Name:"mycookie", Value:"SomeValue", Path:"/mysite", Domain:"", Expires:time.Time{wall:0x0, ext:0, loc:(*time.Location)(nil)}, RawExpires:"", MaxAge:0, Secure:true, HttpOnly:true, Raw:"", Unparsed:[]string(nil)}
解析cookie的值Raw
填充,而构建的cookie没有Raw
值,可以理解。