From 173d50327be627134170c72f7f9175e1e13b752c Mon Sep 17 00:00:00 2001 From: Daniel Peng Date: Mon, 31 Aug 2026 17:26:45 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix=20signed=20integer=20list=20?= =?UTF-8?q?parsing?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/utils/str_utils.py | 17 ++++++++++++++++- test/backend/utils/test_str_utils.py | 24 +++++++++++++++++++++++- 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/backend/utils/str_utils.py b/backend/utils/str_utils.py index dc7887595a..0dc1f1abb5 100644 --- a/backend/utils/str_utils.py +++ b/backend/utils/str_utils.py @@ -1,6 +1,9 @@ +import logging import re from typing import List, Optional +logger = logging.getLogger(__name__) + def remove_think_blocks(text: str) -> str: """Remove ... blocks including inner content.""" @@ -36,4 +39,16 @@ def convert_string_to_list(items_str: Optional[str]) -> List[int]: """ if not items_str or items_str.strip() == "": return [] - return [int(item.strip()) for item in items_str.split(",") if item.strip().isdigit()] + + items = [] + for raw_item in items_str.split(","): + item = raw_item.strip() + if not item: + continue + try: + items.append(int(item)) + except ValueError: + logger.warning( + "convert_string_to_list: dropping non-integer entry %r", item + ) + return items diff --git a/test/backend/utils/test_str_utils.py b/test/backend/utils/test_str_utils.py index ab9b9f25f6..5e57b842b4 100644 --- a/test/backend/utils/test_str_utils.py +++ b/test/backend/utils/test_str_utils.py @@ -1,5 +1,10 @@ import pytest -from backend.utils.str_utils import remove_think_blocks, convert_list_to_string + +from backend.utils.str_utils import ( + convert_list_to_string, + convert_string_to_list, + remove_think_blocks, +) class TestStrUtils: @@ -89,6 +94,23 @@ def test_convert_list_to_string_zero_and_negative(self): result = convert_list_to_string([0, -1, 5]) assert result == "0,-1,5" + def test_convert_string_to_list_round_trips_signed_integers(self): + """Serialized signed integers should round-trip without data loss""" + serialized = convert_list_to_string([0, -1, 5]) + + assert convert_string_to_list(serialized) == [0, -1, 5] + + def test_convert_string_to_list_accepts_whitespace_and_explicit_signs(self): + """Whitespace and explicit integer signs should be accepted""" + assert convert_string_to_list(" -2, +3, 0 ") == [-2, 3, 0] + + def test_convert_string_to_list_warns_and_keeps_valid_entries(self, caplog): + """Malformed entries should be reported without discarding valid values""" + result = convert_string_to_list("invalid, 1, , -2") + + assert result == [1, -2] + assert "dropping non-integer entry 'invalid'" in caplog.text + if __name__ == "__main__": pytest.main()