io.Reader 实践 ApiTool 单元测试

 

package main
import (     "fmt"     "io"     "net/http"     "os" )
func GET(req *http.Request) {     c := http.Client{}     richReq(req)     postReq(req)     resp, err := c.Do(req)     if err != nil {         handleErr(err)         return     }     defer resp.Body.Close()     handleResp(resp) }
func handleErr(err error) {     os.WriteFile("err.txt", []byte(fmt.Sprint(err)), 0777) }
func handleResp(resp *http.Response) {     os.WriteFile("Status.txt", []byte(resp.Status), 0777)     if resp.StatusCode != 200 {         os.Remove("resp.json")         return     }     bs, err := io.ReadAll(resp.Body)     if err != nil {         handleErr(err)         return     }     os.WriteFile("resp.json", bs, 0777) }
func richReq(req *http.Request) {     req.URL.Scheme = CONF["Scheme"].(string)     req.URL.Host = CONF["Host"].(string)     header := http.Header{}     for k, v := range CONF["Header"].(map[string]interface{}) {         header[k] = []string{v.(string)}     }     req.Header = header }
func postReq(req *http.Request) {     if req.Method == "POST" {         bs, err := os.Open("req.json")         if err != nil {             handleErr(err)             return         }         req.Body = io.NopCloser(bs)         req.Header.Set("Content-Type", "applicatipn/json")         os.WriteFile("postReq.txt", []byte("postReq"), 0777)     } }

 

 

package main
import (     "net/http"     "net/url"     "testing" )
func TestGET(t *testing.T) {     type args struct {         req *http.Request     }     tests := []struct {         name string         args args     }{         // {name: "", args: args{req: &http.Request{Method: "GET", URL: &url.URL{Path: "/api/Security/GetCaptcha"}}}},         // {name: "", args: args{req: &http.Request{Method: "GET", URL: &url.URL{Path: "/api/List/Company"}}}},         {name: "", args: args{req: &http.Request{Method: "POST", URL: &url.URL{Path: "/api/CreateUpdate/Company"}}}},     }     for _, tt := range tests {         t.Run(tt.name, func(t *testing.T) {             GET(tt.args.req)         })     } }

 

上一篇:axios拦截器与基本使用


下一篇:Go代码规范梳理