?
This document uses PHP Chinese website manual Release
import "net/http/httptest"
概述
索引
示例
httptest包提供了用于HTTP測試的實(shí)用程序。
常量
func NewRequest(method, target string, body io.Reader) *http.Request
type ResponseRecorder
func NewRecorder() *ResponseRecorder
func (rw *ResponseRecorder) Flush()
func (rw *ResponseRecorder) Header() http.Header
func (rw *ResponseRecorder) Result() *http.Response
func (rw *ResponseRecorder) Write(buf []byte) (int, error)
func (rw *ResponseRecorder) WriteHeader(code int)
func (rw *ResponseRecorder) WriteString(str string) (int, error)
type Server
func NewServer(handler http.Handler) *Server
func NewTLSServer(handler http.Handler) *Server
func NewUnstartedServer(handler http.Handler) *Server
func (s *Server) Certificate() *x509.Certificate
func (s *Server) Client() *http.Client
func (s *Server) Close()
func (s *Server) CloseClientConnections()
func (s *Server) Start()
func (s *Server) StartTLS()
NewTLSServer ResponseRecorder Server
httptest.go recorder.go server.go
如果未在ResponseRecorder上設(shè)置明確的DefaultRemoteAddr,則DefaultRemoteAddr是在RemoteAddr中返回的默認(rèn)遠(yuǎn)程地址。
const DefaultRemoteAddr = "1.2.3.4"
func NewRequest(method, target string, body io.Reader) *http.Request
NewRequest返回一個(gè)新的傳入服務(wù)器請求,適合傳遞給http.Handler進(jìn)行測試。
目標(biāo)是RFC 7230“請求目標(biāo)”:它可以是路徑或絕對URL。如果target是絕對URL,則使用URL中的主機(jī)名稱。否則,使用“example.com”。
如果目標(biāo)具有方案“https”,則TLS字段將設(shè)置為非零虛擬值。
Request.Proto始終是HTTP/1.1。
一個(gè)空的方法意味著“GET”。
提供的body可能是零。如果主體是* bytes.Reader,* strings.Reader或* bytes.Buffer類型,則設(shè)置Request.ContentLength。
NewRequest在測試中容易出錯(cuò),恐慌情況是可以接受的。
要生成客戶端HTTP請求而不是服務(wù)器請求,請參閱net/http軟件包中的NewRequest函數(shù)。
ResponseRecorder是http.ResponseWriter的一個(gè)實(shí)現(xiàn),它記錄了其突變,以便在測試中進(jìn)行后續(xù)檢查。
type ResponseRecorder struct { // Code is the HTTP response code set by WriteHeader. // // Note that if a Handler never calls WriteHeader or Write, // this might end up being 0, rather than the implicit // http.StatusOK. To get the implicit value, use the Result // method. Code int // HeaderMap contains the headers explicitly set by the Handler. // // To get the implicit headers set by the server (such as // automatic Content-Type), use the Result method. HeaderMap http.Header // Body is the buffer to which the Handler's Write calls are sent. // If nil, the Writes are silently discarded. Body *bytes.Buffer // Flushed is whether the Handler called Flush. Flushed bool // contains filtered or unexported fields}
package mainimport ("fmt""io""io/ioutil""net/http""net/http/httptest")func main() { handler := func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "<html><body>Hello World!</body></html>")} req := httptest.NewRequest("GET", "http://example.com/foo", nil) w := httptest.NewRecorder()handler(w, req) resp := w.Result() body, _ := ioutil.ReadAll(resp.Body) fmt.Println(resp.StatusCode) fmt.Println(resp.Header.Get("Content-Type")) fmt.Println(string(body))}
func NewRecorder() *ResponseRecorder
NewRecorder返回一個(gè)初始化的ResponseRecorder。
func (rw *ResponseRecorder) Flush()
Flush設(shè)置rw.Flushed為true。
func (rw *ResponseRecorder) Header() http.Header
標(biāo)題返回響應(yīng)標(biāo)題。
func (rw *ResponseRecorder) Result() *http.Response
結(jié)果返回處理程序生成的響應(yīng)。
返回的Response將至少包含其StatusCode,Header,Body和(可選)Trailer。將來可能會填充更多的字段,因此,調(diào)用者不應(yīng)該將結(jié)果進(jìn)行DeepEqual測試。
Response.Header是第一次寫入調(diào)用時(shí)的頭部快照,或者是在調(diào)用時(shí)(如果處理程序從未寫入過的)。
Response.Body保證為非零,并且Body.Read調(diào)用保證不會返回除io.EOF以外的任何錯(cuò)誤。
只有在處理程序運(yùn)行完成后才能調(diào)用結(jié)果。
func (rw *ResponseRecorder) Write(buf []byte) (int, error)
Write總是成功并寫入rw.Body,如果不是零。
func (rw *ResponseRecorder) WriteHeader(code int)
WriteHeader設(shè)置rw.Code。調(diào)用之后,更改rw.Header不會影響rw.HeaderMap。
func (rw *ResponseRecorder) WriteString(str string) (int, error)
WriteString總是成功并寫入rw.Body,如果不是零。
服務(wù)器是一個(gè)HTTP服務(wù)器,它偵聽本地環(huán)回接口上的系統(tǒng)選擇端口,用于端到端的HTTP測試。
type Server struct { URL string // base URL of form http://ipaddr:port with no trailing slash Listener net.Listener // TLS is the optional TLS configuration, populated with a new config // after TLS is started. If set on an unstarted server before StartTLS // is called, existing fields are copied into the new config. TLS *tls.Config // Config may be changed after calling NewUnstartedServer and // before Start or StartTLS. Config *http.Server // contains filtered or unexported fields}
package mainimport ("fmt""io/ioutil""log""net/http""net/http/httptest")func main() { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello, client")})) defer ts.Close() res, err := http.Get(ts.URL)if err != nil { log.Fatal(err)} greeting, err := ioutil.ReadAll(res.Body) res.Body.Close()if err != nil { log.Fatal(err)} fmt.Printf("%s", greeting)}
func NewServer(handler http.Handler) *Server
NewServer啟動并返回一個(gè)新的服務(wù)器。調(diào)用者在完成時(shí)應(yīng)該調(diào)用Close來關(guān)閉它。
func NewTLSServer(handler http.Handler) *Server
NewTLSServer啟動并使用TLS返回一個(gè)新的服務(wù)器。調(diào)用者在完成時(shí)應(yīng)該調(diào)用Close來關(guān)閉它。
package mainimport ("fmt""io/ioutil""log""net/http""net/http/httptest")func main() { ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello, client")})) defer ts.Close() client := ts.Client() res, err := client.Get(ts.URL)if err != nil { log.Fatal(err)} greeting, err := ioutil.ReadAll(res.Body) res.Body.Close()if err != nil { log.Fatal(err)} fmt.Printf("%s", greeting)}
func NewUnstartedServer(handler http.Handler) *Server
NewUnstartedServer返回一個(gè)新的服務(wù)器,但不啟動它。
更改配置后,調(diào)用者應(yīng)該調(diào)用Start或StartTLS。
調(diào)用者在完成時(shí)應(yīng)該調(diào)用Close來關(guān)閉它。
func (s *Server) Certificate() *x509.Certificate
證書返回服務(wù)器使用的證書,如果服務(wù)器不使用TLS,則返回nil。
func (s *Server) Client() *http.Client
客戶端返回配置為向服務(wù)器發(fā)送請求的HTTP客戶端。它被配置為信任服務(wù)器的TLS測試證書,并關(guān)閉Server.Close上的空閑連接。
func (s *Server) Close()
Close服務(wù)器并阻塞,直到此服務(wù)器上的所有未完成請求都已完成。
func (s *Server) CloseClientConnections()
CloseClientConnections關(guān)閉所有到測試服務(wù)器的開放HTTP連接。
func (s *Server) Start()
Start從NewUnstartedServer啟動服務(wù)器。
func (s *Server) StartTLS()
StartTLS從NewUnstartedServer的服務(wù)器上啟動TLS。