← 返回 Skills 市场
samber

Golang Stretchr Testify

作者 Samuel Berthe · GitHub ↗ · v1.1.1 · MIT-0
cross-platform ✓ 安全检测通过
173
总下载
0
收藏
0
当前安装
2
版本数
在 OpenClaw 中安装
/install golang-stretchr-testify
功能描述
Comprehensive guide to stretchr/testify for Golang testing. Covers assert, require, mock, and suite packages in depth. Use whenever writing tests with testif...
使用说明 (SKILL.md)

Persona: You are a Go engineer who treats tests as executable specifications. You write tests to constrain behavior and make failures self-explanatory — not to hit coverage targets.

Modes:

  • Write mode — adding new tests or mocks to a codebase.
  • Review mode — auditing existing test code for testify misuse.

stretchr/testify

testify complements Go's testing package with readable assertions, mocks, and suites. It does not replace testing — always use *testing.T as the entry point.

This skill is not exhaustive. Please refer to library documentation and code examples for more informations. Context7 can help as a discoverability platform.

assert vs require

Both offer identical assertions. The difference is failure behavior:

  • assert: records failure, continues — see all failures at once
  • require: calls t.FailNow() — use for preconditions where continuing would panic or mislead

Use assert.New(t) / require.New(t) for readability. Name them is and must:

func TestParseConfig(t *testing.T) {
    is := assert.New(t)
    must := require.New(t)

    cfg, err := ParseConfig("testdata/valid.yaml")
    must.NoError(err)    // stop if parsing fails — cfg would be nil
    must.NotNil(cfg)

    is.Equal("production", cfg.Environment)
    is.Equal(8080, cfg.Port)
    is.True(cfg.TLS.Enabled)
}

Rule: require for preconditions (setup, error checks), assert for verifications. Never mix randomly.

Core Assertions

is := assert.New(t)

// Equality
is.Equal(expected, actual)              // DeepEqual + exact type
is.NotEqual(unexpected, actual)
is.EqualValues(expected, actual)        // converts to common type first
is.EqualExportedValues(expected, actual)

// Nil / Bool / Emptiness
is.Nil(obj)                  is.NotNil(obj)
is.True(cond)                is.False(cond)
is.Empty(collection)         is.NotEmpty(collection)
is.Len(collection, n)

// Contains (strings, slices, map keys)
is.Contains("hello world", "world")
is.Contains([]int{1, 2, 3}, 2)
is.Contains(map[string]int{"a": 1}, "a")

// Comparison
is.Greater(actual, threshold)     is.Less(actual, ceiling)
is.Positive(val)                  is.Negative(val)
is.Zero(val)

// Errors
is.Error(err)                     is.NoError(err)
is.ErrorIs(err, ErrNotFound)      // walks error chain
is.ErrorAs(err, &target)
is.ErrorContains(err, "not found")

// Type
is.IsType(&User{}, obj)
is.Implements((*io.Reader)(nil), obj)

Argument order: always (expected, actual) — swapping produces confusing diff output.

Advanced Assertions

is.ElementsMatch([]string{"b", "a", "c"}, result)             // unordered comparison
is.InDelta(3.14, computedPi, 0.01)                            // float tolerance
is.JSONEq(`{"name":"alice"}`, `{"name": "alice"}`)             // ignores whitespace/key order
is.WithinDuration(expected, actual, 5*time.Second)
is.Regexp(`^user-[a-f0-9]+$`, userID)

// Async polling
is.Eventually(func() bool {
    status, _ := client.GetJobStatus(jobID)
    return status == "completed"
}, 5*time.Second, 100*time.Millisecond)

// Async polling with rich assertions
is.EventuallyWithT(func(c *assert.CollectT) {
    resp, err := client.GetOrder(orderID)
    assert.NoError(c, err)
    assert.Equal(c, "shipped", resp.Status)
}, 10*time.Second, 500*time.Millisecond)

testify/mock

Mock interfaces to isolate the unit under test. Embed mock.Mock, implement methods with m.Called(), always verify with AssertExpectations(t).

Key matchers: mock.Anything, mock.AnythingOfType("T"), mock.MatchedBy(func). Call modifiers: .Once(), .Times(n), .Maybe(), .Run(func).

For defining mocks, argument matchers, call modifiers, return sequences, and verification, see Mock reference.

testify/suite

Suites group related tests with shared setup/teardown.

Lifecycle

SetupSuite()    → once before all tests
  SetupTest()   → before each test
    TestXxx()
  TearDownTest() → after each test
TearDownSuite() → once after all tests

Example

type TokenServiceSuite struct {
    suite.Suite
    store   *MockTokenStore
    service *TokenService
}

func (s *TokenServiceSuite) SetupTest() {
    s.store = new(MockTokenStore)
    s.service = NewTokenService(s.store)
}

func (s *TokenServiceSuite) TestGenerate_ReturnsValidToken() {
    s.store.On("Save", mock.Anything, mock.Anything).Return(nil)
    token, err := s.service.Generate("user-42")
    s.NoError(err)
    s.NotEmpty(token)
    s.store.AssertExpectations(s.T())
}

// Required launcher
func TestTokenServiceSuite(t *testing.T) {
    suite.Run(t, new(TokenServiceSuite))
}

Suite methods like s.Equal() behave like assert. For require: s.Require().NotNil(obj).

Common Mistakes

  • Forgetting AssertExpectations(t) — mock expectations silently pass without verification
  • is.Equal(ErrNotFound, err) — fails on wrapped errors. Use is.ErrorIs to walk the chain
  • Swapped argument order — testify assumes (expected, actual). Swapping produces backwards diffs
  • assert for guards — test continues after failure and panics on nil dereference. Use require
  • Missing suite.Run() — without the launcher function, zero tests execute silently
  • Comparing pointersis.Equal(ptr1, ptr2) compares addresses. Dereference or use EqualExportedValues

Linters

Use testifylint to catch wrong argument order, assert/require misuse, and more. See samber/cc-skills-golang@golang-linter skill.

Cross-References

  • → See samber/cc-skills-golang@golang-testing skill for general test patterns, table-driven tests, and CI
  • → See samber/cc-skills-golang@golang-linter skill for testifylint configuration
安全使用建议
This skill is an instruction-only testify guide and appears coherent with its stated purpose. If you plan to install the provided gotests binary, review the github.com/cweill/gotests source (or vendor a vetted version) because 'go install' will download and build code from the network. Also confirm you’re comfortable with the agent using allowed tools (git, gotests, webfetch) and with autonomous invocation; no credentials or system-wide config access are requested.
功能分析
Type: OpenClaw Skill Name: golang-stretchr-testify Version: 1.1.1 The skill bundle is a legitimate and well-structured guide for using the 'stretchr/testify' library in Golang. It provides idiomatic testing patterns, clear distinctions between assertions and requirements, and comprehensive documentation for mocks and suites (SKILL.md, references/mock.md). The allowed tools and installation steps are appropriate for a Go development environment, and the evaluation cases (evals/evals.json) are designed to ensure the AI agent follows best practices without any evidence of malicious intent or prompt injection.
能力评估
Purpose & Capability
Name/description match the requested binaries (go, gotests) and the install (github.com/cweill/gotests). Requiring gotests is proportional for a test-writing helper that may generate test stubs.
Instruction Scope
SKILL.md contains guidance limited to writing and reviewing tests with stretchr/testify; it does not instruct the agent to read unrelated files, environment variables, or exfiltrate data. The allowed tools (git, linters, gotests, WebFetch, etc.) are reasonable for a coding assistant.
Install Mechanism
Install uses 'go' to fetch github.com/cweill/gotests/...@latest which is a public Go package and common for developer tooling. This is expected for a test-generation helper but is a network fetch that will write a binary to disk (gotests); if you require stricter controls, review the upstream package source before installing.
Credentials
No environment variables, credentials, or config paths are requested. The skill does not ask for unrelated tokens or secrets.
Persistence & Privilege
always is false and the skill does not request elevated or persistent platform-wide privileges. Autonomous invocation is allowed by default but not combined with other concerning permissions.
如何使用
  1. 确保已安装 OpenClaw(本地或 Docker 部署)
  2. 在对话框中输入安装命令:/install golang-stretchr-testify
  3. 安装完成后,直接呼叫该 Skill 的名称或使用 /golang-stretchr-testify 触发
  4. 根据 Skill 的参数说明提供必要输入,即可获得结构化输出
版本历史
v1.1.1
- Version bumped to 1.1.1. - Added an evals/evals.json file. - Minor metadata update in SKILL.md (version number updated). - No user-facing changes to documentation or functionality.
v0.1.0
Initial release. - Provides a comprehensive guide to using stretchr/testify in Go tests, including assert, require, mock, and suite packages. - Offers practical usage patterns, advanced assertions, and explanations of common pitfalls. - Includes sample code, lifecycle explanations for test suites, and advice for choosing between assert and require. - Highlights tools like testifylint and cross-references related skills for further reading. - Designed for coding agents and Go projects; not user-invocable.
元数据
Slug golang-stretchr-testify
版本 1.1.1
许可证 MIT-0
累计安装 0
当前安装数 0
历史版本数 2
常见问题

Golang Stretchr Testify 是什么?

Comprehensive guide to stretchr/testify for Golang testing. Covers assert, require, mock, and suite packages in depth. Use whenever writing tests with testif... 它是一个面向 Claude Code / OpenClaw 的 AI Agent Skill 插件,目前累计下载 173 次。

如何安装 Golang Stretchr Testify?

在 OpenClaw 或 Claude Code 对话框中运行命令「/install golang-stretchr-testify」即可一键安装,无需额外配置。

Golang Stretchr Testify 是免费的吗?

是的,Golang Stretchr Testify 完全免费,采用 MIT-0 许可证,可自由下载、安装和使用。

Golang Stretchr Testify 支持哪些平台?

Golang Stretchr Testify 跨平台运行,可在任意部署了 OpenClaw / Claude Code 的环境中使用(cross-platform)。

谁开发了 Golang Stretchr Testify?

由 Samuel Berthe(@samber)开发并维护,当前版本 v1.1.1。

💬 留言讨论