From 9ea3268dfb1f1baa411c83f58397bac012d1cc3c Mon Sep 17 00:00:00 2001 From: Shuhan Si <234333961+2gg-bit@users.noreply.github.com> Date: Tue, 29 Sep 2026 13:30:47 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E6=89=A7=E8=A1=8C=20null=20=E5=8F=82?= =?UTF-8?q?=E6=95=B0=E7=9A=84=E7=B1=BB=E5=9E=8B=E5=92=8C=E6=9E=9A=E4=B8=BE?= =?UTF-8?q?=E6=A0=A1=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- nanobot/agent/tools/base.py | 4 ++++ tests/tools/test_tool_validation.py | 30 +++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/nanobot/agent/tools/base.py b/nanobot/agent/tools/base.py index e88e52ef1..4618af2e8 100644 --- a/nanobot/agent/tools/base.py +++ b/nanobot/agent/tools/base.py @@ -76,7 +76,11 @@ class Schema(ABC): t = Schema.resolve_json_schema_type(raw_type) if nullable and val is None: + if "enum" in schema and val not in schema["enum"]: + return [f"{label} must be one of {schema['enum']}"] return [] + if (raw_type == "null" or raw_type == ["null"]) and val is not None: + return [f"{label} should be null"] if isinstance(raw_type, list): types = [item for item in cast(list[Any], raw_type) if item != "null"] if len(types) > 1: diff --git a/tests/tools/test_tool_validation.py b/tests/tools/test_tool_validation.py index d3ff4cc78..0c2da1653 100644 --- a/tests/tools/test_tool_validation.py +++ b/tests/tools/test_tool_validation.py @@ -918,6 +918,36 @@ def test_resolve_type_union_with_null() -> None: assert Tool._resolve_type(["string", "null"]) == "string" +@pytest.mark.parametrize("raw_type", ["null", ["null"]]) +@pytest.mark.parametrize("value", ["", 0, False, [], {}]) +def test_null_only_schema_rejects_non_null_values(raw_type, value) -> None: + schema = {"type": raw_type} + assert Schema.validate_json_schema_value(value, schema, "value") == [ + "value should be null" + ] + assert Schema.validate_json_schema_value(None, schema) == [] + + +@pytest.mark.parametrize( + "schema", + [ + {"type": ["string", "null"], "enum": ["fast"]}, + {"type": "string", "nullable": True, "enum": ["fast"]}, + {"type": ["integer", "null"], "enum": [1]}, + ], +) +def test_nullable_schema_still_enforces_enum(schema) -> None: + assert Schema.validate_json_schema_value(None, schema, "mode") == [ + f"mode must be one of {schema['enum']}" + ] + assert Schema.validate_json_schema_value(None, {**schema, "enum": [None]}) == [] + + +def test_nullable_string_schema_enforces_enum() -> None: + assert StringSchema(nullable=True, enum=["fast"]).validate_value(None) + assert StringSchema(nullable=True, enum=["fast", None]).validate_value(None) == [] + + def test_resolve_type_only_null() -> None: """Union type ['null'] resolves to None (no non-null type).""" assert Tool._resolve_type(["null"]) is None