diff --git a/haystack/components/preprocessors/text_cleaner.py b/haystack/components/preprocessors/text_cleaner.py index 39372d8d0f6..d77021678ae 100644 --- a/haystack/components/preprocessors/text_cleaner.py +++ b/haystack/components/preprocessors/text_cleaner.py @@ -84,7 +84,11 @@ def run(self, texts: list[str]) -> dict[str, Any]: :param texts: List of strings to clean. :returns: A dictionary with the following key: - `texts`: the cleaned list of strings. + :raises TypeError: + If `texts` is not a list or any element is not a string. """ + if not isinstance(texts, list) or not all(isinstance(text, str) for text in texts): + raise TypeError("`texts` must be a list of strings.") if self._regex: texts = [self._regex.sub("", text) for text in texts] diff --git a/releasenotes/notes/fix-text-cleaner-none-texts-d3a91c47e8b206f5.yaml b/releasenotes/notes/fix-text-cleaner-none-texts-d3a91c47e8b206f5.yaml new file mode 100644 index 00000000000..34808f12de0 --- /dev/null +++ b/releasenotes/notes/fix-text-cleaner-none-texts-d3a91c47e8b206f5.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + ``TextCleaner.run`` now raises a clear ``TypeError`` when ``texts`` is not a list or any element is not a ``str``, + instead of failing later or producing unexpected results. diff --git a/test/components/preprocessors/test_text_cleaner.py b/test/components/preprocessors/test_text_cleaner.py index 0d9e9ae079e..f71e088d7c8 100644 --- a/test/components/preprocessors/test_text_cleaner.py +++ b/test/components/preprocessors/test_text_cleaner.py @@ -2,6 +2,8 @@ # # SPDX-License-Identifier: Apache-2.0 +import pytest + from haystack import Pipeline from haystack.components.preprocessors import TextCleaner @@ -31,6 +33,16 @@ def test_run_with_empty_inputs(): assert result["texts"] == [] +def test_run_rejects_invalid_inputs(): + cleaner = TextCleaner() + + with pytest.raises(TypeError): + cleaner.run(texts=["Hello, World!", None, 42, ""]) # type: ignore[list-item] + + with pytest.raises(TypeError): + cleaner.run(texts=15) # type: ignore[arg-type] + + def test_run_with_regex(): cleaner = TextCleaner(remove_regexps=[r"\d+"]) result = cleaner.run(texts=["Open123 Source", "HaystackAI"])