Run typing checks on our test files
While working on changes to haystack-experimental (https://github.com/deepset-ai/haystack-experimental/pull/430) I wanted to ensure that the protocol I was developing was working as expected with the respective implementations.
I realized though that we never actually test whether our implementations satisfy our protocols since we don't do any type checks on actual test-like code.
Therefore, I think it would be a good idea if we add type checking to our test code in our repos so we can better catch these issues. This will be quite a bit work to get our tests fully compliant but perhaps we could do it in a piece-meal approach where we only turn on type checking in a small part of tests and grow from there.
Components
- [x]
test/components/audio/ - [x]
test/components/builders/ - [x]
test/components/caching/ - [ ]
test/components/classifiers/ - [ ]
test/components/connectors/ - [x]
test/components/converters/ - [x]
test/components/embedders/ - [ ]
test/components/evaluators/ - [x]
test/components/extractors/ - [x]
test/components/fetchers/ - [x]
test/components/generators/ - [x]
test/components/joiners/ - [ ]
test/components/preprocessors/ - [x]
test/components/query/ - [x]
test/components/rankers/ - [ ]
test/components/readers/ - [x]
test/components/retrievers/ - [ ]
test/components/routers/ - [x]
test/components/samplers/ - [ ]
test/components/tools/ - [x]
test/components/validators/ - [ ]
test/components/websearch/ - [x]
test/components/writers/
Document Stores
- [x]
test/document_stores/
Agents
- [ ]
test/components/agents/
Other
- [x]
test/core/ - [x]
test/dataclasses/ - [x]
test/evaluation/ - [x]
test/fuzz/ - [ ]
test/hooks/ - [x]
test/human_in_the_loop/ - [x]
test/marshal/ - [x]
test/skill_stores/ - [x]
test/testing/ - [ ]
test/token_counters/ - [x]
test/tools/(top-level, distinct fromtest/components/tools/) - [x]
test/tracing/ - [x]
test/utils/
Hi, is this still relevant? Should I take it?
I took the next piece of this, test/components/embedders/. Most of the errors there were tests passing a wrong type on purpose to check the raised TypeError, plus a few missing annotations. Opening a PR now.
I can take the next small increment for this issue: add test/components/caching/ to the existing mypy target, fix only the type errors needed in its two CacheChecker test modules, and run the focused mypy/pytest checks before opening a PR. I checked that the existing recent contribution covered test/components/embedders/; I will keep this scope disjoint.
Working on adding typing checks for \ est/components/writers/!
#12318 covers test/components/joiners/.
The checklist above has drifted from the types allowlist in pyproject.toml, which makes it easy to pick something that is already done:
Already in the allowlist on main, but unchecked here: test/core/, test/dataclasses/, test/document_stores/, test/evaluation/, test/marshal/, test/testing/, test/tools/, test/tracing/, test/utils/, test/components/caching/, test/components/generators/.
Listed here but no longer in the repo: test/components/audio/, classifiers/, connectors/, readers/, tools/, websearch/, and test/human_in_the_loop/ (now test/hooks/human_in_the_loop, already in the allowlist).
That leaves 19 directories actually open: agents, builders, converters, evaluators, extractors, fetchers, joiners (this PR), preprocessors, query, rankers, retrievers, routers, samplers and validators under test/components/, plus test/fuzz/, test/skill_stores/, test/token_counters/, test/hooks/compaction/ and test/hooks/tool_result_offloading/.
I can take the next disjoint increment: est/components/agents/. I verified that it is not yet in the current ypes allowlist and found no open or closed PR claiming that directory. I will first run the directory through the repository's mypy configuration, keep changes limited to test typing fixes plus the allowlist entry, and run the focused agent tests and formatting before opening a PR.
Baseline result: type-checking the full est/components/agents/ directory currently reports 136 errors across six files, so treating it as one increment would be too broad and review-heavy. I am narrowing this contribution to est/components/agents/test_state_class.py, which has three related generic-inference errors in one test. I will add that file to the mypy target, make the minimal type annotation needed, and validate the file plus the focused tests. The remaining agent test files stay unclaimed.
I can take the next disjoint increment: test/components/extractors/.
It's not in the types allowlist in pyproject.toml on main, and I found no open or closed PR claiming it... the increments currently in flight are test/components/rankers/ (#12319) and test/components/agents/test_state_class.py (#12327), both disjoint from this.
Baseline is 6 errors across 3 files, so it works as a single reviewable increment rather than needing to be narrowed further:
test_regex_text_extractor.py: a missing annotation, and a deliberate wrong-type call underpytest.raises(TypeError)test_llm_metadata_extractor.py: a deliberate missing-argument call, plus"ChatGenerator" has no attribute "to_dict"intest_from_dict_openaiimage/test_llm_document_content_extractor.py: a deliberate missing-argument call, andlen()on astr | None
The to_dict one is the protocol-vs-implementation gap this issue was opened for, so I narrowed it with isinstance rather than an ignore, that also pins that from_dict rebuilt an OpenAIChatGenerator.
Changes stay limited to test typing fixes plus the allowlist entry. Opening the PR shortly.
-Anmol :)
I can take test/components/routers/ next. It is not in the types allowlist on main, and there is no open or closed PR covering it.
Baseline: 63 errors across 4 test files, 43 of them in test_conditional_router.py.
The bulk are arg-type, from route lists being inferred as list[dict[str, object]] where list[Route] is expected. Since Route is a TypedDict, annotating those literals is worth more than silencing the error: mypy then checks each route against the actual schema (condition, output, output_name, output_type) instead of accepting any dict.
The rest are union-attr where the metadata router tests reach for .data or .content on a Document | ByteStream, plus a few attr-defined on the __haystack_input__ / __haystack_output__ attributes the @component decorator adds at runtime.
Planning to keep it to one PR, same shape as #12318 and #12319.
I can take the next disjoint increment: test/components/converters/test_utils.py. It is not in the current types allowlist, and I found no open or closed PR or issue comment claiming this file. The repository mypy baseline reports two deliberate invalid-input calls in this file; I will keep the change to the allowlist entry plus minimal typing annotations for those calls, then run the focused mypy/pytest checks and formatting before opening a PR.
Opened #12433 covering test/components/samplers/, picking a directory that doesn't overlap the increments already in flight (#12343 has extractors/).
Baseline there was 2 errors, both the same one:
test/components/samplers/test_top_p.py:68: error: Value of type variable "SupportsRichComparisonT" of "sorted" cannot be "float | None" [type-var]
test/components/samplers/test_top_p.py:87: error: same
The directory only holds __init__.py and test_top_p.py, so it's fully covered.
Still unclaimed as far as I can tell, if anyone is looking for a next increment: evaluators/, fetchers/ (4 errors), preprocessors/, retrievers/, hooks/budget/, and hooks/tool_result_offloading/ (4 errors). builders/ has 25 and is probably worth splitting.
[!NOTE] AI-assisted (Claude Code); verified before posting.
I can take the next disjoint increment: test/components/fetchers/.
Current main still omits it from the types target, and the directory contains one test module with four current mypy errors. I’ll keep this scoped to the minimal typing fixes in test/components/fetchers/test_link_content_fetcher.py plus the pyproject.toml target entry, then run the focused mypy check, focused unit tests, and formatting before opening a PR.
I’ll also disclose the AI-assisted implementation and review in the PR.
I can take the next disjoint increment: test/components/evaluators/.
It is not in the current types target, and it doesn't overlap the increments already in flight: #12435 has fetchers/, #12343 has extractors/, #12433 has samplers/, and @Gout999 claimed converters/test_utils.py.
Current baseline there is 19 mypy errors across 5 of the 10 test modules:
- 6
var-annotatedon empty list literals intest_document_recall.pyandtest_document_ndcg.py, which just need an annotation. - 11 in
test_llm_evaluator.pyandtest_sas_evaluator.pythat come from deliberate invalid-input calls insidepytest.raisesblocks, so those get narrow# type: ignore[...]comments in the same style as #12394. - 3
attr-definedon__haystack_output__, which the@componentdecorator adds at runtime.
I'll keep this scoped to the minimal typing fixes plus the types target entry in pyproject.toml, with no change to what any test asserts.
I can take the next disjoint increment: test/components/builders/.
It is not in the current types target on main, and no open or closed PR or comment covers it. The increments in flight are extractors/ (#12343), samplers/ (#12433) and fetchers/ (#12435), so this doesn't overlap any of them.
Baseline is 25 errors across 2 of the 3 test modules:
- 12
attr-definedon__haystack_input__/__haystack_output__, which the@componentdecorator attaches at runtime. - 8
index/union-attrfrom readingbuilder.template[0].text, wheretemplateis typedlist[ChatMessage] | str | None. Those get narrowed with an assert rather than silenced. - 1
list-itemon a deliberate mixed-type template inside a validation test, so that one gets a narrow# type: ignore[list-item]. - 2
no-untyped-deffor missing return annotations.
Scoped to the minimal typing fixes plus the types target entry, with no change to what any test asserts.
Note for whoever picks the next one: every increment edits the same single types = "..." line in pyproject.toml, so whichever lands first leaves the others conflicting. #12433 and #12435 are both showing conflicts right now and just need a rebase of that one line.
I can take the next disjoint increment: test/components/retrievers/.
It is not in the current types target on main, and no open or closed PR or comment covers it. It also doesn't overlap fetchers/ (#12435), the only increment still in flight.
Baseline is 78 errors across 11 of the 16 test modules, concentrated in three files:
test_auto_merging_retriever.py/_async.py(20 each) — mostlycall-overloadfrom adocsvariable that is first thedictreturned byHierarchicalDocumentSplitter.runand then reassigned to a retriever result, so mypy can't keep one type for it. Fixed by giving the two values separate names.test_multi_retriever.py(18) —no-untyped-defandassignment.- The remaining 8 files have 1-7 errors each:
type-varonsortedoverfloat | None,method-assignon monkeypatchedto_dict, and ano-redefon a re-annotated local.
Scoped to the minimal typing fixes plus the types target entry, with no change to what any test asserts.
I can take test/components/extractors/ next. It doesn't overlap fetchers/ (#12435), the only other increment in flight.
One thing worth flagging: this directory is already clean. mypy test/components/extractors/ reports Success: no issues found in 5 source files against current main, but the path was never added to the types target, so CI isn't actually checking it — any typing regression introduced there today would go unnoticed.
So this increment is a one-line change to pyproject.toml, with no source edits needed. Happy to fold it into someone else's PR instead if that's tidier; it seemed worth closing the gap either way.
I can take the next disjoint increment: test/components/preprocessors/.
It is not in the current types target on main, and no open or closed PR or comment covers it — fetchers/ (#12435) and retrievers/ (#12481) are the only increments in flight, and neither overlaps.
Baseline is 265 errors across 9 of the 13 files, but that number is misleading. 206 of them are in test_recursive_splitter.py alone, and they all cascade from one pattern repeated seven times, where the dict returned by run() is rebound to the list it holds:
doc_chunks = splitter.run([doc])
doc_chunks = doc_chunks["documents"]
Giving the two values separate names drops that file to 26 and the directory to 85 — in line with the recent increments.
Nine open PRs add tests to these files, but all of them are pure additions; a three-way merge against each produces zero conflicts, so this shouldn't step on any of them.
Opened #12504.
Taking test/hooks/budget/ — the smallest of the test/hooks/ gaps. The types target currently covers only test/hooks/human_in_the_loop, so budget/, compaction/, tool_result_offloading/ and the three test/hooks/*.py root files are all still unchecked.
Baseline is 3 errors in test_hooks.py, and neither group is a blanket-annotation case:
KeepIterating, the inline stub passed as anon_exithook, is missing theto_dict/from_dictmembers theHookprotocol requires (list-itemat L106). Implementing them viadefault_to_dict/default_from_dictmatches theLifecycleHookstubs #12681 just added intest/components/agents/test_agent_hooks.py.- the two
agent.chat_generator.run = MagicMock(...)lines aremethod-assign. Replacing a bound method on a mock generator is the intended pattern here, so those get a narrow# type: ignore[method-assign]rather than a restructure.
No overlap with compaction/, tool_result_offloading/ or the agents/ / converters/ remainders — happy to take another of those next if nobody else has.
Taking the three test/hooks/ root modules next — test_from_function.py, test_invocation.py, test_utils.py — as a follow-up to #12710 (test/hooks/budget/).
Baseline is 56 errors, but 44 of them come from a single cause: six inline stub hooks (RecordingHook, ThreadRecordingHook, AsyncRecordingHook, LifecycleSpy, WarmOnlyHook, PlainHook) are missing the to_dict / from_dict members the Hook protocol requires, so every list they appear in fails list-item. Implementing the pair via default_to_dict / default_from_dict — the shape #12681 used for LifecycleHook — clears all 44.
The rest: a handful of hook dictionaries inferred as dict[str, ...] where the callee wants HookPoint keys, fixed with an explicit annotation; and one .function read off a Hook, narrowed with isinstance rather than suppressed.
Five suppressions remain, all in TestFunctionHookConstruction, where the test deliberately passes a wrong callable to assert FunctionHook rejects it — there the type error is the thing under test.
Still not touching compaction/ or tool_result_offloading/; those are the larger remaining test/hooks/ gaps and I'd rather land these two first.
Taking test/hooks/tool_result_offloading/.
Opened #12720 with the minimal typing fixes plus the types target entry in pyproject.toml:
- Added
test/hooks/tool_result_offloading/to thetypesscript line inpyproject.toml. - In
test/hooks/tool_result_offloading/test_policies.py: addedisinstance(restored, OffloadOverChars)assertion to narrow the restored policy before accessing.threshold. - In
test/hooks/tool_result_offloading/test_hooks.py:- Updated
TextOnlyToolResultStore.writeparametercontenttostr | bytesto satisfyToolResultStoreprotocol under LSP. - Added explicit type annotation for
content: list[TextContent | ImageContent | FileContent]in test cases. - Added narrow
# type: ignore[method-assign]and# type: ignore[attr-defined]for mock generator setup.
- Updated
Passed all 40 unit tests, hatch run test:types (508 source files), and hatch run fmt-check locally.