[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M79HZC8SKZPWVZN87KZS1QDC":3,"skill-same:01M79HZC8SKZPWVZN87KZS1QDC":63},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":29,"commitSha":30,"skillDirectory":31,"forksCount":14,"repositoryHtmlUrl":32,"repositoryHomepageUrl":6,"ownerHtmlUrl":33,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":34,"install":35,"resources":48},"01M79HZC8SKZPWVZN87KZS1QDC","pytest-skill",null,"Production-grade pytest guidance for Python tests: authoring, fixtures, parametrization, assertions, mocking, markers, discovery, plugins, hooks, debugging, output, warnings, doctests, CI, and migration from unittest. Use this skill whenever a request mentions pytest, conftest.py, fixtures, pytest.mark, parametrization, test discovery, pytest plugins\u002Fhooks, or asks how to write, run, debug, organize, or improve Python tests with pytest. For PySpark or Databricks-specific testing, also use pytest-databricks.","TinhAnhGitHub\u002Fdotfiles","TinhAnhGitHub","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F120301674?v=4","01M79HBSJDQR2K995751YCVA6Z","Tinh Anh","01M79HBSK2A9425SRS875ZBDWC",0,"MIT","https:\u002F\u002Fgithub.com\u002FTinhAnhGitHub\u002Fdotfiles\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fpython\u002Fpytest-skill\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: pytest-skill\ndescription: >\n  Production-grade pytest guidance for Python tests: authoring, fixtures,\n  parametrization, assertions, mocking, markers, discovery, plugins, hooks,\n  debugging, output, warnings, doctests, CI, and migration from unittest.\n  Use this skill whenever a request mentions pytest, conftest.py, fixtures,\n  pytest.mark, parametrization, test discovery, pytest plugins\u002Fhooks, or asks\n  how to write, run, debug, organize, or improve Python tests with pytest.\n  For PySpark or Databricks-specific testing, also use pytest-databricks.\nlicense: MIT\nmetadata:\n  author: TestMu AI\n  version: \"2.0\"\n  source: \"https:\u002F\u002Fdocs.pytest.org\u002Fen\u002Fstable\u002F\"\n---\n\n# Pytest Skill\n\nUse this as an implementation playbook, not as a reason to add dependencies or\nover-engineer a small test. Prefer the smallest pytest feature that gives a\nclear, isolated, behavior-focused test.\n\n## Operating workflow\n\n1. **Inspect before editing.** Read the target module, nearby tests,\n   `conftest.py` files, and the active pytest configuration. Check\n   `pytest --version` and installed plugins when behavior may be version- or\n   plugin-dependent.\n2. **Classify the test.** Choose pure unit, integration, subprocess\u002FCLI,\n   async, plugin, doctest, or compatibility testing. Do not use a real network,\n   cloud resource, clock, or random source in a unit test unless that behavior\n   is explicitly the subject of the test.\n3. **Choose the narrowest mechanism.** Organize pytest tests in a dedicated\n   `Test*` class for the production function or class under test, and use plain\n   `assert` statements within its test methods; use fixtures for\n   dependencies\u002Flifecycle; `parametrize` for known static decision tables;\n   `subtests` only for dynamic cases discovered during execution; `hypothesis`\n   for invariant fuzzing; and mocks only at an external boundary. Control clocks\n   with `time-machine` rather than `freezegun` or `time.sleep()`.\n4. **Make isolation explicit.** Prefer function-scoped fixtures, `tmp_path`, and\n   transactional rollback savepoints for databases (`join_transaction_mode=\"create_savepoint\"`).\n   Split state-changing setup into small yield fixtures with teardown immediately\n   after `yield`. Avoid hidden `autouse` state unless it is truly global test policy.\n5. **Verify in layers.** Run collection first, the focused test, the relevant\n   test directory\u002Fmarker, and then the full suite when practical. Report\n   skipped, xfailed, warnings, and deselected tests rather than hiding them.\n\nRead the reference that matches the task:\n\n| Need | Reference |\n|---|---|\n| Official how-to, pytest 8\u002F9 features (RaisesGroup, subtests, @argument-file, colored diffs) | `reference\u002Fofficial-patterns.md` |\n| Deep fixture, assertion, cache, configuration, CI, and plugin playbook | `reference\u002Fplaybook.md` |\n| Advanced architectures: typed factories, SQLAlchemy 2 savepoint rollback, pytest-asyncio 0.24+, time-machine, hypothesis, syrupy snapshots, xdist worker isolation | `reference\u002Fadvanced-patterns.md` |\n\nFor Spark, Databricks Connect, `dbutils`, `WorkspaceClient`, or\n`databricks-labs-pytester`, load `pytest-databricks` as well; do not replace its\nenvironment-specific guidance with generic mocks.\n\n## Core test patterns\n\n## Project test organization, paths, and documentation\n\nApply these conventions to all pytest code unless the project has an explicit,\ndocumented exception:\n\n- Separate test suites into `tests\u002Funit\u002F` and `tests\u002Fintegration\u002F`. Put shared\n  fixtures, hooks, and pytest configuration in `tests\u002Fconftest.py`, and reuse\n  those fixtures rather than recreating common setup in individual test files.\n- Treat `pytestconfig.rootpath` as the base for test resources. Construct paths\n  with `pathlib.Path`, never hard-code absolute paths, and avoid `.resolve()`\n  when it would bind the test to a machine-specific layout. Define reusable\n  resource-directory fixtures in `tests\u002Fconftest.py` and inject them where\n  needed:\n\n  ```python\n  from pathlib import Path\n\n  import pytest\n\n\n  @pytest.fixture\n  def fixtures_dir(pytestconfig) -> Path:\n      return pytestconfig.rootpath \u002F \"tests\" \u002F \"fixtures\"\n  ```\n\n  A test should then compose its resource path from the injected fixture, for\n  example `data_path = fixtures_dir \u002F \"data.json\"`.\n- Begin every test file with a module docstring that identifies the component,\n  the covered scenarios, and whether the file contains unit or integration\n  tests. Give every test method a concise docstring stating the behavior under\n  test, its input or setup, its expected behavior, and the regression or\n  contract it protects.\n- Organize tests by production symbol. Use one dedicated `Test*` class for each\n  production function or class, with only the relevant cases for that symbol in the\n  class. Do not write standalone `test_*` functions. Name classes and methods\n  with pytest conventions and observable behavior, such as `TestParseEmail`,\n  `test_returns_expected_value`, and `test_raises_for_invalid_input`.\n\nThe expected layout is:\n\n```text\ntests\u002F\n├── conftest.py\n├── unit\u002F\n└── integration\u002F\n```\n\nKeep unit tests isolated and deterministic. Use integration tests when a case\ndepends on multiple components, external services, databases, filesystems, or\ninfrastructure.\n\n\n### Plain tests and assertion introspection\n\n```python\nimport pytest\n\n\nclass TestTotal:\n    def test_includes_tax(self):\n        \"\"\"Checks subtotal 10 at 20 percent tax returns 12, protecting tax arithmetic.\"\"\"\n        assert total(subtotal=10, tax_rate=0.2) == 12\n\n\nclass TestParseEmail:\n    def test_reports_invalid_input(self):\n        \"\"\"Checks invalid email input raises its validation error, preserving the input contract.\"\"\"\n        with pytest.raises(ValueError, match=r\"invalid email\") as exc_info:\n            parse_email(\"not-an-email\")\n        assert exc_info.value.args[0] == \"invalid email\"\n\n\nclass TestCalculateRatio:\n    def test_returns_approximate_float_result(self):\n        \"\"\"Checks one divided by three is accurate within tolerance, guarding float precision.\"\"\"\n        assert calculate_ratio(1, 3) == pytest.approx(1 \u002F 3, rel=1e-6)\n```\n\nUse `assert left == right`, not `self.assertEqual`; pytest rewrites asserts to\nshow useful diffs for strings, sequences, mappings, sets, and expressions.\nAdd a message only when it adds domain context. Use `pytest.fail()` for a\nfailure discovered by control flow, not as a replacement for normal asserts.\n\nFor modern Python exception groups, use `pytest.RaisesGroup` and\n`pytest.RaisesExc` when the group structure matters. Do not assert only that an\nexception group contains one expected exception if additional unexpected\nexceptions would make the test unsafe.\n\n### Fixtures: dependency injection and lifecycle\n\n```python\nimport pytest\n\n\n@pytest.fixture\ndef user_factory():\n    created = []\n\n    def make_user(name=\"Alice\"):\n        user = {\"name\": name}\n        created.append(user)\n        return user\n\n    yield make_user\n    # Replace this with real cleanup when the fixture creates resources.\n    created.clear()\n\n\nclass TestUserFactory:\n    def test_creates_user_with_given_name(self, user_factory):\n        \"\"\"Checks the fixture factory creates Bob data, preserving fixture-provided setup.\"\"\"\n        assert user_factory(\"Bob\") == {\"name\": \"Bob\"}\n```\n\nRules that prevent most fixture bugs:\n\n- A test requests a fixture by naming it as an argument; fixtures can request\n  other fixtures and pytest caches one instance per test\u002Fscope.\n- Use `function` scope by default. Use `class`, `module`, `package`, or\n  `session` only when sharing is safe and materially reduces setup cost.\n- A broader-scoped fixture cannot depend on a narrower-scoped fixture\n  (`ScopeMismatch`). A callable `scope=` can select scope from a CLI option.\n- Prefer one state-changing action per yield fixture. Teardown runs in reverse\n  dependency order; `addfinalizer` is useful when cleanup must be registered\n  conditionally after setup succeeds.\n- Use factory fixtures when one test needs multiple independently-created\n  objects. Do not call a fixture function directly; compose it or use\n  `request.getfixturevalue()` only for genuinely dynamic lookup.\n- Use `request.node`, `request.param`, `request.config`, and markers for\n  carefully scoped dynamic behavior. Keep the normal dependency graph explicit.\n- Put shared fixtures in the nearest appropriate `conftest.py`. A closer\n  `conftest.py` can override an upstream fixture; `usefixtures` is for setup\n  whose returned value is not needed by the test.\n\n`autouse=True` is appropriate for narrowly-scoped global policy such as\nresetting process state or installing a safety guard. It is usually a smell for\ndata setup because it hides why a test depends on that state.\n\n### Parametrization and test IDs\n\n```python\nimport pytest\n\n\nclass TestNormalizeName:\n    @pytest.mark.parametrize(\n        \"raw,expected\",\n        [\n            pytest.param(\" Alice \", \"Alice\", id=\"trimmed\"),\n            pytest.param(\"\", \"\", id=\"empty\"),\n            pytest.param(None, None, marks=pytest.mark.xfail(reason=\"pending API decision\"), id=\"none\"),\n        ],\n    )\n    def test_returns_normalized_value(self, raw, expected):\n        \"\"\"Checks named inputs normalize as expected, documenting API edge-case behavior.\"\"\"\n        assert normalize_name(raw) == expected\n```\n\n- Give meaningful `ids` for domain cases; IDs become part of node IDs and make\n  failures\u002Fselective reruns understandable.\n- Stack decorators for a Cartesian product only when every combination is\n  meaningful. Prefer explicit case objects when the matrix would explode.\n- Use `indirect=True` to pass a value into a fixture, and fixture\n  `params=[...]` when the fixture itself is the varying dependency.\n- Parameter values are passed as-is, not copied. Never mutate shared list\u002Fdict\n  parameters; construct fresh values or use immutable case data.\n- Apply `pytest.param(..., marks=...)` for a single-case skip\u002Fxfail.\n- Use `pytest_generate_tests(metafunc)` for collection-time cases from CLI\n  options or checked-in data. Decide and document the empty-case policy.\n\nUse `subtests` (pytest 9+) when cases are discovered only during test\nexecution and all failures should be reported in one test. Parametrization is\nbetter when cases should be collected, selected by node ID, rerun individually,\nor handled by `--last-failed`.\n\n### Mocking and monkeypatching\n\nPatch the name looked up by the system under test, not necessarily the name in\nthe dependency's original module:\n\n```python\nclass TestFetchUser:\n    def test_returns_user_from_http_response(self, mocker):\n        \"\"\"Checks a mocked user response returns Ada, protecting the HTTP boundary contract.\"\"\"\n        response = mocker.Mock(status_code=200)\n        response.json.return_value = {\"id\": 7, \"name\": \"Ada\"}\n        mocker.patch(\"myapp.users.requests.get\", return_value=response)\n\n        assert fetch_user(7)[\"name\"] == \"Ada\"\n\n\nclass TestLoadSettings:\n    def test_reads_test_environment(self, monkeypatch):\n        \"\"\"Checks test environment variables configure settings, preventing process-state leakage.\"\"\"\n        monkeypatch.setenv(\"APP_ENV\", \"test\")\n        monkeypatch.delenv(\"OPTIONAL_FLAG\", raising=False)\n        assert load_settings().environment == \"test\"\n```\n\n- Use `pytest-mock`'s `mocker` for `patch`, `spy`, `stub`, and automatic mock\n  cleanup; use `unittest.mock` when the project already standardizes on it.\n- Use `monkeypatch.setattr\u002Fdelattr`, `setitem\u002Fdelitem`, `setenv\u002Fdelenv`,\n  `syspath_prepend`, `chdir`, and `monkeypatch.context()` for reversible local\n  changes. `raising=False` is intentional only when absence is valid.\n- Prefer dependency injection or a small fake when it makes the boundary\n  clearer. Use `spec`\u002F`autospec` where appropriate so a mock cannot invent an\n  invalid API. Assert important observable calls, not every implementation\n  detail.\n- For async calls use `AsyncMock` and await the system under test; do not make a\n  synchronous mock pretend to be awaitable.\n\n### Markers, skips, and xfails\n\nRegister custom markers and run with `--strict-markers`:\n\n```toml\n[tool.pytest.ini_options]\nmarkers = [\n  \"unit: fast isolated tests\",\n  \"integration: uses a real service or local integration runtime\",\n  \"slow: takes longer than the normal test budget\",\n]\n```\n\n```python\nimport pytest\n\n\nclass TestDatabaseRoundTrip:\n    @pytest.mark.integration\n    def test_persists_and_reads_data(self, database):\n        \"\"\"Checks the integration database round trip, protecting multi-component persistence.\"\"\"\n        ...\n\n\nclass TestGpuPath:\n    @pytest.mark.skipif(not HAS_GPU, reason=\"requires GPU\")\n    def test_uses_gpu_when_available(self):\n        \"\"\"Checks GPU-capable setup follows the GPU path, preserving optional hardware support.\"\"\"\n        ...\n\n\nclass TestKnownBug:\n    @pytest.mark.xfail(strict=True, raises=KnownBug, reason=\"issue #123\")\n    def test_exposes_known_bug(self):\n        \"\"\"Exercises the known failing setup, ensuring the tracked defect remains visible.\"\"\"\n        ...\n```\n\nUse `pytest.importorskip(\"optional_pkg\", minversion=\"...\")` for optional\ndependencies. Use imperative `pytest.skip()`\u002F`pytest.xfail()` only when the\ncondition is known during setup or execution. Make xfails strict in CI when an\nunexpected pass should force removal of stale bug metadata. Never use skip or\nxfail to conceal an ordinary failing test.\n\n### Files, output, logs, and warnings\n\n- Use `tmp_path` (`pathlib.Path`) for per-test files and `tmp_path_factory` for\n  expensive session-shared artifacts. Use `--basetemp` only with a disposable\n  directory because it is cleared before the run.\n- Use `capsys` for Python-level text output, `capsysbinary` for bytes, `capfd`\n  or `capfdbinary` for subprocess\u002Ffile-descriptor output, and\n  `capsys.disabled()` for a short intentionally-live block.\n- Use `caplog.at_level()`\u002F`set_level()`, `caplog.records`, `record_tuples`, and\n  `caplog.clear()` to test logging behavior. Configure live\u002Ffile logging only\n  when it helps the workflow; do not assert on formatting unless formatting is\n  the contract.\n- Use `pytest.warns()` to assert an expected warning and `recwarn` to inspect\n  all warnings. Treat unexpected deprecations as errors in CI, with narrow,\n  documented filters for intentionally legacy behavior.\n\n### Async, CLI, doctest, and unittest compatibility\n\n- For async tests, use `pytest-asyncio` (0.24+) with explicit loop scoping:\n  configure `asyncio_default_fixture_loop_scope = \"function\"` in `pyproject.toml`\n  and align fixture\u002Ftest `loop_scope` to prevent event loop mismatch errors.\n  Use `pytest.RaisesGroup` to test concurrent task failures inside `asyncio.TaskGroup`.\n- For a CLI, prefer invoking the real entry point in a subprocess when process\n  boundaries, exit codes, or stdout\u002Fstderr matter; use `capsys` for a direct\n  function-level CLI test.\n- Run docstrings with `--doctest-modules` and text examples with\n  `--doctest-glob`. Use `doctest_optionflags`, `doctest_namespace`,\n  `getfixture('fixture_name')`, and `--doctest-continue-on-failure` deliberately.\n- pytest runs `unittest.TestCase` suites, including their setup methods and\n  skips. During migration, retain compatibility first; do not assume normal\n  pytest fixture arguments or parametrization work inside `TestCase` methods.\n  New pytest tests should normally use fixtures and plain asserts.\n\n## Discovery and command cookbook\n\n```bash\n# Run and select\npython -m pytest                         # current interpreter; adds cwd to sys.path\npytest tests\u002F                            # directory\npytest tests\u002Ftest_api.py::TestUsers::test_create\npytest 'tests\u002Ftest_api.py::test_parse[empty]'  # quote [] in shells that expand it\npytest -k 'login and not slow'\npytest -m 'unit and not integration'\npytest --pyargs installed_package.tests\npytest @tests-to-run.txt                 # one path\u002Fnode\u002Foption per line (pytest 8.2+)\n\n# Understand collection\u002Fconfiguration\npytest --version\npytest --collect-only -q\npytest --fixtures\npytest --markers\npytest --trace-config                    # active plugins and conftest files\npytest --setup-show tests\u002Ftest_api.py\npytest --setup-plan                       # inspect fixture plan without running\n\n# Tight feedback loop\npytest -x --maxfail=3\npytest --lf                             # only last failures; use --lfnf=none if desired\npytest --ff                             # failures first, then all tests\npytest --nf                             # newest files first\npytest --cache-show\npytest --cache-clear\npytest --durations=10 --durations-min=1.0\n\n# Debug\u002Freport\npytest -x --pdb\npytest --trace\npytest -l --tb=short\npytest --full-trace\npytest -ra --show-capture=all\npytest --junitxml=reports\u002Fjunit.xml     # CI report\n```\n\n`-n auto`, `--cov`, `--html`, `--timeout`, `--reruns`, and stepwise options\ncome from plugins. Confirm the plugin is installed and active before adding\nthem to project defaults. Use `pytest -p no:PLUGIN` or\n`PYTEST_DISABLE_PLUGIN_AUTOLOAD=1` to diagnose plugin interference.\n\nWhen invoking from Python, call `pytest.main([...])` with explicit arguments\nand inspect its return value. Avoid calling `pytest.main()` repeatedly in one\nprocess because imported test modules remain cached.\n\n## Configuration baseline\n\nPrefer the project's existing configuration format. A conservative baseline is:\n\n```toml\n[tool.pytest.ini_options]\ntestpaths = [\"tests\"]\naddopts = [\"-ra\", \"--strict-markers\", \"--strict-config\", \"--tb=short\"]\nmarkers = [\n  \"unit: fast isolated tests\",\n  \"integration: tests using external or integration resources\",\n  \"slow: tests outside the normal runtime budget\",\n]\n```\n\nAdd coverage, async, timeout, logging, doctest, or warning policy only when the\ncorresponding dependency and project policy exist. Do not blindly combine\n`-v` and `-q`, or make every local run stop at the first failure. Check the\nactual configuration source with `pytest --help` and the session header; pytest\nconfiguration files are not merged arbitrarily.\n\n## Plugin and hook work\n\nUse a local `conftest.py` for project-only fixtures and hooks. Use a package\nplugin when behavior is reusable across projects. Register a plugin through a\n`pytest11` entry point when it must be installable. Test plugins with the\nbuilt-in `pytester` fixture by creating temporary test files and asserting\noutcomes.\n\nSafe hook rules:\n\n- Hook argument names are validated and optional arguments can be omitted.\n- Most non-test-running hooks should not raise; turn user\u002Fconfig errors into a\n  clear `pytest.UsageError` or a controlled report.\n- Use `@pytest.hookimpl(tryfirst=True\u002Ftrylast=True)` only when ordering is part\n  of the design. Hook wrappers are generator functions that yield exactly once.\n- For custom collection, use public `pytest.File`, `pytest.Item`,\n  `pytest.Directory`, `pytest_collect_file`, or `pytest_collect_directory` APIs;\n  implement `runtest`, `repr_failure`, and `reportinfo` for useful failures.\n- Use `pytest_collection_modifyitems` for collection-time marking\u002Fdeselection,\n  but keep policy visible and test it. `pytest_assertrepr_compare` and\n  `pytest.register_assert_rewrite()` are advanced tools for shared helpers.\n\n## Quality gates and anti-patterns\n\n- Name tests after behavior and keep Arrange–Act–Assert readable.\n- Test public behavior and contracts, not private call order.\n- Keep tests independent, deterministic, and safe to run in any order or with\n  xdist. Seed or inject randomness and control time rather than sleeping.\n- Separate unit\u002Fintegration\u002Fe2e markers and make external-resource tests opt-in\n  or skip with an explicit reason.\n- Avoid mutable module globals, broad `except Exception`, test ordering,\n  unconditional network calls, hard-coded temp paths, over-mocking, and tests\n  with no meaningful assertion.\n- Treat retries as a last-resort quarantine for diagnosed environmental\n  flakiness; fix the race or isolation problem instead of masking it.\n\n## Official coverage map\n\nThe companion reference was refreshed against the current pytest stable docs:\n\n- **How-to:** invocation, assertions, fixtures, marks, parametrization,\n  subtests, temporary paths, monkeypatch, doctests, cache, failures, output,\n  logging, capture, warnings, skip\u002Fxfail, plugins, plugin writing\u002Fhooks,\n  existing suites, unittest, xunit setup, and bash completion.\n- **Examples:** failure reports, basic patterns, parametrization, custom marks,\n  collection-aware session fixtures, custom discovery, non-Python collectors,\n  and custom directory collectors.\n\nSource index: \u003Chttps:\u002F\u002Fdocs.pytest.org\u002Fen\u002Fstable\u002Fhow-to\u002Findex.html> and\n\u003Chttps:\u002F\u002Fdocs.pytest.org\u002Fen\u002Fstable\u002Fexample\u002Findex.html>.\n","# Pytest Skill\n\nUse this as an implementation playbook, not as a reason to add dependencies or\nover-engineer a small test. Prefer the smallest pytest feature that gives a\nclear, isolated, behavior-focused test.\n\n## Operating workflow\n\n1. **Inspect before editing.** Read the target module, nearby tests,\n   `conftest.py` files, and the active pytest configuration. Check\n   `pytest --version` and installed plugins when behavior may be version- or\n   plugin-dependent.\n2. **Classify the test.** Choose pure unit, integration, subprocess\u002FCLI,\n   async, plugin, doctest, or compatibility testing. Do not use a real network,\n   cloud resource, clock, or random source in a unit test unless that behavior\n   is explicitly the subject of the test.\n3. **Choose the narrowest mechanism.** Organize pytest tests in a dedicated\n   `Test*` class for the production function or class under test, and use plain\n   `assert` statements within its test methods; use fixtures for\n   dependencies\u002Flifecycle; `parametrize` for known static decision tables;\n   `subtests` only for dynamic cases discovered during execution; `hypothesis`\n   for invariant fuzzing; and mocks only at an external boundary. Control clocks\n   with `time-machine` rather than `freezegun` or `time.sleep()`.\n4. **Make isolation explicit.** Prefer function-scoped fixtures, `tmp_path`, and\n   transactional rollback savepoints for databases (`join_transaction_mode=\"create_savepoint\"`).\n   Split state-changing setup into small yield fixtures with teardown immediately\n   after `yield`. Avoid hidden `autouse` state unless it is truly global test policy.\n5. **Verify in layers.** Run collection first, the focused test, the relevant\n   test directory\u002Fmarker, and then the full suite when practical. Report\n   skipped, xfailed, warnings, and deselected tests rather than hiding them.\n\nRead the reference that matches the task:\n\n| Need | Reference |\n|---|---|\n| Official how-to, pytest 8\u002F9 features (RaisesGroup, subtests, @argument-file, colored diffs) | `reference\u002Fofficial-patterns.md` |\n| Deep fixture, assertion, cache, configuration, CI, and plugin playbook | `reference\u002Fplaybook.md` |\n| Advanced architectures: typed factories, SQLAlchemy 2 savepoint rollback, pytest-asyncio 0.24+, time-machine, hypothesis, syrupy snapshots, xdist worker isolation | `reference\u002Fadvanced-patterns.md` |\n\nFor Spark, Databricks Connect, `dbutils`, `WorkspaceClient`, or\n`databricks-labs-pytester`, load `pytest-databricks` as well; do not replace its\nenvironment-specific guidance with generic mocks.\n\n## Core test patterns\n\n## Project test organization, paths, and documentation\n\nApply these conventions to all pytest code unless the project has an explicit,\ndocumented exception:\n\n- Separate test suites into `tests\u002Funit\u002F` and `tests\u002Fintegration\u002F`. Put shared\n  fixtures, hooks, and pytest configuration in `tests\u002Fconftest.py`, and reuse\n  those fixtures rather than recreating common setup in individual test files.\n- Treat `pytestconfig.rootpath` as the base for test resources. Construct paths\n  with `pathlib.Path`, never hard-code absolute paths, and avoid `.resolve()`\n  when it would bind the test to a machine-specific layout. Define reusable\n  resource-directory fixtures in `tests\u002Fconftest.py` and inject them where\n  needed:\n\n  ```python\n  from pathlib import Path\n\n  import pytest\n\n\n  @pytest.fixture\n  def fixtures_dir(pytestconfig) -> Path:\n      return pytestconfig.rootpath \u002F \"tests\" \u002F \"fixtures\"\n  ```\n\n  A test should then compose its resource path from the injected fixture, for\n  example `data_path = fixtures_dir \u002F \"data.json\"`.\n- Begin every test file with a module docstring that identifies the component,\n  the covered scenarios, and whether the file contains unit or integration\n  tests. Give every test method a concise docstring stating the behavior under\n  test, its input or setup, its expected behavior, and the regression or\n  contract it protects.\n- Organize tests by production symbol. Use one dedicated `Test*` class for each\n  production function or class, with only the relevant cases for that symbol in the\n  class. Do not write standalone `test_*` functions. Name classes and methods\n  with pytest conventions and observable behavior, such as `TestParseEmail`,\n  `test_returns_expected_value`, and `test_raises_for_invalid_input`.\n\nThe expected layout is:\n\n```text\ntests\u002F\n├── conftest.py\n├── unit\u002F\n└── integration\u002F\n```\n\nKeep unit tests isolated and deterministic. Use integration tests when a case\ndepends on multiple components, external services, databases, filesystems, or\ninfrastructure.\n\n\n### Plain tests and assertion introspection\n\n```python\nimport pytest\n\n\nclass TestTotal:\n    def test_includes_tax(self):\n        \"\"\"Checks subtotal 10 at 20 percent tax returns 12, protecting tax arithmetic.\"\"\"\n        assert total(subtotal=10, tax_rate=0.2) == 12\n\n\nclass TestParseEmail:\n    def test_reports_invalid_input(self):\n        \"\"\"Checks invalid email input raises its validation error, preserving the input contract.\"\"\"\n        with pytest.raises(ValueError, match=r\"invalid email\") as exc_info:\n            parse_email(\"not-an-email\")\n        assert exc_info.value.args[0] == \"invalid email\"\n\n\nclass TestCalculateRatio:\n    def test_returns_approximate_float_result(self):\n        \"\"\"Checks one divided by three is accurate within tolerance, guarding float precision.\"\"\"\n        assert calculate_ratio(1, 3) == pytest.approx(1 \u002F 3, rel=1e-6)\n```\n\nUse `assert left == right`, not `self.assertEqual`; pytest rewrites asserts to\nshow useful diffs for strings, sequences, mappings, sets, and expressions.\nAdd a message only when it adds domain context. Use `pytest.fail()` for a\nfailure discovered by control flow, not as a replacement for normal asserts.\n\nFor modern Python exception groups, use `pytest.RaisesGroup` and\n`pytest.RaisesExc` when the group structure matters. Do not assert only that an\nexception group contains one expected exception if additional unexpected\nexceptions would make the test unsafe.\n\n### Fixtures: dependency injection and lifecycle\n\n```python\nimport pytest\n\n\n@pytest.fixture\ndef user_factory():\n    created = []\n\n    def make_user(name=\"Alice\"):\n        user = {\"name\": name}\n        created.append(user)\n        return user\n\n    yield make_user\n    # Replace this with real cleanup when the fixture creates resources.\n    created.clear()\n\n\nclass TestUserFactory:\n    def test_creates_user_with_given_name(self, user_factory):\n        \"\"\"Checks the fixture factory creates Bob data, preserving fixture-provided setup.\"\"\"\n        assert user_factory(\"Bob\") == {\"name\": \"Bob\"}\n```\n\nRules that prevent most fixture bugs:\n\n- A test requests a fixture by naming it as an argument; fixtures can request\n  other fixtures and pytest caches one instance per test\u002Fscope.\n- Use `function` scope by default. Use `class`, `module`, `package`, or\n  `session` only when sharing is safe and materially reduces setup cost.\n- A broader-scoped fixture cannot depend on a narrower-scoped fixture\n  (`ScopeMismatch`). A callable `scope=` can select scope from a CLI option.\n- Prefer one state-changing action per yield fixture. Teardown runs in reverse\n  dependency order; `addfinalizer` is useful when cleanup must be registered\n  conditionally after setup succeeds.\n- Use factory fixtures when one test needs multiple independently-created\n  objects. Do not call a fixture function directly; compose it or use\n  `request.getfixturevalue()` only for genuinely dynamic lookup.\n- Use `request.node`, `request.param`, `request.config`, and markers for\n  carefully scoped dynamic behavior. Keep the normal dependency graph explicit.\n- Put shared fixtures in the nearest appropriate `conftest.py`. A closer\n  `conftest.py` can override an upstream fixture; `usefixtures` is for setup\n  whose returned value is not needed by the test.\n\n`autouse=True` is appropriate for narrowly-scoped global policy such as\nresetting process state or installing a safety guard. It is usually a smell for\ndata setup because it hides why a test depends on that state.\n\n### Parametrization and test IDs\n\n```python\nimport pytest\n\n\nclass TestNormalizeName:\n    @pytest.mark.parametrize(\n        \"raw,expected\",\n        [\n            pytest.param(\" Alice \", \"Alice\", id=\"trimmed\"),\n            pytest.param(\"\", \"\", id=\"empty\"),\n            pytest.param(None, None, marks=pytest.mark.xfail(reason=\"pending API decision\"), id=\"none\"),\n        ],\n    )\n    def test_returns_normalized_value(self, raw, expected):\n        \"\"\"Checks named inputs normalize as expected, documenting API edge-case behavior.\"\"\"\n        assert normalize_name(raw) == expected\n```\n\n- Give meaningful `ids` for domain cases; IDs become part of node IDs and make\n  failures\u002Fselective reruns understandable.\n- Stack decorators for a Cartesian product only when every combination is\n  meaningful. Prefer explicit case objects when the matrix would explode.\n- Use `indirect=True` to pass a value into a fixture, and fixture\n  `params=[...]` when the fixture itself is the varying dependency.\n- Parameter values are passed as-is, not copied. Never mutate shared list\u002Fdict\n  parameters; construct fresh values or use immutable case data.\n- Apply `pytest.param(..., marks=...)` for a single-case skip\u002Fxfail.\n- Use `pytest_generate_tests(metafunc)` for collection-time cases from CLI\n  options or checked-in data. Decide and document the empty-case policy.\n\nUse `subtests` (pytest 9+) when cases are discovered only during test\nexecution and all failures should be reported in one test. Parametrization is\nbetter when cases should be collected, selected by node ID, rerun individually,\nor handled by `--last-failed`.\n\n### Mocking and monkeypatching\n\nPatch the name looked up by the system under test, not necessarily the name in\nthe dependency's original module:\n\n```python\nclass TestFetchUser:\n    def test_returns_user_from_http_response(self, mocker):\n        \"\"\"Checks a mocked user response returns Ada, protecting the HTTP boundary contract.\"\"\"\n        response = mocker.Mock(status_code=200)\n        response.json.return_value = {\"id\": 7, \"name\": \"Ada\"}\n        mocker.patch(\"myapp.users.requests.get\", return_value=response)\n\n        assert fetch_user(7)[\"name\"] == \"Ada\"\n\n\nclass TestLoadSettings:\n    def test_reads_test_environment(self, monkeypatch):\n        \"\"\"Checks test environment variables configure settings, preventing process-state leakage.\"\"\"\n        monkeypatch.setenv(\"APP_ENV\", \"test\")\n        monkeypatch.delenv(\"OPTIONAL_FLAG\", raising=False)\n        assert load_settings().environment == \"test\"\n```\n\n- Use `pytest-mock`'s `mocker` for `patch`, `spy`, `stub`, and automatic mock\n  cleanup; use `unittest.mock` when the project already standardizes on it.\n- Use `monkeypatch.setattr\u002Fdelattr`, `setitem\u002Fdelitem`, `setenv\u002Fdelenv`,\n  `syspath_prepend`, `chdir`, and `monkeypatch.context()` for reversible local\n  changes. `raising=False` is intentional only when absence is valid.\n- Prefer dependency injection or a small fake when it makes the boundary\n  clearer. Use `spec`\u002F`autospec` where appropriate so a mock cannot invent an\n  invalid API. Assert important observable calls, not every implementation\n  detail.\n- For async calls use `AsyncMock` and await the system under test; do not make a\n  synchronous mock pretend to be awaitable.\n\n### Markers, skips, and xfails\n\nRegister custom markers and run with `--strict-markers`:\n\n```toml\n[tool.pytest.ini_options]\nmarkers = [\n  \"unit: fast isolated tests\",\n  \"integration: uses a real service or local integration runtime\",\n  \"slow: takes longer than the normal test budget\",\n]\n```\n\n```python\nimport pytest\n\n\nclass TestDatabaseRoundTrip:\n    @pytest.mark.integration\n    def test_persists_and_reads_data(self, database):\n        \"\"\"Checks the integration database round trip, protecting multi-component persistence.\"\"\"\n        ...\n\n\nclass TestGpuPath:\n    @pytest.mark.skipif(not HAS_GPU, reason=\"requires GPU\")\n    def test_uses_gpu_when_available(self):\n        \"\"\"Checks GPU-capable setup follows the GPU path, preserving optional hardware support.\"\"\"\n        ...\n\n\nclass TestKnownBug:\n    @pytest.mark.xfail(strict=True, raises=KnownBug, reason=\"issue #123\")\n    def test_exposes_known_bug(self):\n        \"\"\"Exercises the known failing setup, ensuring the tracked defect remains visible.\"\"\"\n        ...\n```\n\nUse `pytest.importorskip(\"optional_pkg\", minversion=\"...\")` for optional\ndependencies. Use imperative `pytest.skip()`\u002F`pytest.xfail()` only when the\ncondition is known during setup or execution. Make xfails strict in CI when an\nunexpected pass should force removal of stale bug metadata. Never use skip or\nxfail to conceal an ordinary failing test.\n\n### Files, output, logs, and warnings\n\n- Use `tmp_path` (`pathlib.Path`) for per-test files and `tmp_path_factory` for\n  expensive session-shared artifacts. Use `--basetemp` only with a disposable\n  directory because it is cleared before the run.\n- Use `capsys` for Python-level text output, `capsysbinary` for bytes, `capfd`\n  or `capfdbinary` for subprocess\u002Ffile-descriptor output, and\n  `capsys.disabled()` for a short intentionally-live block.\n- Use `caplog.at_level()`\u002F`set_level()`, `caplog.records`, `record_tuples`, and\n  `caplog.clear()` to test logging behavior. Configure live\u002Ffile logging only\n  when it helps the workflow; do not assert on formatting unless formatting is\n  the contract.\n- Use `pytest.warns()` to assert an expected warning and `recwarn` to inspect\n  all warnings. Treat unexpected deprecations as errors in CI, with narrow,\n  documented filters for intentionally legacy behavior.\n\n### Async, CLI, doctest, and unittest compatibility\n\n- For async tests, use `pytest-asyncio` (0.24+) with explicit loop scoping:\n  configure `asyncio_default_fixture_loop_scope = \"function\"` in `pyproject.toml`\n  and align fixture\u002Ftest `loop_scope` to prevent event loop mismatch errors.\n  Use `pytest.RaisesGroup` to test concurrent task failures inside `asyncio.TaskGroup`.\n- For a CLI, prefer invoking the real entry point in a subprocess when process\n  boundaries, exit codes, or stdout\u002Fstderr matter; use `capsys` for a direct\n  function-level CLI test.\n- Run docstrings with `--doctest-modules` and text examples with\n  `--doctest-glob`. Use `doctest_optionflags`, `doctest_namespace`,\n  `getfixture('fixture_name')`, and `--doctest-continue-on-failure` deliberately.\n- pytest runs `unittest.TestCase` suites, including their setup methods and\n  skips. During migration, retain compatibility first; do not assume normal\n  pytest fixture arguments or parametrization work inside `TestCase` methods.\n  New pytest tests should normally use fixtures and plain asserts.\n\n## Discovery and command cookbook\n\n```bash\n# Run and select\npython -m pytest                         # current interpreter; adds cwd to sys.path\npytest tests\u002F                            # directory\npytest tests\u002Ftest_api.py::TestUsers::test_create\npytest 'tests\u002Ftest_api.py::test_parse[empty]'  # quote [] in shells that expand it\npytest -k 'login and not slow'\npytest -m 'unit and not integration'\npytest --pyargs installed_package.tests\npytest @tests-to-run.txt                 # one path\u002Fnode\u002Foption per line (pytest 8.2+)\n\n# Understand collection\u002Fconfiguration\npytest --version\npytest --collect-only -q\npytest --fixtures\npytest --markers\npytest --trace-config                    # active plugins and conftest files\npytest --setup-show tests\u002Ftest_api.py\npytest --setup-plan                       # inspect fixture plan without running\n\n# Tight feedback loop\npytest -x --maxfail=3\npytest --lf                             # only last failures; use --lfnf=none if desired\npytest --ff                             # failures first, then all tests\npytest --nf                             # newest files first\npytest --cache-show\npytest --cache-clear\npytest --durations=10 --durations-min=1.0\n\n# Debug\u002Freport\npytest -x --pdb\npytest --trace\npytest -l --tb=short\npytest --full-trace\npytest -ra --show-capture=all\npytest --junitxml=reports\u002Fjunit.xml     # CI report\n```\n\n`-n auto`, `--cov`, `--html`, `--timeout`, `--reruns`, and stepwise options\ncome from plugins. Confirm the plugin is installed and active before adding\nthem to project defaults. Use `pytest -p no:PLUGIN` or\n`PYTEST_DISABLE_PLUGIN_AUTOLOAD=1` to diagnose plugin interference.\n\nWhen invoking from Python, call `pytest.main([...])` with explicit arguments\nand inspect its return value. Avoid calling `pytest.main()` repeatedly in one\nprocess because imported test modules remain cached.\n\n## Configuration baseline\n\nPrefer the project's existing configuration format. A conservative baseline is:\n\n```toml\n[tool.pytest.ini_options]\ntestpaths = [\"tests\"]\naddopts = [\"-ra\", \"--strict-markers\", \"--strict-config\", \"--tb=short\"]\nmarkers = [\n  \"unit: fast isolated tests\",\n  \"integration: tests using external or integration resources\",\n  \"slow: tests outside the normal runtime budget\",\n]\n```\n\nAdd coverage, async, timeout, logging, doctest, or warning policy only when the\ncorresponding dependency and project policy exist. Do not blindly combine\n`-v` and `-q`, or make every local run stop at the first failure. Check the\nactual configuration source with `pytest --help` and the session header; pytest\nconfiguration files are not merged arbitrarily.\n\n## Plugin and hook work\n\nUse a local `conftest.py` for project-only fixtures and hooks. Use a package\nplugin when behavior is reusable across projects. Register a plugin through a\n`pytest11` entry point when it must be installable. Test plugins with the\nbuilt-in `pytester` fixture by creating temporary test files and asserting\noutcomes.\n\nSafe hook rules:\n\n- Hook argument names are validated and optional arguments can be omitted.\n- Most non-test-running hooks should not raise; turn user\u002Fconfig errors into a\n  clear `pytest.UsageError` or a controlled report.\n- Use `@pytest.hookimpl(tryfirst=True\u002Ftrylast=True)` only when ordering is part\n  of the design. Hook wrappers are generator functions that yield exactly once.\n- For custom collection, use public `pytest.File`, `pytest.Item`,\n  `pytest.Directory`, `pytest_collect_file`, or `pytest_collect_directory` APIs;\n  implement `runtest`, `repr_failure`, and `reportinfo` for useful failures.\n- Use `pytest_collection_modifyitems` for collection-time marking\u002Fdeselection,\n  but keep policy visible and test it. `pytest_assertrepr_compare` and\n  `pytest.register_assert_rewrite()` are advanced tools for shared helpers.\n\n## Quality gates and anti-patterns\n\n- Name tests after behavior and keep Arrange–Act–Assert readable.\n- Test public behavior and contracts, not private call order.\n- Keep tests independent, deterministic, and safe to run in any order or with\n  xdist. Seed or inject randomness and control time rather than sleeping.\n- Separate unit\u002Fintegration\u002Fe2e markers and make external-resource tests opt-in\n  or skip with an explicit reason.\n- Avoid mutable module globals, broad `except Exception`, test ordering,\n  unconditional network calls, hard-coded temp paths, over-mocking, and tests\n  with no meaningful assertion.\n- Treat retries as a last-resort quarantine for diagnosed environmental\n  flakiness; fix the race or isolation problem instead of masking it.\n\n## Official coverage map\n\nThe companion reference was refreshed against the current pytest stable docs:\n\n- **How-to:** invocation, assertions, fixtures, marks, parametrization,\n  subtests, temporary paths, monkeypatch, doctests, cache, failures, output,\n  logging, capture, warnings, skip\u002Fxfail, plugins, plugin writing\u002Fhooks,\n  existing suites, unittest, xunit setup, and bash completion.\n- **Examples:** failure reports, basic patterns, parametrization, custom marks,\n  collection-aware session fixtures, custom discovery, non-Python collectors,\n  and custom directory collectors.\n\nSource index: \u003Chttps:\u002F\u002Fdocs.pytest.org\u002Fen\u002Fstable\u002Fhow-to\u002Findex.html> and\n\u003Chttps:\u002F\u002Fdocs.pytest.org\u002Fen\u002Fstable\u002Fexample\u002Findex.html>.\n",{"name":5,"license":15,"metadata":24,"description":28},{"author":25,"source":26,"version":27},"TestMu AI","https:\u002F\u002Fdocs.pytest.org\u002Fen\u002Fstable\u002F","2.0","Production-grade pytest guidance for Python tests: authoring, fixtures, parametrization, assertions, mocking, markers, discovery, plugins, hooks, debugging, output, warnings, doctests, CI, and migration from unittest. Use this skill whenever a request mentions pytest, conftest.py, fixtures, pytest.mark, parametrization, test discovery, pytest plugins\u002Fhooks, or asks how to write, run, debug, organize, or improve Python tests with pytest. For PySpark or Databricks-specific testing, also use pytest-databricks.\n","main","866ae6a554678d3e3f49ffc21d262023ebaad8ba",".agents\u002Fskills\u002Fpython\u002Fpytest-skill","https:\u002F\u002Fgithub.com\u002FTinhAnhGitHub\u002Fdotfiles","https:\u002F\u002Fgithub.com\u002FTinhAnhGitHub","2026-09-13 19:29:17",{"source":8,"skillName":5,"commands":36,"prompt":46,"zipAvailable":47},[37,40,43],{"tool":38,"command":39},"npx","npx skills add TinhAnhGitHub\u002Fdotfiles --skill pytest-skill",{"tool":41,"command":42},"bunx","bunx skills add TinhAnhGitHub\u002Fdotfiles --skill pytest-skill",{"tool":44,"command":45},"pnpm","pnpm dlx skills add TinhAnhGitHub\u002Fdotfiles --skill pytest-skill","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FTinhAnhGitHub\u002Fdotfiles\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fpython\u002Fpytest-skill\u002FSKILL.md",true,[49,55,59],{"path":50,"resourceType":51,"resourceTypeDesc":52,"sizeBytes":53,"sourceHtmlUrl":54},"reference\u002Fadvanced-patterns.md","REFERENCE","参考文档",21329,"https:\u002F\u002Fgithub.com\u002FTinhAnhGitHub\u002Fdotfiles\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fpython\u002Fpytest-skill\u002Freference\u002Fadvanced-patterns.md",{"path":56,"resourceType":51,"resourceTypeDesc":52,"sizeBytes":57,"sourceHtmlUrl":58},"reference\u002Fofficial-patterns.md",20778,"https:\u002F\u002Fgithub.com\u002FTinhAnhGitHub\u002Fdotfiles\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fpython\u002Fpytest-skill\u002Freference\u002Fofficial-patterns.md",{"path":60,"resourceType":51,"resourceTypeDesc":52,"sizeBytes":61,"sourceHtmlUrl":62},"reference\u002Fplaybook.md",37073,"https:\u002F\u002Fgithub.com\u002FTinhAnhGitHub\u002Fdotfiles\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fpython\u002Fpytest-skill\u002Freference\u002Fplaybook.md",[64,73,81,88,95,102],{"skillNo":65,"name":66,"nameZh":6,"description":67,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":68,"licenseFileUrl":69,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":19},"01M79J5BK2TVBQQ0KK708PSZMR","skill-creator","Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.","Apache-2.0","https:\u002F\u002Fgithub.com\u002FTinhAnhGitHub\u002Fdotfiles\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fworkspace\u002Fskill-creator\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FTinhAnhGitHub\u002Fdotfiles\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fworkspace\u002Fskill-creator\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":77,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":19},"01M79J2E55JTK0CP3KW3G3AKT5","book-to-skill","Converts books and documents (PDF, EPUB, DOCX, HTML, Markdown, plain text, RTF, MOBI\u002FAZW with Calibre) into structured agent skills, extracting frameworks, mental models, principles, techniques, and anti-patterns. Use when the user wants to study a document through GitHub Copilot CLI, Amp, Claude Code, or Hermes Agent, apply an author's frameworks while working, or build a reusable knowledge base from a file.","https:\u002F\u002Fgithub.com\u002FTinhAnhGitHub\u002Fdotfiles\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fworkspace\u002Fbook-to-skill\u002FLICENSE.md","https:\u002F\u002Fgithub.com\u002FTinhAnhGitHub\u002Fdotfiles\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fworkspace\u002Fbook-to-skill\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":68,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":19},"01M79HT43X9GXDJHRBBM90KYHZ","mongodb-search-and-ai","Guides MongoDB users through implementing and optimizing Atlas Search (full-text), Vector Search (semantic), and Hybrid Search solutions. Use this skill when users need to build search functionality for text-based queries (autocomplete, fuzzy matching, faceted search), semantic similarity (embeddings, RAG applications), or combined approaches. Also use when users need text containment, substring matching ('contains', 'includes', 'appears in'), case-insensitive or multi-field text search, or filtering across many fields with variable combinations. Provides workflows for selecting the right search type, creating indexes, constructing queries, and optimizing performance using the MongoDB MCP server.","https:\u002F\u002Fgithub.com\u002FTinhAnhGitHub\u002Fdotfiles\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fframework\u002Fmongodb\u002Fsearch-and-ai\u002FSKILL.md",[],[],{"skillNo":89,"name":90,"nameZh":6,"description":91,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":68,"licenseFileUrl":6,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":19},"01M79HSS371CGV85SC9QS0C5HS","mongodb-schema-design","MongoDB schema design patterns and anti-patterns. Use when designing data models, reviewing schemas, migrating from SQL, or troubleshooting performance issues caused by schema problems. Triggers on \"design schema\", \"embed vs reference\", \"MongoDB data model\", \"schema review\", \"unbounded arrays\", \"one-to-many\", \"tree structure\", \"16MB limit\", \"schema validation\", \"JSON Schema\", \"time series\", \"schema migration\", \"polymorphic\", \"TTL\", \"data lifecycle\", \"archive\", \"index explosion\", \"unnecessary indexes\", \"approximation pattern\", \"document versioning\".","https:\u002F\u002Fgithub.com\u002FTinhAnhGitHub\u002Fdotfiles\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fframework\u002Fmongodb\u002Fschema-design\u002FSKILL.md",[],[],{"skillNo":96,"name":97,"nameZh":6,"description":98,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":68,"licenseFileUrl":6,"sourceHtmlUrl":99,"categories":100,"keywords":101,"publishedAt":19},"01M79HSC2ZG7W2VG71TCEGF7WP","mongodb-query-optimizer","Help with MongoDB query optimization and indexing. Use only when the user asks for optimization or performance: \"How do I optimize this query?\", \"How do I index this?\", \"Why is this query slow?\", \"Can you fix my slow queries?\", \"What are the slow queries on my cluster?\", etc. Do not invoke for general MongoDB query writing unless user asks for performance or index help. Prefer indexing as optimization strategy. Use MongoDB MCP when available.","https:\u002F\u002Fgithub.com\u002FTinhAnhGitHub\u002Fdotfiles\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fframework\u002Fmongodb\u002Fquery-optimizer\u002FSKILL.md",[],[],{"skillNo":103,"name":104,"nameZh":6,"description":105,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":68,"licenseFileUrl":6,"sourceHtmlUrl":106,"categories":107,"keywords":108,"publishedAt":19},"01M79HS5FJY9V815ZW66WWZ4X5","mongodb-pymongo","Use for Python applications that use PyMongo 4.x or BSON: MongoClient or AsyncMongoClient, Database and Collection APIs, CRUD, cursors, aggregation, transactions, change streams, BSON\u002FExtended JSON\u002FObjectId\u002FUUID\u002Fdatetime handling, CodecOptions and custom codecs, indexes, Database.command(), Atlas Search APIs, driver monitoring, or Python logging. Invoke whenever implementing, reviewing, debugging, or migrating PyMongo or Motor code, even when the user only mentions a Python MongoDB client, `bson`, or `AsyncMongoClient`. For pool sizing and cross-driver connection tuning, also load `mongodb\u002Fconnection`; for query-plan\u002Findex performance, load `mongodb\u002Fquery-optimizer`; for Search or Vector Search solution design, load `mongodb\u002Fsearch-and-ai`.","https:\u002F\u002Fgithub.com\u002FTinhAnhGitHub\u002Fdotfiles\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fframework\u002Fmongodb\u002Fpymongo\u002FSKILL.md",[],[]]