Preface
In the previous article, I also developed an independent automatic testing tool that can be tested according to the OpenAPI documentation and output a test report after the test is completed. The report content includes whether each interface passes the test and the response time, etc.
I used the go language to develop this tool, mainly considering that the go language can be cross-compiled in a fool-like way, and the generated executable file can be directly uploaded to the server, which is very convenient.
PS: go It's really torment to write in language! I feel that there are many awkward things in the grammar, but it was so cool when I built that I couldn't refuse it at all.
In order to avoid being too long, this article first introduces the components used, implements and parses the OpenAPI document generation test configuration in detail, and then introduces the subsequent articles.
Network request
The standard librarynet/http
The packet provides the function of sending HTTP requests. After obtaining the data, useFunction parsing JSON data. This package is relatively low-level and is sufficient for simple network requests, but I still want to choose a better component.
Resty is a simple and powerful Go HTTP client with a chained API that can easily send HTTP requests and process JSON data. It provides a wealth of features including automatic retry, timeout settings, request and response logs, etc. You can use Resty to send requests of various types such as GET, POST, PUT, DELETE, etc., and it can automatically parse the responding JSON data into a Go structure.
Now the v2 version is available, which supports HTTP/2, WebSocket, and cookie operations, and provides a more concise and easy-to-use API.
Project address:/go-resty/resty
It's OK to use
GET method
import "/go-resty/resty/v2" req := ().SetHeader("Authorization", "token "+) (map[string]string{ "year": "2024", }) resp, err = ("path")
POST method
(map[string]string{ "year": "2024", }) resp, err = ("path")
SetBody
The parameters areinterface{}
Types, there are a lot of types that can be passed in. I still pass the dictionary here like GET, but in fact I should pass it.struct
More.
Log Component
I used the log built in the go language, but it seems that there are few functions and no log levels. Can this be called a log library?
Then I found a lot of logrus libraries on GitHub, but I felt that this is a relatively old library, which is not easy to use, and formatter was not easy to use. I found that this library has entered a retirement state after reading the project homepage introduction...
It lets me check out, for example,Zerolog, Zap, and Apex.
Logrus is in maintenance-mode. We will not be introducing new features. It's simply too hard to do in a way that won't break many people's projects, which is the last thing you want from your Logging library (again...).
Project address:/sirupsen/logrus
So, in the end, I used the uber log library/zap
logrus using & configuration
Although I changed zap later, I will still record the use of logrus.
I have basically tried several third-party formatters listed on the project homepage, just this onenested-logrus-formatter
It's easier to use.
The following configuration implements the output of logs to the console and files simultaneously.
import ( nested "/antonfisher/nested-logrus-formatter" "/sirupsen/logrus" "os" ) func initLogger() * { () (true) (&{}) // Create a file as log output file, err := ("", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) if err != nil { ("Cannot open log file: %v", err) } // Create a multiwriter to output logs to the console and files at the same time mw := (, file) // Add a Hook to Logger = mw return file } func main() { file := initLogger() defer func(file *) { err := () if err != nil { (err) } }(file) }
zap Use & Configure
Zap is much easier to use than logrus. It is used out of the box. With zapcore, you can configure multiple outputs, or you can set the files to be divided by log size, and you can also connect to other log collection platforms. It has basically achieved the level of modern log components...
It also implements the output of logs to the console and files simultaneously.
import ( "/zap" "/zap/zapcore" "os" ) func buildLogger() * { config := () = zapcore.ISO8601TimeEncoder consoleEncoder := (config) fileEncoder := (config) logFile, _ := ("./", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 06666) tee := ( (fileEncoder, (logFile), ), (consoleEncoder, (), ), ) var zapLogging = ( tee, (), (), ) var logger = () return logger } func main() { logger := buildLogger() defer () }
swagger component
I tried using go swagger here
Project address:/go-swagger/go-swagger
This can be installed using scoop
scoop install go-swagger
It is average, and it is not as easy to use as swagger code generator.
I didn't continue exploring.
PS: There are several swagger code generator tools in the IDE of the Jetbrains system, which are very powerful and can generate various codes.
However, I still implemented OpenAPI document parsing myself (more flexible), so I haven't used this powerful tool yet.
Excel export
I'm using this for Excel operation/xuri/excelize/v2
I didn't pay attention at first, but later I found that this was actually from Qi'anxin open source... Then I looked at the qax-os group and found that several open source projects are all unrelated to security and are not doing their jobs!
There is no comparison with other ones. It looks like there are quite a lot of stars, so I just use them as soon as I get started.
It feels OK.
func exportTestReportsToExcel(testReports []*, filename string) error { // Create a new Excel file f := () // Create a worksheet called "Test Report" index, err := ("Test Report") if err != nil { return err } // Set worksheet column name ("Test Report", "A1", "Interface Name") ("Test Report", "B1", "Interface Path") ("Test Report", "C1", "Whether the test passes") ("Test Report", "D1", "Time to take (seconds)") // traverse the test report and write data in the worksheet for i, report := range testReports { row := i + 2 ("Test Report", ("A%d", row), ) ("Test Report", ("B%d", row), ) ("Test Report", ("C%d", row), func() string { if { return "yes" } return "no" }()) ("Test Report", ("D%d", row), ()) } // Set up activity worksheets (index) // Save Excel files to disk err = (filename) if err != nil { return err } return nil }
Make complaints
Tripartite Expressions
I really want to complain about why go does not have ternary expressions, and using anonymous functions is really cumbersome! !
It is said that because I think the ternary expression can write a lot of incomprehensible code, so I don’t plan to support it, so I’m going to give up because of the choke.
But this is not a problem for me. I can write a function to simulate it. Now go seems to have updated the generic function, so I don’t have to use interface to simulate it.
func If[T any](condition bool, trueVal, falseVal T) T { if condition { return trueVal } return falseVal }
When using it
result := If[string](, "success", "Not passed")
Support type derivation, so[string]
It can also be omitted.
In this way, the anonymous functions in the code exported to Excel can be changed to this, which is much more concise!
("Test Report", ("C%d", row), If(, "yes", "no"))
Array sorting
It wasn't a big complaint at first, it was a picky one. The sorting of go is not that easy, but it is not difficult to use.
Using anonymous functions can achieve sorting by field, which is similar to using function pointers in C language. It is worthy of being a C language with gc
The data structure of the test report is like this
// Report Test Reporttype Report struct { ApiName string ApiPath string IsPassed bool Elapsed Response *ApiResponse }
I want to be right[]*Report
Array sorting can be usedmethod
// Sort by Elapsed attribute, from large to small(testReports, func(i, j int) bool { return testReports[i].Elapsed > testReports[j].Elapsed })
In comparison, Linq is still comfortable with CS.
((a, b) => a - b);
summary
That's it, a very simple gadget, because I'm still in the novice stage of go, I will record it every time I use a new library.
References
Detailed explanation of the use of uber's Go log library zap -Detailed explanation of the use of Golang log operation library zap
The above is the detailed explanation of the detailed explanation of using Go language to develop automation API testing tools. For more information about Go automation API testing tools, please pay attention to my other related articles!