Go 的测试踩坑

ysmood:一直在用 testify 写测试,它算是所有测试库里面比较简单可依赖的。然而它还是有些多年没解决的问题。比如比较时间的大小( v2 才支持了,还在开发中)。

比如下面的代码,看上去很正常,但是其实会触发 testify 的 bug:

import (
	"testing"

	"github.com/stretchr/testify/suite"
)

func Test(t *testing.T) {
	suite.Run(t, &Suite{})
}

type Suite struct {
	suite.Suite
}

func (s *Suite) TestA() {
	s.T().Parallel()
	s.Equal(2, 1)
}

func (s *Suite) TestB() {
	s.T().Parallel()
}

具体的讨论可以看这里: https://github.com/stretchr/testify/issues/187

testify 之所以有这个问题,核心原因是它的设计会导致 Suite 在多个子测试中被竞争。
为了处理这个问题写了个轻量的库,无任何依赖可以用来替代 testify 的 suite,配合 testify 的 assert 的用法如下:

import (
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"github.com/ysmood/got"
)

func Test(t *testing.T) {
	got.Each(t, beforeEach)
}

func beforeEach(t *testing.T) Suite {
	t.Parallel()
	return Suite{assert.New(t)}
}

type Suite struct { // struct that holds subtests
	*assert.Assertions
}

func (s Suite) A() { // test case A
	time.Sleep(time.Second)
	s.Equal(1, 1)
}

func (s Suite) B() { // test case B
	time.Sleep(time.Second)
	s.Equal(2, 1)
}

也可以独立使用,用来做一些简单的测试应该会很顺手,不需要写一堆 Test 前缀和 t *testing.T 了:

import (
	"testing"

	"github.com/ysmood/got"
)

func Test(t *testing.T) {
	got.Each(t, S{})
}

type S struct {
	got.Assertion
}

func (s S) A() {
	s.Eq(1, 1)
}

func (s S) B() {
	s.Gt(2, 1)
}

项目地址: https://github.com/ysmood/got

pwli:没有看太懂…

ysmood:@pwli 具体的讨论看这个 https://github.com/stretchr/testify/issues/187

超火爆的 go 微服务框架推荐

kevinwan:go-zero 内置完整微服务治理能力,千万级日活实践检验,工具自动生成微服务,只需编写业务代码即可 开源一个月即获 1.3k stars 项目地址: https://github.com/tal-tech/go-zero 快速开始: https://github.com/tal-tech/go-zero/blob/master/doc/b…

求问 Go 设置结构体属性的样式

hjahgdthab750:实际在用的时候似乎有两种形式,但是不知道那种更优或者各自的场景 type A { X string B string } func (a *A) SetX (error) {} func (a A) GetX (string,error) {} func NewA() { a = A{} // 第一种 a.X,err = a.Ge…

招一个 Go 开发,国庆节前有效-美团

iamecho:HC:招一个 Go 开发,国庆节前有效。工作 2 年以上。 团队:美团基础架构调度系统团队,Kubernetes 与云原生,面试对云相关没什么要求,后期感兴趣可以内部慢慢转向云相关。 需要可以简历发送到:iamwgliang#gmail.com

go 超级萌新,求问 go-cache 的问题

hbolive:背景:刚过完 go 语法,还没入门那种,现在有个 go-cache 的例子,有 3 个问题请教大家目的:设置缓存,在缓存未过期时从缓存读取数据,如果读取失败,则将缓存内容写入缓存;最后将内容打印出来。package mainimport ( "fmt" "time" "github.com/patrickmn/go-cache")func m…

Go 中怎么实现类似 Java 里的枚举类型?

woostundy:用定义常量来实现枚举类型,太简易了。没法通过值找到枚举名称,没法约束值范围,没法输出所有可选枚举值。 试过在自定义类型上面加 String(), All() 方法,但代码又多又丑陋。 有什么好的写法或者第三方包能实现吗?scnace:code generation (逃 lbp0200:直接复制粘贴了type Direction intc…