write-tests
Skill584 starsChanged 10 months agoMITView on GitHub
Guide for writing unit tests. Use this when creating tests to verify Python logic.
33 other projects use a version of this.
Adopted by
Most recently taken up by
- dzhng/skillstheir own version, first seen Oct 4, 2026
- dzhng/jevgreptheir own version, first seen Oct 2, 2026
- dzhng/duet-agenttheir own version, first seen Oct 2, 2026
- aprameyak/coding-skillstheir own version, first seen Oct 2, 2026
- getsentry/sentry-javascripttheir own version, first seen Sep 27, 2026
- NarekManukyan/flutter-mobx-kittheir own version, first seen Sep 17, 2026
Used with
Projects with it also use audit-choices, close-spec and 10 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
dzhngSkillaudit-choices
Audit the choices an implementing agent made, not its diff — a pure decision audit that traces the session's history into a choices ledger, changes no code, and never blocks an unsupervised run. Working code still embeds architecture the user never chose; surface it because future work inherits it. Use when the user wants to review the decisions the AI made on their behalf, before merging or committing AI-implemented work, when integrating a delegated subagent's pass, or when a fix "works" but might be a point fix.
Also in 3 projects that use this
dzhngSkillclose-spec
When a spec under specs/<feature>/ is done shipping (a write-spec build, or any planned task that produced a spec), archive it to specs/done/ and rewrite it from a build-plan into a durable rationale — the why, the principles, the invariants — pointing back to the real code for the how. Use when implementation has landed and the plan no longer matches what shipped, or the user says a feature/spec is finished. Pairs with [write-spec](../write-spec/SKILL.md) (the plan this closes) and [review](../review/SKILL.md) (run before closing).
Also in 3 projects that use this
LucasMatuszewskiSkillaudit-agents
Audit and maintain agent configuration files (.claude/agents, AGENTS.md, CLAUDE.md, agent-memory). Checks for duplicates, outdated info, naming conflicts, wrong technical facts, and files over 200 lines. Fixes all issues and commits.
Also in 3 projects that use this
Halcyon666Skillwrite-skills
Creates high-quality Agent Skills (SKILL.md files) that follow the open Agent Skills specification. Use when asked to create a skill, write a SKILL.md, package agent instructions, build a reusable capability, or turn a workflow into a shareable skill. Produces spec-compliant, concise, well-structured skills optimized for agent discovery and execution.
Also in 3 projects that use this
isLinXuSkilleval-skills
AI Agent Skill unit testing framework. A framework-agnostic toolkit for discovering, scaffolding, selecting, evaluating, and reporting on AI skills. Use this skill to assess skill quality before production, compare candidate skills on the same benchmark, enforce quality gates in CI/CD, and generate human-readable evaluation reports.
Also in 3 projects that use this
TrecekSkillaudit-tests
Audit the test suite for useless tests, consolidation opportunities, over-mocking, weak assertions, and other test quality issues. Use when user says "audit tests", "audit test suite", "review tests", or "test quality check". Generates an improvement plan in temp/ with explanations for each proposed change.
Also in 3 projects that use this
- +6 more from dzhng
Other versions33 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 33
- getsentry/sentry-javascript★ 8.8ksame name
- huggingface/OpenEnv★ 2.6ksame name
- dzhng/jevgrep★ 2.3ksame name
- NeoLabHQ/context-engineering-kit★ 1.7ksame name
- dzhng/skills★ 978same name
- atherio-danp/cde-dotnetcc★ 109same name
- getsentry/abacus★ 77same name
- alamops/skills★ 52same name
- dzhng/duet-agent★ 46same name
- igmarin/rails-agent-skills★ 27same name
23 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository16 other files it gives its agents.
- AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- add-functionSkill
- build-docsSkill
- code-styleSkill
- dax-optimizationSkill
- direct-lake-operationsSkill
- github-repo-exploreSkill
- planning-with-filesSkill
- pr-review-commentsSkill
- query-builder-daxSkill
- rest-api-patternsSkill
- run-testsSkill
- sql_to_daxSkill
- tom-operationsSkill
- ui-stylingSkill
The file
We split this skill into the rules it gives an agent
10 rules. 0 are common, 9 are distinctive, and 1 is very specific to this project.
0
Common
Most of the 31 edited versions we read keep these.
9
Distinctive
This author's own choices. Worth a look.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 12
Use this skill when you need to:
- Distinctive: line 13
Write tests for new functions
- Distinctive: line 14
Add test coverage for existing code
- Distinctive: line 15
Test error handling and edge cases
- Very specific: line 43
Test files: test_*.py or *_test.py
- Distinctive: line 370
Before committing new tests:
- Distinctive: line 372
Run the tests locally:
- Distinctive: line 377
Verify tests pass consistently (run multiple times)
- Distinctive: line 379
Check test coverage for the new code
- Distinctive: line 381
Ensure tests are independent and don't rely on each other
“Common” is measured: kept by at least 6 in 10 of the 31 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Writing Tests
This skill covers how to write tests for the Semantic Link Labs project.
When to Use This Skill
Use this skill when you need to:
- Write tests for new functions
- Add test coverage for existing code
- Test error handling and edge cases
- Validate input parsing and data transformations
Test Framework
| Component | Details |
| Framework | pytest |
| Location | tests/ directory |
| Assertions | Standard pytest assertions |
Test File Structure
tests/
├── __init__.py
├── test_helper_functions.py
├── test_workspaces.py
├── test_admin.py
└── ...Naming Conventions
- Test files:
test_*.pyor*_test.py - Test functions:
test_<function_name>_<scenario> - Test classes:
Test<ClassName>
Writing Basic Tests
Simple Function Test
import pytest
import pandas as pd
def test_my_function_returns_dataframe():
"""Test that my_function returns a DataFrame."""
from sempy_labs import my_function
result = my_function()
assert isinstance(result, pd.DataFrame)
def test_my_function_has_expected_columns():
"""Test that result has expected columns."""
from sempy_labs import my_function
result = my_function()
expected_columns = ["Id", "Name", "Type"]
for col in expected_columns:
assert col in result.columnsTest with Parameters
def test_my_function_filters_by_type():
"""Test that my_function filters by item_type."""
from sempy_labs import my_function
result = my_function(item_type="Report")
assert all(result["Type"] == "Report")Testing Error Handling
Expected Exceptions
def test_my_function_raises_on_invalid_workspace():
"""Test that invalid workspace raises ValueError."""
from sempy_labs import my_function
with pytest.raises(ValueError, match="Invalid workspace"):
my_function(workspace="NonExistent")
def test_my_function_raises_on_missing_parameter():
"""Test that missing required parameter raises error."""
from sempy_labs import my_function
with pytest.raises(TypeError):
my_function() # Missing required parameterException Message Matching
def test_error_message_is_descriptive():
"""Test that error message contains helpful information."""
from sempy_labs import my_function
with pytest.raises(ValueError) as exc_info:
my_function(invalid_param="bad")
assert "invalid_param" in str(exc_info.value)
assert "bad" in str(exc_info.value)Using Fixtures
Basic Fixture
import pytest
import pandas as pd
@pytest.fixture
def sample_dataframe():
"""Create a sample DataFrame for testing."""
return pd.DataFrame({
"Id": ["1", "2", "3"],
"Name": ["Item A", "Item B", "Item C"],
"Type": ["Report", "Dataset", "Report"],
})
def test_filter_function(sample_dataframe):
"""Test filtering function with sample data."""
from sempy_labs._helper_functions import filter_items
result = filter_items(sample_dataframe, type="Report")
assert len(result) == 2
assert all(result["Type"] == "Report")Fixture with Parameters
@pytest.fixture(params=["Report", "Dataset", "Lakehouse"])
def item_type(request):
"""Parameterized fixture for item types."""
return request.param
def test_with_different_item_types(item_type):
"""Test function with different item types."""
from sempy_labs import my_function
result = my_function(item_type=item_type)
assert isinstance(result, pd.DataFrame)Mocking External Dependencies
Mocking API Calls
from unittest.mock import patch, MagicMock
def test_function_with_mocked_api():
"""Test with mocked API response."""
mock_response = MagicMock()
mock_response.json.return_value = {
"value": [
{"id": "123", "name": "Test Item"}
]
}
mock_response.status_code = 200
with patch('sempy_labs._helper_functions._base_api') as mock_api:
mock_api.return_value = mock_response
from sempy_labs import list_items
result = list_items()
assert len(result) == 1
assert result.iloc[0]["Name"] == "Test Item"Mocking Fabric Client
from unittest.mock import patch
def test_function_with_mocked_fabric():
"""Test with mocked sempy.fabric calls."""
with patch('sempy.fabric.resolve_workspace_id') as mock_resolve:
mock_resolve.return_value = "12345678-1234-1234-1234-123456789012"
from sempy_labs._helper_functions import resolve_workspace_id
result = resolve_workspace_id("My Workspace")
mock_resolve.assert_called_once()Parameterized Tests
Multiple Input Values
import pytest
@pytest.mark.parametrize("input_value,expected", [
("value1", "result1"),
("value2", "result2"),
("value3", "result3"),
])
def test_function_with_multiple_inputs(input_value, expected):
"""Test function with multiple input values."""
from sempy_labs import my_function
result = my_function(input_value)
assert result == expectedTesting Edge Cases
@pytest.mark.parametrize("workspace", [
None, # Default workspace
"My Workspace", # By name
"12345678-1234-1234-1234-123456789012", # By UUID string
])
def test_accepts_various_workspace_formats(workspace):
"""Test that function accepts various workspace formats."""
from sempy_labs import my_function
# Should not raise
result = my_function(workspace=workspace)
assert result is not NoneTesting DataFrame Results
Column Validation
def test_result_has_required_columns():
"""Test that result DataFrame has required columns."""
from sempy_labs import list_items
result = list_items()
required_columns = ["Id", "Name", "Type"]
for col in required_columns:
assert col in result.columns, f"Missing column: {col}"Data Type Validation
def test_result_column_types():
"""Test that result columns have correct types."""
from sempy_labs import list_items
result = list_items()
assert result["Id"].dtype == "object" # string
assert result["Name"].dtype == "object" # stringEmpty Result Handling
def test_handles_empty_result():
"""Test that function handles empty results gracefully."""
from sempy_labs import list_items
result = list_items(item_type="NonExistentType")
assert isinstance(result, pd.DataFrame)
assert result.empty
# Columns should still exist even if empty
assert "Id" in result.columnsTest Organization
Grouping Related Tests
class TestWorkspaceFunctions:
"""Tests for workspace-related functions."""
def test_list_workspaces(self):
"""Test listing workspaces."""
pass
def test_resolve_workspace_id(self):
"""Test resolving workspace ID."""
pass
def test_resolve_workspace_name(self):
"""Test resolving workspace name."""
pass
class TestHelperFunctions:
"""Tests for helper utility functions."""
def test_is_valid_uuid(self):
"""Test UUID validation."""
pass
def test_create_dataframe(self):
"""Test DataFrame creation helper."""
passBest Practices
Do's
- ✅ Use descriptive test names
- ✅ Test one thing per test function
- ✅ Include docstrings explaining what's being tested
- ✅ Use fixtures for reusable setup
- ✅ Test both success and failure cases
- ✅ Mock external dependencies when needed
Don'ts
- ❌ Don't test multiple behaviors in one test
- ❌ Don't rely on external services in unit tests
- ❌ Don't use hardcoded secrets or credentials
- ❌ Don't write tests that depend on test execution order
- ❌ Don't ignore flaky tests - fix them
Pre-Commit Test Checklist
Before committing new tests:
- Run the tests locally:
pytest -sv tests/ -k my_new_test - Verify tests pass consistently (run multiple times)
- Check test coverage for the new code
- Ensure tests are independent and don't rely on each other
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

