Build AI methods with your coding agent, then run them anywhere: as an MCP for chatbots, as a webapp for people, or via API for your software.
Refactor _parse_pipe_spec_from_json to use parse_pipe_spec for improved output handling and backward compatibility. Add comprehensive unit tests for parse_pipe_spec and pipe_spec_to_toml to ensure correct behavior across various pipe types and scenarios.
Louis Choquela1f9f5306421
diff --git a/pipelex/builder/operations/pipe_ops.py b/pipelex/builder/operations/pipe_ops.pyindex efdc614b9..df03ad0be 100644--- a/pipelex/builder/operations/pipe_ops.py+++ b/pipelex/builder/operations/pipe_ops.py@@ -86,10 +86,15 @@ def parse_pipe_spec(pipe_type: str, spec_data: dict[str, Any]) -> PipeSpec:else:spec_data.pop("expression")- # Accept output as dict with "type" key → extract the type string+ # Accept output as dict → extract the concept string+ # Agents sometimes structure the output like inputs (as a dict).+ # Handle {"type": "ConceptName"} and single-item dicts like {"result": "Text"}.if "output" in spec_data and isinstance(spec_data["output"], dict):- if "type" in spec_data["output"]:- spec_data["output"] = spec_data["output"]["type"]+ output_dict: dict[str, Any] = spec_data["output"]+ if "type" in output_dict:+ spec_data["output"] = output_dict["type"]+ elif len(output_dict) == 1:+ spec_data["output"] = next(iter(output_dict.values()))return spec_class.model_validate(spec_data)diff --git a/pipelex/cli/agent_cli/commands/pipe_cmd.py b/pipelex/cli/agent_cli/commands/pipe_cmd.pyindex 2e72d2d5f..2fb9dc4ef 100644--- a/pipelex/cli/agent_cli/commands/pipe_cmd.py+++ b/pipelex/cli/agent_cli/commands/pipe_cmd.py@@ -13,6 +13,7 @@ import tomlkitimport typerfrom pydantic import ValidationError+from pipelex.builder.operations.pipe_ops import parse_pipe_specfrom pipelex.builder.pipe.pipe_batch_spec import PipeBatchSpecfrom pipelex.builder.pipe.pipe_compose_spec import PipeComposeSpecfrom pipelex.builder.pipe.pipe_condition_spec import PipeConditionSpec@@ -23,7 +24,6 @@ from pipelex.builder.pipe.pipe_llm_spec import PipeLLMSpecfrom pipelex.builder.pipe.pipe_parallel_spec import PipeParallelSpecfrom pipelex.builder.pipe.pipe_sequence_spec import PipeSequenceSpecfrom pipelex.builder.pipe.pipe_spec import PipeSpec-from pipelex.builder.pipe.pipe_spec_map import pipe_type_to_spec_classfrom pipelex.cli.agent_cli.commands.agent_output import agent_errorfrom pipelex.core.pipes.pipe_blueprint import PipeTypefrom pipelex.language.toml_string_utils import format_toml_string@@ -158,65 +158,9 @@ def _add_type_specific_fields(pipe_spec: PipeSpec, pipe_table: tomlkit.TOMLDocumdef _parse_pipe_spec_from_json(pipe_type: str, spec_data: dict[str, Any]) -> PipeSpec:"""Parse and validate a PipeSpec from JSON data.- Args:- pipe_type: The type of pipe (e.g., "PipeLLM", "PipeSequence").- spec_data: Raw JSON data for the pipe spec.-- Returns:- Validated PipeSpec instance of the correct type.-- Raises:- ValueError: If the pipe type is invalid.- ValidationError: If validation fails.+ Thin wrapper around parse_pipe_spec from pipe_ops for backward compatibility."""- if pipe_type not in pipe_type_to_spec_class:- valid_types = list(pipe_type_to_spec_class.keys())- msg = f"Invalid pipe type '{pipe_type}'. Must be one of: {valid_types}"- raise ValueError(msg)-- spec_class = pipe_type_to_spec_class[pipe_type]-- # Add type to spec_data if not present- spec_data["type"] = pipe_type-- # Accept common aliases for "pipe_code"- for alias in ("code", "the_pipe_code", "name"):- if alias in spec_data:- if "pipe_code" not in spec_data:- spec_data["pipe_code"] = spec_data.pop(alias)- else:- spec_data.pop(alias)-- # Handle steps/branches conversion - need to convert pipe to pipe_code- if "steps" in spec_data:- converted_steps = []- for step in spec_data["steps"]:- if "pipe" in step and "pipe_code" not in step:- step["pipe_code"] = step.pop("pipe")- converted_steps.append(step)- spec_data["steps"] = converted_steps-- if "branches" in spec_data:- converted_branches = []- for branch in spec_data["branches"]:- if "pipe" in branch and "pipe_code" not in branch:- branch["pipe_code"] = branch.pop("pipe")- converted_branches.append(branch)- spec_data["branches"] = converted_branches-- # Handle expression -> jinja2_expression_template for PipeCondition- if pipe_type == "PipeCondition" and "expression" in spec_data:- if "jinja2_expression_template" not in spec_data:- spec_data["jinja2_expression_template"] = spec_data.pop("expression")- else:- spec_data.pop("expression")-- # Accept output as dict with "type" key → extract the type string- if "output" in spec_data and isinstance(spec_data["output"], dict):- if "type" in spec_data["output"]:- spec_data["output"] = spec_data["output"]["type"]-- return spec_class.model_validate(spec_data)+ return parse_pipe_spec(pipe_type, spec_data)def pipe_cmd(diff --git a/tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py b/tests/unit/pipelex/builder/operations/test_parse_pipe_spec.pynew file mode 100644index 000000000..8a1b51153--- /dev/null+++ b/tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py@@ -0,0 +1,270 @@+"""Unit tests for parse_pipe_spec from pipelex.builder.operations.pipe_ops."""++from __future__ import annotations++from typing import Any, ClassVar++import pytest+from pydantic import ValidationError++from pipelex.builder.operations.pipe_ops import parse_pipe_spec+from pipelex.builder.pipe.pipe_batch_spec import PipeBatchSpec+from pipelex.builder.pipe.pipe_condition_spec import PipeConditionSpec+from pipelex.builder.pipe.pipe_extract_spec import PipeExtractSpec+from pipelex.builder.pipe.pipe_func_spec import PipeFuncSpec+from pipelex.builder.pipe.pipe_img_gen_spec import PipeImgGenSpec+from pipelex.builder.pipe.pipe_llm_spec import PipeLLMSpec+from pipelex.builder.pipe.pipe_parallel_spec import PipeParallelSpec+from pipelex.builder.pipe.pipe_search_spec import PipeSearchSpec+from pipelex.builder.pipe.pipe_sequence_spec import PipeSequenceSpec+++class _BaseLLM:+ SPEC: ClassVar[dict[str, Any]] = {+ "pipe_code": "test_pipe",+ "description": "Test LLM pipe",+ "model": "$writing-creative",+ "inputs": {"text": "Text"},+ "output": "Text",+ "prompt": "Write about @text",+ }+++class TestParsePipeSpec:+ """Comprehensive tests for parse_pipe_spec: validation, aliases, tolerance, and dispatch."""++ # -- invalid pipe type ------------------------------------------------++ def test_unknown_type_raises(self) -> None:+ with pytest.raises(ValueError, match="Invalid pipe type"):+ parse_pipe_spec("PipeNonExistent", {"pipe_code": "x", "description": "x"})++ def test_error_lists_valid_types(self) -> None:+ with pytest.raises(ValueError, match="PipeLLM"):+ parse_pipe_spec("PipeBogus", {"pipe_code": "x", "description": "x"})++ # -- pipe_code aliases ------------------------------------------------++ def test_canonical_pipe_code(self) -> None:+ result = parse_pipe_spec("PipeLLM", {**_BaseLLM.SPEC})+ assert result.pipe_code == "test_pipe"++ @pytest.mark.parametrize(+ ("alias", "value"),+ [+ ("the_pipe_code", "via_the_pipe_code"),+ ("code", "via_code"),+ ("name", "via_name"),+ ("pipe_name", "via_pipe_name"),+ ],+ )+ def test_pipe_code_alias_accepted(self, alias: str, value: str) -> None:+ spec = {key: val for key, val in _BaseLLM.SPEC.items() if key != "pipe_code"}+ spec[alias] = value+ result = parse_pipe_spec("PipeLLM", spec)+ assert result.pipe_code == value++ def test_canonical_pipe_code_takes_precedence_over_alias(self) -> None:+ """When pipe_code is present, aliases are ignored and cleaned up."""+ spec = {**_BaseLLM.SPEC, "code": "alias_value", "name": "another_alias"}+ result = parse_pipe_spec("PipeLLM", spec)+ assert result.pipe_code == "test_pipe"++ def test_first_alias_wins_when_no_canonical(self) -> None:+ """When multiple aliases are present without pipe_code, iteration order wins (the_pipe_code first)."""+ spec = {key: val for key, val in _BaseLLM.SPEC.items() if key != "pipe_code"}+ spec["code"] = "second"+ spec["the_pipe_code"] = "first"+ spec["name"] = "third"+ result = parse_pipe_spec("PipeLLM", spec)+ assert result.pipe_code == "first"++ # -- output dict tolerance --------------------------------------------++ def test_output_as_string(self) -> None:+ result = parse_pipe_spec("PipeLLM", {**_BaseLLM.SPEC, "output": "Article"})+ assert result.output == "Article"++ def test_output_dict_with_type_key(self) -> None:+ result = parse_pipe_spec("PipeLLM", {**_BaseLLM.SPEC, "output": {"type": "Article"}})+ assert result.output == "Article"++ def test_output_single_item_dict(self) -> None:+ """A single-item dict is unambiguous — extract the value."""+ result = parse_pipe_spec("PipeLLM", {**_BaseLLM.SPEC, "output": {"result": "Article"}})+ assert result.output == "Article"++ def test_output_multi_item_dict_raises(self) -> None:+ """A multi-item dict is ambiguous — validation fails."""+ with pytest.raises(ValidationError):+ parse_pipe_spec("PipeLLM", {**_BaseLLM.SPEC, "output": {"a": "Text", "b": "Image"}})++ def test_output_type_key_takes_precedence_in_dict(self) -> None:+ """When 'type' key is present in output dict, it wins even if other keys exist."""+ result = parse_pipe_spec("PipeLLM", {**_BaseLLM.SPEC, "output": {"type": "Article", "extra": "ignored"}})+ assert result.output == "Article"++ # -- steps/branches 'pipe' → 'pipe_code' alias -----------------------++ def test_sequence_steps_pipe_alias(self) -> None:+ spec: dict[str, Any] = {+ "pipe_code": "my_seq",+ "description": "A sequence",+ "inputs": {"doc": "Document"},+ "output": "Text",+ "steps": [+ {"pipe": "step_one", "result": "intermediate"},+ {"pipe": "step_two", "result": "final"},+ ],+ }+ result = parse_pipe_spec("PipeSequence", spec)+ assert isinstance(result, PipeSequenceSpec)+ assert result.steps[0].pipe_code == "step_one"+ assert result.steps[1].pipe_code == "step_two"++ def test_sequence_steps_canonical_pipe_code(self) -> None:+ spec: dict[str, Any] = {+ "pipe_code": "my_seq",+ "description": "A sequence",+ "inputs": {"doc": "Document"},+ "output": "Text",+ "steps": [{"pipe_code": "step_one", "result": "intermediate"}],+ }+ result = parse_pipe_spec("PipeSequence", spec)+ assert isinstance(result, PipeSequenceSpec)+ assert result.steps[0].pipe_code == "step_one"++ def test_parallel_branches_pipe_alias(self) -> None:+ spec: dict[str, Any] = {+ "pipe_code": "my_par",+ "description": "Parallel branches",+ "inputs": {"doc": "Document"},+ "output": "Text",+ "add_each_output": True,+ "branches": [+ {"pipe": "branch_a", "result": "result_a"},+ {"pipe": "branch_b", "result": "result_b"},+ ],+ }+ result = parse_pipe_spec("PipeParallel", spec)+ assert isinstance(result, PipeParallelSpec)+ assert result.branches[0].pipe_code == "branch_a"+ assert result.branches[1].pipe_code == "branch_b"++ # -- PipeCondition expression alias -----------------------------------++ _BASE_CONDITION: ClassVar[dict[str, Any]] = {+ "pipe_code": "my_cond",+ "description": "Route by status",+ "inputs": {"status": "Text"},+ "output": "Text",+ "outcomes": {"high": "handle_high", "low": "handle_low"},+ "default_outcome": "handle_default",+ }++ def test_condition_expression_alias(self) -> None:+ spec = {**self._BASE_CONDITION, "expression": "{{ status }}"}+ result = parse_pipe_spec("PipeCondition", spec)+ assert isinstance(result, PipeConditionSpec)+ assert result.jinja2_expression_template == "{{ status }}"++ def test_condition_canonical_jinja2_field(self) -> None:+ spec = {**self._BASE_CONDITION, "jinja2_expression_template": "{{ status }}"}+ result = parse_pipe_spec("PipeCondition", spec)+ assert isinstance(result, PipeConditionSpec)+ assert result.jinja2_expression_template == "{{ status }}"++ def test_condition_canonical_takes_precedence(self) -> None:+ spec = {**self._BASE_CONDITION, "jinja2_expression_template": "{{ canonical }}", "expression": "{{ alias }}"}+ result = parse_pipe_spec("PipeCondition", spec)+ assert isinstance(result, PipeConditionSpec)+ assert result.jinja2_expression_template == "{{ canonical }}"++ # -- does not mutate caller's dict ------------------------------------++ def test_original_dict_unchanged(self) -> None:+ original: dict[str, Any] = {+ "code": "my_pipe",+ "description": "Test",+ "model": "$writing-creative",+ "inputs": {"text": "Text"},+ "output": "Text",+ "prompt": "Write about @text",+ }+ snapshot = dict(original)+ parse_pipe_spec("PipeLLM", original)+ assert original == snapshot++ def test_nested_step_dicts_not_mutated(self) -> None:+ step = {"pipe": "step_one", "result": "intermediate"}+ spec: dict[str, Any] = {+ "pipe_code": "my_seq",+ "description": "A sequence",+ "inputs": {"doc": "Document"},+ "output": "Text",+ "steps": [step],+ }+ step_snapshot = dict(step)+ parse_pipe_spec("PipeSequence", spec)+ assert step == step_snapshot++ # -- returns correct subclass -----------------------------------------++ @pytest.mark.parametrize(+ ("pipe_type", "spec_data", "expected_class"),+ [+ (+ "PipeLLM",+ {**_BaseLLM.SPEC},+ PipeLLMSpec,+ ),+ (+ "PipeFunc",+ {"pipe_code": "my_func", "description": "A function", "inputs": {"data": "Text"}, "output": "Text", "function_name": "process_data"},+ PipeFuncSpec,+ ),+ (+ "PipeImgGen",+ {+ "pipe_code": "my_img",+ "description": "Generate image",+ "inputs": {"prompt_text": "ImgGenPrompt"},+ "output": "Image",+ "prompt": "Generate: $prompt_text",+ },+ PipeImgGenSpec,+ ),+ (+ "PipeExtract",+ {"pipe_code": "my_extract", "description": "Extract text", "inputs": {"doc": "Document"}, "output": "Page[]"},+ PipeExtractSpec,+ ),+ (+ "PipeSearch",+ {+ "pipe_code": "my_search",+ "description": "Search the web",+ "inputs": {"query_text": "Text"},+ "output": "Text",+ "prompt": "Search for @query_text",+ },+ PipeSearchSpec,+ ),+ (+ "PipeBatch",+ {+ "pipe_code": "my_batch",+ "description": "Batch process",+ "inputs": {"items": "Text[]"},+ "output": "Text[]",+ "branch_pipe_code": "process_one",+ "input_list_name": "items",+ "input_item_name": "item",+ },+ PipeBatchSpec,+ ),+ ],+ )+ def test_correct_subclass(self, pipe_type: str, spec_data: dict[str, Any], expected_class: type) -> None:+ result = parse_pipe_spec(pipe_type, spec_data)+ assert isinstance(result, expected_class)diff --git a/tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py b/tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.pynew file mode 100644index 000000000..a23d656b6--- /dev/null+++ b/tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py@@ -0,0 +1,426 @@+"""Unit tests for pipe_spec_to_toml from pipelex.builder.operations.pipe_ops."""++from __future__ import annotations++from typing import Any, ClassVar++from pipelex.builder.operations.pipe_ops import parse_pipe_spec, pipe_spec_to_toml+++class _BaseLLM:+ SPEC: ClassVar[dict[str, Any]] = {+ "pipe_code": "test_pipe",+ "description": "Test LLM pipe",+ "model": "$writing-creative",+ "inputs": {"text": "Text"},+ "output": "Text",+ "prompt": "Write about @text",+ }+++class TestPipeSpecToToml:+ """Comprehensive tests for pipe_spec_to_toml covering all pipe types."""++ # -- PipeLLM ----------------------------------------------------------++ def test_llm_basic_structure(self) -> None:+ spec = parse_pipe_spec("PipeLLM", {**_BaseLLM.SPEC})+ toml = pipe_spec_to_toml(spec)+ assert "[pipe.test_pipe]" in toml+ assert 'type = "PipeLLM"' in toml+ assert 'description = "Test LLM pipe"' in toml+ assert 'output = "Text"' in toml++ def test_llm_inputs_as_inline_table(self) -> None:+ spec = parse_pipe_spec("PipeLLM", {**_BaseLLM.SPEC})+ toml = pipe_spec_to_toml(spec)+ assert 'inputs = {text = "Text"}' in toml++ def test_llm_model_in_toml(self) -> None:+ spec = parse_pipe_spec("PipeLLM", {**_BaseLLM.SPEC})+ toml = pipe_spec_to_toml(spec)+ assert 'model = "$writing-creative"' in toml++ def test_llm_no_model_omits_field(self) -> None:+ data = {key: val for key, val in _BaseLLM.SPEC.items() if key != "model"}+ spec = parse_pipe_spec("PipeLLM", data)+ toml = pipe_spec_to_toml(spec)+ assert "model" not in toml++ def test_llm_system_prompt_in_toml(self) -> None:+ spec = parse_pipe_spec("PipeLLM", {**_BaseLLM.SPEC, "system_prompt": "You are a helpful writer."})+ toml = pipe_spec_to_toml(spec)+ assert "system_prompt" in toml+ assert "You are a helpful writer." in toml++ def test_llm_prompt_in_toml(self) -> None:+ spec = parse_pipe_spec("PipeLLM", {**_BaseLLM.SPEC})+ toml = pipe_spec_to_toml(spec)+ assert "prompt" in toml+ assert "Write about @text" in toml++ def test_llm_no_inputs_omits_inputs(self) -> None:+ empty_inputs: dict[str, str] = {}+ data = {**_BaseLLM.SPEC, "inputs": empty_inputs}+ spec = parse_pipe_spec("PipeLLM", data)+ toml = pipe_spec_to_toml(spec)+ assert "inputs" not in toml++ def test_llm_multiple_inputs(self) -> None:+ data = {**_BaseLLM.SPEC, "inputs": {"text": "Text", "context": "Document"}}+ spec = parse_pipe_spec("PipeLLM", data)+ toml = pipe_spec_to_toml(spec)+ assert 'text = "Text"' in toml+ assert 'context = "Document"' in toml++ # -- PipeFunc ---------------------------------------------------------++ def test_func_function_name_in_toml(self) -> None:+ spec = parse_pipe_spec(+ "PipeFunc",+ {"pipe_code": "my_func", "description": "Run a function", "inputs": {"data": "Text"}, "output": "Text", "function_name": "process_data"},+ )+ toml = pipe_spec_to_toml(spec)+ assert 'function_name = "process_data"' in toml+ assert 'type = "PipeFunc"' in toml++ # -- PipeImgGen -------------------------------------------------------++ def test_img_gen_model_and_prompt_in_toml(self) -> None:+ spec = parse_pipe_spec(+ "PipeImgGen",+ {+ "pipe_code": "gen_image",+ "description": "Generate image",+ "inputs": {"prompt_text": "ImgGenPrompt"},+ "output": "Image",+ "model": "$gen-image",+ "prompt": "Generate: $prompt_text",+ },+ )+ toml = pipe_spec_to_toml(spec)+ assert 'model = "$gen-image"' in toml+ assert "Generate: $prompt_text" in toml++ def test_img_gen_no_model_omits_field(self) -> None:+ spec = parse_pipe_spec(+ "PipeImgGen",+ {+ "pipe_code": "gen_image",+ "description": "Generate image",+ "inputs": {"prompt_text": "ImgGenPrompt"},+ "output": "Image",+ "prompt": "Generate: $prompt_text",+ },+ )+ toml = pipe_spec_to_toml(spec)+ assert "model" not in toml++ # -- PipeExtract ------------------------------------------------------++ def test_extract_model_in_toml(self) -> None:+ spec = parse_pipe_spec(+ "PipeExtract",+ {+ "pipe_code": "my_extract",+ "description": "Extract text",+ "inputs": {"doc": "Document"},+ "output": "Page[]",+ "model": "@default-extract-document",+ },+ )+ toml = pipe_spec_to_toml(spec)+ assert 'model = "@default-extract-document"' in toml++ def test_extract_max_page_images_in_toml(self) -> None:+ spec = parse_pipe_spec(+ "PipeExtract",+ {+ "pipe_code": "my_extract",+ "description": "Extract text",+ "inputs": {"doc": "Document"},+ "output": "Page[]",+ "max_page_images": 5,+ },+ )+ toml = pipe_spec_to_toml(spec)+ assert "max_page_images = 5" in toml++ def test_extract_page_views_in_toml(self) -> None:+ spec = parse_pipe_spec(+ "PipeExtract",+ {+ "pipe_code": "my_extract",+ "description": "Extract text",+ "inputs": {"doc": "Document"},+ "output": "Page[]",+ "page_views": True,+ },+ )+ toml = pipe_spec_to_toml(spec)+ assert "page_views = true" in toml++ def test_extract_no_optional_fields_omits_them(self) -> None:+ spec = parse_pipe_spec(+ "PipeExtract",+ {"pipe_code": "my_extract", "description": "Extract text", "inputs": {"doc": "Document"}, "output": "Page[]"},+ )+ toml = pipe_spec_to_toml(spec)+ assert "model" not in toml+ assert "max_page_images" not in toml+ assert "page_views" not in toml++ # -- PipeSearch -------------------------------------------------------++ def test_search_all_fields_in_toml(self) -> None:+ spec = parse_pipe_spec(+ "PipeSearch",+ {+ "pipe_code": "web_search",+ "description": "Search the web",+ "inputs": {"query_text": "Text"},+ "output": "Text",+ "model": "$search-model",+ "prompt": "Search for @query_text",+ "from_date": "2024-01-01",+ "to_date": "2024-12-31",+ "include_domains": ["example.com", "docs.example.com"],+ "exclude_domains": ["spam.com"],+ "max_results": 10,+ },+ )+ toml = pipe_spec_to_toml(spec)+ assert 'model = "$search-model"' in toml+ assert "Search for @query_text" in toml+ assert 'from_date = "2024-01-01"' in toml+ assert 'to_date = "2024-12-31"' in toml+ assert "example.com" in toml+ assert "spam.com" in toml+ assert "max_results = 10" in toml++ def test_search_minimal(self) -> None:+ spec = parse_pipe_spec(+ "PipeSearch",+ {"pipe_code": "web_search", "description": "Search", "inputs": {"query_text": "Text"}, "output": "Text", "prompt": "Find @query_text"},+ )+ toml = pipe_spec_to_toml(spec)+ assert "Find @query_text" in toml+ assert "from_date" not in toml+ assert "to_date" not in toml+ assert "include_domains" not in toml+ assert "exclude_domains" not in toml+ assert "max_results" not in toml+ assert "model" not in toml++ # -- PipeSequence -----------------------------------------------------++ def test_sequence_steps_in_toml(self) -> None:+ spec = parse_pipe_spec(+ "PipeSequence",+ {+ "pipe_code": "my_seq",+ "description": "A sequence",+ "inputs": {"doc": "Document"},+ "output": "Text",+ "steps": [+ {"pipe_code": "step_one", "result": "intermediate"},+ {"pipe_code": "step_two", "result": "final"},+ ],+ },+ )+ toml = pipe_spec_to_toml(spec)+ assert 'type = "PipeSequence"' in toml+ assert "step_one" in toml+ assert "step_two" in toml+ assert "intermediate" in toml+ assert "final" in toml++ def test_sequence_step_with_batch_over(self) -> None:+ spec = parse_pipe_spec(+ "PipeSequence",+ {+ "pipe_code": "my_seq",+ "description": "A sequence with batch",+ "inputs": {"items": "Text[]"},+ "output": "Text[]",+ "steps": [+ {"pipe_code": "process", "result": "processed", "batch_over": "items", "batch_as": "item"},+ ],+ },+ )+ toml = pipe_spec_to_toml(spec)+ assert "batch_over" in toml+ assert "batch_as" in toml+ assert "items" in toml++ # -- PipeParallel -----------------------------------------------------++ def test_parallel_branches_and_add_each_output(self) -> None:+ spec = parse_pipe_spec(+ "PipeParallel",+ {+ "pipe_code": "my_par",+ "description": "Parallel branches",+ "inputs": {"doc": "Document"},+ "output": "Text",+ "add_each_output": True,+ "branches": [+ {"pipe_code": "branch_a", "result": "result_a"},+ {"pipe_code": "branch_b", "result": "result_b"},+ ],+ },+ )+ toml = pipe_spec_to_toml(spec)+ assert 'type = "PipeParallel"' in toml+ assert "add_each_output = true" in toml+ assert "branch_a" in toml+ assert "branch_b" in toml++ def test_parallel_combined_output_in_toml(self) -> None:+ spec = parse_pipe_spec(+ "PipeParallel",+ {+ "pipe_code": "my_par",+ "description": "Parallel with combined output",+ "inputs": {"doc": "Document"},+ "output": "Text",+ "add_each_output": False,+ "combined_output": "MergedResult",+ "branches": [+ {"pipe_code": "branch_a", "result": "result_a"},+ ],+ },+ )+ toml = pipe_spec_to_toml(spec)+ assert 'combined_output = "MergedResult"' in toml++ # -- PipeCondition ----------------------------------------------------++ def test_condition_expression_outcomes_default(self) -> None:+ spec = parse_pipe_spec(+ "PipeCondition",+ {+ "pipe_code": "my_cond",+ "description": "Route by status",+ "inputs": {"status": "Text"},+ "output": "Text",+ "jinja2_expression_template": "{{ status }}",+ "outcomes": {"high": "handle_high", "low": "handle_low"},+ "default_outcome": "handle_default",+ },+ )+ toml = pipe_spec_to_toml(spec)+ assert 'type = "PipeCondition"' in toml+ assert "{{ status }}" in toml+ assert "handle_high" in toml+ assert "handle_low" in toml+ assert 'default_outcome = "handle_default"' in toml++ # -- PipeBatch --------------------------------------------------------++ def test_batch_fields_in_toml(self) -> None:+ spec = parse_pipe_spec(+ "PipeBatch",+ {+ "pipe_code": "my_batch",+ "description": "Batch process",+ "inputs": {"items": "Text[]"},+ "output": "Text[]",+ "branch_pipe_code": "process_one",+ "input_list_name": "items",+ "input_item_name": "item",+ },+ )+ toml = pipe_spec_to_toml(spec)+ assert 'type = "PipeBatch"' in toml+ assert 'branch_pipe_code = "process_one"' in toml+ assert 'input_list_name = "items"' in toml+ assert 'input_item_name = "item"' in toml++ # -- PipeCompose (template mode) --------------------------------------++ def test_compose_template_mode_fields(self) -> None:+ spec = parse_pipe_spec(+ "PipeCompose",+ {+ "pipe_code": "render_greeting",+ "description": "Render a greeting",+ "inputs": {"name": "native.Text"},+ "output": "native.Text",+ "target_format": "markdown",+ "template": "Hello @name!",+ },+ )+ toml = pipe_spec_to_toml(spec)+ assert 'type = "PipeCompose"' in toml+ assert 'target_format = "markdown"' in toml+ assert 'template = "Hello @name!"' in toml++ def test_compose_no_construct_in_template_mode(self) -> None:+ spec = parse_pipe_spec(+ "PipeCompose",+ {+ "pipe_code": "render_greeting",+ "description": "Render a greeting",+ "inputs": {"name": "native.Text"},+ "output": "native.Text",+ "target_format": "markdown",+ "template": "Hello @name!",+ },+ )+ toml = pipe_spec_to_toml(spec)+ assert "construct" not in toml++ # -- PipeCompose (construct mode) -------------------------------------++ def test_compose_construct_with_from_mappings(self) -> None:+ spec = parse_pipe_spec(+ "PipeCompose",+ {+ "pipe_code": "compose_sheet",+ "description": "Compose interview sheet",+ "inputs": {"analysis": "MatchAnalysis", "questions": "InterviewQuestion[]"},+ "output": "InterviewSheet",+ "construct": {+ "score": {"from": "analysis.overall_score"},+ "questions": {"from": "questions"},+ },+ },+ )+ toml = pipe_spec_to_toml(spec)+ assert "[pipe.compose_sheet.construct]" in toml+ assert 'score = {from = "analysis.overall_score"}' in toml++ def test_compose_construct_with_static_values(self) -> None:+ spec = parse_pipe_spec(+ "PipeCompose",+ {+ "pipe_code": "compose_report",+ "description": "Compose a report",+ "inputs": {"title": "native.Text"},+ "output": "Report",+ "construct": {+ "title": {"from": "title"},+ "version": "1.0",+ "page_count": 42,+ },+ },+ )+ toml = pipe_spec_to_toml(spec)+ assert 'version = "1.0"' in toml+ assert "page_count = 42" in toml++ def test_compose_no_template_in_construct_mode(self) -> None:+ spec = parse_pipe_spec(+ "PipeCompose",+ {+ "pipe_code": "compose_report",+ "description": "Compose a report",+ "inputs": {"title": "native.Text"},+ "output": "Report",+ "construct": {"title": {"from": "title"}},+ },+ )+ toml = pipe_spec_to_toml(spec)+ assert "target_format" not in toml+ assert "template" not in tomldiff --git a/tests/unit/pipelex/cli/test_pipe_cmd.py b/tests/unit/pipelex/cli/test_pipe_cmd.pyindex ffa9dae73..5f0b2fddf 100644--- a/tests/unit/pipelex/cli/test_pipe_cmd.py+++ b/tests/unit/pipelex/cli/test_pipe_cmd.py@@ -1,200 +1,35 @@-"""Unit tests for the agent CLI pipe command — non-nominal / tolerance cases."""+"""Unit tests for the agent CLI pipe command — CLI-specific behavior.++parse_pipe_spec tolerance tests (aliases, output dict, etc.) live in+tests/unit/pipelex/builder/operations/test_parse_pipe_spec.py.+pipe_spec_to_toml tests live in tests/unit/pipelex/builder/operations/test_pipe_spec_to_toml.py.+This file tests CLI-layer concerns: pipe_type extraction from JSON,+and the CLI-specific TOML serialization (_pipe_spec_to_toml which uses format_toml_string).+"""from __future__ import annotationsfrom typing import Any, ClassVar-import pytest-from pydantic import ValidationError-from pipelex.cli.agent_cli.commands.pipe_cmd import (_parse_pipe_spec_from_json, # noqa: PLC2701 # pyright: ignore[reportPrivateUsage]_pipe_spec_to_toml, # noqa: PLC2701 # pyright: ignore[reportPrivateUsage])-# ----------------------------------------------------------------------------# _parse_pipe_spec_from_json — pipe_code aliases-# -----------------------------------------------------------------------------class TestPipeCodeAliases:- """The parser should accept 'code', 'the_pipe_code', and 'name' as aliases for 'pipe_code'."""+class TestCliPipeCmd:+ """CLI-specific tests: pipe_type extraction from JSON and CLI TOML serialization."""_BASE_LLM: ClassVar[dict[str, Any]] = {- "description": "Test pipe",+ "pipe_code": "my_llm_pipe",+ "description": "Test LLM pipe","model": "$writing-creative","inputs": {"text": "Text"},"output": "Text",- "prompt": "Write something about @text",- }-- def test_canonical_pipe_code(self) -> None:- spec = {**self._BASE_LLM, "pipe_code": "my_pipe"}- result = _parse_pipe_spec_from_json("PipeLLM", spec)- assert result.pipe_code == "my_pipe"-- def test_alias_code(self) -> None:- spec = {**self._BASE_LLM, "code": "my_pipe"}- result = _parse_pipe_spec_from_json("PipeLLM", spec)- assert result.pipe_code == "my_pipe"-- def test_alias_the_pipe_code(self) -> None:- spec = {**self._BASE_LLM, "the_pipe_code": "my_pipe"}- result = _parse_pipe_spec_from_json("PipeLLM", spec)- assert result.pipe_code == "my_pipe"-- def test_alias_name(self) -> None:- spec = {**self._BASE_LLM, "name": "my_pipe"}- result = _parse_pipe_spec_from_json("PipeLLM", spec)- assert result.pipe_code == "my_pipe"-- def test_canonical_ignores_alias(self) -> None:- """When pipe_code is present, alias keys are removed so Pydantic doesn't reject them."""- spec = {**self._BASE_LLM, "pipe_code": "canonical", "code": "alias"}- result = _parse_pipe_spec_from_json("PipeLLM", spec)- assert result.pipe_code == "canonical"-- def test_multiple_aliases_all_cleaned_up(self) -> None:- """When pipe_code and multiple aliases are present, all aliases are removed."""- spec = {**self._BASE_LLM, "code": "my_pipe", "name": "alt"}- result = _parse_pipe_spec_from_json("PipeLLM", spec)- assert result.pipe_code == "my_pipe"-- def test_three_aliases_all_cleaned_up(self) -> None:- """When pipe_code and all aliases are present, all aliases are removed."""- spec = {**self._BASE_LLM, "code": "my_pipe", "the_pipe_code": "alt", "name": "alt2"}- result = _parse_pipe_spec_from_json("PipeLLM", spec)- assert result.pipe_code == "my_pipe"---# ----------------------------------------------------------------------------# _parse_pipe_spec_from_json — output dict tolerance-# ------------------------------------------------------------------------------class TestOutputDictTolerance:- """The parser should accept output as {"type": "ConceptName"} and extract the string."""-- _BASE_LLM: ClassVar[dict[str, Any]] = {- "pipe_code": "test_pipe",- "description": "Test pipe",- "model": "$writing-creative",- "inputs": {"text": "Text"},"prompt": "Write about @text",}- def test_output_as_string(self) -> None:- spec = {**self._BASE_LLM, "output": "ImgGenPrompt"}- result = _parse_pipe_spec_from_json("PipeLLM", spec)- assert result.output == "ImgGenPrompt"-- def test_output_as_dict_with_type_key(self) -> None:- spec = {**self._BASE_LLM, "output": {"type": "ImgGenPrompt"}}- result = _parse_pipe_spec_from_json("PipeLLM", spec)- assert result.output == "ImgGenPrompt"-- def test_output_dict_without_type_key_passes_through(self) -> None:- """If the dict has no 'type' key, let Pydantic handle the error."""- spec = {**self._BASE_LLM, "output": {"name": "ImgGenPrompt"}}- with pytest.raises(ValidationError):- _parse_pipe_spec_from_json("PipeLLM", spec)---# ----------------------------------------------------------------------------# _parse_pipe_spec_from_json — steps/branches 'pipe' → 'pipe_code' alias-# ------------------------------------------------------------------------------class TestStepsBranchesAlias:- """Steps and branches should accept 'pipe' as an alias for 'pipe_code'."""-- def test_sequence_steps_pipe_alias(self) -> None:- spec: dict[str, Any] = {- "pipe_code": "my_seq",- "description": "A sequence",- "inputs": {"doc": "Document"},- "output": "Text",- "steps": [- {"pipe": "step_one", "result": "intermediate"},- {"pipe": "step_two", "result": "final"},- ],- }- result = _parse_pipe_spec_from_json("PipeSequence", spec)- assert result.steps[0].pipe_code == "step_one" # type: ignore[attr-defined]- assert result.steps[1].pipe_code == "step_two" # type: ignore[attr-defined]-- def test_sequence_steps_pipe_code_canonical(self) -> None:- spec: dict[str, Any] = {- "pipe_code": "my_seq",- "description": "A sequence",- "inputs": {"doc": "Document"},- "output": "Text",- "steps": [- {"pipe_code": "step_one", "result": "intermediate"},- ],- }- result = _parse_pipe_spec_from_json("PipeSequence", spec)- assert result.steps[0].pipe_code == "step_one" # type: ignore[attr-defined]-- def test_parallel_branches_pipe_alias(self) -> None:- spec: dict[str, Any] = {- "pipe_code": "my_parallel",- "description": "Parallel branches",- "inputs": {"doc": "Document"},- "output": "Text",- "add_each_output": True,- "branches": [- {"pipe": "branch_a", "result": "result_a"},- {"pipe": "branch_b", "result": "result_b"},- ],- }- result = _parse_pipe_spec_from_json("PipeParallel", spec)- assert result.branches[0].pipe_code == "branch_a" # type: ignore[attr-defined]- assert result.branches[1].pipe_code == "branch_b" # type: ignore[attr-defined]---# ----------------------------------------------------------------------------# _parse_pipe_spec_from_json — PipeCondition expression alias-# ------------------------------------------------------------------------------class TestConditionExpressionAlias:- """PipeCondition should accept 'expression' as alias for 'jinja2_expression_template'."""-- def test_expression_alias(self) -> None:- spec: dict[str, Any] = {- "pipe_code": "my_condition",- "description": "Route by status",- "inputs": {"status": "Text"},- "output": "Text",- "expression": "{{ status }}",- "outcomes": {"high": "handle_high", "low": "handle_low"},- "default_outcome": "handle_default",- }- result = _parse_pipe_spec_from_json("PipeCondition", spec)- assert result.jinja2_expression_template == "{{ status }}" # type: ignore[attr-defined]-- def test_canonical_expression_field(self) -> None:- spec: dict[str, Any] = {- "pipe_code": "my_condition",- "description": "Route by status",- "inputs": {"status": "Text"},- "output": "Text",- "jinja2_expression_template": "{{ status }}",- "outcomes": {"high": "handle_high", "low": "handle_low"},- "default_outcome": "handle_default",- }- result = _parse_pipe_spec_from_json("PipeCondition", spec)- assert result.jinja2_expression_template == "{{ status }}" # type: ignore[attr-defined]---# ----------------------------------------------------------------------------# _parse_pipe_spec_from_json — pipe_type alias in JSON-# ------------------------------------------------------------------------------class TestPipeTypeAlias:- """'pipe_type' in spec JSON should be accepted as alias for 'type'."""+ # -- pipe_type alias in JSON (handled by pipe_cmd, not parse_pipe_spec) --def test_type_extracted_from_spec(self) -> None:"""When type is in the spec dict it should be used (and popped)."""@@ -207,41 +42,11 @@ class TestPipeTypeAlias:"output": "Text","prompt": "Write about @text",}- # Simulate what pipe_cmd does: pop 'type' and pass it as pipe_typepipe_type = spec.pop("type")result = _parse_pipe_spec_from_json(pipe_type, spec)assert result.pipe_code == "test"--# ----------------------------------------------------------------------------# _parse_pipe_spec_from_json — invalid pipe type-# ------------------------------------------------------------------------------class TestInvalidPipeType:- """Invalid pipe types should raise ValueError."""-- def test_invalid_pipe_type(self) -> None:- with pytest.raises(ValueError, match="Invalid pipe type"):- _parse_pipe_spec_from_json("PipeNonExistent", {"pipe_code": "x", "description": "x"})---# ----------------------------------------------------------------------------# _pipe_spec_to_toml — model in TOML output-# ------------------------------------------------------------------------------class TestPipeSpecToToml:- """Verify TOML output contains model presets correctly."""-- _BASE_LLM: ClassVar[dict[str, Any]] = {- "pipe_code": "my_llm_pipe",- "description": "Test LLM pipe",- "model": "$writing-creative",- "inputs": {"text": "Text"},- "output": "Text",- "prompt": "Write about @text",- }+ # -- CLI TOML serialization (uses format_toml_string) -----------------def test_llm_model_appears_in_toml(self) -> None:spec = _parse_pipe_spec_from_json("PipeLLM", {**self._BASE_LLM})@@ -326,14 +131,7 @@ class TestPipeSpecToToml:toml = _pipe_spec_to_toml(spec)assert "model =" not in toml--# ----------------------------------------------------------------------------# End-to-end: combined tolerance scenarios-# ------------------------------------------------------------------------------class TestEndToEndTolerance:- """Test combined tolerance scenarios with direct model field."""+ # -- End-to-end: combined tolerance through CLI layer ------------------def test_model_with_dict_output_both_tolerated(self) -> None:"""The agent sends model preset and output as dict — both should be tolerated."""