Skip to content

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.

Restored pyright checking of tests, fixed the issues it raised Added Unit tests for PlxFactory

Louis Choquel8b2b3b2ad107
diff --git a/pipelex/language/plx_factory.py b/pipelex/language/plx_factory.py
index 84354ea99..294985259 100644
--- a/pipelex/language/plx_factory.py
+++ b/pipelex/language/plx_factory.py
@@ -29,7 +29,7 @@ class PlxFactory:
return get_config().pipelex.plx_config
@classmethod
- def _format_tomlkit_string(cls, text: str) -> Any: # Can't type this because of tomlkit
+ def format_tomlkit_string(cls, text: str) -> Any: # Can't type this because of tomlkit
r"""Build a tomlkit string node.
- If `force_multiline` or the text contains '\\n', we emit a triple-quoted multiline string.
- When multiline, `ensure_trailing_newline` puts the closing quotes on their own line.
@@ -50,7 +50,7 @@ class PlxFactory:
return tomlkit_string(normalized, multiline=needs_multiline, literal=use_literal)
@classmethod
- def _convert_dicts_to_inline_tables(cls, value: Any, field_ordering: list[str] | None = None) -> Any: # Can't type this because of tomlkit
+ def convert_dicts_to_inline_tables(cls, value: Any, field_ordering: list[str] | None = None) -> Any: # Can't type this because of tomlkit
"""Recursively convert Python values; dicts -> inline tables; lists kept as arrays."""
if isinstance(value, Mapping):
value = cast("Mapping[str, Any]", value)
@@ -58,10 +58,10 @@ class PlxFactory:
if field_ordering:
for key in field_ordering:
if key in value:
- inline_table_obj[key] = cls._convert_dicts_to_inline_tables(value=value[key])
+ inline_table_obj[key] = cls.convert_dicts_to_inline_tables(value=value[key])
else:
for key, value_item in value.items():
- inline_table_obj[key] = cls._convert_dicts_to_inline_tables(value=value_item)
+ inline_table_obj[key] = cls.convert_dicts_to_inline_tables(value=value_item)
return inline_table_obj
elif isinstance(value, list):
@@ -73,19 +73,19 @@ class PlxFactory:
element = cast("Mapping[str, Any]", element)
inline_element = inline_table()
for inner_key, inner_value in element.items():
- inline_element[inner_key] = cls._convert_dicts_to_inline_tables(value=inner_value)
+ inline_element[inner_key] = cls.convert_dicts_to_inline_tables(value=inner_value)
array_obj.append(inline_element) # pyright: ignore[reportUnknownMemberType]
else:
- array_obj.append(cls._convert_dicts_to_inline_tables(value=element)) # pyright: ignore[reportUnknownMemberType]
+ array_obj.append(cls.convert_dicts_to_inline_tables(value=element)) # pyright: ignore[reportUnknownMemberType]
return array_obj
elif isinstance(value, str):
- return cls._format_tomlkit_string(text=value)
+ return cls.format_tomlkit_string(text=value)
else:
return value
@classmethod
- def _convert_mapping_to_table(
+ def convert_mapping_to_table(
cls, mapping: Mapping[str, Any], field_ordering: list[str] | None = None
) -> Any: # Can't type this because of tomlkit
"""Convert a mapping into a TOML Table where any nested mappings (third level+)
@@ -103,18 +103,18 @@ class PlxFactory:
field_value = mapping[field_key]
if isinstance(field_value, Mapping):
# Third-level mapping -> inline table
- tbl.add(field_key, cls._convert_dicts_to_inline_tables(field_value))
+ tbl.add(field_key, cls.convert_dicts_to_inline_tables(field_value))
else:
- tbl.add(field_key, cls._convert_dicts_to_inline_tables(field_value))
+ tbl.add(field_key, cls.convert_dicts_to_inline_tables(field_value))
# Add any remaining fields not in the ordering
for field_key, field_value in mapping.items():
if field_key not in field_ordering and field_key != "category":
if isinstance(field_value, Mapping):
# Third-level mapping -> inline table
- tbl.add(field_key, cls._convert_dicts_to_inline_tables(field_value))
+ tbl.add(field_key, cls.convert_dicts_to_inline_tables(field_value))
else:
- tbl.add(field_key, cls._convert_dicts_to_inline_tables(field_value))
+ tbl.add(field_key, cls.convert_dicts_to_inline_tables(field_value))
else:
# No field ordering provided, use original logic
for field_key, field_value in mapping.items():
@@ -124,14 +124,14 @@ class PlxFactory:
if isinstance(field_value, Mapping):
# Third-level mapping -> inline table
- tbl.add(field_key, cls._convert_dicts_to_inline_tables(field_value))
+ tbl.add(field_key, cls.convert_dicts_to_inline_tables(field_value))
else:
- tbl.add(field_key, cls._convert_dicts_to_inline_tables(field_value))
+ tbl.add(field_key, cls.convert_dicts_to_inline_tables(field_value))
return tbl
# TODO: replace this by a proper toml formatter utility
@classmethod
- def _add_spaces_to_inline_tables(cls, toml_string: str) -> str:
+ def add_spaces_to_inline_tables(cls, toml_string: str) -> str:
"""Add spaces inside inline table curly braces.
Converts {key = value} to { key = value }.
@@ -196,7 +196,7 @@ class PlxFactory:
return find_and_replace_inline_tables(toml_string)
@classmethod
- def _make_table_obj_for_pipe(cls, section_value: Mapping[str, Any]) -> Any:
+ def make_table_obj_for_pipe(cls, section_value: Mapping[str, Any]) -> Any:
"""Make a table object for a pipe section."""
log.debug("******** Making table object for pipe section ********")
table_obj = table()
@@ -204,15 +204,15 @@ class PlxFactory:
log.debug(f"------ Field {field_key} is a {type(field_value)}")
if not isinstance(field_value, Mapping):
log.debug(f"Field is not a mapping: key = {field_key}, value = {field_value}")
- table_obj.add(field_key, cls._convert_dicts_to_inline_tables(field_value))
+ table_obj.add(field_key, cls.convert_dicts_to_inline_tables(field_value))
continue
log.debug(f"Field is a mapping: key = {field_key}, value = {field_value}")
field_value = cast("Mapping[str, Any]", field_value)
- table_obj.add(field_key, cls._convert_mapping_to_table(field_value, field_ordering=cls._plx_config().pipes.field_ordering))
+ table_obj.add(field_key, cls.convert_mapping_to_table(field_value, field_ordering=cls._plx_config().pipes.field_ordering))
return table_obj
@classmethod
- def _make_table_obj_for_concept(cls, section_value: Mapping[str, Any]) -> Any:
+ def make_table_obj_for_concept(cls, section_value: Mapping[str, Any]) -> Any:
"""Make a table object for a concept section."""
log.debug("******** Making table object for concept section ********")
table_obj = table()
@@ -253,7 +253,7 @@ class PlxFactory:
log.debug(f"Structure for '{concept_key}' is a mapping: {structure_field_value}")
structure_table_obj.add(
structure_field_key,
- cls._convert_dicts_to_inline_tables(
+ cls.convert_dicts_to_inline_tables(
value=structure_field_value, field_ordering=cls._plx_config().concepts.structure_field_ordering
),
)
@@ -261,7 +261,7 @@ class PlxFactory:
else:
# sub_table = _convert_mapping_to_table(concept_field_value)
log.debug(f"{concept_key}/'{concept_field_key}' is inline: {concept_field_value}")
- concept_table_obj.add(concept_field_key, cls._convert_dicts_to_inline_tables(concept_field_value))
+ concept_table_obj.add(concept_field_key, cls.convert_dicts_to_inline_tables(concept_field_value))
table_obj.add(concept_key, concept_table_obj)
return table_obj
@@ -274,7 +274,7 @@ class PlxFactory:
for root_key, root_value in data.items():
if not isinstance(root_value, Mapping):
log.debug(f"Root root_key is not a mapping: key = {root_key}, value = {root_value}")
- document_root.add(root_key, cls._convert_dicts_to_inline_tables(root_value))
+ document_root.add(root_key, cls.convert_dicts_to_inline_tables(root_value))
continue
# It's a mapping, therefore it's a section
@@ -288,15 +288,15 @@ class PlxFactory:
continue
match section_key:
case SectionKey.PIPE:
- table_obj_for_pipe = cls._make_table_obj_for_pipe(section_value)
+ table_obj_for_pipe = cls.make_table_obj_for_pipe(section_value)
document_root.add(section_key, table_obj_for_pipe)
case SectionKey.CONCEPT:
- table_obj_for_concept = cls._make_table_obj_for_concept(section_value)
+ table_obj_for_concept = cls.make_table_obj_for_concept(section_value)
document_root.add(section_key, table_obj_for_concept)
toml_output = tomlkit.dumps(document_root) # pyright: ignore[reportUnknownMemberType]
if cls._plx_config().inline_tables.spaces_inside_curly_braces:
- return cls._add_spaces_to_inline_tables(toml_output)
+ return cls.add_spaces_to_inline_tables(toml_output)
return toml_output
@classmethod
diff --git a/pyproject.toml b/pyproject.toml
index 0cad96831..f4d38d4c5 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -115,7 +115,7 @@ module = ["filetype", "json2html", "pypdfium2", "pypdfium2.raw"]
[tool.pyright]
pythonVersion = "3.11"
include = ["pipelex", "tests"]
-exclude = ["**/__pycache__", ".venv", ".git", "build", "dist", "tests"]
+exclude = ["**/__pycache__", ".venv", ".git", "build", "dist"]
analyzeUnannotatedFunctions = true
deprecateTypingAliases = false
disableBytesTypePromotions = true
diff --git a/tests/integration/pipelex/language/test_plx_factory.py b/tests/integration/pipelex/language/test_plx_factory.py
new file mode 100644
index 000000000..a7cbbed86
--- /dev/null
+++ b/tests/integration/pipelex/language/test_plx_factory.py
@@ -0,0 +1,22 @@
+from pathlib import Path
+from typing import Type
+
+import pytest
+
+from pipelex import log, pretty_print
+from pipelex.core.bundles.pipelex_bundle_blueprint import PipelexBundleBlueprint
+from pipelex.language.plx_factory import PlxFactory
+
+from tests.unit.pipelex.core.test_data import InterpreterTestCases
+
+
+class TestPlxFactoryIntegration:
+
+ @pytest.mark.parametrize("test_name,expected_plx_content,blueprint", InterpreterTestCases.VALID_TEST_CASES)
+ def test_make_plx_content(self, test_name: str, expected_plx_content: str, blueprint: PipelexBundleBlueprint):
+ """Test making blueprint from various valid PLX content."""
+ plx_content = PlxFactory.make_plx_content(blueprint=blueprint)
+ pretty_print(plx_content, title=f"Plx content {test_name}")
+ pretty_print(expected_plx_content, title=f"Expected PLX content {test_name}")
+ assert plx_content == expected_plx_content
+
diff --git a/tests/test_pipelines/discord_newsletter.py b/tests/test_pipelines/discord_newsletter.py
index 6de3cb373..6bd5799a7 100644
--- a/tests/test_pipelines/discord_newsletter.py
+++ b/tests/test_pipelines/discord_newsletter.py
@@ -2,6 +2,7 @@
from pydantic import Field
from pipelex.core.stuffs.stuff_content import StructuredContent
+from pipelex.tools.typing.pydantic_utils import CustomBaseModel, empty_list_factory_of
class Attachment(StructuredContent):
@@ -24,8 +25,8 @@ class DiscordMessage(StructuredContent):
author: str = Field(..., description="Author of the message")
content: str = Field(..., description="Content of the message")
- attachments: list[Attachment] = Field(default_factory=list, description="List of message attachments")
- embeds: list[Embed] = Field(default_factory=list, description="List of message embeds")
+ attachments: list[Attachment] = Field(default_factory=empty_list_factory_of(Attachment), description="List of message attachments")
+ embeds: list[Embed] = Field(default_factory=empty_list_factory_of(Embed), description="List of message embeds")
link: str = Field(..., description="Link to the message")
@@ -34,7 +35,7 @@ class DiscordChannelUpdate(StructuredContent):
name: str = Field(..., description="Name of the Discord channel")
position: int = Field(..., description="Position of the channel")
- messages: list[DiscordMessage] = Field(default_factory=list, description="List of messages in the channel")
+ messages: list[DiscordMessage] = Field(default_factory=empty_list_factory_of(DiscordMessage), description="List of messages in the channel")
class ChannelSummary(StructuredContent):
@@ -48,6 +49,6 @@ class Newsletter(StructuredContent):
"""Represents the final newsletter content"""
weekly_summary: str = Field(..., description="200 character summary of weekly Share channel content")
- new_members: list[str] = Field(default_factory=list, description="New member introductions in bullet points")
- channel_sections: list[ChannelSummary] = Field(default_factory=list, description="Ordered channel summaries")
- geographic_hubs: list[ChannelSummary] = Field(default_factory=list, description="Geographic hub channels grouped at end")
+ new_members: list[str] = Field(default_factory=empty_list_factory_of(str), description="New member introductions in bullet points")
+ channel_sections: list[ChannelSummary] = Field(default_factory=empty_list_factory_of(ChannelSummary), description="Ordered channel summaries")
+ geographic_hubs: list[ChannelSummary] = Field(default_factory=empty_list_factory_of(ChannelSummary), description="Geographic hub channels grouped at end")
diff --git a/tests/test_pipelines/test_structures_basic.py b/tests/test_pipelines/test_structures_basic.py
index cfc6fddfe..b7228f507 100644
--- a/tests/test_pipelines/test_structures_basic.py
+++ b/tests/test_pipelines/test_structures_basic.py
@@ -5,6 +5,7 @@ from datetime import datetime
from pydantic import Field
from pipelex.core.stuffs.stuff_content import StructuredContent
+from pipelex.tools.typing.pydantic_utils import empty_list_factory_of
class ConceptWithSimpleStructure(StructuredContent):
@@ -28,7 +29,7 @@ class ConceptWithLists(StructuredContent):
"""A structure with list fields."""
string_list: list[str] = Field(default_factory=list, description="A list of strings")
- number_list: list[int] = Field(default_factory=list, description="A list of numbers")
+ number_list: list[int] = Field(default_factory=empty_list_factory_of(int), description="A list of numbers")
optional_list: list[str] | None = Field(None, description="An optional list")
@@ -37,4 +38,4 @@ class ConceptWithNestedStructures(StructuredContent):
simple_nested: ConceptWithSimpleStructure = Field(..., description="A nested simple structure")
optional_nested: ConceptWithOptionals | None = Field(None, description="An optional nested structure")
- list_of_nested: list[ConceptWithSimpleStructure] = Field(default_factory=list, description="A list of nested structures")
+ list_of_nested: list[ConceptWithSimpleStructure] = Field(default_factory=empty_list_factory_of(ConceptWithSimpleStructure), description="A list of nested structures")
diff --git a/tests/test_pipelines/test_structures_complex.py b/tests/test_pipelines/test_structures_complex.py
index 7ba682a6d..0ecc88e1d 100644
--- a/tests/test_pipelines/test_structures_complex.py
+++ b/tests/test_pipelines/test_structures_complex.py
@@ -5,6 +5,7 @@ from pydantic import Field
from pipelex.core.stuffs.stuff_content import StructuredContent
from tests.test_pipelines.test_structures_basic import ConceptWithOptionals, ConceptWithSimpleStructure
+from pipelex.tools.typing.pydantic_utils import empty_list_factory_of
class ConceptWithDicts(StructuredContent):
@@ -20,7 +21,7 @@ class ConceptWithUnions(StructuredContent):
string_or_int: str | int = Field(..., description="A field that can be string or int")
optional_union: str | bool | None = Field(None, description="An optional union field")
- list_of_unions: list[str | int] = Field(default_factory=list, description="A list of union types")
+ list_of_unions: list[str | int] = Field(default_factory=lambda: [], description="A list of union types")
class ConceptWithComplexUnions(StructuredContent):
@@ -37,7 +38,7 @@ class ConceptWithNestedUnions(StructuredContent):
simple_or_complex: ConceptWithSimpleStructure | ConceptWithOptionals = Field(..., description="Simple or complex structure")
list_of_union_structures: list[ConceptWithSimpleStructure | ConceptWithUnions] = Field(
- default_factory=list, description="List of different structure types",
+ default_factory=lambda: [], description="List of different structure types",
)
optional_nested_union: ConceptWithUnions | ConceptWithComplexUnions | None = Field(
None, description="Optional union of union structures",
diff --git a/tests/unit/pipelex/language/__init__.py b/tests/unit/pipelex/language/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/unit/pipelex/language/test_plx_factory.py b/tests/unit/pipelex/language/test_plx_factory.py
index ac5aa56d4..4b71c2687 100644
--- a/tests/unit/pipelex/language/test_plx_factory.py
+++ b/tests/unit/pipelex/language/test_plx_factory.py
@@ -1,22 +1,454 @@
from pathlib import Path
-from typing import Type
+from typing import Any, Dict, List, Mapping
import pytest
+import tomlkit
+from tomlkit import array, inline_table, table
+from pytest_mock import MockerFixture
from pipelex import log, pretty_print
from pipelex.core.bundles.pipelex_bundle_blueprint import PipelexBundleBlueprint
-from pipelex.language.plx_factory import PlxFactory
+from pipelex.language.plx_config import PlxConfig, PlxConfigStrings, PlxConfigInlineTables, PlxConfigForConcepts, PlxConfigForPipes
+from pipelex.language.plx_factory import PlxFactory, SectionKey
from tests.unit.pipelex.core.test_data import InterpreterTestCases
-class TestPlxFactory:
+class TestPlxFactoryUnit:
+ """Unit tests for PlxFactory methods."""
- @pytest.mark.parametrize("test_name,expected_plx_content,blueprint", InterpreterTestCases.VALID_TEST_CASES)
- def test_make_plx_content(self, test_name: str, expected_plx_content: str, blueprint: PipelexBundleBlueprint):
- """Test making blueprint from various valid PLX content."""
- plx_content = PlxFactory.make_plx_content(blueprint=blueprint)
- pretty_print(plx_content, title=f"Plx content {test_name}")
- pretty_print(expected_plx_content, title=f"Expected PLX content {test_name}")
- assert plx_content == expected_plx_content
+ @pytest.fixture
+ def mock_plx_config(self) -> PlxConfig:
+ """Create a mock PLX configuration for testing."""
+ return PlxConfig(
+ strings=PlxConfigStrings(
+ prefer_literal=True,
+ force_multiline=False,
+ length_limit_to_multiline=50,
+ ensure_trailing_newline=True,
+ ensure_leading_blank_line=False,
+ ),
+ inline_tables=PlxConfigInlineTables(
+ spaces_inside_curly_braces=True,
+ ),
+ concepts=PlxConfigForConcepts(
+ structure_field_ordering=["type", "definition", "inputs", "output"],
+ ),
+ pipes=PlxConfigForPipes(
+ field_ordering=["type", "definition", "inputs", "output"],
+ ),
+ )
+ @pytest.fixture
+ def sample_mapping_data(self) -> Dict[str, Any]:
+ """Sample mapping data for testing."""
+ return {
+ "simple_field": "simple_value",
+ "nested_mapping": {
+ "inner_key": "inner_value",
+ "inner_number": 42,
+ },
+ "list_field": ["item1", "item2", "item3"],
+ "complex_list": [
+ {"name": "first", "value": 1},
+ {"name": "second", "value": 2},
+ ],
+ }
+
+ def test_format_tomlkit_string_simple(self, mocker: MockerFixture, mock_plx_config: PlxConfig):
+ """Test formatting simple strings."""
+ _mock_config = mocker.patch.object(PlxFactory, '_plx_config', return_value=mock_plx_config)
+
+ # Test simple string
+ result = PlxFactory.format_tomlkit_string("simple text")
+ assert isinstance(result, tomlkit.items.String) # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType]
+ # The actual string value without quotes
+ assert result.value == "simple text"
+
+ def test_format_tomlkit_string_multiline(self, mocker: MockerFixture, mock_plx_config: PlxConfig):
+ """Test formatting multiline strings."""
+ _mock_config = mocker.patch.object(PlxFactory, '_plx_config', return_value=mock_plx_config)
+
+ # Test string with newlines
+ multiline_text = "line1\nline2\nline3"
+ result = PlxFactory.format_tomlkit_string(multiline_text)
+ assert isinstance(result, tomlkit.items.String) # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType]
+ # Should be multiline with trailing newline
+ assert result.value == "line1\nline2\nline3\n"
+ # Check if it's a multiline string by checking if it has newlines in the value
+ assert "\n" in result.value
+
+ def test_format_tomlkit_string_force_multiline(self, mocker: MockerFixture, mock_plx_config: PlxConfig):
+ """Test force multiline configuration."""
+ mock_plx_config.strings.force_multiline = True
+ _mock_config = mocker.patch.object(PlxFactory, '_plx_config', return_value=mock_plx_config)
+
+ result = PlxFactory.format_tomlkit_string("short")
+ assert isinstance(result, tomlkit.items.String) # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType]
+ # Should be multiline even for short text
+ assert result.value == "short\n"
+ # Check if it's a multiline string by checking if it has newlines in the value
+ assert "\n" in result.value
+
+ def test_format_tomlkit_string_length_limit(self, mocker: MockerFixture, mock_plx_config: PlxConfig):
+ """Test length limit for multiline conversion."""
+ mock_plx_config.strings.length_limit_to_multiline = 10
+ _mock_config = mocker.patch.object(PlxFactory, '_plx_config', return_value=mock_plx_config)
+
+ long_text = "this is a very long text that exceeds the limit"
+ result = PlxFactory.format_tomlkit_string(long_text)
+ assert isinstance(result, tomlkit.items.String) # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType]
+ # Should be multiline due to length
+ assert result.value == "this is a very long text that exceeds the limit\n"
+ # Check if it's a multiline string by checking if it has newlines in the value
+ assert "\n" in result.value
+
+ def test_format_tomlkit_string_leading_blank_line(self, mocker: MockerFixture, mock_plx_config: PlxConfig):
+ """Test leading blank line configuration."""
+ mock_plx_config.strings.ensure_leading_blank_line = True
+ mock_plx_config.strings.force_multiline = True
+ _mock_config = mocker.patch.object(PlxFactory, '_plx_config', return_value=mock_plx_config)
+
+ result = PlxFactory.format_tomlkit_string("content")
+ assert isinstance(result, tomlkit.items.String) # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType]
+ # Should have leading blank line
+ assert result.value == "\ncontent\n"
+ # Check if it's a multiline string by checking if it has newlines in the value
+ assert "\n" in result.value
+
+ def test_convert_dicts_to_inline_tables_simple_dict(self, mocker: MockerFixture, mock_plx_config: PlxConfig):
+ """Test converting simple dictionary to inline table."""
+ _mock_config = mocker.patch.object(PlxFactory, '_plx_config', return_value=mock_plx_config)
+
+ input_dict = {"key1": "value1", "key2": "value2"}
+ result = PlxFactory.convert_dicts_to_inline_tables(input_dict)
+
+ assert isinstance(result, tomlkit.items.InlineTable) # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType]
+ assert result["key1"].value == "value1"
+ assert result["key2"].value == "value2"
+
+ def test_convert_dicts_to_inline_tables_with_field_ordering(self, mocker: MockerFixture, mock_plx_config: PlxConfig):
+ """Test converting dictionary with field ordering."""
+ _mock_config = mocker.patch.object(PlxFactory, '_plx_config', return_value=mock_plx_config)
+
+ input_dict = {"key2": "value2", "key1": "value1", "key3": "value3"}
+ field_ordering = ["key1", "key3"]
+ result = PlxFactory.convert_dicts_to_inline_tables(input_dict, field_ordering)
+
+ assert isinstance(result, tomlkit.items.InlineTable) # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType]
+ # Check that ordered fields come first
+ keys = list(result.keys())
+ assert keys[0] == "key1"
+ assert keys[1] == "key3"
+ # Note: the implementation might not include all keys if not in ordering
+ if len(keys) > 2:
+ assert keys[2] == "key2"
+
+ def test_convert_dicts_to_inline_tables_nested_dict(self, mocker: MockerFixture, mock_plx_config: PlxConfig):
+ """Test converting nested dictionary."""
+ _mock_config = mocker.patch.object(PlxFactory, '_plx_config', return_value=mock_plx_config)
+
+ input_dict = {
+ "outer": {
+ "inner": "value"
+ }
+ }
+ result = PlxFactory.convert_dicts_to_inline_tables(input_dict)
+
+ assert isinstance(result, tomlkit.items.InlineTable) # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType]
+ assert isinstance(result["outer"], tomlkit.items.InlineTable) # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType]
+ assert result["outer"]["inner"].value == "value"
+
+ def test_convert_dicts_to_inline_tables_list_with_dicts(self, mocker: MockerFixture, mock_plx_config: PlxConfig):
+ """Test converting list containing dictionaries."""
+ _mock_config = mocker.patch.object(PlxFactory, '_plx_config', return_value=mock_plx_config)
+
+ input_list = [
+ {"name": "first", "value": 1},
+ {"name": "second", "value": 2}
+ ]
+ result = PlxFactory.convert_dicts_to_inline_tables(input_list)
+
+ assert isinstance(result, tomlkit.items.Array) # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType]
+ assert len(result) == 2
+ assert isinstance(result[0], tomlkit.items.InlineTable) # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType]
+ assert result[0]["name"].value == "first"
+ assert result[0]["value"] == 1
+
+ def test_convert_dicts_to_inline_tables_string_handling(self, mocker: MockerFixture, mock_plx_config: PlxConfig):
+ """Test string handling in conversion."""
+ _mock_config = mocker.patch.object(PlxFactory, '_plx_config', return_value=mock_plx_config)
+
+ # Test simple string
+ result = PlxFactory.convert_dicts_to_inline_tables("simple string")
+ assert isinstance(result, tomlkit.items.String) # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType]
+
+ # Test other types pass through
+ assert PlxFactory.convert_dicts_to_inline_tables(42) == 42
+ assert PlxFactory.convert_dicts_to_inline_tables(True) is True
+
+ def test_convert_mapping_to_table(self, mocker: MockerFixture, mock_plx_config: PlxConfig, sample_mapping_data: Dict[str, Any]):
+ """Test converting mapping to table."""
+ _mock_config = mocker.patch.object(PlxFactory, '_plx_config', return_value=mock_plx_config)
+
+ result = PlxFactory.convert_mapping_to_table(sample_mapping_data)
+
+ assert isinstance(result, tomlkit.items.Table) # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType]
+ assert "simple_field" in result
+ assert "nested_mapping" in result
+ assert "list_field" in result
+ assert "complex_list" in result
+
+ def test_convert_mapping_to_table_with_field_ordering(self, mocker: MockerFixture, mock_plx_config: PlxConfig):
+ """Test converting mapping with field ordering."""
+ _mock_config = mocker.patch.object(PlxFactory, '_plx_config', return_value=mock_plx_config)
+
+ mapping = {"field3": "value3", "field1": "value1", "field2": "value2"}
+ field_ordering = ["field1", "field2"]
+
+ result = PlxFactory.convert_mapping_to_table(mapping, field_ordering)
+
+ assert isinstance(result, tomlkit.items.Table) # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType]
+ # Check ordering (note: tomlkit preserves insertion order)
+ keys = list(result.keys())
+ assert keys[0] == "field1"
+ assert keys[1] == "field2"
+ assert keys[2] == "field3"
+
+ def test_convert_mapping_to_table_skips_category(self, mocker: MockerFixture, mock_plx_config: PlxConfig):
+ """Test that category field is skipped."""
+ _mock_config = mocker.patch.object(PlxFactory, '_plx_config', return_value=mock_plx_config)
+
+ mapping = {"field1": "value1", "category": "should_be_skipped", "field2": "value2"}
+ result = PlxFactory.convert_mapping_to_table(mapping)
+
+ assert isinstance(result, tomlkit.items.Table) # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType]
+ assert "field1" in result
+ assert "field2" in result
+ assert "category" not in result
+
+ def test_add_spaces_to_inline_tables_simple(self):
+ """Test adding spaces to simple inline tables."""
+ input_toml = "{key = value}"
+ result = PlxFactory.add_spaces_to_inline_tables(input_toml)
+ assert result == "{ key = value }"
+
+ def test_add_spaces_to_inline_tables_already_spaced(self):
+ """Test that already spaced tables are preserved."""
+ input_toml = "{ key = value }"
+ result = PlxFactory.add_spaces_to_inline_tables(input_toml)
+ assert result == "{ key = value }"
+
+ def test_add_spaces_to_inline_tables_nested(self):
+ """Test adding spaces to nested inline tables."""
+ input_toml = "{outer = {inner = value}}"
+ result = PlxFactory.add_spaces_to_inline_tables(input_toml)
+ assert result == "{ outer = { inner = value } }"
+
+ def test_add_spaces_to_inline_tables_with_jinja2(self):
+ """Test that Jinja2 templates are preserved."""
+ input_toml = "template = '{{ variable }}' and {key = value}"
+ result = PlxFactory.add_spaces_to_inline_tables(input_toml)
+ assert result == "template = '{{ variable }}' and { key = value }"
+
+ def test_add_spaces_to_inline_tables_complex(self):
+ """Test complex inline table spacing."""
+ input_toml = "config = {db = {host = 'localhost', port = 5432}, cache = {enabled = true}}"
+ result = PlxFactory.add_spaces_to_inline_tables(input_toml)
+ expected = "config = { db = { host = 'localhost', port = 5432 }, cache = { enabled = true } }"
+ assert result == expected
+
+ def test_add_spaces_to_inline_tables_partial_spacing(self):
+ """Test partial spacing scenarios."""
+ # Left space only
+ input_toml = "{ key = value}"
+ result = PlxFactory.add_spaces_to_inline_tables(input_toml)
+ assert result == "{ key = value }"
+
+ # Right space only
+ input_toml = "{key = value }"
+ result = PlxFactory.add_spaces_to_inline_tables(input_toml)
+ assert result == "{ key = value }"
+
+ def test_make_table_obj_for_pipe(self, mocker: MockerFixture, mock_plx_config: PlxConfig):
+ """Test making table object for pipe section."""
+ _mock_config = mocker.patch.object(PlxFactory, '_plx_config', return_value=mock_plx_config)
+
+ pipe_data = {
+ "type": "PipeLLM",
+ "definition": "Test pipe",
+ "inputs": {"input1": "Text"},
+ "output": "Text",
+ "nested_config": {
+ "param1": "value1",
+ "param2": 42
+ }
+ }
+
+ result = PlxFactory.make_table_obj_for_pipe(pipe_data)
+
+ assert isinstance(result, tomlkit.items.Table) # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType]
+ assert "type" in result
+ assert "definition" in result
+ assert "inputs" in result
+ assert "output" in result
+ assert "nested_config" in result
+
+ def test_make_table_obj_for_concept_simple_string(self, mocker: MockerFixture, mock_plx_config: PlxConfig):
+ """Test making table object for concept with simple string definition."""
+ _mock_config = mocker.patch.object(PlxFactory, '_plx_config', return_value=mock_plx_config)
+
+ concept_data = {
+ "SimpleConcept": "A simple concept definition"
+ }
+
+ result = PlxFactory.make_table_obj_for_concept(concept_data)
+
+ assert isinstance(result, tomlkit.items.Table) # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType]
+ assert "SimpleConcept" in result
+ assert result["SimpleConcept"] == "A simple concept definition"
+
+ def test_make_table_obj_for_concept_with_structure(self, mocker: MockerFixture, mock_plx_config: PlxConfig):
+ """Test making table object for concept with structure."""
+ _mock_config = mocker.patch.object(PlxFactory, '_plx_config', return_value=mock_plx_config)
+
+ concept_data = {
+ "ComplexConcept": {
+ "definition": "A complex concept",
+ "structure": {
+ "field1": "string",
+ "field2": "int"
+ }
+ }
+ }
+
+ result = PlxFactory.make_table_obj_for_concept(concept_data)
+
+ assert isinstance(result, tomlkit.items.Table) # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType]
+ assert "ComplexConcept" in result
+ assert isinstance(result["ComplexConcept"], tomlkit.items.Table) # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType]
+ assert "definition" in result["ComplexConcept"]
+ assert "structure" in result["ComplexConcept"]
+
+ def test_make_table_obj_for_concept_structure_string(self, mocker: MockerFixture, mock_plx_config: PlxConfig):
+ """Test concept with structure as string."""
+ _mock_config = mocker.patch.object(PlxFactory, '_plx_config', return_value=mock_plx_config)
+
+ concept_data = {
+ "ConceptWithStringStructure": {
+ "structure": "SomeClass"
+ }
+ }
+
+ result = PlxFactory.make_table_obj_for_concept(concept_data)
+
+ assert isinstance(result, tomlkit.items.Table) # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType]
+ concept_table = result["ConceptWithStringStructure"]
+ assert isinstance(concept_table, tomlkit.items.Table) # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType]
+ assert concept_table["structure"] == "SomeClass"
+
+ def test_make_table_obj_for_concept_invalid_structure(self, mocker: MockerFixture, mock_plx_config: PlxConfig):
+ """Test error handling for invalid structure types."""
+ _mock_config = mocker.patch.object(PlxFactory, '_plx_config', return_value=mock_plx_config)
+
+ concept_data = {
+ "InvalidConcept": {
+ "structure": 123 # Invalid type
+ }
+ }
+
+ with pytest.raises(TypeError, match="Structure field value is not a mapping"):
+ PlxFactory.make_table_obj_for_concept(concept_data)
+
+ def test_make_table_obj_for_concept_invalid_concept_value(self, mocker: MockerFixture, mock_plx_config: PlxConfig):
+ """Test error handling for invalid concept value types."""
+ _mock_config = mocker.patch.object(PlxFactory, '_plx_config', return_value=mock_plx_config)
+
+ concept_data = {
+ "InvalidConcept": 123 # Invalid type
+ }
+
+ with pytest.raises(TypeError, match="Concept field value is not a mapping"):
+ PlxFactory.make_table_obj_for_concept(concept_data)
+
+ def test_dict_to_plx_styled_toml_with_spacing(self, mocker: MockerFixture, mock_plx_config: PlxConfig):
+ """Test dict to PLX styled TOML with spacing enabled."""
+ mock_plx_config.inline_tables.spaces_inside_curly_braces = True
+ _mock_config = mocker.patch.object(PlxFactory, '_plx_config', return_value=mock_plx_config)
+ mock_add_spaces = mocker.patch.object(PlxFactory, 'add_spaces_to_inline_tables', return_value="spaced_output")
+
+ data = {"domain": "test", "definition": "test domain"}
+
+ result = PlxFactory.dict_to_plx_styled_toml(data)
+
+ assert result == "spaced_output"
+ mock_add_spaces.assert_called_once()
+
+ def test_dict_to_plx_styled_toml_without_spacing(self, mocker: MockerFixture, mock_plx_config: PlxConfig):
+ """Test dict to PLX styled TOML without spacing."""
+ mock_plx_config.inline_tables.spaces_inside_curly_braces = False
+ _mock_config = mocker.patch.object(PlxFactory, '_plx_config', return_value=mock_plx_config)
+ mock_add_spaces = mocker.patch.object(PlxFactory, 'add_spaces_to_inline_tables')
+
+ data = {"domain": "test", "definition": "test domain"}
+
+ result = PlxFactory.dict_to_plx_styled_toml(data)
+
+ # Should not call add_spaces_to_inline_tables
+ mock_add_spaces.assert_not_called()
+ assert isinstance(result, str)
+
+ def test_dict_to_plx_styled_toml_empty_sections(self, mocker: MockerFixture, mock_plx_config: PlxConfig):
+ """Test handling of empty sections."""
+ _mock_config = mocker.patch.object(PlxFactory, '_plx_config', return_value=mock_plx_config)
+
+ data: dict[str, Any] = {
+ "domain": "test",
+ "concept": {}, # Empty concept section
+ "pipe": {} # Empty pipe section
+ }
+
+ result = PlxFactory.dict_to_plx_styled_toml(data)
+
+ # Empty sections should be skipped
+ assert "concept" not in result
+ assert "pipe" not in result
+ assert "domain" in result
+
+ def test_dict_to_plx_styled_toml_with_pipe_section(self, mocker: MockerFixture, mock_plx_config: PlxConfig):
+ """Test dict to PLX styled TOML with pipe section."""
+ _mock_config = mocker.patch.object(PlxFactory, '_plx_config', return_value=mock_plx_config)
+
+ data = {
+ "domain": "test",
+ "pipe": {
+ "test_pipe": {
+ "type": "PipeLLM",
+ "definition": "Test pipe"
+ }
+ }
+ }
+
+ result = PlxFactory.dict_to_plx_styled_toml(data)
+
+ assert "domain" in result
+ assert "[pipe.test_pipe]" in result
+ assert "type" in result
+ assert "definition" in result
+
+ def test_dict_to_plx_styled_toml_with_concept_section(self, mocker: MockerFixture, mock_plx_config: PlxConfig):
+ """Test dict to PLX styled TOML with concept section."""
+ _mock_config = mocker.patch.object(PlxFactory, '_plx_config', return_value=mock_plx_config)
+
+ data = {
+ "domain": "test",
+ "concept": {
+ "TestConcept": "A test concept"
+ }
+ }
+
+ result = PlxFactory.dict_to_plx_styled_toml(data)
+
+ assert "domain" in result
+ assert "[concept]" in result
+ assert "TestConcept" in result