[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M792CS4WYKBTHYGMJMJ6KQ53":3,"skill-same:01M792CS4WYKBTHYGMJMJ6KQ53":61},{"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":38,"commitSha":39,"skillDirectory":40,"forksCount":41,"repositoryHtmlUrl":42,"repositoryHomepageUrl":6,"ownerHtmlUrl":43,"ownerBlogUrl":44,"ownerDescription":45,"updatedAt":46,"install":47,"resources":60},"01M792CS4WYKBTHYGMJMJ6KQ53","langchain-local-dev-loop",null,"Build a fast, deterministic local test loop for LangChain 1.0 \u002F LangGraph 1.0\n— FakeListChatModel fixtures, pytest config, VCR cassettes with key redaction,\nwarning-filter policy. Use when adding tests to a new chain, fixing a flaky\ntest, or making integration tests reproducible.\nTrigger with \"langchain pytest\", \"FakeListChatModel\", \"VCR langchain\",\n\"langchain test fixtures\", \"langchain integration test\".","jukeyman\u002Fjukeyman-skills","jukeyman","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F142960420?v=4","01M78FR4Y3DHMMCBCC0GXXNB3F","RICK JEFFERSON","01M78FR4Z8RVQRAD31Y5J7V6EB",1,"MIT","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fsaas-packs--langchain-py-pack--langchain-local-dev-loop\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: langchain-local-dev-loop\ndescription: |\n  Build a fast, deterministic local test loop for LangChain 1.0 \u002F LangGraph 1.0\n  — FakeListChatModel fixtures, pytest config, VCR cassettes with key redaction,\n  warning-filter policy. Use when adding tests to a new chain, fixing a flaky\n  test, or making integration tests reproducible.\n  Trigger with \"langchain pytest\", \"FakeListChatModel\", \"VCR langchain\",\n  \"langchain test fixtures\", \"langchain integration test\".\nallowed-tools: Read, Write, Edit, Bash(pytest:*), Bash(python:*), Bash(pip:*)\nversion: 2.0.0\nlicense: MIT\nauthor: Jeremy Longshore \u003Cjeremy@intentsolutions.io>\ntags: [saas, langchain, langgraph, python, langchain-1.0, testing, pytest, vcr]\ncompatible-with: claude-code, codex\n---\n\n# LangChain Local Dev Loop (Python)\n\n## Overview\n\nAn engineer writes the most natural assertion possible:\n\n```python\ndef test_summarize():\n    out = chain.invoke({\"text\": \"...\"})\n    assert out.content == \"expected summary\"\n```\n\nIt passes locally against Claude at `temperature=0`. It fails in CI on the third\nrun with a one-token delta in the output. That is P05: Anthropic's `temperature=0`\nis not greedy — it still samples. Tests against live Claude are not deterministic,\nperiod.\n\nSo the engineer swaps in `FakeListChatModel(responses=[\"expected summary\"])` and\nthe assertion passes. Then the downstream callback that logs cost blows up in CI\nwith `KeyError: 'token_usage'` — because `FakeListChatModel` does not emit\n`response_metadata[\"token_usage\"]` (P43). Production code reads that key, so\neither the fake has to synthesize it or the test has to skip the callback.\n\nMeanwhile, the first integration test under VCR records a cassette that ships\n`Authorization: Bearer sk-ant-api03-...` in the repo (P44). PR review catches it;\nthe reviewer revokes the key; the dev loop is hosed for an afternoon.\n\nAnd none of this matters if pytest cannot even collect the suite because\n`import langchain_community` emits a `DeprecationWarning` that `-W error` promotes\nto failure (P45).\n\nThis skill installs the four layers that make the whole loop fast and safe:\n`FakeListChatModel` \u002F `FakeListLLM` with a metadata-emitting subclass (fixes P43);\nVCR with `filter_headers` plus a pre-commit hook (fixes P44); pytest\n`filterwarnings` policy in `pyproject.toml` (fixes P45); and an env-var-gated\nintegration marker so the default `pytest` run never touches live APIs.\n\n**Speed targets:** unit tests with `FakeListChatModel` run in **\u003C 100ms** per\ntest; VCR-replayed integration tests run in **500ms – 2s** per test; live\nintegration tests (the `RUN_INTEGRATION=1` gate) run only in nightly or\nmanual workflows.\n\n**Pin:** `langchain-core 1.0.x`, `langgraph 1.0.x`, `pytest` current, `vcrpy`\ncurrent. Pain-catalog anchors: P05, P43, P44, P45.\n\n## Prerequisites\n\n- Python 3.10+\n- `pip install langchain-core>=1.0,\u003C2.0 langgraph>=1.0,\u003C2.0 pytest vcrpy pytest-recording`\n- For integration tests: at least one provider key (`ANTHROPIC_API_KEY`, etc.)\n- Project uses `pyproject.toml` (PEP 621) for pytest config\n\n## Instructions\n\n### Step 1 — Deterministic unit tests with `FakeListChatModel`\n\nUse `FakeListChatModel` from `langchain_core.language_models.fake` for chat\nchains and `FakeListLLM` for legacy completion LLMs. Responses cycle through\nthe list.\n\n```python\nfrom langchain_core.language_models.fake import FakeListChatModel\nfrom langchain_core.prompts import ChatPromptTemplate\n\ndef test_classifier_picks_positive():\n    fake = FakeListChatModel(responses=[\"positive\"])\n    prompt = ChatPromptTemplate.from_messages([(\"user\", \"Classify: {text}\")])\n    chain = prompt | fake\n    out = chain.invoke({\"text\": \"I love it\"})\n    assert out.content == \"positive\"\n```\n\nThis is deterministic, runs in single-digit milliseconds, and has zero provider\ndependency. Use it for every chain assertion that does not specifically require\nreal model behavior.\n\n### Step 2 — Subclass `FakeListChatModel` to emit `response_metadata` (P43 fix)\n\nThe stock fake emits no `response_metadata[\"token_usage\"]`. If your chain has a\ncallback that records cost, the callback crashes under the fake. Subclass and\nsynthesize the metadata instead of mocking around the callback:\n\n```python\nfrom langchain_core.language_models.fake import FakeListChatModel\nfrom langchain_core.outputs import ChatGeneration, ChatResult\nfrom langchain_core.messages import AIMessage\n\nclass FakeChatWithUsage(FakeListChatModel):\n    \"\"\"FakeListChatModel that emits response_metadata['token_usage'] so\n    downstream callbacks reading token usage do not crash under test.\"\"\"\n\n    def _generate(self, messages, stop=None, run_manager=None, **kwargs):\n        response = self.responses[self.i % len(self.responses)]\n        self.i += 1\n        message = AIMessage(\n            content=response,\n            response_metadata={\n                \"token_usage\": {\n                    \"input_tokens\": 10,\n                    \"output_tokens\": len(response.split()),\n                    \"total_tokens\": 10 + len(response.split()),\n                },\n                \"model_name\": \"fake-chat\",\n            },\n            usage_metadata={\n                \"input_tokens\": 10,\n                \"output_tokens\": len(response.split()),\n                \"total_tokens\": 10 + len(response.split()),\n            },\n        )\n        return ChatResult(generations=[ChatGeneration(message=message)])\n```\n\nUse `FakeChatWithUsage` whenever a chain's observability \u002F cost path is in the\nassertion surface. See [Fake Model Fixtures](references\u002Ffake-model-fixtures.md)\nfor agent, retriever, and embedder fakes.\n\n### Step 3 — pytest fixtures that wire the fake into chains\n\nPut fixtures in `tests\u002Fconftest.py` so they are shared across the suite:\n\n```python\n# tests\u002Fconftest.py\nimport pytest\nfrom langchain_core.prompts import ChatPromptTemplate\nfrom tests.fakes import FakeChatWithUsage\n\n@pytest.fixture\ndef fake_chat():\n    \"\"\"Reusable fake chat model. Override responses per-test via\n    monkeypatch.setattr(fake_chat, 'responses', [...]).\"\"\"\n    return FakeChatWithUsage(responses=[\"ok\"])\n\n@pytest.fixture\ndef summarize_chain(fake_chat):\n    prompt = ChatPromptTemplate.from_messages([\n        (\"system\", \"Summarize the user's text in one line.\"),\n        (\"user\", \"{text}\"),\n    ])\n    return prompt | fake_chat\n```\n\nPer-test response override:\n\n```python\ndef test_summary_shape(summarize_chain, fake_chat):\n    fake_chat.responses = [\"short summary\"]\n    out = summarize_chain.invoke({\"text\": \"long input\"})\n    assert out.content == \"short summary\"\n```\n\n### Step 4 — VCR cassettes for integration tests with key redaction (P44 fix)\n\nUnit tests should never touch the network. Integration tests do, exactly once —\nto record a cassette — and every subsequent run replays from the cassette file.\n`vcrpy` records headers by default, which means `Authorization: Bearer sk-...`\nlands in the fixture unless you filter it.\n\nConfigure VCR in `tests\u002Fconftest.py`:\n\n```python\n# tests\u002Fconftest.py (continued)\nimport pytest\n\n@pytest.fixture(scope=\"module\")\ndef vcr_config():\n    return {\n        \"filter_headers\": [\n            \"authorization\",\n            \"x-api-key\",\n            \"anthropic-version\",\n            \"openai-organization\",\n            \"cookie\",\n        ],\n        \"filter_query_parameters\": [\"api_key\"],\n        # Block accidental re-recording in CI:\n        \"record_mode\": \"none\",\n    }\n```\n\nUse `pytest-recording`:\n\n```python\nimport pytest\n\n@pytest.mark.vcr  # cassette at tests\u002Fcassettes\u002F\u003Ctest_name>.yaml\n@pytest.mark.integration\ndef test_live_claude_short_answer():\n    from langchain_anthropic import ChatAnthropic\n    chat = ChatAnthropic(model=\"claude-sonnet-4-6\", temperature=0, timeout=30)\n    out = chat.invoke(\"Say 'ok' and nothing else.\")\n    assert \"ok\" in out.content.lower()\n```\n\nTo record (once, locally, with a real key): `pytest --record-mode=once tests\u002F`.\nEvery other run replays — cassettes are committed, real API is never hit again.\n\n**Pre-commit hook to block key leaks:**\n\n```bash\n# .git\u002Fhooks\u002Fpre-commit or .pre-commit-config.yaml entry\n#!\u002Fusr\u002Fbin\u002Fenv bash\nset -e\nif git diff --cached --name-only | grep -q '^tests\u002Fcassettes\u002F'; then\n    if git diff --cached -U0 -- 'tests\u002Fcassettes\u002F' | \\\n       grep -E '(sk-ant-[a-zA-Z0-9_-]+|sk-[a-zA-Z0-9]{20,}|Bearer\\s+[a-zA-Z0-9_-]{20,})'; then\n        echo \"ERROR: API key pattern found in staged cassette.\" >&2\n        exit 1\n    fi\nfi\n```\n\nSee [VCR Cassette Hygiene](references\u002Fvcr-cassette-hygiene.md) for the full\npre-commit config, record-new-episodes flow, shared-cassette patterns, and the\nPR review checklist.\n\n### Step 5 — Pytest warnings + markers in `pyproject.toml` (P45 fix)\n\n`langchain_community` and some provider SDKs emit `DeprecationWarning` at import\ntime. If the suite runs `-W error`, collection fails before any test does. Set\nthe policy once in `pyproject.toml`:\n\n```toml\n[tool.pytest.ini_options]\nminversion = \"8.0\"\ntestpaths = [\"tests\"]\naddopts = [\n    \"-ra\",\n    \"--strict-markers\",\n    \"--strict-config\",\n    \"-W\", \"error\",\n]\nmarkers = [\n    \"integration: hits real APIs or replays VCR cassettes (set RUN_INTEGRATION=1)\",\n    \"slow: takes > 1s per test\",\n    \"smoke: minimal healthcheck run in CI\",\n]\nfilterwarnings = [\n    \"error\",\n    \"ignore::DeprecationWarning:langchain_community.*\",\n    \"ignore::DeprecationWarning:pydantic.*\",\n    \"ignore::PendingDeprecationWarning:langchain_core.*\",\n]\n```\n\nSee [Pytest Config](references\u002Fpytest-config.md) for the full skeleton\nincluding coverage config and parallel execution notes.\n\n### Step 6 — Integration-test gating via env var\n\nDefault `pytest` must never hit real APIs. Gate on `RUN_INTEGRATION=1`:\n\n```python\n# tests\u002Fconftest.py (continued)\nimport os\nimport pytest\n\ndef pytest_collection_modifyitems(config, items):\n    if os.getenv(\"RUN_INTEGRATION\") == \"1\":\n        return\n    skip_integration = pytest.mark.skip(reason=\"set RUN_INTEGRATION=1 to run\")\n    for item in items:\n        if \"integration\" in item.keywords:\n            item.add_marker(skip_integration)\n```\n\nCI default: `pytest` (unit only). Nightly \u002F manual: `RUN_INTEGRATION=1 pytest -m integration`.\n\n### Step 7 — LangGraph tests: per-test `thread_id` + state assertions\n\nLangGraph state is scoped to a `thread_id`. Tests that share a `thread_id` leak\nstate between each other. Give every test a fresh `thread_id` and a fresh\n`MemorySaver`:\n\n```python\nfrom langgraph.checkpoint.memory import MemorySaver\nimport uuid, pytest\n\n@pytest.fixture\ndef graph_config():\n    return {\"configurable\": {\"thread_id\": str(uuid.uuid4())}}\n\n@pytest.fixture\ndef checkpointed_graph(fake_chat):\n    from my_app.graphs import build_graph\n    return build_graph(fake_chat).compile(checkpointer=MemorySaver())\n\ndef test_node_emits_plan(checkpointed_graph, graph_config, fake_chat):\n    fake_chat.responses = [\"step 1\\nstep 2\\nstep 3\"]\n    result = checkpointed_graph.invoke({\"goal\": \"deploy\"}, graph_config)\n    # Assert state shape per node, not just the final output:\n    assert result[\"plan\"] == [\"step 1\", \"step 2\", \"step 3\"]\n    # Time-travel: inspect every checkpoint for debugging\n    history = list(checkpointed_graph.get_state_history(graph_config))\n    assert history[-1].values == {\"goal\": \"deploy\"}  # initial state\n```\n\nSubgraph isolation testing cross-references `langchain-langgraph-subgraphs`\n(pain P21 — parent cannot read child state unless the key is in the parent\nschema). See [LangGraph Test Patterns](references\u002Flanggraph-test-patterns.md)\nfor the subgraph-shared-state test recipe.\n\n## Output\n\n- `tests\u002Ffakes.py` with `FakeChatWithUsage` subclass that emits `response_metadata`\n- `tests\u002Fconftest.py` with fake-model fixtures, VCR config, and `RUN_INTEGRATION` gate\n- `pyproject.toml` `[tool.pytest.ini_options]` block with markers and `filterwarnings`\n- `tests\u002Fcassettes\u002F` committed with filtered headers (no `Authorization` \u002F `x-api-key`)\n- Pre-commit hook grepping cassettes for `sk-` \u002F `sk-ant-` \u002F `Bearer` patterns\n- LangGraph tests with per-test `thread_id` and `MemorySaver` — no cross-test leakage\n\n## Test-type matrix\n\n| Type | Model | Network | Target speed | Determinism | Use case |\n|------|-------|---------|--------------|-------------|----------|\n| Unit | `FakeListChatModel` \u002F `FakeChatWithUsage` | none | **\u003C 100ms** | total | Chain shape, parser, routing logic |\n| Integration (VCR) | real model, replayed cassette | replay only | **500ms – 2s** | total (once recorded) | End-to-end chain behavior, provider-specific edge cases |\n| Integration (live) | real model | live API | 2s – 30s | probabilistic (P05) | Nightly smoke, recording new cassettes, provider regression |\n| Smoke | real model, minimal prompt | live API | \u003C 5s | probabilistic | CI healthcheck — 1 test per provider, gated on `RUN_INTEGRATION=1` |\n| Load | real model | live API | minutes | probabilistic | Throughput \u002F retry-storm reproduction, never in PR CI |\n\n## Error Handling\n\n| Error | Cause | Fix |\n|-------|-------|-----|\n| `AssertionError` on content despite `temperature=0` | Anthropic `temperature=0` still samples (P05) | Switch to `FakeListChatModel` or VCR replay |\n| `KeyError: 'token_usage'` under fake model | `FakeListChatModel` emits no `response_metadata` (P43) | Use `FakeChatWithUsage` subclass from Step 2 |\n| PR review flags `Authorization: Bearer sk-...` in cassette | VCR recorded headers by default (P44) | Set `filter_headers` before recording; re-record; add pre-commit grep hook |\n| `pytest` fails at collection with `DeprecationWarning` | `-W error` + SDK import warnings (P45) | Add `filterwarnings = [\"ignore::DeprecationWarning:langchain_community.*\"]` |\n| `vcr.errors.CannotOverwriteExistingCassetteException` | Test changed request shape but cassette is stale | `pytest --record-mode=new_episodes` locally, inspect diff, commit |\n| LangGraph test pollutes next test's state | Shared `thread_id` + shared `MemorySaver` | Per-test `thread_id=uuid.uuid4()`, per-test `MemorySaver()` |\n\n## Examples\n\n### A flaky chain assertion, fixed in three commits\n\n1. **Commit 1 — failing test** uses real `ChatAnthropic`, passes locally, fails\n   1-in-5 in CI at `temperature=0` (P05).\n2. **Commit 2 — swap to fake model** uses `FakeListChatModel`, passes\n   deterministically, but the cost-logging callback crashes (P43).\n3. **Commit 3 — fake with metadata** uses `FakeChatWithUsage`, the callback\n   reads `response_metadata[\"token_usage\"]` cleanly, the test is green and\n   runs in 40ms.\n\nSee [Fake Model Fixtures](references\u002Ffake-model-fixtures.md) for the full\nworked example including agent and retriever fakes.\n\n### Recording a cassette without leaking a key\n\n```bash\n# 1. Ensure conftest.py has filter_headers configured FIRST\n# 2. Record with real key present in the environment\nANTHROPIC_API_KEY=sk-ant-... pytest --record-mode=once tests\u002Fintegration\u002Ftest_summarize.py\n# 3. Verify no leak\ngrep -E 'sk-|Bearer' tests\u002Fcassettes\u002F*.yaml && echo \"LEAK\" || echo \"clean\"\n# 4. Commit cassettes\u002F — pre-commit hook runs the same grep as a hard gate\ngit add tests\u002Fcassettes\u002F && git commit -m \"test: record summarize cassette\"\n```\n\nSee [VCR Cassette Hygiene](references\u002Fvcr-cassette-hygiene.md) for\nrecord-new-episodes mode, rerecord-on-mismatch, and the PR review checklist.\n\n### LangGraph time-travel debugging on a failing test\n\nWhen a graph test fails mid-graph, `get_state_history(config)` returns every\ncheckpoint — you can replay from any point by passing its `config.checkpoint_id`\nback into `graph.invoke`. See\n[LangGraph Test Patterns](references\u002Flanggraph-test-patterns.md) for the full\ntime-travel debugging recipe and the subgraph-shared-state test pattern\n(cross-ref `langchain-langgraph-subgraphs` \u002F pain L30).\n\n## Resources\n\n- [LangChain Python: testing guide](https:\u002F\u002Fpython.langchain.com\u002Fdocs\u002Fcontributing\u002Ftesting\u002F)\n- [`FakeListChatModel` API](https:\u002F\u002Fpython.langchain.com\u002Fapi_reference\u002Fcore\u002Flanguage_models\u002Flangchain_core.language_models.fake.FakeListChatModel.html)\n- [`vcrpy` documentation](https:\u002F\u002Fvcrpy.readthedocs.io\u002F)\n- [`pytest-recording`](https:\u002F\u002Fpytest-vcr.readthedocs.io\u002F)\n- [LangGraph `MemorySaver` + `get_state_history`](https:\u002F\u002Flangchain-ai.github.io\u002Flanggraph\u002Fhow-tos\u002Ftime-travel\u002F)\n- [Pytest `filterwarnings`](https:\u002F\u002Fdocs.pytest.org\u002Fen\u002Fstable\u002Fhow-to\u002Fcapture-warnings.html)\n- Pack pain catalog: `docs\u002Fpain-catalog.md` (entries P05, P43, P44, P45)\n","# LangChain Local Dev Loop (Python)\n\n## Overview\n\nAn engineer writes the most natural assertion possible:\n\n```python\ndef test_summarize():\n    out = chain.invoke({\"text\": \"...\"})\n    assert out.content == \"expected summary\"\n```\n\nIt passes locally against Claude at `temperature=0`. It fails in CI on the third\nrun with a one-token delta in the output. That is P05: Anthropic's `temperature=0`\nis not greedy — it still samples. Tests against live Claude are not deterministic,\nperiod.\n\nSo the engineer swaps in `FakeListChatModel(responses=[\"expected summary\"])` and\nthe assertion passes. Then the downstream callback that logs cost blows up in CI\nwith `KeyError: 'token_usage'` — because `FakeListChatModel` does not emit\n`response_metadata[\"token_usage\"]` (P43). Production code reads that key, so\neither the fake has to synthesize it or the test has to skip the callback.\n\nMeanwhile, the first integration test under VCR records a cassette that ships\n`Authorization: Bearer sk-ant-api03-...` in the repo (P44). PR review catches it;\nthe reviewer revokes the key; the dev loop is hosed for an afternoon.\n\nAnd none of this matters if pytest cannot even collect the suite because\n`import langchain_community` emits a `DeprecationWarning` that `-W error` promotes\nto failure (P45).\n\nThis skill installs the four layers that make the whole loop fast and safe:\n`FakeListChatModel` \u002F `FakeListLLM` with a metadata-emitting subclass (fixes P43);\nVCR with `filter_headers` plus a pre-commit hook (fixes P44); pytest\n`filterwarnings` policy in `pyproject.toml` (fixes P45); and an env-var-gated\nintegration marker so the default `pytest` run never touches live APIs.\n\n**Speed targets:** unit tests with `FakeListChatModel` run in **\u003C 100ms** per\ntest; VCR-replayed integration tests run in **500ms – 2s** per test; live\nintegration tests (the `RUN_INTEGRATION=1` gate) run only in nightly or\nmanual workflows.\n\n**Pin:** `langchain-core 1.0.x`, `langgraph 1.0.x`, `pytest` current, `vcrpy`\ncurrent. Pain-catalog anchors: P05, P43, P44, P45.\n\n## Prerequisites\n\n- Python 3.10+\n- `pip install langchain-core>=1.0,\u003C2.0 langgraph>=1.0,\u003C2.0 pytest vcrpy pytest-recording`\n- For integration tests: at least one provider key (`ANTHROPIC_API_KEY`, etc.)\n- Project uses `pyproject.toml` (PEP 621) for pytest config\n\n## Instructions\n\n### Step 1 — Deterministic unit tests with `FakeListChatModel`\n\nUse `FakeListChatModel` from `langchain_core.language_models.fake` for chat\nchains and `FakeListLLM` for legacy completion LLMs. Responses cycle through\nthe list.\n\n```python\nfrom langchain_core.language_models.fake import FakeListChatModel\nfrom langchain_core.prompts import ChatPromptTemplate\n\ndef test_classifier_picks_positive():\n    fake = FakeListChatModel(responses=[\"positive\"])\n    prompt = ChatPromptTemplate.from_messages([(\"user\", \"Classify: {text}\")])\n    chain = prompt | fake\n    out = chain.invoke({\"text\": \"I love it\"})\n    assert out.content == \"positive\"\n```\n\nThis is deterministic, runs in single-digit milliseconds, and has zero provider\ndependency. Use it for every chain assertion that does not specifically require\nreal model behavior.\n\n### Step 2 — Subclass `FakeListChatModel` to emit `response_metadata` (P43 fix)\n\nThe stock fake emits no `response_metadata[\"token_usage\"]`. If your chain has a\ncallback that records cost, the callback crashes under the fake. Subclass and\nsynthesize the metadata instead of mocking around the callback:\n\n```python\nfrom langchain_core.language_models.fake import FakeListChatModel\nfrom langchain_core.outputs import ChatGeneration, ChatResult\nfrom langchain_core.messages import AIMessage\n\nclass FakeChatWithUsage(FakeListChatModel):\n    \"\"\"FakeListChatModel that emits response_metadata['token_usage'] so\n    downstream callbacks reading token usage do not crash under test.\"\"\"\n\n    def _generate(self, messages, stop=None, run_manager=None, **kwargs):\n        response = self.responses[self.i % len(self.responses)]\n        self.i += 1\n        message = AIMessage(\n            content=response,\n            response_metadata={\n                \"token_usage\": {\n                    \"input_tokens\": 10,\n                    \"output_tokens\": len(response.split()),\n                    \"total_tokens\": 10 + len(response.split()),\n                },\n                \"model_name\": \"fake-chat\",\n            },\n            usage_metadata={\n                \"input_tokens\": 10,\n                \"output_tokens\": len(response.split()),\n                \"total_tokens\": 10 + len(response.split()),\n            },\n        )\n        return ChatResult(generations=[ChatGeneration(message=message)])\n```\n\nUse `FakeChatWithUsage` whenever a chain's observability \u002F cost path is in the\nassertion surface. See [Fake Model Fixtures](references\u002Ffake-model-fixtures.md)\nfor agent, retriever, and embedder fakes.\n\n### Step 3 — pytest fixtures that wire the fake into chains\n\nPut fixtures in `tests\u002Fconftest.py` so they are shared across the suite:\n\n```python\n# tests\u002Fconftest.py\nimport pytest\nfrom langchain_core.prompts import ChatPromptTemplate\nfrom tests.fakes import FakeChatWithUsage\n\n@pytest.fixture\ndef fake_chat():\n    \"\"\"Reusable fake chat model. Override responses per-test via\n    monkeypatch.setattr(fake_chat, 'responses', [...]).\"\"\"\n    return FakeChatWithUsage(responses=[\"ok\"])\n\n@pytest.fixture\ndef summarize_chain(fake_chat):\n    prompt = ChatPromptTemplate.from_messages([\n        (\"system\", \"Summarize the user's text in one line.\"),\n        (\"user\", \"{text}\"),\n    ])\n    return prompt | fake_chat\n```\n\nPer-test response override:\n\n```python\ndef test_summary_shape(summarize_chain, fake_chat):\n    fake_chat.responses = [\"short summary\"]\n    out = summarize_chain.invoke({\"text\": \"long input\"})\n    assert out.content == \"short summary\"\n```\n\n### Step 4 — VCR cassettes for integration tests with key redaction (P44 fix)\n\nUnit tests should never touch the network. Integration tests do, exactly once —\nto record a cassette — and every subsequent run replays from the cassette file.\n`vcrpy` records headers by default, which means `Authorization: Bearer sk-...`\nlands in the fixture unless you filter it.\n\nConfigure VCR in `tests\u002Fconftest.py`:\n\n```python\n# tests\u002Fconftest.py (continued)\nimport pytest\n\n@pytest.fixture(scope=\"module\")\ndef vcr_config():\n    return {\n        \"filter_headers\": [\n            \"authorization\",\n            \"x-api-key\",\n            \"anthropic-version\",\n            \"openai-organization\",\n            \"cookie\",\n        ],\n        \"filter_query_parameters\": [\"api_key\"],\n        # Block accidental re-recording in CI:\n        \"record_mode\": \"none\",\n    }\n```\n\nUse `pytest-recording`:\n\n```python\nimport pytest\n\n@pytest.mark.vcr  # cassette at tests\u002Fcassettes\u002F\u003Ctest_name>.yaml\n@pytest.mark.integration\ndef test_live_claude_short_answer():\n    from langchain_anthropic import ChatAnthropic\n    chat = ChatAnthropic(model=\"claude-sonnet-4-6\", temperature=0, timeout=30)\n    out = chat.invoke(\"Say 'ok' and nothing else.\")\n    assert \"ok\" in out.content.lower()\n```\n\nTo record (once, locally, with a real key): `pytest --record-mode=once tests\u002F`.\nEvery other run replays — cassettes are committed, real API is never hit again.\n\n**Pre-commit hook to block key leaks:**\n\n```bash\n# .git\u002Fhooks\u002Fpre-commit or .pre-commit-config.yaml entry\n#!\u002Fusr\u002Fbin\u002Fenv bash\nset -e\nif git diff --cached --name-only | grep -q '^tests\u002Fcassettes\u002F'; then\n    if git diff --cached -U0 -- 'tests\u002Fcassettes\u002F' | \\\n       grep -E '(sk-ant-[a-zA-Z0-9_-]+|sk-[a-zA-Z0-9]{20,}|Bearer\\s+[a-zA-Z0-9_-]{20,})'; then\n        echo \"ERROR: API key pattern found in staged cassette.\" >&2\n        exit 1\n    fi\nfi\n```\n\nSee [VCR Cassette Hygiene](references\u002Fvcr-cassette-hygiene.md) for the full\npre-commit config, record-new-episodes flow, shared-cassette patterns, and the\nPR review checklist.\n\n### Step 5 — Pytest warnings + markers in `pyproject.toml` (P45 fix)\n\n`langchain_community` and some provider SDKs emit `DeprecationWarning` at import\ntime. If the suite runs `-W error`, collection fails before any test does. Set\nthe policy once in `pyproject.toml`:\n\n```toml\n[tool.pytest.ini_options]\nminversion = \"8.0\"\ntestpaths = [\"tests\"]\naddopts = [\n    \"-ra\",\n    \"--strict-markers\",\n    \"--strict-config\",\n    \"-W\", \"error\",\n]\nmarkers = [\n    \"integration: hits real APIs or replays VCR cassettes (set RUN_INTEGRATION=1)\",\n    \"slow: takes > 1s per test\",\n    \"smoke: minimal healthcheck run in CI\",\n]\nfilterwarnings = [\n    \"error\",\n    \"ignore::DeprecationWarning:langchain_community.*\",\n    \"ignore::DeprecationWarning:pydantic.*\",\n    \"ignore::PendingDeprecationWarning:langchain_core.*\",\n]\n```\n\nSee [Pytest Config](references\u002Fpytest-config.md) for the full skeleton\nincluding coverage config and parallel execution notes.\n\n### Step 6 — Integration-test gating via env var\n\nDefault `pytest` must never hit real APIs. Gate on `RUN_INTEGRATION=1`:\n\n```python\n# tests\u002Fconftest.py (continued)\nimport os\nimport pytest\n\ndef pytest_collection_modifyitems(config, items):\n    if os.getenv(\"RUN_INTEGRATION\") == \"1\":\n        return\n    skip_integration = pytest.mark.skip(reason=\"set RUN_INTEGRATION=1 to run\")\n    for item in items:\n        if \"integration\" in item.keywords:\n            item.add_marker(skip_integration)\n```\n\nCI default: `pytest` (unit only). Nightly \u002F manual: `RUN_INTEGRATION=1 pytest -m integration`.\n\n### Step 7 — LangGraph tests: per-test `thread_id` + state assertions\n\nLangGraph state is scoped to a `thread_id`. Tests that share a `thread_id` leak\nstate between each other. Give every test a fresh `thread_id` and a fresh\n`MemorySaver`:\n\n```python\nfrom langgraph.checkpoint.memory import MemorySaver\nimport uuid, pytest\n\n@pytest.fixture\ndef graph_config():\n    return {\"configurable\": {\"thread_id\": str(uuid.uuid4())}}\n\n@pytest.fixture\ndef checkpointed_graph(fake_chat):\n    from my_app.graphs import build_graph\n    return build_graph(fake_chat).compile(checkpointer=MemorySaver())\n\ndef test_node_emits_plan(checkpointed_graph, graph_config, fake_chat):\n    fake_chat.responses = [\"step 1\\nstep 2\\nstep 3\"]\n    result = checkpointed_graph.invoke({\"goal\": \"deploy\"}, graph_config)\n    # Assert state shape per node, not just the final output:\n    assert result[\"plan\"] == [\"step 1\", \"step 2\", \"step 3\"]\n    # Time-travel: inspect every checkpoint for debugging\n    history = list(checkpointed_graph.get_state_history(graph_config))\n    assert history[-1].values == {\"goal\": \"deploy\"}  # initial state\n```\n\nSubgraph isolation testing cross-references `langchain-langgraph-subgraphs`\n(pain P21 — parent cannot read child state unless the key is in the parent\nschema). See [LangGraph Test Patterns](references\u002Flanggraph-test-patterns.md)\nfor the subgraph-shared-state test recipe.\n\n## Output\n\n- `tests\u002Ffakes.py` with `FakeChatWithUsage` subclass that emits `response_metadata`\n- `tests\u002Fconftest.py` with fake-model fixtures, VCR config, and `RUN_INTEGRATION` gate\n- `pyproject.toml` `[tool.pytest.ini_options]` block with markers and `filterwarnings`\n- `tests\u002Fcassettes\u002F` committed with filtered headers (no `Authorization` \u002F `x-api-key`)\n- Pre-commit hook grepping cassettes for `sk-` \u002F `sk-ant-` \u002F `Bearer` patterns\n- LangGraph tests with per-test `thread_id` and `MemorySaver` — no cross-test leakage\n\n## Test-type matrix\n\n| Type | Model | Network | Target speed | Determinism | Use case |\n|------|-------|---------|--------------|-------------|----------|\n| Unit | `FakeListChatModel` \u002F `FakeChatWithUsage` | none | **\u003C 100ms** | total | Chain shape, parser, routing logic |\n| Integration (VCR) | real model, replayed cassette | replay only | **500ms – 2s** | total (once recorded) | End-to-end chain behavior, provider-specific edge cases |\n| Integration (live) | real model | live API | 2s – 30s | probabilistic (P05) | Nightly smoke, recording new cassettes, provider regression |\n| Smoke | real model, minimal prompt | live API | \u003C 5s | probabilistic | CI healthcheck — 1 test per provider, gated on `RUN_INTEGRATION=1` |\n| Load | real model | live API | minutes | probabilistic | Throughput \u002F retry-storm reproduction, never in PR CI |\n\n## Error Handling\n\n| Error | Cause | Fix |\n|-------|-------|-----|\n| `AssertionError` on content despite `temperature=0` | Anthropic `temperature=0` still samples (P05) | Switch to `FakeListChatModel` or VCR replay |\n| `KeyError: 'token_usage'` under fake model | `FakeListChatModel` emits no `response_metadata` (P43) | Use `FakeChatWithUsage` subclass from Step 2 |\n| PR review flags `Authorization: Bearer sk-...` in cassette | VCR recorded headers by default (P44) | Set `filter_headers` before recording; re-record; add pre-commit grep hook |\n| `pytest` fails at collection with `DeprecationWarning` | `-W error` + SDK import warnings (P45) | Add `filterwarnings = [\"ignore::DeprecationWarning:langchain_community.*\"]` |\n| `vcr.errors.CannotOverwriteExistingCassetteException` | Test changed request shape but cassette is stale | `pytest --record-mode=new_episodes` locally, inspect diff, commit |\n| LangGraph test pollutes next test's state | Shared `thread_id` + shared `MemorySaver` | Per-test `thread_id=uuid.uuid4()`, per-test `MemorySaver()` |\n\n## Examples\n\n### A flaky chain assertion, fixed in three commits\n\n1. **Commit 1 — failing test** uses real `ChatAnthropic`, passes locally, fails\n   1-in-5 in CI at `temperature=0` (P05).\n2. **Commit 2 — swap to fake model** uses `FakeListChatModel`, passes\n   deterministically, but the cost-logging callback crashes (P43).\n3. **Commit 3 — fake with metadata** uses `FakeChatWithUsage`, the callback\n   reads `response_metadata[\"token_usage\"]` cleanly, the test is green and\n   runs in 40ms.\n\nSee [Fake Model Fixtures](references\u002Ffake-model-fixtures.md) for the full\nworked example including agent and retriever fakes.\n\n### Recording a cassette without leaking a key\n\n```bash\n# 1. Ensure conftest.py has filter_headers configured FIRST\n# 2. Record with real key present in the environment\nANTHROPIC_API_KEY=sk-ant-... pytest --record-mode=once tests\u002Fintegration\u002Ftest_summarize.py\n# 3. Verify no leak\ngrep -E 'sk-|Bearer' tests\u002Fcassettes\u002F*.yaml && echo \"LEAK\" || echo \"clean\"\n# 4. Commit cassettes\u002F — pre-commit hook runs the same grep as a hard gate\ngit add tests\u002Fcassettes\u002F && git commit -m \"test: record summarize cassette\"\n```\n\nSee [VCR Cassette Hygiene](references\u002Fvcr-cassette-hygiene.md) for\nrecord-new-episodes mode, rerecord-on-mismatch, and the PR review checklist.\n\n### LangGraph time-travel debugging on a failing test\n\nWhen a graph test fails mid-graph, `get_state_history(config)` returns every\ncheckpoint — you can replay from any point by passing its `config.checkpoint_id`\nback into `graph.invoke`. See\n[LangGraph Test Patterns](references\u002Flanggraph-test-patterns.md) for the full\ntime-travel debugging recipe and the subgraph-shared-state test pattern\n(cross-ref `langchain-langgraph-subgraphs` \u002F pain L30).\n\n## Resources\n\n- [LangChain Python: testing guide](https:\u002F\u002Fpython.langchain.com\u002Fdocs\u002Fcontributing\u002Ftesting\u002F)\n- [`FakeListChatModel` API](https:\u002F\u002Fpython.langchain.com\u002Fapi_reference\u002Fcore\u002Flanguage_models\u002Flangchain_core.language_models.fake.FakeListChatModel.html)\n- [`vcrpy` documentation](https:\u002F\u002Fvcrpy.readthedocs.io\u002F)\n- [`pytest-recording`](https:\u002F\u002Fpytest-vcr.readthedocs.io\u002F)\n- [LangGraph `MemorySaver` + `get_state_history`](https:\u002F\u002Flangchain-ai.github.io\u002Flanggraph\u002Fhow-tos\u002Ftime-travel\u002F)\n- [Pytest `filterwarnings`](https:\u002F\u002Fdocs.pytest.org\u002Fen\u002Fstable\u002Fhow-to\u002Fcapture-warnings.html)\n- Pack pain catalog: `docs\u002Fpain-catalog.md` (entries P05, P43, P44, P45)\n",{"name":5,"tags":24,"author":33,"license":15,"version":34,"description":35,"allowed-tools":36,"compatible-with":37},[25,26,27,28,29,30,31,32],"saas","langchain","langgraph","python","langchain-1.0","testing","pytest","vcr","Jeremy Longshore \u003Cjeremy@intentsolutions.io>","2.0.0","Build a fast, deterministic local test loop for LangChain 1.0 \u002F LangGraph 1.0\n— FakeListChatModel fixtures, pytest config, VCR cassettes with key redaction,\nwarning-filter policy. Use when adding tests to a new chain, fixing a flaky\ntest, or making integration tests reproducible.\nTrigger with \"langchain pytest\", \"FakeListChatModel\", \"VCR langchain\",\n\"langchain test fixtures\", \"langchain integration test\".\n","Read, Write, Edit, Bash(pytest:*), Bash(python:*), Bash(pip:*)","claude-code, codex","main","99825ad3f3bcc6597ddcc7294a14e6e922f2b67b","skills\u002Fsaas-packs--langchain-py-pack--langchain-local-dev-loop",0,"https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills","https:\u002F\u002Fgithub.com\u002Fjukeyman","https:\u002F\u002FRJBUSINESSSOLUTIONS.ORG","Credit and Finance Expert | Developer\r\n\r\nI'm Rick Jefferson, a seasoned credit and finance expert with over a decade of experience in financial literacy,","2026-07-13 07:03:29",{"source":8,"skillName":5,"commands":48,"prompt":58,"zipAvailable":59},[49,52,55],{"tool":50,"command":51},"npx","npx skills add jukeyman\u002Fjukeyman-skills --skill langchain-local-dev-loop",{"tool":53,"command":54},"bunx","bunx skills add jukeyman\u002Fjukeyman-skills --skill langchain-local-dev-loop",{"tool":56,"command":57},"pnpm","pnpm dlx skills add jukeyman\u002Fjukeyman-skills --skill langchain-local-dev-loop","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fsaas-packs--langchain-py-pack--langchain-local-dev-loop\u002FSKILL.md",true,[],[62,69,76,83,90,98],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":19},"01M79ANS2SM329NEP5ZCX106RR","zustand-store-creator","Create zustand store creator operations. Auto-activating skill for Frontend Development.\nTriggers on: zustand store creator, zustand store creator\nPart of the Frontend Development skill category. Use when working with zustand store creator functionality. Trigger with phrases like \"zustand store creator\", \"zustand creator\", \"zustand\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzustand-store-creator\u002FSKILL.md",[],[],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":19},"01M79AMZKP4YDEZ7EHG1Y7PP74","zero-trust-config-helper","Configure with zero trust config helper operations. Auto-activating skill for Security Advanced.\nTriggers on: zero trust config helper, zero trust config helper\nPart of the Security Advanced skill category. Use when configuring systems or services. Trigger with phrases like \"zero trust config helper\", \"zero helper\", \"zero\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzero-trust-config-helper\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M79AMJSBCEJQNBTYNAHYN5HM","zapier-integration-helper","Assist with zapier integration helper operations. Auto-activating skill for Business Automation.\nTriggers on: zapier integration helper, zapier integration helper\nPart of the Business Automation skill category. Use when working with APIs or building integrations. Trigger with phrases like \"zapier integration helper\", \"zapier helper\", \"zapier\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzapier-integration-helper\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M79AHJZGVMARS13VFQYRR1MP","yaml-config-validator","Validate yaml config validator operations. Auto-activating skill for DevOps Basics.\nTriggers on: yaml config validator, yaml config validator\nPart of the DevOps Basics skill category. Use when configuring systems or services. Trigger with phrases like \"yaml config validator\", \"yaml validator\", \"yaml\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fyaml-config-validator\u002FSKILL.md",[],[],{"skillNo":91,"name":92,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":94,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":19},"01M79AHGDZRN0020RDQSQDPAM8","xvary-stock-research","Thesis-driven equity analysis from public SEC EDGAR and market data; \u002Fanalyze, \u002Fscore, \u002Fcompare workflows with bundled Python tools (Claude Code, Cursor, Codex).","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxvary-stock-research\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxvary-stock-research\u002FSKILL.md",[],[],{"skillNo":99,"name":100,"nameZh":6,"description":101,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":19},"01M79AHCYJ9FV9RMHQ24HDRN33","xss-vulnerability-scanner","Scan xss vulnerability scanner operations. Auto-activating skill for Security Fundamentals.\nTriggers on: xss vulnerability scanner, xss vulnerability scanner\nPart of the Security Fundamentals skill category. Use when working with xss vulnerability scanner functionality. Trigger with phrases like \"xss vulnerability scanner\", \"xss scanner\", \"xss\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxss-vulnerability-scanner\u002FSKILL.md",[],[]]