agentleFS
andrewbartels1andrewbartels1/SolidworksMCP-python/.github/skills/extract-and-test/SKILL.md

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

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
  1. Distinctive:

    Read the target line range.

    line 17
  2. Very specific:

    Write one helper per concern.

    line 37
  3. Very specific:

    Add tests to the file that mirrors the module you changed: src/solidworks_mcp/<path>/<module>.py is tested in …

    line 119
  4. Very specific:

    Use self._build_adapter(monkeypatch) — never construct PyWin32Adapter directly.

    line 125
  5. Very specific:

    Never import win32com, pywintypes, or pythoncom — use monkeypatch.

    line 127
  6. Very specific:

    Use tmp_path fixture for file-existence checks.

    line 128
  7. Very specific:

    Use the top-level SolidWorksMCPError import (already present at module top).

    line 130
  8. Distinctive:

    Run only the new tests first (no coverage threshold):

    line 156
  9. Distinctive:

    Run the whole file to catch regressions:

    line 162
  10. Distinctive:

    All tests must pass before the task is complete.

    line 168

≈ “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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Extract & Test — pywin32_adapter.py

Apply this skill whenever a method in src/solidworks_mcp/adapters/pywin32_adapter.py contains:

  • Deeply nested try/except blocks 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/_operation lambda

Step 1 — Read and Analyse

Read the target line range. For each logical block, fill in this table:

ConcernCOM calls involvedFailure modeReturn contract
(fill in)(fill in)(fill in)(fill in)

Apply these heuristics to determine the right helper shape:

ShapeWhen to use
-> None (log, never raise)Setup/orientation side-effects — failure is acceptable
-> boolCOM operation that writes a file; True = file exists
-> dict | NoneCOM selection/query strategy; None = this strategy failed, try next
-> dict (raises on failure)Last-chance fallback or invoker — surface error to caller
@staticmethodPure 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 construct PyWin32Adapter directly.
  • Mock COM objects with SimpleNamespace + unittest.mock.Mock.
  • Never import win32com, pywintypes, or pythoncom — use monkeypatch.
  • Use tmp_path fixture 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 SolidWorksMCPError import (already present at module top); do NOT add a local from solidworks_mcp.exceptions import SolidWorksMCPError inline — it creates a different class object that won't match pytest.raises.

Coverage requirement per helper:

ScenarioMust cover
Happy pathReturns expected value when COM calls succeed
Failure pathReturns None / False / raises when COM call fails or returns False
Edge casesNone 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>" -q

Run the whole file to catch regressions:

.\.venv\Scripts\python.exe -m pytest tests/solidworks_mcp/<path>/test_<module>.py -q --no-cov

All 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 SolidWorksMCPError

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.