Recently, when I was Learning Golang language, I met a senior who told me that I had a Learning principle: Learning By Doing. It fits well with my previous experience of learning Java. I struggled in the learning pit for several days and almost forgot this important success lesson.

So what do you do for exercise? So I have a path for myself, which is to start with interface testing, move from functional testing to performance testing, and then master basic Server development skills.

First of all, the HTTP interface test to achieve several common functions, mainly to obtain the HTTPrequest object, send request parsing response and the basic configuration of HttpClient.

The implementation here is relatively simple and shallow, which reminds me of the FunTester testing framework’s beginning by encapsulating the API provided by HttpClient.jar.

Here I’m using the HTTP API provided by the Net/HTTP package that comes with the Golang SDK, although it provides methods wrapped in http.postform (), http.post (), and http.get (). However, there was a lack of flexibility in handling headers and cookies in HTTPrequest, so I repackaged the NET/HTTP API for a second time. There are a few omissions, such as HTTPstatus judgment and content-type auto-handling in the header, which will be fleshes out in the future, but is intended to be useful for the time being.

HTTP client encapsulation

package task

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
	"time"
)

var Client http.Client = clients()

// Res simulates the response structure
// @Description:
type Res struct {
	Have string `json:"Have"`
}

// Get Gets the Get request
// @Description:
// @param uri
// @param args
// @return *http.Request
func Get(uri string, args map[string]interface{}) *http.Request {
	uri = uri + ToValues(args)
	request, _ := http.NewRequest("get", uri, nil)
	return request
}

// PostForm POST interface form form
// @Description:
// @param path
// @param args
// @return *http.Request
func PostForm(path string, args map[string]interface{}) *http.Request {
	request, _ := http.NewRequest("post", path, strings.NewReader(ToValues(args)))
	return request
}

// PostJson POST request,JSON parameter
// @Description:
// @param path
// @param args
// @return *http.Request
func PostJson(path string, args map[string]interface{}) *http.Request {
	marshal, _ := json.Marshal(args)
	request, _ := http.NewRequest("post", path, bytes.NewReader(marshal))

	return request
}

// ToValues parses map into HTTP parameters for GET and POST form forms
// @Description:
// @param args
// @return string
func ToValues(args map[string]interface{}) string {
	ifargs ! =nil && len(args) > 0 {
		params := url.Values{}
		for k, v := range args {
			params.Set(k, fmt.Sprintf("%v", v))
		}
		return params.Encode()
	}
	return ""
}

// Response Obtains Response details. The default value is []byte
// @Description:
// @param request
// @return []byte
func Response(request *http.Request) []byte {
	res, err := Client.Do(request)
	iferr ! =nil {
		return nil
	}
	body, _ := ioutil.ReadAll(res.Body) // Read the response body, which returns []byte
	defer res.Body.Close()
	return body
}

// clients Initializes the requesting client
// @Description:
// @return http.Client
func clients(a) http.Client {
	return http.Client{
		Timeout: time.Duration(5) * time.Second, // The timeout period
		Transport: &http.Transport{
			MaxIdleConnsPerHost:   5.// Maximum number of idle connections for a single route
			MaxConnsPerHost:       100.// Maximum number of connections for a single route
			IdleConnTimeout:       90 * time.Second,
			TLSHandshakeTimeout:   10 * time.Second,
			ExpectContinueTimeout: 1 * time.Second,
		},
	}
}

// ParseRes parses the response
// @Description:
// @receiver r
// @param res
func (r *Res) ParseRes(res []byte) {
	json.Unmarshal(res, r)
}

// ParseRes parses the response and converts []byte into an incoming object
// @Description:
// @param res
// @param r
//
func ParseRes(res []byte, r interface{}) {
	json.Unmarshal(res, r)
}

Copy the code

The test script

package main

import (
	"fmt"
	"funtester/src/task"
	"io"
	"log"
	"net/http"
	"os"
	"time"
)

const (
	a = iota
	b
	c
	d
	e
)

func init(a) {
	os.Mkdir("./log/".0777)
	os.Mkdir("./long/".0777)
	file := "./log/" + string(time.Now().Format("20060102")) + ".log"
	openFile, _ := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
	writer := io.MultiWriter(os.Stdout, openFile)
	log.SetOutput(writer)
	log.SetFlags(log.LstdFlags | log.Lshortfile | log.Ldate)
}

func main(a) {

	url := "http://localhost:12345/test"
	args := map[string]interface{} {"name": "FunTester"."fun":  "fdsafj",
	}
	cookie := &http.Cookie{
		Name:  "token",
		Value: "fsjej09u0934jtej",
	}
	get := task.Get(url, args)
	get.Header.Add("user_agent"."FunTester")
	get.AddCookie(cookie)
	response := task.Response(get)
	fmt.Println(string(response))
	form := task.PostForm(url, args)
	bytes := task.Response(form)
	fmt.Println(string(bytes))
	json := task.PostJson(url, args)
	res := task.Response(json)
	fmt.Println(string(res))

}

Copy the code

Console output

GOROOT=/usr/local/go #gosetup GOPATH=/Users/oker/go #gosetup /usr/local/go/bin/go build -o /private/var/folders/7b/0djfgf7j7p9ch_hgm9wx9n6w0000gn/T/GoLand/___go_build_funtester_src_m funtester/src/m #gosetup / private/var/folders / 7 b / 0 djfgf7j7p9ch_hgm9wx9n6w0000gn/T/GoLand ___go_build_funtester_src_m get request post request form form Post request JSON form Process Finished with the exit code 0Copy the code

Testing services

The moco_FunTester test framework is still used.

package com.mocofun.moco.main

import com.funtester.utils.ArgsUtil
import com.mocofun.moco.MocoServer

class Share extends MocoServer {

    static void main(String[] args) {
        def util = new ArgsUtil(args)
        // def server = getServerNoLog(util.getintordefault (0,12345))
        def server = getServer(util.getIntOrdefault(0.12345))
        server.get(urlStartsWith("/test")).response("Get request")
        server.post(both(urlStartsWith("/test"), existForm("fun"))).response("Post request form")
        server.post(both(urlStartsWith("/test"), existParams("fun"))).response("Post request JSON form")
        server.get(urlStartsWith("/qps")).response(qps(textRes("Congratulations on reaching QPS!"), 1))
Server. response(delay(jsonRes(getJson("Have=Fun ~ Tester!" )), 1000))
        server.response("Have Fun ~ Tester!")
        def run = run(server)
        waitForKey("fan")
        run.stop()
    }
}


Copy the code

Have Fun ~ Tester!

  • FunTester test framework architecture diagram
  • JMeter Chinese Operation Manual with a sense of time
  • 140 interview questions (UI, Linux, MySQL, API, security)
  • Graphic HTTP brain map
  • Fiddler Everywhere is the future
  • JVM command brain map for testing
  • The Definitive Guide to Java Performance
  • FunTester Framework Tutorial
  • Tease the interface documentation together
  • Bind mobile phone number performance test
  • Selenium4 Alpha-7 Upgrade experience
  • What happens if you have 100 years of membership
  • LT browser – responsive web testing tool
  • Java NIO is used in interface automation