""" ALLI Phase 2 — Step 2.2: Node Standard v1 Contract Acceptance Tests Verifies the 5 acceptance criteria for Step 2.2: 1. Frontend and backend agree on the schema contract. 2. Existing 32 frontend schemas remain compatible and parse without error. 3. Settings, validation, code generation, and dependencies have explicit definitions. 4. Existing registered nodes continue to work and adhere to the contract. 5. Schema serialization, deserialization, and validation tests pass 100%. """ import json import re import pytest from pathlib import Path from language_core.node_schema import ( NodeDefinition, PortDefinition, ParameterDefinition, ParameterOption, ParameterType, NodeSettingsDefinition, NodeValidationDefinition, NodeCodegenDefinition, DocumentationMetadata, ExecutionHandlerDefinition, default_registry, check_type_compatibility, ) class TestStep22SchemaContractAgreement: """Criteria 1 & 3: Explicit definitions for settings, validation, codegen, dependencies.""" def test_node_definition_fields_and_defaults(self): node = NodeDefinition( type="custom.demo", label="Demo Node", category="Demo", description="Testing contract agreement", inputs=[PortDefinition(id="in_val", name="Input", type="int")], parameters=[ParameterDefinition(id="mode", name="Mode", type=ParameterType.STRING, default="fast")], outputs=[PortDefinition(id="out_val", name="Output", type="int")], ) # Canonical type and id alias assert node.type == "custom.demo" assert node.id == "custom.demo" assert node.version == "1.0.0" assert node.icon == "Activity" assert node.dependencies == [] assert node.settings is None assert node.validation is None assert node.codegen is None def test_node_settings_definition_fields(self): settings = NodeSettingsDefinition( timeout_seconds=10.0, retry_count=2, fallback_on_error=0, cache_policy="session", continue_on_error=True, execute_once=True, ) assert settings.timeout_seconds == 10.0 assert settings.retry_count == 2 assert settings.fallback_on_error == 0 assert settings.cache_policy == "session" assert settings.continue_on_error is True assert settings.execute_once is True def test_node_validation_definition_fields(self): val_rules = NodeValidationDefinition( required_parameters=["mode"], min_inputs=1, max_inputs=3, custom_rules=["RULE_NON_EMPTY"], ) assert val_rules.required_parameters == ["mode"] assert val_rules.min_inputs == 1 assert val_rules.max_inputs == 3 assert val_rules.custom_rules == ["RULE_NON_EMPTY"] def test_node_codegen_definition_fields(self): codegen = NodeCodegenDefinition( template="{result} = compute({x})", imports=["math", "sys"], requirements=["numpy>=1.24.0"], variable_prefix="calc", ) assert codegen.template == "{result} = compute({x})" assert codegen.imports == ["math", "sys"] assert codegen.requirements == ["numpy>=1.24.0"] assert codegen.variable_prefix == "calc" class TestStep22PydanticValidationIntegrity: """Criteria 5: Validation tests ensure zero silent failures and reject invalid schemas.""" def test_reject_duplicate_input_port_ids(self): with pytest.raises(ValueError, match="Duplicate input port IDs"): NodeDefinition( type="test.dup_in", label="Dup In", category="Test", description="Test duplicate input port", inputs=[ PortDefinition(id="x", name="X1", type="int"), PortDefinition(id="x", name="X2", type="int"), ], parameters=[], outputs=[], ) def test_reject_duplicate_output_port_ids(self): with pytest.raises(ValueError, match="Duplicate output port IDs"): NodeDefinition( type="test.dup_out", label="Dup Out", category="Test", description="Test duplicate output port", inputs=[], parameters=[], outputs=[ PortDefinition(id="res", name="Result 1", type="int"), PortDefinition(id="res", name="Result 2", type="int"), ], ) def test_reject_duplicate_parameter_ids(self): with pytest.raises(ValueError, match="Duplicate parameter IDs"): NodeDefinition( type="test.dup_param", label="Dup Param", category="Test", description="Test duplicate parameter", inputs=[], parameters=[ ParameterDefinition(id="rate", name="Rate 1", type=ParameterType.NUMBER, default=1.0), ParameterDefinition(id="rate", name="Rate 2", type=ParameterType.NUMBER, default=2.0), ], outputs=[], ) def test_reject_non_namespaced_node_type(self): with pytest.raises(ValueError, match="must be namespaced with at least one dot"): NodeDefinition( type="nodot", label="No Dot", category="Test", description="Invalid type without dot", inputs=[], parameters=[], outputs=[], ) def test_reject_mismatched_id_and_type(self): with pytest.raises(ValueError, match="must match node type"): NodeDefinition( id="other.id", type="test.mismatch", label="Mismatch", category="Test", description="Mismatched id and type", inputs=[], parameters=[], outputs=[], ) def test_reject_invalid_select_options_default(self): with pytest.raises(ValueError, match="not found in options"): ParameterDefinition( id="mode", name="Mode", type=ParameterType.SELECT, default="unknown_choice", options=[ ParameterOption(value="a", label="Choice A"), ParameterOption(value="b", label="Choice B"), ], ) def test_reject_numeric_bounds_violation_in_default(self): with pytest.raises(ValueError, match="is below minimum"): ParameterDefinition( id="count", name="Count", type=ParameterType.NUMBER, default=-5, min_value=0, max_value=100, ) class TestStep22SerializationRoundtrip: """Criteria 5: Full JSON serialization and deserialization roundtrip.""" def test_schema_model_dump_and_json_roundtrip(self): for node in default_registry.list_all(): # 1. model_dump dict d = node.model_dump() assert isinstance(d, dict) assert d["type"] == node.type assert d["id"] == node.type # 2. JSON serialize string json_str = json.dumps(d) assert isinstance(json_str, str) # 3. JSON deserialize back to NodeDefinition reloaded = NodeDefinition.model_validate(json.loads(json_str)) assert reloaded.type == node.type assert reloaded.id == node.type assert len(reloaded.inputs) == len(node.inputs) assert len(reloaded.parameters) == len(node.parameters) assert len(reloaded.outputs) == len(node.outputs) class TestStep22Existing32FrontendSchemasCompatibility: """Criteria 2: Preserves backward compatibility with existing 32 frontend schemas.""" def test_all_frontend_registry_types_loadable(self): frontend_registry_file = Path(r"d:\ALLI\alli_frontend\src\lib\schema\standard-node-registry.ts") assert frontend_registry_file.exists(), "Frontend standard-node-registry.ts must exist" content = frontend_registry_file.read_text(encoding="utf-8") types_found = re.findall(r'^\s*"([a-zA-Z0-9_\-\.]+)":\s*\{', content, re.MULTILINE) assert len(types_found) >= 32, f"Expected at least 32 frontend schema keys, found {len(types_found)}" # Every frontend type must have dot namespacing for t in types_found: assert "." in t, f"Frontend type '{t}' must contain a dot namespace" class TestStep22ExistingRegisteredNodesContinueToWork: """Criteria 4: Existing registered nodes work seamlessly with Node Standard v1.""" def test_math_sqrt_continues_to_execute(self): res = default_registry.execute("math.sqrt", {"x": 49.0}) assert res["result"] == 7.0 def test_core_variable_continues_to_execute(self): res = default_registry.execute("core.variable", {}, {"literal_value": "100", "var_type": "int"}) assert res["out_val"] == 100 def test_core_binary_op_continues_to_execute(self): res = default_registry.execute("core.binary_op", {"a": 15, "b": 25}, {"operator": "+"}) assert res["result"] == 40 def test_control_if_else_continues_to_execute(self): res = default_registry.execute("control.if_else", {"condition": True, "then_val": "OK", "else_val": "FAIL"}) assert res["result"] == "OK" assert res["branch_taken"] == "then" def test_io_print_continues_to_execute(self): res = default_registry.execute("io.print", {"value": "Phase 2 Verified"}, {"prefix": "[ALLI] "}) assert res["out"] == "Phase 2 Verified" assert res["printed_string"] == "[ALLI] Phase 2 Verified"