test-patterns
Write and run tests across languages and frameworks. Use when setting up test suites, writing unit/integration/E2E tests, measuring coverage, mocking dependencies, or debugging test failures. Covers Node.js (Jest/Vitest), Python (pytest), Go, Rust, and Bash.
What this skill does
# Test Patterns
Write, run, and debug tests across languages. Covers unit tests, integration tests, E2E tests, mocking, coverage, and TDD workflows.
## When to Use
- Setting up a test suite for a new project
- Writing unit tests for functions or modules
- Writing integration tests for APIs or database interactions
- Setting up code coverage measurement
- Mocking external dependencies (APIs, databases, file system)
- Debugging flaky or failing tests
- Implementing test-driven development (TDD)
## Node.js (Jest / Vitest)
### Setup
```bash
# Jest
npm install -D jest
# Add to package.json: "scripts": { "test": "jest" }
# Vitest (faster, ESM-native)
npm install -D vitest
# Add to package.json: "scripts": { "test": "vitest" }
```
### Unit Tests
```javascript
// math.js
export function add(a, b) { return a + b; }
export function divide(a, b) {
if (b === 0) throw new Error('Division by zero');
return a / b;
}
// math.test.js
import { add, divide } from './math.js';
describe('add', () => {
test('adds two positive numbers', () => {
expect(add(2, 3)).toBe(5);
});
test('handles negative numbers', () => {
expect(add(-1, 1)).toBe(0);
});
test('handles zero', () => {
expect(add(0, 0)).toBe(0);
});
});
describe('divide', () => {
test('divides two numbers', () => {
expect(divide(10, 2)).toBe(5);
});
test('throws on division by zero', () => {
expect(() => divide(10, 0)).toThrow('Division by zero');
});
test('handles floating point', () => {
expect(divide(1, 3)).toBeCloseTo(0.333, 3);
});
});
```
### Async Tests
```javascript
// api.test.js
import { fetchUser } from './api.js';
test('fetches user by id', async () => {
const user = await fetchUser('123');
expect(user).toHaveProperty('id', '123');
expect(user).toHaveProperty('name');
expect(user.name).toBeTruthy();
});
test('throws on missing user', async () => {
await expect(fetchUser('nonexistent')).rejects.toThrow('Not found');
});
```
### Mocking
```javascript
// Mock a module
jest.mock('./database.js');
import { getUser } from './database.js';
import { processUser } from './service.js';
test('processes user from database', async () => {
// Setup mock return value
getUser.mockResolvedValue({ id: '1', name: 'Alice', active: true });
const result = await processUser('1');
expect(result.processed).toBe(true);
expect(getUser).toHaveBeenCalledWith('1');
expect(getUser).toHaveBeenCalledTimes(1);
});
// Mock fetch
global.fetch = jest.fn();
test('calls API with correct params', async () => {
fetch.mockResolvedValue({
ok: true,
json: async () => ({ data: 'test' }),
});
const result = await myApiCall('/endpoint');
expect(fetch).toHaveBeenCalledWith('/endpoint', expect.objectContaining({
method: 'GET',
}));
});
// Spy on existing method (don't replace, just observe)
const consoleSpy = jest.spyOn(console, 'log').mockImplementation();
// ... run code ...
expect(consoleSpy).toHaveBeenCalledWith('expected message');
consoleSpy.mockRestore();
```
### Coverage
```bash
# Jest
npx jest --coverage
# Vitest
npx vitest --coverage
# Check coverage thresholds (jest.config.js)
# coverageThreshold: { global: { branches: 80, functions: 80, lines: 80, statements: 80 } }
```
## Python (pytest)
### Setup
```bash
pip install pytest pytest-cov
```
### Unit Tests
```python
# calculator.py
def add(a, b):
return a + b
def divide(a, b):
if b == 0:
raise ValueError("Division by zero")
return a / b
# test_calculator.py
import pytest
from calculator import add, divide
def test_add():
assert add(2, 3) == 5
def test_add_negative():
assert add(-1, 1) == 0
def test_divide():
assert divide(10, 2) == 5.0
def test_divide_by_zero():
with pytest.raises(ValueError, match="Division by zero"):
divide(10, 0)
def test_divide_float():
assert divide(1, 3) == pytest.approx(0.333, abs=0.001)
```
### Parametrized Tests
```python
@pytest.mark.parametrize("a,b,expected", [
(2, 3, 5),
(-1, 1, 0),
(0, 0, 0),
(100, -50, 50),
])
def test_add_cases(a, b, expected):
assert add(a, b) == expected
```
### Fixtures
```python
import pytest
import json
import tempfile
import os
@pytest.fixture
def sample_users():
"""Provide test user data."""
return [
{"id": 1, "name": "Alice", "email": "[email protected]"},
{"id": 2, "name": "Bob", "email": "[email protected]"},
]
@pytest.fixture
def temp_db(tmp_path):
"""Provide a temporary SQLite database."""
import sqlite3
db_path = tmp_path / "test.db"
conn = sqlite3.connect(str(db_path))
conn.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)")
conn.commit()
yield conn
conn.close()
def test_insert_users(temp_db, sample_users):
for user in sample_users:
temp_db.execute("INSERT INTO users VALUES (?, ?, ?)",
(user["id"], user["name"], user["email"]))
temp_db.commit()
count = temp_db.execute("SELECT COUNT(*) FROM users").fetchone()[0]
assert count == 2
# Fixture with cleanup
@pytest.fixture
def temp_config_file():
path = tempfile.mktemp(suffix=".json")
with open(path, "w") as f:
json.dump({"key": "value"}, f)
yield path
os.unlink(path)
```
### Mocking
```python
from unittest.mock import patch, MagicMock, AsyncMock
# Mock a function
@patch('mymodule.requests.get')
def test_fetch_data(mock_get):
mock_get.return_value.status_code = 200
mock_get.return_value.json.return_value = {"data": "test"}
result = fetch_data("https://api.example.com")
assert result == {"data": "test"}
mock_get.assert_called_once_with("https://api.example.com")
# Mock async
@patch('mymodule.aiohttp.ClientSession.get', new_callable=AsyncMock)
async def test_async_fetch(mock_get):
mock_get.return_value.__aenter__.return_value.json = AsyncMock(return_value={"ok": True})
result = await async_fetch("/endpoint")
assert result["ok"] is True
# Context manager mock
def test_file_reader():
with patch("builtins.open", MagicMock(return_value=MagicMock(
read=MagicMock(return_value='{"key": "val"}'),
__enter__=MagicMock(return_value=MagicMock(read=MagicMock(return_value='{"key": "val"}'))),
__exit__=MagicMock(return_value=False),
))):
result = read_config("fake.json")
assert result["key"] == "val"
```
### Coverage
```bash
# Run with coverage
pytest --cov=mypackage --cov-report=term-missing
# HTML report
pytest --cov=mypackage --cov-report=html
# Open htmlcov/index.html
# Fail if coverage below threshold
pytest --cov=mypackage --cov-fail-under=80
```
## Go
### Unit Tests
```go
// math.go
package math
import "errors"
func Add(a, b int) int { return a + b }
func Divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
// math_test.go
package math
import (
"testing"
"math"
)
func TestAdd(t *testing.T) {
tests := []struct {
name string
a, b int
expected int
}{
{"positive", 2, 3, 5},
{"negative", -1, 1, 0},
{"zeros", 0, 0, 0},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := Add(tt.a, tt.b)
if got != tt.expected {
t.Errorf("Add(%d, %d) = %d, want %d", tt.a, tt.b, got, tt.expected)
}
})
}
}
func TestDivide(t *testing.T) {
result, err := Divide(10, 2)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if math.Abs(result-5.0) > 0.001 {
t.Errorf("Divide(10, 2) = %f, want 5.0", result)
}
}
func TestDivideByZero(t *testing.T) {
_, err := Divide(10, 0)
if err == nil {
t.Error("expected error for division by zero")
}
}
```
### Run Tests
```bash
# All tests
go test ./...
# Verbose
go test -v ./...
# Specific package
go test ./pkg/math/
# WitRelated in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.