《使用Gin框架构建分布式应用》阅读笔记:p272-p306
2024-10-31 18:25 codists

《用Gin框架构建分布式应用》学习第15天,p272-p306总结,总35页。

一、技术总结

1.TDD(test-driven development)

虽然经常看到TDD这个属于,从本人的工作经历看,实际开发中用得相对较少。

2.unitest(单元测试)

go语言开发中,使用testify进行单元测试开发。

(1)创建测试文件

测试文件以xxx_test.go命名,与xxx.go在同一目录下。示例:main.go和mian_test.go在同一目录下。

(2)编写测试函数

测试函数必须Test作为前缀,后面跟被测试函数名,示例:被测试函数名称为IndexHandler,测试函数名称为TestIndexHandler。

main.go:

// main.go

package main

import (

"github.com/gin-gonic/gin"

"net/http"

)

func IndexHandler(c *gin.Context) {

c.JSON(http.StatusOK, gin.H{"message": "hello world"})

}

func SetupServer() *gin.Engine {

router := gin.Default()

router.GET("/", IndexHandler)

return router

}

func main() {

err := SetupServer().Run()

if err != nil {

return

}

}

main_test.go:

package main

import (

"github.com/stretchr/testify/assert"

"io"

"net/http"

"net/http/httptest"

"testing"

)

func TestIndexHandler(t *testing.T) {

// 不适用 testify

// 注意,因为`{"message":"hello world"}`是字符串,所以冒号后面如果有空格,在判断相等的时候也会有影响

// mockUserResp := `{"message":"hello world"}`

//

// ts := httptest.NewServer(SetupServer())

// defer ts.Close()

//

// res, err := http.Get(ts.URL + "/")

// if err != nil {

// t.Fatalf("Expected no error: got %v", err)

// }

//

// defer res.Body.Close()

//

// if res.StatusCode != http.StatusOK {

// t.Fatalf("Expected status code 200: got %v", res.StatusCode)

// }

//

// // ioutil.ReadAll 已不推荐使用

// // responseData, err := ioutil.ReadAll(res.Body)

// responseData, err := io.ReadAll(res.Body)

// if string(responseData) != mockUserResp {

// t.Fatalf("Expected hello world message: got %v", string(responseData))

// }

// 使用 testify

mockUserResp := `{"message": "hello world"}`

ts := httptest.NewServer(SetupServer())

defer ts.Close()

res, err := http.Get(ts.URL + "/")

defer res.Body.Close()

assert.Nil(t, err)

assert.Equal(t, http.StatusOK, res.StatusCode)

responseData, err := io.ReadAll(res.Body)

assert.Equal(t, mockUserResp, string(responseData))

}

(3)执行测试

go test

3.coverage(测试覆盖率)

p282, Test coverage describes how much of a package's code is exercised by running the package's tests.

4.integration test(集成测试)

integration test就是多个功能一起测试。

5.security test(安全测试)

go语言开发中,使用gosec进行安全测试。

6.postman

书上介绍了postman的collection, environment, scripts的使用,基本属于工作中常用到的操作。当然,postman本身也不复杂。

go语言开发中,使用

7.吐槽系列

// chapter 01

router := gin.Default()

// chapter 07

r := gin.Default()

作者在chapter 01用的名称是router, 那么在chapter 07也应该用这个,而不是r,保持字段名称的一致性!想起本人在实际工作中遇到的一个项目,其中表示“设备”的名称就用了三个:eqp, equip, equipment,但其实都是指同一个东西,这无形中会导致一些问题:(1)阅读代码的人会有疑问,这三个表示的是同一个东西吗?(2)写代码的时候得思考,用的是哪个名称。

二、英语总结

无。

三、其它

今天没有什么想说的。

四、参考资料

1. 编程

(1) Mohamed Labouardy,《Building Distributed Applications in Gin》:
https://book.douban.com/subject/35610349

2. 英语

(1) Etymology Dictionary:https://www.etymonline.com

(2) Cambridge Dictionary:https://dictionary.cambridge.org

欢迎搜索及关注:编程人(a_codists)

特别声明:本文系网络转载,如有侵权请联系删除,版权归原作者所有