extract-and-test
Skill121 starsChanged 4 months agoMITView on GitHub
Use when refactoring a method in pywin32_adapter.py that contains untestable closures, nested try/except blocks, or COM logic that can't be unit-tested in isolation. Apply SOLID principles: extract helpers, refactor to thin orchestrator, add full branch-coverage tests. Trigger phrases: extract helper, SOLID refactor, untestable closure, nested try/except, branch coverage, TestPyWin32AdapterBranches, pywin32_adapter method, select_feature, execute_macro, export_image, adapter refactor.
1 other project uses a version of this.
Adopted by
Most recently taken up by
- levy-street/world-of-claudecrafttheir own version, first seen Oct 8, 2026
Other versions1 project uses a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 1
- levy-street/world-of-claudecraft★ 2.3ksame name
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 repository12 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- docs/llms.txtllms.txt
- live-demo-signoffSkill
- openspec-apply-changeSkill
- openspec-archive-changeSkill
- openspec-exploreSkill
- openspec-proposal-auditorSkill
- openspec-proposeSkill
- openspec-sync-specsSkill
- openspec-update-changeSkill
- feature-tree-reconstructionSkill
- printer-profile-tolerancingSkill
The file
We split this skill into the rules it gives an agent
10 rules. About 0 are common, 4 are distinctive, and 6 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈4
Distinctive · estimate
This author's own choices. Worth a look.
6
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 17
Read the target line range.
- Very specific: line 37
Write one helper per concern.
- Very specific: line 119
Add tests to the file that mirrors the module you changed: src/solidworks_mcp/<path>/<module>.py is tested in …
- Very specific: line 125
Use self._build_adapter(monkeypatch) — never construct PyWin32Adapter directly.
- Very specific: line 127
Never import win32com, pywintypes, or pythoncom — use monkeypatch.
- Very specific: line 128
Use tmp_path fixture for file-existence checks.
- Very specific: line 130
Use the top-level SolidWorksMCPError import (already present at module top).
- Distinctive: line 156
Run only the new tests first (no coverage threshold):
- Distinctive: line 162
Run the whole file to catch regressions:
- Distinctive: line 168
All tests must pass before the task is complete.
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Extract & Test — pywin32_adapter.py
Apply this skill whenever a method in src/solidworks_mcp/adapters/pywin32_adapter.py contains:
- Deeply nested
try/exceptblocks or inner closures that can't be tested in isolation - Mixed concerns (COM selection strategy + fallback + error handling all in one body)
- A closure that calls
self._attempt(...)with an inner_run/_operationlambda
Step 1 — Read and Analyse
Read the target line range. For each logical block, fill in this table:
| Concern | COM calls involved | Failure mode | Return contract |
| (fill in) | (fill in) | (fill in) | (fill in) |
Apply these heuristics to determine the right helper shape:
| Shape | When to use |
-> None (log, never raise) | Setup/orientation side-effects — failure is acceptable |
-> bool | COM operation that writes a file; True = file exists |
-> dict | None | COM selection/query strategy; None = this strategy failed, try next |
-> dict (raises on failure) | Last-chance fallback or invoker — surface error to caller |
@staticmethod | Pure string/data transformation with no self state |
Step 2 — Extract Helpers
Write one helper per concern. Insert helpers immediately before the async def they support.
def _<verb>_<noun>(self, <args>) -> <return type>:
"""<One-line description>.
Args:
<arg>: <description>
Returns:
<type>: <description>
Raises:
<ExceptionType>: <when>
"""
...Examples by return contract:
# Graceful-failure helper — log, never raise
def _set_view_orientation(self, target_doc, orientation, view_const) -> None:
try:
target_doc.ShowNamedView2("", view_const)
except Exception:
logger.warning("Could not set view orientation to %s", orientation)
# Boolean helper — True = file written
def _save_screenshot_with_modelview(self, model_view, path, width, height) -> bool:
try:
model_view.SaveBitmapWithVariableSize(path, width, height)
return os.path.exists(path)
except Exception:
return False
# Optional-dict helper — None = strategy failed, try next
def _try_select_by_extension(self, target_doc, candidates, feature_name) -> dict | None:
for candidate in candidates:
for entity_type in ENTITY_TYPES:
try:
if target_doc.Extension.SelectByID2(candidate, entity_type, 0, 0, 0, False, 0, None, 0):
return {"selected": True, "feature_name": feature_name, ...}
except Exception:
continue
return None
# Raising helper — last-chance invoker
def _invoke_run_macro2(self, macro_path, module_name, proc_name) -> dict:
result = self.swApp.RunMacro2(macro_path, module_name, proc_name, 0, 0)
success = result[0] if isinstance(result, (list, tuple)) else bool(result)
if not success:
raise SolidWorksMCPError(f"RunMacro2 failed for {macro_path}")
return {"macro_path": macro_path, "module_name": module_name}Step 3 — Refactor the Orchestrator
Replace the closure body with a sequential if result: return result chain:
def _operation() -> dict:
target_doc = self.currentModel
candidates = self._build_feature_candidate_names(feature_name, target_doc)
result = self._try_select_by_extension(target_doc, candidates, feature_name)
if result:
return result
result = self._try_select_by_component(target_doc, candidates, feature_name)
if result:
return result
result = self._try_select_by_feature_tree(target_doc, feature_name, candidates)
if result:
return result
return {"selected": False, "feature_name": feature_name}Step 4 — Write Tests
Add tests to the file that mirrors the module you changed: src/solidworks_mcp/<path>/<module>.py
is tested in tests/solidworks_mcp/<path>/test_<module>.py (for example
adapters/solidworks/features.py -> tests/solidworks_mcp/adapters/solidworks/test_features.py).
Adapter mixin files each have a TestPyWin32AdapterBranches class with the _build_adapter helper.
Critical rules:
- Use
self._build_adapter(monkeypatch)— never constructPyWin32Adapterdirectly. - Mock COM objects with
SimpleNamespace+unittest.mock.Mock. - Never import
win32com,pywintypes, orpythoncom— use monkeypatch. - Use
tmp_pathfixture for file-existence checks. - Tests must be class-level methods at 4-space indentation under the class — never nested inside another test function.
- Use the top-level
SolidWorksMCPErrorimport (already present at module top); do NOT add a localfrom solidworks_mcp.exceptions import SolidWorksMCPErrorinline — it creates a different class object that won't matchpytest.raises.
Coverage requirement per helper:
| Scenario | Must cover |
| Happy path | Returns expected value when COM calls succeed |
| Failure path | Returns None / False / raises when COM call fails or returns False |
| Edge cases | None input, empty list, fallback chain exhausted |
def test_<helper_name>_<scenario>(self, monkeypatch) -> None:
"""<helper_name> should <expected behaviour> when <condition>."""
adapter = self._build_adapter(monkeypatch)
# arrange
target_doc = SimpleNamespace(Method=Mock(return_value=<value>))
# act
result = adapter.<helper_name>(target_doc, ...)
# assert
assert result == <expected>Step 5 — Validate
Run only the new tests first (no coverage threshold):
.\.venv\Scripts\python.exe -m pytest -o addopts="" tests/solidworks_mcp/<path>/test_<module>.py -k "<new_test_fragment>" -qRun the whole file to catch regressions:
.\.venv\Scripts\python.exe -m pytest tests/solidworks_mcp/<path>/test_<module>.py -q --no-covAll tests must pass before the task is complete.
Known Pitfall — SolidWorksMCPError identity
The project uses src.solidworks_mcp.exceptions as the import path in the adapter module. If a test imports from solidworks_mcp.exceptions import SolidWorksMCPError inline, Python loads a separate module object and pytest.raises won't catch the exception even though the message is identical. Always use the module-level import:
# at the top of the test file:
from src.solidworks_mcp.exceptions import SolidWorksMCPErrorDoes 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.

