Logo de Go Testing

Go Testing

Comunidade
Integralist
go-testing

Write unit and integration tests for Go services. Use when creating, editing, or updating tests, test helpers, mocks, fuzz tests, or benchmarks in Go projects.

Visão geral

Publicado porIntegralist
Repositórioagent-skills
Nome da habilidadego-testing
Estrelas
26
Forks
1
Arquivos incluídos
4
Links
  • Instruções em Markdown

    Um arquivo SKILL.md que o modelo carrega sob demanda, consumindo tokens apenas quando uma solicitação é realmente relevante para a habilidade.

  • Funciona com qualquer LLM

    Habilidades de IA são Markdown simples, não código específico de um provedor, por isso funcionam com GPT, Claude, Gemini, Grok ou um modelo local.

  • 4 arquivos incluídos

    Scripts, modelos de documentos e referências que o modelo pode ler enquanto trabalha. Os arquivos são somente leitura e nunca são executados.

  • Código aberto

    Publicada por Integralist no GitHub. Leia o conteúdo-fonte antes de instalar.

Instalação

Instale a habilidade de IA Go Testing no TypingMind para usá-la com qualquer LLM ou adicione-a a outro agente que leia SKILL.md.

1

Instalar no TypingMind

O TypingMind instala uma habilidade diretamente da pasta dela no GitHub — lê o arquivo SKILL.md, reúne os arquivos de recursos em um pacote e armazena o resultado localmente.

  1. Abra o app e vá para Plugins → Habilidades.
  2. Escolha "Instalar do GitHub".
  3. Cole a URL da pasta da habilidade exibida abaixo e confirme.
    https://github.com/Integralist/agent-skills/tree/main/.agents/skills/go-testing
  4. Ative a habilidade em cada chat em que quiser disponibilizá-la.
Plugins → Habilidades → Nova habilidade → Via URL GitHub, depois cole a URL da pasta e pressione Continuar.
2

Instalar em outro agente

Qualquer agente que leia o formato Agent Skills pode usar esta habilidade — copie a pasta para o diretório de habilidades desse agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/Integralist/agent-skills.git /tmp/agent-skills
mkdir -p .claude/skills
cp -r /tmp/agent-skills/.agents/skills/go-testing .claude/skills/go-testing
Reinicie Claude Code após copiar para que a nova habilidade seja reconhecida.

Use no TypingMind

Ative Go Testing em qualquer chat do TypingMind e o modelo cuida do resto. O nome e a descrição da habilidade ficam no prompt do sistema e, assim que uma solicitação relevante aparece, o modelo carrega as instruções completas automaticamente — sem precisar de acionamento manual e sem consumir tokens até que ela seja realmente usada.

O modelo carrega Go Testing automaticamente assim que uma solicitação é relevante para essa habilidade.

Funciona com qualquer modelo de IA

Habilidades de IA são instruções em Markdown simples, não código específico de um provedor. Por isso, Go Testing não fica vinculada ao modelo para o qual foi criada. Instale-a uma vez no TypingMind e use-a com GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama ou um modelo local executado por conta própria — tudo com suas próprias chaves de API.

  • Carregada apenas quando necessário

    O prompt do sistema contém apenas o nome e a descrição. As instruções são buscadas na primeira solicitação relevante, então uma habilidade sem uso não gera custo.

  • Troque de modelo durante a conversa

    Como a habilidade é composta de instruções, não de código, trocar de modelo não afeta seu funcionamento — o próximo modelo lê o mesmo arquivo SKILL.md.

Instruções da habilidade

Este é o conteúdo de SKILL.md que o modelo carrega. Leia antes de instalar — uma habilidade é um conjunto de instruções que seu modelo seguirá.

Write Go tests test-first, with each case proving one behaviour through the package's public API. Load the conventions-go skill too: it sets style and linter rules for test code (testCases/tc, rr, noctx, scopeguard, comments, testify/mock), and wins where the two overlap. Before writing or changing tests, read TEST-CONTRACTS for assertion contracts. For acceptance suites, also load conventions-acceptance-tests: it owns scenario-to-code structure for Go/Godog and Make/Bash workflows.

Style. For unit tests, ask whether the user prefers table-driven (default) or f-tests (helper f in named subtests).

A test written before its types exist fails to compile, which doesn't count as red. So:

  1. Stub the types and signatures, returning zero values or a sentinel such as errors.New("unimplemented").
  2. Write the test against the stub and run go test; it must compile and fail on its assertion.
  3. Write the least code that passes, then tidy up and delete dead code.

What each test proves

  • One behaviour per case. The case name states it; a case proving two things becomes two cases.
  • Every error path. Each error the public API can return gets a case that checks the failure, matching errors with errors.Is or errors.AsType. Match on a substring only for an unexported third-party error.
  • Real assertions. Assert state changes, header values, or payloads, never only assert.NoError when the call returns values. Assert the fields that matter rather than whole structs with reflect.DeepEqual or cmp.Diff, which fail on timestamps and generated IDs.
  • Nothing unused. Deleting any field or setup step must break the test. Split cases with different setup into separate tables.
  • Distinct paths only. Each case covers its own branch or dimension, not a trivial variation of another. Add to an existing table before writing a new Test* function.
  • Cancellation. A long-running, I/O-bound, or goroutine-spawning function gets a test proving it stops promptly when ctx is cancelled.
  • Public API. Test through exported names, preferably from package foo_test. Reach each branch through the public call that triggers it; delete any branch no public path reaches. Extract logic to internal/ only when it is a module with its own interface and a second caller or adapter (see code-module-design), not just to make it testable.
  • No coverage loss. Refactoring tests must never lower package statement coverage (go test -cover).

Patterns

Testify mocks. When a test double embeds mock.Mock, call its methods through the embedded field—for example, m.Mock.Called(...) rather than m.Called(...). The explicit receiver makes the mock dependency visible.

Table-driven:

go
// TestNormalize proves Normalize upper-cases input and rejects empty
// strings with ErrEmptyInput.
func TestNormalize(t *testing.T) {
	testCases := []struct {
		// name states the behaviour this case proves.
		name string
		// input is passed to Normalize.
		input string
		// expected is the result on success.
		expected string
		// wantErr is the sentinel to match with errors.Is, or nil.
		wantErr error
	}{
		{name: "upper-cases valid input", input: "hello", expected: "HELLO"},
		{name: "rejects empty input", input: "", wantErr: ErrEmptyInput},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			result, err := Normalize(tc.input)
			if tc.wantErr != nil {
				if !errors.Is(err, tc.wantErr) {
					t.Fatalf("expected %v, got %v", tc.wantErr, err)
				}
				return
			}
			if err != nil {
				t.Fatalf("unexpected error: %v", err)
			}
			if result != tc.expected {
				t.Errorf("expected %q, got %q", tc.expected, result)
			}
		})
	}
}

When cases prove one invariant across operations with different signatures, give each case an invoke func(*Repository) error closure rather than reaching for generics.

F-test:

go
// TestShout proves Shout upper-cases its input.
func TestShout(t *testing.T) {
	// f checks one input against its expected output.
	f := func(t *testing.T, input, expected string) {
		t.Helper()
		if got := Shout(input); got != expected {
			t.Fatalf("Shout(%q) = %q; want %q", input, got, expected)
		}
	}

	t.Run("converts to uppercase", func(t *testing.T) { f(t, "hello", "HELLO") })
	t.Run("handles empty string", func(t *testing.T) { f(t, "", "") })
}

Helpers and context. Call t.Helper() in every helper. Pass t.Context() (Go 1.24+), not context.Background(), to code under test; it cancels when the test ends. Don't block on a bare <-t.Context().Done() for an async wait, or a stuck test hangs until the suite times out; bound it:

go
ctx, cancel := context.WithTimeout(t.Context(), time.Second)
defer cancel()

select {
case <-renewed:
case <-ctx.Done():
	t.Fatalf("claim was not renewed: %v", ctx.Err())
}

Assertions. Prefer t.Errorf and t.Fatalf; use testify/assert for complex checks.

Running and references

bash
make test                                    # unit tests
make test-integration                        # integration tests
go test -v -run TestName ./pkg/...           # one test
go test -race ./...                          # race detector
go test -cover ./...                         # coverage

For specialised work, read:

  • INTEGRATION.md: e2e tests under the e2e build tag.
  • ACCEPTANCE.md: a runnable Godog wiring example for the canonical living features.
  • FUZZ-AND-BENCHMARKS.md: testing.F fuzzing and b.Loop() benchmarks.
  • COVERAGE-PRUNING.md: finding and pruning overlapping tests with Tobari.
  • The mutation-testing skill: checking whether tests catch behaviour changes.

Arquivos incluídos

O modelo lê esses arquivos sob demanda enquanto a habilidade está carregada. Eles são disponibilizados para leitura e nunca são executados.

Perguntas frequentes

O que a habilidade de IA Go Testing faz?

Write unit and integration tests for Go services. Use when creating, editing, or updating tests, test helpers, mocks, fuzz tests, or benchmarks in Go projects.

Por que usar Go Testing no TypingMind?

Porque basta instalar uma vez para usar com qualquer modelo. Go Testing é escrito em Markdown simples, e não em código específico de um provedor, então a mesma habilidade funciona com GPT-5, Claude, Gemini, Grok ou um modelo local — e é possível trocar de modelo no meio do chat sem que ela deixe de funcionar. O TypingMind usa suas próprias chaves de API, então o pagamento é feito diretamente aos provedores, em vez de uma assinatura por licença de usuário, e suas habilidades e chats permanecem no seu próprio armazenamento.

Como instalar Go Testing no TypingMind?

Abra Plugins → Habilidades → Instalar do GitHub no TypingMind e cole https://github.com/Integralist/agent-skills/tree/main/.agents/skills/go-testing. O TypingMind lê o arquivo SKILL.md, reúne os arquivos da habilidade e a instala para que possa ser ativada em cada chat.

Quais modelos de IA podem usar Go Testing?

Qualquer modelo conectado no TypingMind. As habilidades de IA são instruções em Markdown simples, e não código específico de um provedor. Assim, GPT, Claude, Gemini, Grok e modelos locais podem carregar esta habilidade quando uma solicitação corresponder a ela.

Quantos modelos de IA posso usar com Go Testing?

Quantos quiser. Desde que o modelo ofereça suporte a habilidades, é possível usar Go Testing com ele — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e outros — tudo no TypingMind com suas próprias chaves de API.

A habilidade de IA Go Testing é gratuita?

A habilidade é publicada no GitHub por Integralist. Consulte os termos de licenciamento no repositório. O pagamento é feito apenas ao seu provedor de IA pelos tokens usados.

O que são habilidades de IA?

Uma habilidade de IA é um conjunto reutilizável de instruções que ensina um modelo de IA a realizar uma tarefa específica. Ela segue o formato aberto Agent Skills: um arquivo SKILL.md com nome e descrição, além de scripts, modelos de documento ou arquivos de referência de que o modelo possa precisar. O modelo lê as instruções apenas quando sua solicitação corresponde à habilidade, então uma habilidade instalada não gera custos até ser usada.

Qual é a diferença entre habilidades de IA e plugins ou servidores MCP?

Um plugin ou servidor MCP oferece ao modelo novas ferramentas para chamar — código que é executado em algum lugar e retorna um resultado. Já uma habilidade de IA fornece conhecimento e um processo ao modelo: como abordar uma tarefa, quais etapas seguir e como deve ser um bom resultado. As habilidades são escritas em Markdown simples, por isso não precisam de servidor, chave de API nem ambiente de execução, e funcionam com qualquer modelo.

Ver todos

Crie seu próprio espaço de IA agora

Inscreva-se na nossa newsletter para receber novidades sobre recursos e futuros sorteios 👇