How to use TestResponse method of http Package

Best K6 code snippet using http.TestResponse

http.go

Source:http.go Github

copy

Full Screen

...18}19func (h *HTTPTestData) GetRequestCount() int {20 return len(h.RequestCase)21}22func (h *HTTPTestData) FetchTestResponse(i int) *Response {23 return h.Response[h.RequestCase[i]]24}25func (h *HTTPTestData) GetResponseCount() int {26 return len(h.ResponseCase)27}28func NewHTTPTestData() HTTPTestData {29 return HTTPTestData{30 Request: TestRequests,31 RequestCase: TestCaseSlice,32 Response: TestResponses,33 ResponseCase: TestCaseSlice,34 }35}36//Request は37type Request struct {38 HTTP *http.Request39 String string40 header41 Query query42}43type query struct {44 Raw string45 Keys []string46 Result map[string]interface{}47 Fetch string48}49type header struct {50 Header http.Header51 HeaderSlice []string52}53//Response は54type Response struct {55 HTTP *http.Response56 String string57 header58 Body body59}60type body struct {61 Raw string62 IO io.ReadCloser63}64var (65 host = "localhost"66 //TestURLPackageURL はテスト用のURLデータ67 TestURLPackageURL, _ = url.Parse("http://localhost/testing/")68 //TestURLPackageURLPlusQuery はテスト用のクエリ付きのデータです69 TestURLPackageURLPlusQuery, _ = url.Parse("http://localhost/testing/?input=usa")70 //TestHeader はテスト用のhttpHeader71 TestHeader = http.Header{72 "Host": {"loacalhost"},73 "Accept-Encoding": {"gzip", "deflate"},74 "Accept-Language": {"en-us"},75 "Foo": {"Bar", "two"},76 }77 TestHeaderKeys = []string{"Accept-Encoding", "Accept-Language", "Foo", "Host"}78 TestFailHeader = http.Header{}79 //TestHeaderSlice はHeaderの情報をstring sliceでまとめたもの80 TestHeaderSlice = []string{"Accept-Encoding: gzip,deflate", "Accept-Language: en-us", "Foo: Bar,two", "Host: loacalhost"}81 Testheaderstruct = header{TestHeader, TestHeaderSlice}82 TestCaseSlice = []string{"FORM_success", "FORM_ADD_success", "JSON_success", "JSON_fail", "GET", "GET_Query"}83 //TestQuery はFORM形式とJSON形式のクエリ84 TestQuery = map[string]query{85 TestCaseSlice[0]: {86 Raw: `name=hoge&age=20&like=mikan`,87 Keys: []string{"name", "age", "like"},88 Result: map[string]interface{}{"name": "hoge", "age": "20", "like": "mikan"},89 Fetch: `age=20&like=mikan&name=hoge`,90 },91 TestCaseSlice[1]: {92 Raw: `name=hoge&age=20&like=mikanA`,93 Keys: []string{"name", "age", "like"},94 Result: map[string]interface{}{"name": "hoge", "age": "20", "like": "mikanA"},95 Fetch: `age=20&like=mikanA&name=hoge`,96 },97 TestCaseSlice[2]: {98 Raw: `{"age":20,"lang":["jp","en","fr"],"like":"mikan","name":"hoge"}`,99 Keys: []string{"name", "age", "like", "lang"},100 Result: map[string]interface{}{"name": "hoge", "age": float64(20), "like": "mikan", "lang": []interface{}{"jp", "en", "fr"}},101 Fetch: `{"age":20,"lang":["jp","en","fr"],"like":"mikan","name":"hoge"}`,102 },103 TestCaseSlice[3]: {104 Raw: `{"name":hoge}`,105 Keys: []string{},106 Result: map[string]interface{}{},107 Fetch: `{}`,108 },109 TestCaseSlice[4]: {110 Raw: ``,111 Keys: []string{},112 Result: map[string]interface{}{},113 Fetch: ``,114 },115 TestCaseSlice[5]: {116 Raw: `input=usa`,117 Keys: []string{},118 Result: map[string]interface{}{},119 Fetch: `input=usa`,120 },121 }122 TestRequests = map[string]*Request{123 TestCaseSlice[0]: {124 HTTP: &http.Request{Method: "POST", URL: TestURLPackageURL, Proto: "HTTP/1.0", ProtoMajor: 1, ProtoMinor: 0, Header: TestHeader,125 Body: ioutil.NopCloser(strings.NewReader(TestQuery[TestCaseSlice[0]].Raw)), ContentLength: int64(len(TestQuery[TestCaseSlice[0]].Fetch)), Host: host},126 String: "POST /testing/ HTTP/1.0\n" + strings.Join(TestHeaderSlice, "\n") + "\n\n" + TestQuery[TestCaseSlice[0]].Fetch,127 header: Testheaderstruct,128 Query: TestQuery[TestCaseSlice[0]],129 },130 TestCaseSlice[1]: {131 HTTP: &http.Request{Method: "POST", URL: TestURLPackageURL, Proto: "HTTP/1.0", ProtoMajor: 1, ProtoMinor: 0, Header: TestHeader,132 Body: ioutil.NopCloser(strings.NewReader(TestQuery[TestCaseSlice[1]].Raw)), ContentLength: int64(len(TestQuery[TestCaseSlice[1]].Fetch)), Host: host},133 String: "POST /testing/ HTTP/1.0\n" + strings.Join(TestHeaderSlice, "\n") + "\n\n" + TestQuery[TestCaseSlice[1]].Fetch,134 header: Testheaderstruct,135 Query: TestQuery[TestCaseSlice[1]],136 },137 TestCaseSlice[2]: {138 HTTP: &http.Request{Method: "POST", URL: TestURLPackageURL, Proto: "HTTP/1.0", ProtoMajor: 1, ProtoMinor: 0, Header: TestHeader,139 Body: ioutil.NopCloser(strings.NewReader(TestQuery[TestCaseSlice[2]].Raw)), ContentLength: int64(len(TestQuery[TestCaseSlice[2]].Fetch)), Host: host},140 String: "POST /testing/ HTTP/1.0\n" + strings.Join(TestHeaderSlice, "\n") + "\n\n" + TestQuery[TestCaseSlice[2]].Fetch,141 header: Testheaderstruct,142 Query: TestQuery[TestCaseSlice[2]],143 },144 TestCaseSlice[3]: {145 HTTP: &http.Request{Method: "POST", URL: TestURLPackageURL, Proto: "HTTP/1.0", ProtoMajor: 1, ProtoMinor: 0, Header: TestHeader,146 Body: ioutil.NopCloser(strings.NewReader(TestQuery[TestCaseSlice[3]].Raw)), ContentLength: int64(len(TestQuery[TestCaseSlice[3]].Fetch)), Host: host},147 String: "POST /testing/ HTTP/1.0\n" + strings.Join(TestHeaderSlice, "\n") + "\n\n" + TestQuery[TestCaseSlice[3]].Fetch,148 header: Testheaderstruct,149 Query: TestQuery[TestCaseSlice[3]],150 },151 TestCaseSlice[4]: {152 HTTP: &http.Request{Method: "GET", URL: TestURLPackageURL, Proto: "HTTP/1.0", ProtoMajor: 1, ProtoMinor: 0, Header: TestHeader,153 Body: ioutil.NopCloser(strings.NewReader(TestQuery[TestCaseSlice[4]].Raw)), ContentLength: int64(len(TestQuery[TestCaseSlice[4]].Raw)), Host: host},154 String: "GET /testing/ HTTP/1.0\n" + strings.Join(TestHeaderSlice, "\n") + "\n\n" + TestQuery[TestCaseSlice[4]].Fetch,155 header: Testheaderstruct,156 Query: TestQuery[TestCaseSlice[4]],157 },158 TestCaseSlice[5]: {159 HTTP: &http.Request{Method: "GET", URL: TestURLPackageURLPlusQuery, Proto: "HTTP/1.0", ProtoMajor: 1, ProtoMinor: 0, Header: TestHeader,160 Body: ioutil.NopCloser(strings.NewReader(TestQuery[TestCaseSlice[5]].Raw)), ContentLength: int64(len(TestQuery[TestCaseSlice[5]].Raw)), Host: host},161 String: "GET /testing/?input=usa HTTP/1.0\n" + strings.Join(TestHeaderSlice, "\n") + "\n\n" + TestQuery[TestCaseSlice[5]].Fetch,162 header: Testheaderstruct,163 Query: TestQuery[TestCaseSlice[5]],164 },165 }166 TestResponse = http.Response{167 Status: "200 OK",168 StatusCode: 200,169 Proto: "HTTP/1.0",170 ProtoMajor: 1,171 ProtoMinor: 0,172 Header: TestHeader,173 TransferEncoding: []string{"chunked"},174 }175 TestHTML = `<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"176 "http://www.w3.org/TR/html4/strict.dtd">177<html>178 <head>179 <title>タイトルを指定する</title>180 </head>181 <body>182 ここに内容を書く183 </body>184</html>`185 TestBodys = map[string]body{186 TestCaseSlice[0]: {187 Raw: TestHTML,188 IO: ioutil.NopCloser(strings.NewReader(TestHTML)),189 },190 TestCaseSlice[1]: {191 Raw: TestHTML,192 IO: ioutil.NopCloser(strings.NewReader(TestHTML)),193 },194 TestCaseSlice[2]: {195 Raw: TestHTML,196 IO: ioutil.NopCloser(strings.NewReader(TestHTML)),197 },198 TestCaseSlice[3]: {199 Raw: TestHTML,200 IO: ioutil.NopCloser(strings.NewReader(TestHTML)),201 },202 TestCaseSlice[4]: {203 Raw: TestHTML,204 IO: ioutil.NopCloser(strings.NewReader(TestHTML)),205 },206 TestCaseSlice[5]: {207 Raw: TestHTML,208 IO: ioutil.NopCloser(strings.NewReader(TestHTML)),209 },210 }211 testHTTPSetFunc = func(casestr string) *http.Response {212 TestResponse.Body = TestBodys[casestr].IO213 TestResponse.ContentLength = int64(len(TestBodys[casestr].Raw))214 TestResponse.Request = TestRequests[casestr].HTTP215 return &TestResponse216 }217 TestResponses = map[string]*Response{218 TestCaseSlice[0]: {219 HTTP: testHTTPSetFunc(TestCaseSlice[0]),220 String: TestResponse.Proto + " " + TestResponse.Status + "\n" + strings.Join(TestHeaderSlice, "\n") + "\n\n" + TestBodys[TestCaseSlice[0]].Raw,221 header: Testheaderstruct,222 Body: TestBodys[TestCaseSlice[0]],223 },224 TestCaseSlice[1]: {225 HTTP: testHTTPSetFunc(TestCaseSlice[1]),226 String: TestResponse.Proto + " " + TestResponse.Status + "\n" + strings.Join(TestHeaderSlice, "\n") + "\n\n" + TestBodys[TestCaseSlice[1]].Raw,227 header: Testheaderstruct,228 Body: TestBodys[TestCaseSlice[1]],229 },230 TestCaseSlice[2]: {231 HTTP: testHTTPSetFunc(TestCaseSlice[2]),232 String: TestResponse.Proto + " " + TestResponse.Status + "\n" + strings.Join(TestHeaderSlice, "\n") + "\n\n" + TestBodys[TestCaseSlice[2]].Raw,233 header: Testheaderstruct,234 Body: TestBodys[TestCaseSlice[2]],235 },236 TestCaseSlice[3]: {237 HTTP: testHTTPSetFunc(TestCaseSlice[3]),238 String: TestResponse.Proto + " " + TestResponse.Status + "\n" + strings.Join(TestHeaderSlice, "\n") + "\n\n" + TestBodys[TestCaseSlice[3]].Raw,239 header: Testheaderstruct,240 Body: TestBodys[TestCaseSlice[3]],241 },242 TestCaseSlice[4]: {243 HTTP: testHTTPSetFunc(TestCaseSlice[4]),244 String: TestResponse.Proto + " " + TestResponse.Status + "\n" + strings.Join(TestHeaderSlice, "\n") + "\n\n" + TestBodys[TestCaseSlice[4]].Raw,245 header: Testheaderstruct,246 Body: TestBodys[TestCaseSlice[4]],247 },248 TestCaseSlice[5]: {249 HTTP: testHTTPSetFunc(TestCaseSlice[5]),250 String: TestResponse.Proto + " " + TestResponse.Status + "\n" + strings.Join(TestHeaderSlice, "\n") + "\n\n" + TestBodys[TestCaseSlice[5]].Raw,251 header: Testheaderstruct,252 Body: TestBodys[TestCaseSlice[5]],253 },254 }255)...

Full Screen

Full Screen

testing.go

Source:testing.go Github

copy

Full Screen

...10 "strings"11 "testing"12)13// BUG(tqbf): rename functions14// A TestResponse tries to capture all the stuff from an HTTP Response15// that you might want to peek at when validating a test.16type TestResponse struct {17 Path string18 Method string19 Code int20 Body []byte21 Err error22 Response *http.Response23 T *testing.T24 Cookies map[string]string25}26func (r *TestResponse) String() string {27 err := ""28 if r.Err != nil {29 err = fmt.Sprintf(" ERROR: %s", r.Err)30 }31 return fmt.Sprintf(`%s %s (response: %d, %d bytes)%s32%s33`, r.Method, r.Path, r.Code, len(r.Body), err, hex.Dump(r.Body))34}35// Reader returns an io.Reader for the body of the Response36func (t *TestResponse) Reader() io.Reader {37 return bytes.NewReader(t.Body)38}39// Given a net/http Response, get a TestResponse.40func TestResponseFromResponse(res *http.Response) (ret *TestResponse) {41 ret = &TestResponse{42 Code: res.StatusCode,43 Response: res,44 }45 ret.Body, ret.Err = ioutil.ReadAll(res.Body)46 if ret.Err != nil {47 return48 }49 ret.Cookies = map[string]string{}50 for _, cookie := range res.Cookies() {51 ret.Cookies[cookie.Name] = cookie.Value52 }53 return ret54}55// Given just an error, get a TestResponse to convey the error to the56// test (obviously everything else will be blank)57func testResponseFromError(err error) (ret *TestResponse) {58 return &TestResponse{59 Err: err,60 }61}62// OK returns true if the Response is superficially OK (no errors,63// etc)64func (r *TestResponse) OK() bool {65 return r.Err == nil66}67// AssetCode returns false, logs, and flags a test failure if the68// response has the wrong response code69func (r *TestResponse) AssertCode(code int) bool {70 r.T.Helper()71 if !r.OK() {72 r.T.Fatalf("request error: %s", r.Err)73 return false74 }75 if r.Code != code {76 r.T.Fatalf("expected code %d, got %d", code, r.Code)77 return false78 }79 return true80}81// AssetCode returns false, logs, and flags a test failure if the82// response has the wrong response code or fails to unmarshal to the83// expected object via JSON84func (r *TestResponse) AssertJson(v interface{}, code int) bool {85 r.T.Helper()86 if !r.AssertCode(code) {87 return false88 }89 decoder := json.NewDecoder(r.Reader())90 if err := decoder.Decode(v); err != nil {91 r.Err = err92 r.T.Fatalf("couldn't decode: %s", err)93 return false94 }95 return true96}97func (r *TestResponse) Assert200Contains(flag string) bool {98 r.T.Helper()99 if !r.AssertCode(200) {100 return false101 }102 if bytes.Index(r.Body, []byte(flag)) == -1 {103 r.T.Fatalf("flag '%s' not found", flag)104 return false105 }106 return true107}108// A Tester is a simple object that allows us to make test request to a109// given URL. Testers are how you get TestResponses. This is really just110// a simple wrapper around the net/http client (you can "test" anything111// with it)112type Tester struct {113 SessionKey string114 Session string115 BaseURL string116 T *testing.T117}118// Given a base URL and the name of the cookie containing sessions,119// get a new tester.120func NewTester(base, sessionKey string) *Tester {121 return &Tester{122 SessionKey: sessionKey,123 BaseURL: base,124 }125}126// Reset resets the tester, in particular forgetting the current remembered127// session128func (t *Tester) Reset() {129 t.Session = ""130}131// from a test response, find the session cookie and remember it132func (t *Tester) recoverSession(r *TestResponse) {133 if !r.OK() {134 return135 }136 for k, v := range r.Cookies {137 if k == t.SessionKey {138 t.Session = v139 break140 }141 }142}143// to an outgoing request, add the session cookie, if we have one yet144func (t *Tester) addSession(req *http.Request) {145 if t.Session != "" {146 req.AddCookie(&http.Cookie{147 Name: t.SessionKey,148 Value: t.Session,149 })150 }151}152// launch an HTTP request with a valid session and use its response153// to create and return a TestResponse154func (t *Tester) exec(req *http.Request, path string) (ret *TestResponse) {155 t.addSession(req)156 client := &http.Client{157 CheckRedirect: func(req *http.Request, via []*http.Request) error {158 return http.ErrUseLastResponse159 },160 }161 res, err := client.Do(req)162 if err != nil {163 ret = testResponseFromError(err)164 ret.T = t.T165 ret.Path = path166 ret.Method = req.Method167 return168 }169 ret = TestResponseFromResponse(res)170 ret.T = t.T171 ret.Path = path172 ret.Method = req.Method173 t.recoverSession(ret)174 return175}176// Perform an HTTP GET to the given relative URL path, returning177// a TestResponse178func (t *Tester) Get(path string) (ret *TestResponse) {179 req, err := http.NewRequest("GET", t.BaseURL+path, nil)180 if err != nil {181 return testResponseFromError(err)182 }183 return t.exec(req, path)184}185// Perform an HTTP POST to the given relative URL path, including186// the "data" string as the body, returning187// a TestResponse188func (t *Tester) Post(path, data string) (ret *TestResponse) {189 req, err := http.NewRequest("POST", t.BaseURL+path,190 strings.NewReader(data))191 if err != nil {192 return testResponseFromError(err)193 }194 return t.exec(req, path)195}196// Perform an HTTP POST w/ application/x-www-form-urlencoded to the given197// relative URL path, including the "data" string as the body, returning198// a TestResponse199func (t *Tester) PostForm(path, data string) (ret *TestResponse) {200 req, err := http.NewRequest("POST", t.BaseURL+path,201 strings.NewReader(data))202 if err != nil {203 return testResponseFromError(err)204 }205 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")206 return t.exec(req, path)207}208// Perform an HTTP POST to the given relative URL path, including209// the "data" object as the body of the request after encoding it210// as JSON, returning a TestResponse211func (t *Tester) PostJson(path string, data interface{}) (ret *TestResponse) {212 buf, err := json.Marshal(data)213 if err != nil {214 return testResponseFromError(err)215 }216 req, err := http.NewRequest("POST", t.BaseURL+path,217 bytes.NewReader(buf))218 if err != nil {219 return testResponseFromError(err)220 }221 return t.exec(req, path)222}223// Perform an HTTP PUT to the given relative URL path, including224// the "data" string as the body, returning225// a TestResponse226func (t *Tester) Put(path, data string) (ret *TestResponse) {227 req, err := http.NewRequest("PUT", t.BaseURL+path,228 strings.NewReader(data))229 if err != nil {230 return testResponseFromError(err)231 }232 return t.exec(req, path)233}234// Perform an HTTP PUT to the given relative URL path, including235// the "data" object as the body of the request after encoding it236// as JSON, returning a TestResponse237func (t *Tester) PutJson(path string, data interface{}) (ret *TestResponse) {238 buf, err := json.Marshal(data)239 if err != nil {240 return testResponseFromError(err)241 }242 req, err := http.NewRequest("PUT", t.BaseURL+path,243 bytes.NewReader(buf))244 if err != nil {245 return testResponseFromError(err)246 }247 return t.exec(req, path)248}249// Perform an HTTP DELETE to the given relative URL path, returning250// a TestResponse251func (t *Tester) Delete(path string) (ret *TestResponse) {252 req, err := http.NewRequest("DELETE", t.BaseURL+path, nil)253 if err != nil {254 return testResponseFromError(err)255 }256 return t.exec(req, path)257}258type T struct {259 *testing.T260}261func NewT(t *testing.T) *T {262 return &T{t}263}264func (t *T) OK(err error, why ...string) bool {265 t.Helper()...

Full Screen

Full Screen

response_test.go

Source:response_test.go Github

copy

Full Screen

...11 Request: &Request{},12}13func TestSetResponse(t *testing.T) {14 for i := 0; i < test.GetRequestCount(); i++ {15 testingdata := test.FetchTestResponse(i)16 testresponse.SetHTTPResponseByResponse(testingdata.HTTP)17 if testresponse.Info.Proto != testingdata.HTTP.Proto || testresponse.Info.ProtoMajor != testingdata.HTTP.ProtoMajor || testresponse.Info.ProtoMinor != testingdata.HTTP.ProtoMinor {18 t.Errorf("プロトコル関連のセッティングが不適切です \n Proto : %v != %v \n ProtoMajor : %v != %v \n ProtoMiner : %v != %v",19 testresponse.Info.Proto, testingdata.HTTP.Proto, testresponse.Info.ProtoMajor, testingdata.HTTP.ProtoMajor,20 testresponse.Info.ProtoMinor, testingdata.HTTP.ProtoMinor)21 }22 if testresponse.Info.Status != testingdata.HTTP.Status || testresponse.Info.StatusCode != testingdata.HTTP.StatusCode {23 t.Errorf("ステータス処理周辺のセッティングが不適切です\n Status : %v != %v \n StatusCode : %v != %v",24 testresponse.Info.Status, testingdata.HTTP.Status, testresponse.Info.StatusCode, testingdata.HTTP.StatusCode)25 }26 if !reflect.DeepEqual(testresponse.Header.Header, testingdata.Header) {27 t.Errorf("http.Headerのセッティングが不適切です \n Header : %v != %v", testresponse.Header.Header, testingdata.Header)28 }29 if testresponse.Body.Body != testingdata.Body.Raw {...

Full Screen

Full Screen

TestResponse

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 req, err := http.NewRequest("GET", "/hello", nil)4 if err != nil {5 fmt.Println("Error in request")6 }7 rr := httptest.NewRecorder()8 handler := http.HandlerFunc(HelloHandler)9 handler.ServeHTTP(rr, req)10 if status := rr.Code; status != http.StatusOK {11 fmt.Println("Error in status")12 }13 expected := `{"hello": "world"}`14 if rr.Body.String() != expected {15 fmt.Println("Error in response")16 }17}18func HelloHandler(w http.ResponseWriter, r *http.Request) {19 fmt.Fprintf(w, `{"hello": "world"}`)20}21import (22func main() {23 req, err := http.NewRequest("GET", "/hello", nil)24 if err != nil {25 fmt.Println("Error in request")26 }27 rr := httptest.NewRecorder()28 handler := http.HandlerFunc(HelloHandler)29 handler.ServeHTTP(rr, req)30 if status := rr.Code; status != http.StatusOK {31 fmt.Println("Error in status")32 }

Full Screen

Full Screen

TestResponse

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 client := &http.Client{}4 if err != nil {5 panic(err)6 }7 resp, err := client.Do(req)8 if err != nil {9 panic(err)10 }11 respBody, err := ioutil.ReadAll(resp.Body)12 if err != nil {13 panic(err)14 }15 fmt.Println("response Status:", resp.Status)16 fmt.Println("response Headers:", resp.Header)17 fmt.Println("response Body:", string(respBody))18 defer resp.Body.Close()19}20response Headers: map[Content-Type:[text/html; charset=ISO-8859-1] Date:[Thu, 06 Feb 2020 10:44:08 GMT] Expires:[-1] P3p:[CP="This is not a P3P policy! See g.co/p3phelp for more info."] Server:[gws] Set-Cookie:[1P_JAR=2020-02-06-10; expires=Sat, 07-Mar-2020 10:44:08 GMT; path=/; domain=.google.com,

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful