agentleFS
xsovad06xsovad06/sova/.claude/skills/testing-patterns/SKILL.md

testing-patterns

Skill2 starsChanged 3 months agoApache-2.0View on GitHub

SOVA test conventions -- pytest async patterns, mock strategies, fixture patterns, dashboard ASGI testing. Auto-activates when writing or modifying test files in the tests/ directory.

24 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use intelligent-routing, api-patterns 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.
  • tiendatworkSkill

    intelligent-routing

    Automatic agent selection and intelligent task routing. Analyzes user requests and automatically selects the best specialist agent(s) without requiring explicit user mentions.

    Also in 3 projects that use this

  • xfstudioSkill

    api-patterns

    API design principles and decision-making. REST vs GraphQL vs tRPC selection, response formats, versioning, pagination.

    Also in 5 projects that use this

  • xfstudioSkill

    rust-pro

    Master Rust 1.75+ with modern async patterns, advanced type system

    Also in 3 projects that use this

  • benshapyroSkill

    documentation-templates

    Generates README files, API documentation, and inline code comments following best practices. Use when creating project documentation, writing READMEs, documenting APIs, or explaining complex code.

    Also in 3 projects that use this

  • +8 more from xfstudio

The file

We split this skill into the rules it gives an agent

4 rules. 0 are common, 1 is distinctive, and 3 are very specific to this project.

  • 0

    Common

    Most of the 17 edited versions we read keep these.

  • 1

    Distinctive

    This author's own choices. Worth a look.

  • 3

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    When writing or modifying files in tests/, follow these conventions.

    line 9
  2. Very specific:

    Multi-call methods: use side_effect list.

    line 71
  3. Very specific:

    Session pattern: always async with await get_session() as session:.

    line 76
  4. Distinctive:

    Direct unit tests for mocked functions: if a function is always mocked in integration tests, SonarCloud flags 0% coverage.

    line 80

“Common” is measured: kept by at least 6 in 10 of the 17 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.

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

SOVA Testing Patterns

When writing or modifying files in tests/, follow these conventions. Reference: docs/testing-guidelines.md.

Framework

  • asyncio_mode = "auto" -- no @pytest.mark.asyncio needed on async tests
  • Most tests are flat in tests/; a few isolated areas (e.g. tests/runtime/) get their own subdirectory with a local conftest.py when their fixtures don't apply elsewhere
  • tests/conftest.py holds only truly cross-suite fixtures: _isolate_sova_env (autouse, strips ambient SOVA_* env vars) and seed_config (seeds DB-backed project_settings instead of writing sova.toml, matching production config storage). Use seed_config(project_dir, **values) for any test that needs configured values, don't write a sova.toml file.
  • Tests grouped with classes. Beyond the shared fixtures above, fixtures are defined per-file, not shared.

Required Fixtures

In-memory DB (autouse in any file touching ORM):

@pytest.fixture(autouse=True)
async def setup_db():
    os.environ["SOVA_DATABASE_URL"] = "sqlite+aiosqlite://"
    await init_db(run_migrations=False)
    yield
    await close_db()
    os.environ.pop("SOVA_DATABASE_URL", None)

Dashboard client:

@pytest.fixture
async def client(tmp_path):
    app = create_app(project_dir=tmp_path)
    transport = ASGITransport(app=app)
    async with AsyncClient(transport=transport, base_url="http://test") as ac:
        yield ac

Mock Rules

  1. Patch at the import site, not the definition site:
    # Correct
    patch("sova.adapters.github.run", new_callable=AsyncMock)
    # Wrong
    patch("sova.utils.shell.run", new_callable=AsyncMock)
  2. Use patch.object for split modules -- patch the actual submodule, not the re-export facade:
    patch.object(agent_lifecycle, "_get_project_agents", return_value=pa)
  3. ShellResult factory -- define per-file:
    def _shell_result(stdout="", stderr="", returncode=0):
        return ShellResult(returncode=returncode, stdout=stdout, stderr=stderr)
  4. Context factory -- define per-file:
    def _make_ctx(**kwargs) -> ExecutionContext:
        defaults = {"project_dir": Path("/tmp/test"), "config": ProjectConfig(),
                    "adapter": _mock_adapter(), "issue_number": "42", "role": "developer"}
        defaults.update(kwargs)
        return ExecutionContext(**defaults)
  5. Multi-call methods: use side_effect list.

Pitfalls

  • Clear caches: file-backed services (handoff, log) cache by mtime. Clear _handoff_caches in tests.
  • Session pattern: always async with await get_session() as session:.
  • DB fixture scope: per-test only. Never scope="module".
  • Don't add new shared fixtures to tests/conftest.py beyond _isolate_sova_env/seed_config: copy per-file helpers instead, unless the fixture is genuinely needed suite-wide.
  • Module-level cache requires setup_method in ALL test classes: when a service function has a module-level cache, add setup_method: clear_cache() to every test class in the file that calls it, not just new ones. Cache type changes (tuple|None -> dict) require updating all reset patterns (= None -> .clear()).
  • Direct unit tests for mocked functions: if a function is always mocked in integration tests, SonarCloud flags 0% coverage. Add a dedicated test class with direct calls to cover the implementation paths (e.g. TestIsIssue alongside code that always mocks _is_issue()).
  • Cover except blocks explicitly for the SonarCloud gate: swallowed-error handlers (except (OSError, Exception)) add uncovered lines that can fail the new_coverage threshold (80%) even on a small diff. Add a test with side_effect=OSError(...) (or the specific exception) that triggers each except path; for file I/O, patch.object(Path, "read_text"/"write_text", side_effect=OSError(...)) covers read and write failures independently.
  • MagicMock(name="foo") sets repr, not .name: name= is a reserved constructor arg. Assign after construction: mock = MagicMock(); mock.name = "foo".
  • Spawn mock functions must use **kwargs: async def _capture_spawn(prompt, cwd, **kwargs) absorbs new parameters without breaking when spawn() gains kwargs.
  • TaskRun uses started_at, not created_at: most ORM models use created_at, but TaskRun uses started_at/ended_at. Referencing TaskRun.created_at raises AttributeError silently swallowed by broad except Exception.

Running

  • make check before push (CI-equivalent)
  • make test-py for pytest only
  • make lint for ShellCheck + Ruff

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.