Golang 单元测试:有哪些误区和实践?

{"type":"doc","content":[{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"背景"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"测试是保证代码质量的有效手段,而单元测试是程序模块儿的最小化验证。单元测试的重要性是不言而喻的。相对手工测试,单元测试具有自动化执行、可自动回归,效率较高的特点。对于问题的发现效率,单测的也相对较高。在开发阶段编写单测 case ,daily push daily test,并通过单测的成功率、覆盖率来衡量代码的质量,能有效保证项目的整体质量。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https:\/\/static001.infoq.cn\/resource\/image\/12\/87\/125e62421e7f056d0c019a6a7a4e9287.jpg","alt":null,"title":"","style":[{"key":"width","value":"100%"},{"key":"bordertype","value":"none"}],"href":"","fromPaste":false,"pastePass":false}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"单测准则"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"什么是好的单测?阿里巴巴的 "},{"type":"link","attrs":{"href":"http:\/\/mp.weixin.qq.com\/s?__biz=MzIzOTU0NTQ0MA==&mid=2247498279&idx=1&sn=313d9b047d8fc7aff7c1f90dc4a3c7e7&chksm=e92ac728de5d4e3e1678a7480752eb92d6346a20804101a7f6d49d0a9f101145fee0f8c033e0&scene=21#wechat_redirect","title":"","type":null},"content":[{"type":"text","text":"《Java 开发手册》"}]},{"type":"text","text":"(点击下载)中描述了好的单测的特征:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"A:(Automatic,自动化):单元测试应该是全自动执行的,并且非交互式的。"}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"I:(Independent,独立性):为了保证单元测试稳定可靠且便于维护,单元测试用例之间决不能互相调用,也不能依赖执行的先后次序。"}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"R:"},{"type":"text","text":"("},{"type":"text","text":"Repeatable,可重复):单元测试通常会被放到持续集成中,每次有代码check in时单元测试都会被执行。如果单测对外部环境(网络、服务、中间件等)有依赖,容易导致持续集成机制的不可用。"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"单测应该是可重复执行的,对外部的依赖、环境的变化要通过 mock 或其他手段屏蔽掉。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在 On the architecture for unit testing [1] 中对好的单测有以下描述:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"简短,只有一个测试目的"}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"简单,数据构造、清理都很简单"}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"快速,执行函数秒级执行"}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"标准,遵守严格的约定(准备测试上下文,执行关键操作,验证结果)"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"单测的误区"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"没有断言。没有断言的单测是没有灵魂的。如果只是 print 出结果,单测是没有意义的。"}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"不接入持续集成。单测不应该是本地的 run once ,而应该接入到研发的整个流程中,合并代码,发布上线都应该触发单测执行,并且可以重复执行。"}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"粒度过大。单测粒度应该尽量小,不应该包含过多计算逻辑,尽量只有输入,输出和断言。"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"很多人不愿意写单测,是因为项目依赖很多,各个函数之间各种调用,不知道如何在一个隔离的测试环境下进行测试。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在实践中我们调研了几种隔离(mock)的手段,下面进行逐一介绍。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"单测实践"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"本次实践的工程项目是一个 http(基于 gin 的http 框架) 的服务。以入口的 controller 层的函数为被测函数,介绍下对它的单测过程。下面的函数的作用是根据工号输出该用户下的代码仓库的 CodeReview 数据。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"可以看到这个函数作为入口层还是比较简单的,只是做了一个参数校验后调用下游并将结果透出。"}]},{"type":"bulletedlist"},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"func ListRepoCrAggregateMetrics(c *gin.Context) {\n workNo := c.Query(\"work_no\")\n if workNo == \"\" {\n c.JSON(http.StatusOK, errors.BuildRsp(errors.ErrorWarpper(errors.ErrParamError.ErrorCode, \"work no miss\"), nil))\n return\n }\n crCtx := code_review.NewCrCtx(c)\n rsp, err := crCtx.ListRepoCrAggregateMetrics(workNo)\n if err != nil {\n c.JSON(http.StatusOK, errors.BuildRsp(errors.ErrorWarpper(errors.ErrDbQueryError.ErrorCode, err.Error()), rsp))\n return\n }\n c.JSON(http.StatusOK, errors.BuildRsp(errors.ErrSuccess, rsp))\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"它的结果大致如下:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"{\n \"data\": {\n \"total\": 10,\n \"code_review\": [\n {\n \"repo\": {\n \"project_id\": 1,\n \"repo_url\": \"test\"\n },\n \"metrics\": {\n \"code_review_rate\": 0.0977918,\n \"thousand_comment_count\": 0,\n \"self_submit_code_review_rate\": 0,\n \"average_merge_cost\": 30462.584,\n \"average_accept_cost\": 30388.75\n }\n }\n ]\n },\n \"errorCode\": 0,\n \"errorMsg\": \"成功\"\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"针对这个函数测试,我们预期覆盖以下场景:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"workNo 为空时报错。"}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"workNo 不为空时范围 ,下游调用成功,repos cr 聚合数据。"}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"workNo 不为空,下游失败,返回报错信息。"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"color","attrs":{"color":"#FF7021","name":"orange"}},{"type":"strong"}],"text":"方案一:不 mock 下游, mock 依赖存储 (不建议)"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"这种方式是通过配置文件,将依赖的存储都连接到本地(比如 sqlite , redis)。这种方式下游没有 mock 而是会继续调用。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"var db *gorm.DB\nfunc getMetricsRepo() *model.MetricsRepo {\n repo := model.MetricsRepo{\n ProjectID: 2,\n RepoPath: \"\/\",\n FileCount: 5,\n CodeLineCount: 76,\n OwnerWorkNo: \"999999\",\n }\n return &repo\n}\nfunc getTeam() *model.Teams {\n team := model.Teams{\n WorkNo: \"999999\",\n }\n return &team\n}\nfunc init() {\n db, err := gorm.Open(\"sqlite3\", \"test.db\")\n if err != nil {\n os.Exit(-1)\n }\n db.Debug()\n db.DropTableIfExists(model.MetricsRepo{})\n db.DropTableIfExists(model.Teams{})\n db.CreateTable(model.MetricsRepo{})\n db.CreateTable(model.Teams{})\n db.FirstOrCreate(getMetricsRepo())\n db.FirstOrCreate(getTeam())\n}\ntype RepoMetrics struct {\n CodeReviewRate float32 `json:\"code_review_rate\"` \n ThousandCommentCount uint `json:\"thousand_comment_count\"` \n SelfSubmitCodeReviewRate float32 `json:\"self_submit_code_review_rate\"` \n}\ntype RepoCodeReview struct {\n Repo repo.Repo `json:\"repo\"`\n RepoMetrics RepoMetrics `json:\"metrics\"`\n}\ntype RepoCrMetricsRsp struct {\n Total int `json:\"total\"`\n RepoCodeReview []*RepoCodeReview `json:\"code_review\"`\n}\nfunc TestListRepoCrAggregateMetrics(t *testing.T) {\n w := httptest.NewRecorder()\n _, engine := gin.CreateTestContext(w)\n engine.GET(\"\/api\/test\/code_review\/repo\", ListRepoCrAggregateMetrics)\n req, _ := http.NewRequest(\"GET\", \"\/api\/test\/code_review\/repo?work_no=999999\", nil)\n engine.ServeHTTP(w, req)\n assert.Equal(t, w.Code, 200)\n var v map[string]RepoCrMetricsRsp\n json.Unmarshal(w.Body.Bytes(), &v)\n assert.EqualValues(t, 1, v[\"data\"].Total)\n assert.EqualValues(t, 2, v[\"data\"].RepoCodeReview[0].Repo.ProjectID)\n assert.EqualValues(t, 0, v[\"data\"].RepoCodeReview[0].RepoMetrics.CodeReviewRate)\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"上面的代码,我们没有对被测代码做改动。但是在运行 go test 进行测试时,需要指定配置到测试配置。被测项目是通过环境变量设置的。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"shell"},"content":[{"type":"text","text":"RDSC_CONF=$sourcepath\/test\/data\/config.yml go test -v -cover=true -coverprofile=$sourcepath\/cover\/cover.cover .\/..."}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"初始化测试环境,清空DB数据,写入被测数据。"}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"执行测试方法。"}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"断言测试结果。"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"color","attrs":{"color":"#FF7021","name":"orange"}},{"type":"strong"}],"text":"方案二:下游通过 interface 被 mock(推荐)"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"gomock[2] 是 Golang 官方提供的 Go 语言 mock 框架。它能够很好的和 Go testing 模块儿结合,也能用于其他的测试环境中。Gomock 包括依赖库 gomock 和接口生成工具 mockgen 两部分,gomock 用于完成桩对象的管理, mockgen 用于生成对应的 mock 文件。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"type Foo interface {\n Bar(x int) int\n}\nfunc SUT(f Foo) {\n \/\/ ...\n}\nctrl := gomock.NewController(t)\n \/\/ Assert that Bar() is invoked.\n defer ctrl.Finish()\n \/\/mockgen -source=foo.g\n m := NewMockFoo(ctrl)\n \/\/ Asserts that the first and only call to Bar() is passed 99.\n \/\/ Anything else will fail.\n m.\n EXPECT().\n Bar(gomock.Eq(99)).\n Return(101)\nSUT(m)"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"上面的例子,接口 Foo 被 mock。回到我们的项目,在我们上面的被测代码中是通过内部声明对象进行调用的。使用 gomock 需要修改代码,把依赖通过参数暴露出来,然后初始化时。下面是修改后的被测函数:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"type RepoCrCRController struct {\n c *gin.Context\n crCtx code_review.CrCtxInterface\n}\nfunc NewRepoCrCRController(ctx *gin.Context, cr code_review.CrCtxInterface) *TeamCRController {\n return &TeamCRController{c: ctx, crCtx: cr}\n}\nfunc (ctrl *RepoCrCRController)ListRepoCrAggregateMetrics(c *gin.Context) {\n workNo := c.Query(\"work_no\")\n if workNo == \"\" {\n c.JSON(http.StatusOK, errors.BuildRsp(errors.ErrorWarpper(errors.ErrParamError.ErrorCode, \"员工工号信息错误\"), nil))\n return\n }\n rsp, err := ctrl.crCtx.ListRepoCrAggregateMetrics(workNo)\n if err != nil {\n c.JSON(http.StatusOK, errors.BuildRsp(errors.ErrorWarpper(errors.ErrDbQueryError.ErrorCode, err.Error()), rsp))\n return\n }\n c.JSON(http.StatusOK, errors.BuildRsp(errors.ErrSuccess, rsp))\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"这样通过 gomock 生成 mock 接口可以进行测试了:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"func TestListRepoCrAggregateMetrics(t *testing.T) { \n ctrl := gomock.NewController(t)\n defer ctrl.Finish()\n m := mock.NewMockCrCtxInterface(ctrl)\n resp := &code_review.RepoCrMetricsRsp{\n }\n m.EXPECT().ListRepoCrAggregateMetrics(\"999999\").Return(resp, nil)\n w := httptest.NewRecorder()\n ctx, engine := gin.CreateTestContext(w)\n repoCtrl := NewRepoCrCRController(ctx, m)\n engine.GET(\"\/api\/test\/code_review\/repo\", repoCtrl.ListRepoCrAggregateMetrics)\n req, _ := http.NewRequest(\"GET\", \"\/api\/test\/code_review\/repo?work_no=999999\", nil)\n engine.ServeHTTP(w, req)\n assert.Equal(t, w.Code, 200)\n got := gin.H{}\n json.NewDecoder(w.Body).Decode(&got)\n assert.EqualValues(t, got[\"errorCode\"], 0)\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"color","attrs":{"color":"#FF7021","name":"orange"}},{"type":"strong"}],"text":"方案三:通过 monkey patch 方式 mock 下游 (推荐)"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在上面的例子中,我们需要修改代码来实现 interface 的mock,对于对象成员函数,无法进行 mock。monkey patch 通过运行时对底层指针内容修改的方式,实现对 instance method 的 mock (注意,这里要求 instance 的 method 必须是可以暴露的)。用 monkey 方式测试如下:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"func TestListRepoCrAggregateMetrics(t *testing.T) {\n w := httptest.NewRecorder()\n _, engine := gin.CreateTestContext(w)\n engine.GET(\"\/api\/test\/code_review\/repo\", ListRepoCrAggregateMetrics)\n var crCtx *code_review.CrCtx\n repoRet := code_review.RepoCrMetricsRsp{\n }\n monkey.PatchInstanceMethod(reflect.TypeOf(crCtx), \"ListRepoCrAggregateMetrics\",\n func(ctx *code_review.CrCtx, workNo string) (*code_review.RepoCrMetricsRsp, error) {\n if workNo == \"999999\" {\n repoRet.Total = 0\n repoRet.RepoCodeReview = []*code_review.RepoCodeReview{}\n }\n return &repoRet, nil\n })\n req, _ := http.NewRequest(\"GET\", \"\/api\/test\/code_review\/repo?work_no=999999\", nil)\n engine.ServeHTTP(w, req)\n assert.Equal(t, w.Code, 200)\n var v map[string]code_review.RepoCrMetricsRsp\n json.Unmarshal(w.Body.Bytes(), &v)\n assert.EqualValues(t, 0, v[\"data\"].Total)\n assert.Len(t, v[\"data\"].RepoCodeReview, 0)\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"color","attrs":{"color":"#FF7021","name":"orange"}},{"type":"strong"}],"text":"方案四:存储层 mock"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"Go-sqlmock 可以针对接口 sql\/driver[3] 进行 mock。它可以不用真实的 db ,而模拟 sql driver 行为,实现强大的底层数据测试。下面是我们采用 table driven[4] 写法来进行数据相关测试的例子。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"package store\nimport (\n \"database\/sql\/driver\"\n \"github.com\/DATA-DOG\/go-sqlmock\"\n \"github.com\/gin-gonic\/gin\"\n \"github.com\/jinzhu\/gorm\"\n \"github.com\/stretchr\/testify\/assert\"\n \"net\/http\/httptest\"\n \"testing\"\n)\ntype RepoCommitAndCRCountMetric struct {\n ProjectID uint `json:\"project_id\"`\n RepoCommitCount uint `json:\"repo_commit_count\"`\n RepoCodeReviewCommitCount uint `json:\"repo_code_review_commit_count\"`\n}\nvar (\n w = httptest.NewRecorder()\n ctx, _ = gin.CreateTestContext(w)\n ret = []RepoCommitAndCRCountMetric{}\n)\nfunc TestCrStore_FindColumnValues1(t *testing.T) {\n type fields struct {\n g *gin.Context\n db func() *gorm.DB\n }\n type args struct {\n table string\n column string\n whereAndOr []SqlFilter\n group string\n out interface{}\n }\n tests := []struct {\n name string\n fields fields\n args args\n wantErr bool\n checkFunc func()\n }{\n {\n name: \"whereAndOr is null\",\n fields: fields{\n db: func() *gorm.DB {\n sqlDb, mock, _ := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual))\n rs1 := sqlmock.NewRows([]string{\"project_id\", \"repo_commit_count\", \"repo_code_review_commit_count\"}).FromCSVString(\"1, 2, 3\")\n mock.ExpectQuery(\"SELECT project_id, sum(commit_count) as repo_commit_count, sum(code_review_commit_count) as repo_code_review_commit_count FROM `metrics_repo_cr` GROUP BY project_id\").WillReturnRows(rs1)\n gdb, _ := gorm.Open(\"mysql\", sqlDb)\n gdb.Debug()\n return gdb\n },\n },\n args: args{\n table: \"metrics_repo_cr\",\n column: \"project_id, sum(commit_count) as repo_commit_count, sum(code_review_commit_count) as repo_code_review_commit_count\",\n whereAndOr: []SqlFilter{},\n group: \"project_id\",\n out: &ret,\n },\n checkFunc: func() {\n assert.EqualValues(t, 1, ret[0].ProjectID, \"project id should be 1\")\n assert.EqualValues(t, 2, ret[0].RepoCommitCount, \"RepoCommitCount id should be 2\")\n assert.EqualValues(t, 3, ret[0].RepoCodeReviewCommitCount, \"RepoCodeReviewCommitCount should be 3\")\n },\n },\n {\n name: \"whereAndOr is not null\",\n fields: fields{\n db: func() *gorm.DB {\n sqlDb, mock, _ := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual))\n rs1 := sqlmock.NewRows([]string{\"project_id\", \"repo_commit_count\", \"repo_code_review_commit_count\"}).FromCSVString(\"1, 2, 3\")\n mock.ExpectQuery(\"SELECT project_id, sum(commit_count) as repo_commit_count, sum(code_review_commit_count) as repo_code_review_commit_count FROM `metrics_repo_cr` WHERE (metrics_repo_cr.project_id in (?)) GROUP BY project_id\").\n WithArgs(driver.Value(1)).WillReturnRows(rs1)\n gdb, _ := gorm.Open(\"mysql\", sqlDb)\n gdb.Debug()\n return gdb\n },\n },\n args: args{\n table: \"metrics_repo_cr\",\n column: \"project_id, sum(commit_count) as repo_commit_count, sum(code_review_commit_count) as repo_code_review_commit_count\",\n whereAndOr: []SqlFilter{\n {\n Condition: SQLWHERE,\n Query: \"metrics_repo_cr.project_id in (?)\",\n Arg: []uint{1},\n },\n },\n group: \"project_id\",\n out: &ret,\n },\n checkFunc: func() {\n assert.EqualValues(t, 1, ret[0].ProjectID, \"project id should be 1\")\n assert.EqualValues(t, 2, ret[0].RepoCommitCount, \"RepoCommitCount id should be 2\")\n assert.EqualValues(t, 3, ret[0].RepoCodeReviewCommitCount, \"RepoCodeReviewCommitCount should be 3\")\n },\n },\n {\n name: \"group is null\",\n fields: fields{\n db: func() *gorm.DB {\n sqlDb, mock, _ := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual))\n rs1 := sqlmock.NewRows([]string{\"project_id\", \"repo_commit_count\", \"repo_code_review_commit_count\"}).FromCSVString(\"1, 2, 3\")\n mock.ExpectQuery(\"SELECT project_id, sum(commit_count) as repo_commit_count, sum(code_review_commit_count) as repo_code_review_commit_count FROM `metrics_repo_cr` WHERE (metrics_repo_cr.project_id in (?))\").\n WithArgs(driver.Value(1)).WillReturnRows(rs1)\n gdb, _ := gorm.Open(\"mysql\", sqlDb)\n gdb.Debug()\n return gdb\n },\n },\n args: args{\n table: \"metrics_repo_cr\",\n column: \"project_id, sum(commit_count) as repo_commit_count, sum(code_review_commit_count) as repo_code_review_commit_count\",\n whereAndOr: []SqlFilter{\n {\n Condition: SQLWHERE,\n Query: \"metrics_repo_cr.project_id in (?)\",\n Arg: []uint{1},\n },\n },\n group: \"\",\n out: &ret,\n },\n checkFunc: func() {\n assert.EqualValues(t, 1, ret[0].ProjectID, \"project id should be 1\")\n assert.EqualValues(t, 2, ret[0].RepoCommitCount, \"RepoCommitCount id should be 2\")\n assert.EqualValues(t, 3, ret[0].RepoCodeReviewCommitCount, \"RepoCodeReviewCommitCount should be 3\")\n },\n },\n }\n for _, tt := range tests {\n t.Run(tt.name, func(t *testing.T) {\n cs := &CrStore{\n g: ctx,\n }\n db = tt.fields.db()\n if err := cs.FindColumnValues(tt.args.table, tt.args.column, tt.args.whereAndOr, tt.args.group, tt.args.out); (err != nil) != tt.wantErr {\n t.Errorf(\"FindColumnValues() error = %v, wantErr %v\", err, tt.wantErr)\n }\n tt.checkFunc()\n })\n }\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"color","attrs":{"color":"#FF7021","name":"orange"}},{"type":"strong"}],"text":"持续集成"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"Aone (阿里内部项目协作管理平台)提供了类似 travis-ci [5] 的功能:测试服务 [6]。我们可以通过创建单测类型的任务或者直接使用实验室进行单测集成。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"shell"},"content":[{"type":"text","text":"# 执行测试命令\nmkdir -p $sourcepath\/cover\nRDSC_CONF=$sourcepath\/config\/config.yaml go test -v -cover=true -coverprofile=$sourcepath\/cover\/cover.cover .\/...\nret=$?; if [[ $ret -ne 0 && $ret -ne 1 ]]; then exit $ret; fi"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"增量覆盖率可以通过 gocov\/gocov-xml 转换成 xml 报告,然后通过 diff_cover 输出增量报告:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"shell"},"content":[{"type":"text","text":"cp $sourcepath\/cover\/cover.cover \/root\/cover\/cover.cover\npip install diff-cover==2.6.1\ngocov convert cover\/cover.cover | gocov-xml > coverage.xml\ncd $sourcepath\ndiff-cover $sourcepath\/coverage.xml --compare-branch=remotes\/origin\/develop > diff.out"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"设置触发的集成阶段:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https:\/\/static001.infoq.cn\/resource\/image\/73\/af\/73b43637541281b1dcab4c59f00cacaf.jpg","alt":null,"title":"","style":[{"key":"width","value":"100%"},{"key":"bordertype","value":"none"}],"href":"","fromPaste":false,"pastePass":false}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https:\/\/static001.infoq.cn\/resource\/image\/9f\/1a\/9f3b36e80e8deb25f9a26970157c911a.jpg","alt":null,"title":"","style":[{"key":"width","value":"100%"},{"key":"bordertype","value":"none"}],"href":"","fromPaste":false,"pastePass":false}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"参考资料:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"[1]https:\/\/thomasvilhena.com\/2020\/04\/on-the-architecture-for-unit-testing"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"[2]https:\/\/github.com\/golang\/mock"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"[3]https:\/\/godoc.org\/database\/sql\/driver"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"[4]https:\/\/github.com\/golang\/go\/wiki\/TableDrivenTests"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"[5]https:\/\/travis-ci.org\/"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"[6]https:\/\/help.aliyun.com\/document_detail\/64021.html"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"作者"},{"type":"text","text":":石窗"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"原文"},{"type":"text","text":":"},{"type":"link","attrs":{"href":"https:\/\/mp.weixin.qq.com\/s\/Fj_ebCAUPlgTUPdsIg7CnA","title":"xxx","type":null},"content":[{"type":"text","text":"Golang单元测试:有哪些误区和实践?"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"来源"},{"type":"text","text":":高德技术 - 微信公众号 [ID:amap_tech]"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"转载"},{"type":"text","text":":著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}}]}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章