acolomba/blackvuesync/python-unit-testing
Claude Code and agent skill by acolomba/blackvuesync
- community
- ext:[{"type":"hook","description":"Pre/post lifecycle hooks"}]
Checking that the SKILL.md file is still in the repository.
Unit testing rules for Python -- pairing, coverage, case structure, naming, assertions, test doubles, test data, hermeticity, and production design for tests. Apply when writing or changing test/**/*.py or the source modules they pair with.
Install
npx vskill@latest install acolomba/blackvuesync/python-unit-testingSemi-extensibleMentions customization, but needs skill-specific knowledge. Read the extensible skills standard
SKILL.md
The same SKILL.md was published earlier as acolomba/blackvuesync/python-unit-testing.
Python unit testing rules
"Do" and "Do not" are hard rules. "Prefer" states the default and allows a justified exception. "May" grants a permission. Copy the Good form.
Every case must discriminate the behavior named in its title: a wrong implementation makes the assertion fail. A test with weak assertions costs all the maintenance of a test and gives none of the protection.
Tools
Use pytest for the runner, fixtures, and the built-in monkeypatch, tmp_path, and capsys fixtures; PyHamcrest's assert_that() and its matchers for assertions; pytest.raises() for errors; unittest.mock.create_autospec() for strict interaction mocks and unittest.mock.Mock(wraps=...) for spies; pytest-cov for coverage.
Do not add another runner, assertion library, or mocking library: no unittest.TestCase, pytest-mock, pytest-asyncio, freezegun, responses, or snapshot plugins.
Pairing and coverage
- The root-level application module
blackvuesync.pypairs withtest/blackvuesync_test.py, which imports it and owns its public behavior. Developer scripts and behavioral-test support are outside this pairing gate. - No exclusions. Re-exporting
__init__.pymodules,__main__.py, type-only modules, and one-function modules all need a test module. The one exemption is an__init__.pyholding nothing but a docstring, which only marks a package. If a module is not worth a test, fold it into its consumer. scripts/check_corresponding_tests.py, run by pre-commit and byscripts/check.sh, fails when a module has no test module, when a test module does not import its module, or when a test module has no module.- Do not put tests under
src/, name themtest_*.py, or test one source module from another module's test. - Test support (fakes, seeds, fixtures in
conftest.py) needs no meta-tests; a fake is verified through its shared contract. - The unit suite measures line and branch coverage and meets the coverage floor configured in
pyproject.toml. Raise coverage as behavior changes; 100% is not a migration requirement. - Do not add
# pragma: no cover, coverageexclude_lines, oromitentries. Remove dead code or cover it through a public-behavior case. - Run
pytest <test-path>while developing,scripts/coverage-direct.sh <source-path> <test-path>for the pair, andscripts/check.shbefore completion.
Case structure
- Write independent test functions:
def test_rejects_an_unknown_order() -> None:. - When a module has several public entrypoints, group each one's cases in a top-level class named after it (
class TestPlace:,class TestCancel:). A single-entrypoint module keeps cases at module level. Do not nest classes. - Do not group by private helpers or use a class to share mutable setup: a test class has no
__init__, attributes, orsetup_method(). - Each case gets fresh state and dependencies. Prefer construction inside the case. A function-scoped fixture may create new per-case instances; do not use a
module,class,package, orsessionscoped fixture for stateful objects. Only a stateless stub (a fixedclock) may live at module scope. - Do not commit
@pytest.mark.skip,skipif, orxfail, or calls topytest.skip()orpytest.xfail(). The one exception is the strict negative control of a shared contract (see Patterns). - Name each case with a short snake-case sentence stating public behavior:
test_rejects_an_unknown_order, nottest_works,test_happy_path, ortest_cancel. A durable requirement ID may appear; plan, phase, or ticket references may not. The name is the title, so do not add a docstring that restates it. - Mark phases with lowercase
# arrange,# act,# assertcomments, in that order, separated by a blank line. Awith pytest.raises(...)block is the act; assert the error's fields after it under# assert. Use# act & assertonly when that block is the whole assertion. Parametrized cases still use separate phases. Add no other comments unless setup is not obvious.
Naming values
Name values after their production role. Do not use result, res, ret, data, value, instance, subject, sut, or a bare actual.
- Module under test:
order_service. Its returned value:order. - Expected value:
expected_order, or the seed fixture that provides it (placed_order). Prefer an inline literal when it is short and used once. - Test double: the production role only,
orders,payments,clock. Do not addmock,fake, orstubto the name; how it is created shows the kind. - Spy: the observed method with a
_spysuffix,put_spy. - Caught error:
raised, frompytest.raises(...) as raised. - Parametrized arguments: the parameter and the promised outcome,
lines, total.
Reference case
OrderService(clock=..., events=..., ids=..., orders=..., payments=...) takes every collaborator explicitly. clock and ids are stub functions, orders is a stateful fake from the concern's conftest.py, payments and events are strict mocks, and cart / placed_order are seed fixtures.
Good
A mock whose expected call list is empty proves that the module does not touch that port: assert_that(events.mock_calls, equal_to([])).
Assertions
- Prefer PyHamcrest's
assert_that(actual, matcher)to state the condition. The matcher names the condition, and a failure reports the expected and the actual value. Pass a reason as the third argument only when it adds a fact the matcher does not report. A plainassertis the exception, for a condition that no matcher states. - Assert the public result and public state before any interaction. Do not replace a result assertion with a call assertion. When relocating a case, preserve its assertions unless the contract changed.
- Compare whole values with
equal_to(). Usecontains_inanyorder()for a list whose order is not part of the promise, andsame_instance()for identity. Do not assert existence, length, or one attribute at a time when the whole value is the promise:has_item(),has_items(),has_entries(),has_length(), andinstance_of()pass for a partial value. A standalone negative assertion (assert_that(order, not_none()),assert_that(order, is_not(cancelled))) passes for almost any value; assert what the value is. - Assert errors by class and structured fields, not by message text; do not pass
match=topytest.raises():
- When bytes are the contract (a file, packet, archive, encoded value), compare the complete bytes. Do not decode or normalize the output unless consumers do.
- Build expected values independently. Do not call the production formatter or serializer, transform the adapter result, ask a harness for the answer, or use a snapshot assertion.
- Drive an
async defentrypoint withasyncio.run()inside the case, and await every coroutine. pytest runs withfilterwarnings = ["error"], so a coroutine that is never awaited fails the case instead of passing it.
Test doubles
| Role | Use | Assert | |
|---|---|---|---|
| Fake | A working, simplified, stateful implementation | The public result and resulting state | |
| Stub | A canned value or error that drives one path | The module's result, not the stub's call count | |
| Spy | Real behavior with recorded calls | Public behavior first; calls only when the observation is the promise | |
| Mock | A prescribed interaction | The promised calls, arguments, and order |
Use the tool that matches the role. Do not turn a stub into a mock by asserting its calls. Do not verify incidental spy calls.
Fakes. A FakeThing class in the concern's conftest.py, handed out by a function-scoped fixture, stands in for a stateful boundary (store, repository, remote). Seed it through its public contract: orders.put(placed_order). copy.deepcopy() mutable values at ingress and egress. Do not simulate a database or filesystem with a graph of mocks. Do not let a fake grow into a second real implementation.
Stubs. A plain function or small class that satisfies the port (def ids() -> str: return "order-123") for a fixed clock, ID, one-shot failure, remote response, or capability flag; mypy checks it where the port is expected. Use Mock(side_effect=[...]) only when a plain function is not enough, such as a sequence of answers. Assert the module's result, not the stub's calls.
Spies. put_spy = Mock(wraps=orders.put) installed with monkeypatch.setattr(orders, "put", put_spy), only when real behavior must run and the observation is the promise ("writes exactly once", "does not rewrite"). Read put_spy.mock_calls after the result assertions. With a return_value or side_effect it is a stub.
Mocks. create_autospec(), only when the interaction is public behavior: charging, publishing, notifying, transaction control, invoking a callback, issuing a command.
- Create
create_autospec(Port, instance=True, spec_set=True)inside the case. Autospec rejects a call that does not match the port's signature, andspec_setrejects an attribute the port does not have. A bareMock()orMagicMock()accepts anything. - Set every return value and error the module uses:
payments.charge.return_value = receipt,payments.charge.side_effect = PaymentDeclinedError("customer-1"). An autospecced method returns aMagicMockby default, which hides a missing setup. - Assert the complete call list with
equal_to()at the end of the case, after result and state assertions:assert_that(payments.mock_calls, equal_to([call.charge("customer-1", 25)])). It fails on a missing, extra, reordered, or differently argued call. - Do not use
assert_called(),assert_called_once(),assert_any_call(), orassert_has_calls(), which pass with extra calls, or a barecall_count. Do not assert in a fixture teardown or shared helper. - Use
unittest.mock.ANYonly for an argument that cannot be compared by value (a callback, a stream), and assert its meaningful properties separately.
When order across mocks is the promise, attach every mock to one recorder and compare its whole call list:
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 95 of 100Pattern checks on the skill's files.
- Model reviewPassed
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/python-unit-testing/SKILL.md
Popularity
- 7-day trend score
- 5
Not refreshed yet.
Extension points
hookPre/post lifecycle hooks
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/acolomba/blackvuesync/python-unit-testing)