Write tests in GO language + gin

Introduction

Please see sourcegraph.com/github for the time being. This article introduces some of the code you saw earlier. Let's write a simple test with golang + gin. Difficult to test

Referenced

environment

go version go1.13.8 linux/amd64

code

Create main.go. http://localhost:8080/ping When you connect to, "pong" is returned. If you set / ps (post) to {"name": "someone"}, you will get a "someone" message. In case of an error, "error" is returned.

main.go


package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

type User struct {
	Name string `json:"name" binding:"required"`
}

func router() *gin.Engine {
	r := gin.Default()
	r.GET("/ping", func(c *gin.Context) {
		// const StatusOK untyped int = 200
		// gin.H is map[string]interface{}Same as
		c.JSON(http.StatusOK, gin.H{"msg": "pong"})
	})
	r.POST("/ps", func(c *gin.Context) {
		var u User
		if err := c.BindJSON(&u); err != nil {
			// const StatusUnauthorized untyped int = 401
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "error"})
			return
		}
		c.JSON(http.StatusOK, gin.H{"msg": u})
	})
	return r
}
func main() {
	router().Run()
}

Let's test

This is the official test.

Test 1


func TestPingRouter(t *testing.T) {
	router := router()
	w := httptest.NewRecorder()
	//c, _ := gin.CreateTestContext(w)
	req, _ := http.NewRequest("GET", "/ping", nil)
	router.ServeHTTP(w, req)

	assert.Equal(t, 200, w.Code)
	// ...
	assert.Equal(t, w.Body.String(), "{\"msg\":\"pong\"}")
}

Next is the POST test. This test sends "foo". Then it will be returned in JSON. Then check if it is "foo". If it matches, the test is successful. It seems interesting to add assert.Equal () one after another and try various things. (Supplement) c.Request, _ = http.NewRequest ()-> How to write context_test.go. req, _: = http.NewRequest ()-> How to write a tutorial-like part of gin req and c.Request were probably the same, both were * Requests.

Test 2


func TestPs(t *testing.T) {
	router := router()
	w := httptest.NewRecorder()
	c, _ := gin.CreateTestContext(w)
	body := bytes.NewBufferString("{\"name\":\"foo\"}")
	c.Request, _ = http.NewRequest("POST", "/ps", body)
	// req, _ := http.NewRequest("POST", "/ps", body)
	router.ServeHTTP(w, c.Request)

	assert.JSONEq(t, w.Body.String(), "{\"msg\":{\"name\":\"foo\"}}")
	assert.Equal(t, w.Code, 200)
	// ...
}

Almost the same as in context_test.go

Test 3


func TestPs2(t *testing.T) {
	w := httptest.NewRecorder()
	c, _ := gin.CreateTestContext(w)
	body := bytes.NewBufferString("{\"foo\":\"bar\",\"bar\":\"foo\"}")
	c.Request, _ = http.NewRequest("POST", "/ps", body)
	c.Request.Header.Add("Content-Type", binding.MIMEJSON)
	var obj struct {
		Foo string `json:"foo"`
		Bar string `json:"bar"`
	}
	c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "error"})
	assert.Equal(t, w.Code, 401)
	assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8")
	assert.NoError(t, c.BindJSON(&obj))
	assert.Equal(t, obj.Foo, "bar")
	assert.Equal(t, obj.Bar, "foo")
	assert.NotEqual(t, obj.Foo, "xxxx")
	assert.Empty(t, c.Errors)
}

Test 1 is a / ping (GET) test and test 2 and test 3 are / ps (POST) tests.

end

For Bind JSON in main.go Investigative notes on gin Binding and Validation

Recommended Posts

Write tests in GO language + gin
Write Pulumi in Go
Write Spider tests in Scrapy
Try implementing Yubaba in Go language
Use optinal type-like in Go language
Post to slack in Go language
Write C unit tests in Python
Do something object-oriented in GO language
Java programmer touched Go language (Implement Java inheritance in Go language)
I wrote the hexagonal architecture in go language
Write Kikagaku-style algorithm theory in Go Primality test
Create a web server in Go language (net/http) (2)
Write DCGAN in Keras
Go language learning record
Go language environment construction
Write tests in Python to profile and check coverage
Go language cheat sheet
Create a web server in Go language (net / http) (1)
Go language to see and remember Part 7 C language in GO language
[Go language] How to get terminal input in real time
To write a test in Go, first design the interface
Machine language embedding in C language
Write standard input in code
Write beta distribution in Python
Write python in Rstudio (reticulate)
Write Spigot in VS Code
Implement recursive closures in Go
Write data in HDF format
Programming language in "Hello World"
go language learning miscellaneous notes 1
[Golang] About Go language channel
Created a package to support AWS Lambda development in Go language
Created gomi, a trash can tool for rm in Go language
Read the config file in Go language! Introducing a simple sample