Логотип Go Testing

Go Testing

Спільнота
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.

Огляд

ВидавецьIntegralist
Репозиторійagent-skills
Назва навичкиgo-testing
Зірки
26
Форки
1
Файли в пакеті
4
Посилання
  • Інструкції у форматі Markdown

    Файл SKILL.md, який модель завантажує за потреби, тож токени витрачаються лише тоді, коли запит справді відповідає навичці.

  • Працює з будь-якою LLM

    Навички ШІ — це звичайний Markdown, а не код для певного постачальника, тому вони працюють із GPT, Claude, Gemini, Grok або локальною моделлю.

  • Файлів у комплекті: 4

    Скрипти, шаблони й довідкові матеріали, які модель може читати під час роботи. Файли доступні лише для читання й ніколи не виконуються.

  • Відкритий вихідний код

    Опубліковано на GitHub користувачем Integralist. Перегляньте вихідний вміст перед установленням.

Встановлення

Установіть навичку ШІ Go Testing у TypingMind, щоб використовувати її з будь-якою LLM, або додайте її до іншого агента, що читає SKILL.md.

1

Встановити в TypingMind

TypingMind встановлює навичку безпосередньо з її папки GitHub — читає SKILL.md, збирає файли ресурсів у пакет і зберігає результат локально.

  1. Відкрийте застосунок і перейдіть до Плагіни → Навички.
  2. Виберіть «Встановити з GitHub».
  3. Вставте наведений нижче URL папки навички та підтвердьте встановлення.
    https://github.com/Integralist/agent-skills/tree/main/.agents/skills/go-testing
  4. Увімкніть навичку в кожному чаті, де хочете її використовувати.
Плагіни → Навички → Нова навичка → За URL GitHub, потім вставте URL папки й натисніть «Продовжити».
2

Встановити в іншому агенті

Будь-який агент, що підтримує формат Agent Skills, може використовувати цю навичку — скопіюйте папку до каталогу навичок цього агента.

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
Після копіювання перезапустіть Claude Code, щоб завантажити нову навичку.

Використовуйте навичку в TypingMind

Увімкніть навичку Go Testing в будь-якому чаті TypingMind, і далі модель усе зробить сама. Назва й опис навички містяться в системному промпті, а щойно надходить відповідний запит, модель самостійно завантажує повні інструкції — вам не потрібно викликати навичку вручну, і до фактичного використання вона не витрачає токенів.

Модель самостійно завантажує навичку Go Testing, щойно надходить відповідний запит.

Працює з будь-якою моделлю ШІ

Навички ШІ — це звичайні інструкції Markdown, а не код для певного постачальника, тому навичка Go Testing не прив’язана до моделі, для якої її створено. Установіть її один раз у TypingMind і використовуйте з GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama або локальною моделлю, яку ви запускаєте самостійно, — усе з вашими власними ключами API.

  • Завантажується лише за потреби

    Системний промпт містить лише назву й опис. Інструкції завантажуються за першого відповідного запиту, тож невикористана навичка нічого не коштує.

  • Змінюйте моделі під час чату

    Оскільки навичка — це інструкції, а не код, зміна моделі не порушує її роботу: наступна модель читає той самий файл SKILL.md.

Інструкції навички

Це вміст файлу SKILL.md, який завантажує модель. Прочитайте його перед установленням — навичка містить інструкції, яких дотримуватиметься ваша модель.

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.

Файли в пакеті

Модель читає ці файли за потреби, поки навичку завантажено. Вони доступні для читання й ніколи не виконуються.

Поширені запитання

Що робить навичка ШІ 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.

Навіщо використовувати Go Testing у TypingMind?

Тому що ви встановлюєте її один раз і використовуєте з будь-якою моделлю. Go Testing — це звичайний Markdown, а не код для конкретного постачальника, тому та сама навичка працює з GPT-5, Claude, Gemini, Grok або локальною моделлю. Ви можете змінити модель навіть посеред чату, і навичка продовжить працювати. TypingMind використовує ваші власні ключі API, тож ви платите безпосередньо постачальникам замість передплати за кожне місце користувача, а ваші навички й чати залишаються у вашому сховищі.

Як встановити Go Testing у TypingMind?

Відкрийте в TypingMind Плагіни → Навички → Встановити з GitHub і вставте https://github.com/Integralist/agent-skills/tree/main/.agents/skills/go-testing. TypingMind прочитає файл SKILL.md, додасть супровідні файли та встановить навичку, яку можна вмикати окремо для кожного чату.

Які моделі ШІ можуть використовувати Go Testing?

Будь-яка модель, яку ви підключите в TypingMind. Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для конкретного постачальника, тому GPT, Claude, Gemini, Grok і локальні моделі можуть завантажувати цю навичку, коли запит їй відповідає.

Зі скількома моделями ШІ можна використовувати Go Testing?

Зі скількома забажаєте. Якщо модель підтримує навички, ви можете використовувати з нею Go Testing — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama та інші — усе в TypingMind із власними ключами API.

Чи безкоштовна навичка ШІ Go Testing?

Навичку опубліковано на GitHub: Integralist. Умови ліцензування дивіться в репозиторії. Ви платите лише своєму постачальнику ШІ за використані токени.

Що таке навички ШІ?

Навичка ШІ — це багаторазовий набір інструкцій, який навчає модель ШІ виконувати одне конкретне завдання. Він відповідає відкритому формату Agent Skills: файл SKILL.md із назвою та описом, а також скрипти, шаблони чи довідкові файли, які можуть знадобитися моделі. Модель читає інструкції лише тоді, коли ваш запит відповідає навичці, тому встановлена навичка нічого не коштує, доки її не використано.

Чим навички ШІ відрізняються від плагінів або серверів MCP?

Плагін або сервер MCP надає моделі нові інструменти для виклику — код, який десь виконується й повертає результат. Натомість навичка ШІ надає моделі знання та порядок дій: як підійти до завдання, яких кроків дотримуватися та яким має бути якісний результат. Навички — це звичайний Markdown, тож їм не потрібні ні сервер, ні ключ API, ні середовище виконання, і вони працюють із будь-якою моделлю.

Усі

Створіть власний ШІ-простір уже зараз

Підпишіться на нашу розсилку, щоб дізнаватися про нові функції та майбутні розіграші 👇