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.

fix all tests

thomashebrard2a7850927955
diff --git a/pipelex/core/stuffs/stuff_factory.py b/pipelex/core/stuffs/stuff_factory.py
index ea487a294..b64a88ce0 100644
--- a/pipelex/core/stuffs/stuff_factory.py
+++ b/pipelex/core/stuffs/stuff_factory.py
@@ -162,17 +162,17 @@ class StuffFactory:
# Case 1.3: StuffContent object → Infer concept from class name
if issubclass(type(stuff_content_or_data), StuffContent):
stuff_content = cast("StuffContent", stuff_content_or_data)
-
+
# Case 1.3b: Special handling for ListContent (subcase of 1.3)
if isinstance(stuff_content_or_data, ListContent):
list_content = cast("ListContent[StuffContent]", stuff_content_or_data)
-
+
if len(list_content.items) == 0:
msg = f"Cannot create Stuff '{name}' from empty ListContent"
raise StuffFactoryError(msg)
-
+
first_item = list_content.items[0]
-
+
# Check that items are StuffContent
if not isinstance(first_item, StuffContent): # pyright: ignore[reportUnnecessaryIsInstance]
msg = (
@@ -181,7 +181,7 @@ class StuffFactory:
"ListContent items must be subclasses of StuffContent."
)
raise StuffFactoryError(msg)
-
+
# Check all items are of the same type
for item in list_content.items:
if not isinstance(item, type(first_item)):
@@ -191,7 +191,7 @@ class StuffFactory:
"Every items of the list should be an identical type."
)
raise StuffFactoryError(msg)
-
+
# Get concept from first item's class name
content_class_name = type(first_item).__name__
else:
@@ -234,8 +234,10 @@ class StuffFactory:
if isinstance(first_item, str):
for item in stuff_content_or_data:
if not isinstance(item, str):
- msg = f"Trying to create a Stuff '{name}' from a list of strings but the item {item} is not a string."
- "Every items of the list should be a identical type. If its a string, everything should be a string."
+ msg = (
+ f"Trying to create a Stuff '{name}' from a list of strings but the item {item} is not a string. "
+ "Every items of the list should be a identical type. If its a string, everything should be a string."
+ )
raise StuffFactoryError(msg)
items = [TextContent(text=item) for item in cast("list[str]", stuff_content_or_data)]
@@ -254,9 +256,11 @@ class StuffFactory:
# Check all items are of the same type
for item in stuff_content_or_data:
if not isinstance(item, type(first_item)):
- msg = f"Trying to create a Stuff '{name}' from a list of '{type(first_item).__name__}' "
- f"but the items are not of the same type. Especially, items {item} is of type {type(item).__name__}"
- "Every items of the list should be a identical type. If its a string, everything should be a string."
+ msg = (
+ f"Trying to create a Stuff '{name}' from a list of '{type(first_item).__name__}' "
+ f"but the items are not of the same type. Especially, items {item} is of type {type(item).__name__}. "
+ "Every items of the list should be a identical type. If its a string, everything should be a string."
+ )
raise StuffFactoryError(msg)
# Check if it's a native concept
diff --git a/tests/unit/core/stuffs/data.py b/tests/unit/core/stuffs/data.py
index aaa438d89..390ad0880 100644
--- a/tests/unit/core/stuffs/data.py
+++ b/tests/unit/core/stuffs/data.py
@@ -19,6 +19,13 @@ class MyConcept(StructuredContent):
arg3: MySubClass = Field(description="Test argument 3")
+class AnotherConcept(StructuredContent):
+ """A concept for testing concept resolution with search domains."""
+
+ name: str = Field(description="Name field")
+ value: int = Field(description="Value field")
+
+
TEST_CASES: list[tuple[str, StuffContentOrData, str, str, Stuff]] = [
# Case 1.1: Content is a string
(
@@ -361,3 +368,211 @@ TEST_CASES: list[tuple[str, StuffContentOrData, str, str, Stuff]] = [
),
),
]
+
+
+# Test cases with search_domains - format: (test_name, stuff_content_or_data, stuff_name, stuff_code, search_domains, expected_stuff)
+SEARCH_DOMAIN_TEST_CASES: list[tuple[str, StuffContentOrData, str, str, list[str], Stuff]] = [
+ # Case with search_domains: StuffContent object
+ (
+ "search-domain-stuff-content",
+ AnotherConcept(name="test", value=42),
+ "stuff_name",
+ "stuff_code",
+ ["test_domain"],
+ Stuff(
+ stuff_name="stuff_name",
+ stuff_code="stuff_code",
+ concept=ConceptFactory.make(
+ concept_code="AnotherConcept",
+ domain="test_domain",
+ description="Test concept for search domains",
+ structure_class_name="AnotherConcept",
+ ),
+ content=AnotherConcept(name="test", value=42),
+ ),
+ ),
+ # Case with search_domains: List of StuffContent objects
+ (
+ "search-domain-list-stuff-content",
+ [
+ AnotherConcept(name="test1", value=1),
+ AnotherConcept(name="test2", value=2),
+ ],
+ "stuff_name",
+ "stuff_code",
+ ["test_domain"],
+ Stuff(
+ stuff_name="stuff_name",
+ stuff_code="stuff_code",
+ concept=ConceptFactory.make(
+ concept_code="AnotherConcept",
+ domain="test_domain",
+ description="Test concept for search domains",
+ structure_class_name="AnotherConcept",
+ ),
+ content=ListContent(
+ items=[
+ AnotherConcept(name="test1", value=1),
+ AnotherConcept(name="test2", value=2),
+ ]
+ ),
+ ),
+ ),
+ # Case with search_domains: ListContent of StuffContent objects
+ (
+ "search-domain-list-content",
+ ListContent(
+ items=[
+ AnotherConcept(name="test1", value=1),
+ AnotherConcept(name="test2", value=2),
+ ]
+ ),
+ "stuff_name",
+ "stuff_code",
+ ["test_domain"],
+ Stuff(
+ stuff_name="stuff_name",
+ stuff_code="stuff_code",
+ concept=ConceptFactory.make(
+ concept_code="AnotherConcept",
+ domain="test_domain",
+ description="Test concept for search domains",
+ structure_class_name="AnotherConcept",
+ ),
+ content=ListContent(
+ items=[
+ AnotherConcept(name="test1", value=1),
+ AnotherConcept(name="test2", value=2),
+ ]
+ ),
+ ),
+ ),
+ # Case with search_domains: Dict with concept and content
+ (
+ "search-domain-dict",
+ {
+ "concept": "test_domain.AnotherConcept",
+ "content": {"name": "test", "value": 100},
+ },
+ "stuff_name",
+ "stuff_code",
+ ["test_domain"],
+ Stuff(
+ stuff_name="stuff_name",
+ stuff_code="stuff_code",
+ concept=ConceptFactory.make(
+ concept_code="AnotherConcept",
+ domain="test_domain",
+ description="Test concept for search domains",
+ structure_class_name="AnotherConcept",
+ ),
+ content=AnotherConcept(name="test", value=100),
+ ),
+ ),
+]
+
+
+# Error test cases - these should raise exceptions
+ERROR_TEST_CASES: list[tuple[str, StuffContentOrData, str, str, list[str] | None, type[Exception], str]] = [
+ # Format: (test_name, stuff_content_or_data, stuff_name, stuff_code, search_domains, expected_exception, error_match)
+ # Empty list - should fail
+ (
+ "error-empty-list",
+ [],
+ "stuff_name",
+ "stuff_code",
+ None,
+ Exception,
+ "empty list",
+ ),
+ # Empty ListContent - should fail
+ (
+ "error-empty-list-content",
+ ListContent(items=[]),
+ "stuff_name",
+ "stuff_code",
+ None,
+ Exception,
+ "empty ListContent",
+ ),
+ # Mixed types in list - should fail
+ (
+ "error-mixed-types-in-list",
+ [
+ TextContent(text="text1"),
+ MyConcept(arg1="arg1", arg2=1, arg3=MySubClass(arg4="arg4")),
+ ],
+ "stuff_name",
+ "stuff_code",
+ None,
+ Exception,
+ "items are not of the same type",
+ ),
+ # Mixed types in ListContent - should fail
+ (
+ "error-mixed-types-in-list-content",
+ ListContent(
+ items=[
+ TextContent(text="text1"),
+ MyConcept(arg1="arg1", arg2=1, arg3=MySubClass(arg4="arg4")),
+ ]
+ ),
+ "stuff_name",
+ "stuff_code",
+ None,
+ Exception,
+ "items are not of the same type",
+ ),
+ # Note: Cannot test ListContent with non-StuffContent items because
+ # Pydantic validates at construction time and would fail before we can test it
+ # Concept not found - should fail
+ (
+ "error-concept-not-found",
+ {"concept": "NonExistentConcept", "content": {"field": "value"}},
+ "stuff_name",
+ "stuff_code",
+ None,
+ Exception,
+ "not found",
+ ),
+ # Dict without concept key - should fail
+ (
+ "error-dict-without-concept",
+ {"content": "some content"},
+ "stuff_name",
+ "stuff_code",
+ None,
+ Exception,
+ "'concept' key",
+ ),
+ # Dict without content key - should fail
+ (
+ "error-dict-without-content",
+ {"concept": "Text"},
+ "stuff_name",
+ "stuff_code",
+ None,
+ Exception,
+ "'content' key",
+ ),
+ # Dict with extra keys - should fail
+ (
+ "error-dict-with-extra-keys",
+ {"concept": "Text", "content": "text", "extra": "key"},
+ "stuff_name",
+ "stuff_code",
+ None,
+ Exception,
+ "exactly keys",
+ ),
+ # Incompatible concept for string content - should fail
+ (
+ "error-incompatible-concept-for-string",
+ {"concept": "test_domain.MyConcept", "content": "plain text"},
+ "stuff_name",
+ "stuff_code",
+ ["test_domain"],
+ Exception,
+ "not compatible",
+ ),
+]
diff --git a/tests/unit/core/stuffs/test_stuff_factory_implicit_memory.py b/tests/unit/core/stuffs/test_stuff_factory_implicit_memory.py
index d36cee690..7831eba7f 100644
--- a/tests/unit/core/stuffs/test_stuff_factory_implicit_memory.py
+++ b/tests/unit/core/stuffs/test_stuff_factory_implicit_memory.py
@@ -11,7 +11,7 @@ from pipelex.core.stuffs.stuff import Stuff
from pipelex.core.stuffs.stuff_factory import StuffFactory
from pipelex.hub import get_concept_library
from pipelex.system.registries.class_registry_utils import ClassRegistryUtils
-from tests.unit.core.stuffs.data import TEST_CASES
+from tests.unit.core.stuffs.data import ERROR_TEST_CASES, SEARCH_DOMAIN_TEST_CASES, TEST_CASES
@pytest.fixture(scope="class")
@@ -46,10 +46,21 @@ def setup_test_concept():
)
concept_library.add_new_concept(concept=concept_not_native_text)
+ # Create AnotherConcept for search domain tests
+ concept_another = ConceptFactory.make(
+ concept_code="AnotherConcept",
+ domain="test_domain",
+ description="Test concept for search domains",
+ structure_class_name="AnotherConcept",
+ )
+ concept_library.add_new_concept(concept=concept_another)
+
yield concept
# Cleanup after test
- concept_library.remove_concepts_by_concept_strings(concept_strings=["test_domain.MyConcept", "test_domain.MyConceptNotNativeText"])
+ concept_library.remove_concepts_by_concept_strings(
+ concept_strings=["test_domain.MyConcept", "test_domain.MyConceptNotNativeText", "test_domain.AnotherConcept"]
+ )
class TestStuffFactoryImplicitMemory:
@@ -57,10 +68,13 @@ class TestStuffFactoryImplicitMemory:
This covers cases where stuff_content_or_data is:
- Case 1: Direct content (no 'concept' key)
- - A string (1.1)
- - A list of strings (1.2)
- - A StuffContent object (1.3)
- - A list of StuffContent objects (1.4)
+ - String (1.1)
+ - List of strings (1.2)
+ - TextContent object - native (1.2b)
+ - List of TextContent objects - native (1.2c)
+ - StuffContent object - custom (1.3 / 1.3a)
+ - ListContent of StuffContent objects (1.3b, formerly 1.5)
+ - List of StuffContent objects (1.4)
- Case 2: Dict with 'concept' AND 'content' keys
- String content (2.1, 2.1b, 2.1c)
- List of strings (2.2, 2.2b)
@@ -86,74 +100,80 @@ class TestStuffFactoryImplicitMemory:
log.info(f"Testing case: {test_name}")
log.debug(f"setup_test_concept: {setup_test_concept}")
+ result = StuffFactory.make_stuff_from_stuff_content_or_data(
+ name=stuff_name,
+ code=stuff_code,
+ stuff_content_or_data=stuff_content_or_data,
+ )
+ pretty_print(result, title=f"Result for test case: {test_name}")
+ pretty_print(expected_stuff, title=f"Expected stuff for test case: {test_name}")
+
+ assert result == expected_stuff, f"Failed for test case: {test_name}"
+
+
+class TestStuffFactoryImplicitMemoryWithSearchDomains:
+ """Test StuffFactory with search_domains parameter.
+
+ This tests that search_domains correctly resolves concepts.
+ """
+ @pytest.mark.parametrize(
+ ("test_name", "stuff_content_or_data", "stuff_name", "stuff_code", "search_domains", "expected_stuff"),
+ SEARCH_DOMAIN_TEST_CASES,
+ )
+ def test_search_domain_case(
+ self,
+ setup_test_concept: Any,
+ test_name: str,
+ stuff_content_or_data: StuffContentOrData,
+ stuff_name: str,
+ stuff_code: str,
+ search_domains: list[str],
+ expected_stuff: Stuff,
+ ):
+ log.info(f"Testing search domain case: {test_name}")
+ log.debug(f"setup_test_concept: {setup_test_concept}")
result = StuffFactory.make_stuff_from_stuff_content_or_data(
name=stuff_name,
code=stuff_code,
stuff_content_or_data=stuff_content_or_data,
+ search_domains=search_domains,
)
+
pretty_print(result, title=f"Result for test case: {test_name}")
pretty_print(expected_stuff, title=f"Expected stuff for test case: {test_name}")
assert result == expected_stuff, f"Failed for test case: {test_name}"
-# class TestStuffFactoryImplicitMemoryEdgeCases:
-# """Test edge cases and error conditions."""
-
-# def test_empty_list_raises_error(self):
-# """Test that empty list raises appropriate error."""
-# with pytest.raises(Exception) as exc_info:
-# StuffFactory.make_stuff_from_stuff_content_using_search_domains(
-# name="test_stuff",
-# stuff_content_or_data=[],
-# search_domains=["test_domain"],
-# )
-# assert "no items" in str(exc_info.value).lower()
-
-# def test_dict_without_concept_raises_error(self):
-# """Test that dict without concept key raises appropriate error."""
-# with pytest.raises(Exception) as exc_info:
-# StuffFactory.make_stuff_from_stuff_content_using_search_domains(
-# name="test_stuff",
-# stuff_content_or_data={"content": "some content"},
-# search_domains=["test_domain"],
-# )
-# assert "concept" in str(exc_info.value).lower()
-
-# def test_dict_without_content_raises_error(self):
-# """Test that dict without content key raises appropriate error."""
-# with pytest.raises(Exception) as exc_info:
-# StuffFactory.make_stuff_from_stuff_content_using_search_domains(
-# name="test_stuff",
-# stuff_content_or_data={"concept": "Text"},
-# search_domains=["test_domain"],
-# )
-# assert "content" in str(exc_info.value).lower()
-
-# def test_concept_not_found_raises_error(self, setup_test_concept):
-# """Test that non-existent concept raises appropriate error."""
-# with pytest.raises(Exception) as exc_info:
-# StuffFactory.make_stuff_from_stuff_content_using_search_domains(
-# name="test_stuff",
-# stuff_content_or_data={
-# "concept": "NonExistentConcept",
-# "content": {"some": "data"},
-# },
-# search_domains=["test_domain"],
-# )
-# # Should raise error about concept not found
-
-# def test_list_with_mixed_types_raises_error(self, setup_test_concept):
-# """Test that list with mixed StuffContent types raises error."""
-# # This should ideally raise an error or at least log a warning
-# # The current implementation might not catch this, but it should
-# with pytest.raises(Exception):
-# StuffFactory.make_stuff_from_stuff_content_using_search_domains(
-# name="test_stuff",
-# stuff_content_or_data=[
-# MyConcept(arg1="arg1", arg2=1, arg3=MySubClass(arg4="arg4")),
-# TextContent(text="different type"), # Different type!
-# ],
-# search_domains=["test_domain"],
-# )
+class TestStuffFactoryImplicitMemoryErrors:
+ """Test StuffFactory error cases.
+
+ This tests that the factory properly raises exceptions for invalid inputs.
+ """
+
+ @pytest.mark.parametrize(
+ ("test_name", "stuff_content_or_data", "stuff_name", "stuff_code", "search_domains", "expected_exception", "error_match"),
+ ERROR_TEST_CASES,
+ )
+ def test_error_case(
+ self,
+ setup_test_concept: Any,
+ test_name: str,
+ stuff_content_or_data: StuffContentOrData,
+ stuff_name: str,
+ stuff_code: str,
+ search_domains: list[str] | None,
+ expected_exception: type[Exception],
+ error_match: str,
+ ):
+ log.info(f"Testing error case: {test_name}")
+ log.debug(f"setup_test_concept: {setup_test_concept}")
+
+ with pytest.raises(expected_exception, match=error_match):
+ StuffFactory.make_stuff_from_stuff_content_or_data(
+ name=stuff_name,
+ code=stuff_code,
+ stuff_content_or_data=stuff_content_or_data,
+ search_domains=search_domains,
+ )
diff --git a/tests/unit/pipelex/client/test_api_serialization.py b/tests/unit/pipelex/client/test_api_serialization.py
index bc3218a1c..416445ba9 100644
--- a/tests/unit/pipelex/client/test_api_serialization.py
+++ b/tests/unit/pipelex/client/test_api_serialization.py
@@ -99,7 +99,7 @@ class TestApiSerialization:
# Check the dict structure
datetime_blueprint = implicit_memory["project_meeting"]
assert isinstance(datetime_blueprint, dict)
- assert datetime_blueprint["concept_code"] == "DateTimeEvent"
+ assert datetime_blueprint["concept"] == "DateTimeEvent"
# Check content is properly serialized
content = datetime_blueprint["content"]
@@ -144,9 +144,8 @@ class TestApiSerialization:
assert "sample_text" in implicit_memory
text_blueprint = cast("dict[str, Any]", implicit_memory["sample_text"])
- assert text_blueprint["concept_code"] == NativeConceptCode.TEXT
- assert isinstance(text_blueprint["content"], str)
- assert text_blueprint["content"] == "Sample text content"
+ assert text_blueprint["concept"] == NativeConceptCode.TEXT
+ assert text_blueprint["content"] == {"text": "Sample text content"}
def test_serialize_number_content(self, number_content_memory: WorkingMemory):
implicit_memory = ApiSerializer.serialize_working_memory_for_api(number_content_memory)
@@ -155,6 +154,6 @@ class TestApiSerialization:
assert "pi_value" in implicit_memory
number_blueprint = cast("dict[str, Any]", implicit_memory["pi_value"])
- assert number_blueprint["concept_code"] == NativeConceptCode.NUMBER
+ assert number_blueprint["concept"] == NativeConceptCode.NUMBER
assert isinstance(number_blueprint["content"], dict)
assert number_blueprint["content"]["number"] == 3.14159
diff --git a/tests/unit/pipelex/core/stuffs/test_stuff_factory_make_stuff_from_content.py b/tests/unit/pipelex/core/stuffs/test_stuff_factory_make_stuff_from_content.py
deleted file mode 100644
index 81135117a..000000000
--- a/tests/unit/pipelex/core/stuffs/test_stuff_factory_make_stuff_from_content.py
+++ /dev/null
@@ -1,361 +0,0 @@
-from typing import Any, ClassVar
-
-import pytest
-from pytest_mock import MockerFixture
-
-from pipelex.core.concepts.concept_native import NativeConceptCode
-from pipelex.core.stuffs.list_content import ListContent
-from pipelex.core.stuffs.structured_content import StructuredContent
-from pipelex.core.stuffs.stuff import Stuff
-from pipelex.core.stuffs.stuff_content import StuffContent
-from pipelex.core.stuffs.stuff_factory import StuffFactory, StuffFactoryError
-from pipelex.core.stuffs.text_content import TextContent
-
-
-class MockCustomContent(StructuredContent):
- title: str
- description: str
-
-
-class TestData:
- TEXT_STRING: ClassVar[str] = "This is a test text"
- CONCEPT_NAME: ClassVar[str] = "TestConcept"
- SEARCH_DOMAINS: ClassVar[list[str]] = ["test", "native"]
- STUFF_NAME: ClassVar[str] = "test_stuff"
- STUFF_CODE: ClassVar[str] = "test123"
-
- # ListContent test data
- TEXT_LIST_ITEMS: ClassVar[list[TextContent]] = [
- TextContent(text="Item 1"),
- TextContent(text="Item 2"),
- ]
- EMPTY_LIST_CONTENT: ClassVar[ListContent[TextContent]] = ListContent(items=[])
-
- # Dictionary test data - native concept
- NATIVE_TEXT_DICT: ClassVar[dict[str, Any]] = {"concept": NativeConceptCode.TEXT.concept_string, "content": {"text": "Native text content"}}
-
- # Dictionary test data - custom concept with concept field
- CUSTOM_CONCEPT_DICT: ClassVar[dict[str, Any]] = {
- "concept": "test.CustomConcept",
- "content": {"title": "Test Title", "description": "Test Description"},
- }
-
- # Dictionary test data - custom concept with concept_code field
- CUSTOM_CONCEPT_CODE_DICT: ClassVar[dict[str, Any]] = {"concept_code": "test.AnotherConcept", "content": {"data": "test data"}}
-
- # Dictionary test data - missing concept
- MISSING_CONCEPT_DICT: ClassVar[dict[str, Any]] = {"content": {"data": "test data"}}
-
- # Dictionary test data - missing content
- MISSING_CONTENT_DICT: ClassVar[dict[str, Any]] = {"concept": "test.SomeConcept"}
-
-
-class TestMakeStuffFromStuffContentUsingSearchDomains:
- def test_listcontent_with_valid_items(self, mocker: MockerFixture):
- list_content: ListContent[TextContent] = ListContent(items=TestData.TEXT_LIST_ITEMS)
-
- mock_stuff = mocker.Mock(spec=Stuff)
- mock_make = mocker.patch.object(StuffFactory, "make_stuff_from_stuff_content_or_data", return_value=mock_stuff)
-
- result = StuffFactory.make_stuff_from_stuff_content_or_data(
- name=TestData.STUFF_NAME,
- stuff_content_or_data=list_content,
- search_domains=TestData.SEARCH_DOMAINS,
- code=TestData.STUFF_CODE,
- )
-
- assert result == mock_stuff
- mock_make.assert_called_once_with(
- concept_name="TextContent",
- search_domains=TestData.SEARCH_DOMAINS,
- content=list_content,
- name=TestData.STUFF_NAME,
- code=TestData.STUFF_CODE,
- )
-
- def test_listcontent_with_empty_items_raises_error(self):
- """Test ListContent with empty items raises StuffFactoryError."""
- with pytest.raises(StuffFactoryError, match="Cannot create Stuff 'test_stuff' from empty list"):
- StuffFactory.make_stuff_from_stuff_content_or_data(
- name=TestData.STUFF_NAME,
- stuff_content_or_data=TestData.EMPTY_LIST_CONTENT,
- search_domains=TestData.SEARCH_DOMAINS,
- )
-
- def test_listcontent_make_stuff_failure_wraps_error(self, mocker: MockerFixture):
- """Test ListContent wraps StuffFactoryError from make_stuff_using_concept_name_and_search_domains."""
- list_content: ListContent[TextContent] = ListContent(items=TestData.TEXT_LIST_ITEMS)
-
- original_error = StuffFactoryError("Original error")
- mocker.patch.object(StuffFactory, "make_stuff_using_concept_name_and_search_domains", side_effect=original_error)
-
- with pytest.raises(StuffFactoryError, match="Could not make stuff for ListContent 'test_stuff': Original error"):
- StuffFactory.make_stuff_from_stuff_content_or_data(
- name=TestData.STUFF_NAME,
- stuff_content_or_data=list_content,
- search_domains=TestData.SEARCH_DOMAINS,
- )
-
- def test_stuffcontent_with_native_concept(self, mocker: MockerFixture):
- """Test StuffContent with native concept class name."""
- mock_concept = mocker.Mock()
- mock_get_native_concept = mocker.patch("pipelex.core.stuffs.stuff_factory.get_native_concept", return_value=mock_concept)
-
- text_content = TextContent(text="test")
-
- mock_stuff = mocker.Mock(spec=Stuff)
- mocker.patch.object(StuffFactory, "make_stuff", return_value=mock_stuff)
-
- result = StuffFactory.make_stuff_from_stuff_content_or_data(
- name=TestData.STUFF_NAME,
- stuff_content_or_data=text_content,
- search_domains=TestData.SEARCH_DOMAINS,
- code=TestData.STUFF_CODE,
- )
-
- assert result == mock_stuff
- mock_get_native_concept.assert_called_once_with(native_concept=NativeConceptCode.TEXT)
-
- def test_stuffcontent_with_non_native_concept(self, mocker: MockerFixture):
- """Test StuffContent with non-native concept properly extracts concept name."""
- custom_content = MockCustomContent(title="Test", description="Test desc")
-
- mock_stuff = mocker.Mock(spec=Stuff)
- mock_make = mocker.patch.object(StuffFactory, "make_stuff_using_concept_name_and_search_domains", return_value=mock_stuff)
-
- result = StuffFactory.make_stuff_from_stuff_content_or_data(
- name=TestData.STUFF_NAME,
- stuff_content_or_data=custom_content,
- search_domains=TestData.SEARCH_DOMAINS,
- )
-
- assert result == mock_stuff
- mock_make.assert_called_once_with(
- concept_name="MockCustom", # Should extract this from MockCustomContent
- search_domains=TestData.SEARCH_DOMAINS,
- content=custom_content,
- name=TestData.STUFF_NAME,
- code=None,
- )
-
- def test_list_with_valid_items(self, mocker: MockerFixture):
- """Test plain list with valid items."""
- test_list = [TextContent(text="Item 1"), TextContent(text="Item 2")]
-
- mock_stuff = mocker.Mock(spec=Stuff)
- mock_make = mocker.patch.object(StuffFactory, "make_stuff_using_concept_name_and_search_domains", return_value=mock_stuff)
-
- result = StuffFactory.make_stuff_from_stuff_content_or_data(
- name=TestData.STUFF_NAME,
- stuff_content_or_data=test_list,
- search_domains=TestData.SEARCH_DOMAINS,
- code=TestData.STUFF_CODE,
- )
-
- assert result == mock_stuff
- # Verify the content is wrapped in ListContent
- call_args = mock_make.call_args[1]
- assert isinstance(call_args["content"], ListContent)
- assert call_args["content"].items == test_list
- assert call_args["concept_name"] == "TextContent"
-
- def test_list_with_empty_items_raises_error(self):
- """Test plain list with empty items raises StuffFactoryError."""
- with pytest.raises(StuffFactoryError, match="List in compact memory has no items"):
- StuffFactory.make_stuff_from_stuff_content_or_data(
- name=TestData.STUFF_NAME,
- stuff_content_or_data=[],
- search_domains=TestData.SEARCH_DOMAINS,
- )
-
- def test_list_make_stuff_failure_wraps_error(self, mocker: MockerFixture):
- """Test plain list wraps StuffFactoryError from make_stuff_using_concept_name_and_search_domains."""
- test_list = [TextContent(text="Item 1")]
-
- original_error = StuffFactoryError("Original error")
- mocker.patch.object(StuffFactory, "make_stuff_using_concept_name_and_search_domains", side_effect=original_error)
-
- with pytest.raises(StuffFactoryError, match="Could not make stuff for list of StuffContent 'test_stuff': Original error"):
- StuffFactory.make_stuff_from_stuff_content_or_data(
- name=TestData.STUFF_NAME,
- stuff_content_or_data=test_list,
- search_domains=TestData.SEARCH_DOMAINS,
- )
-
- def test_string_input(self, mocker: MockerFixture):
- """Test string input creates TextContent with TEXT concept."""
- mock_concept = mocker.Mock()
- mock_concept_factory = mocker.patch("pipelex.core.stuffs.stuff_factory.ConceptFactory")
- mock_concept_factory.make_native_concept.return_value = mock_concept
-
- mock_stuff = mocker.Mock(spec=Stuff)
- mocker.patch.object(StuffFactory, "make_stuff", return_value=mock_stuff)
-
- result = StuffFactory.make_stuff_from_stuff_content_or_data(
- name=TestData.STUFF_NAME,
- stuff_content_or_data=TestData.TEXT_STRING,
- search_domains=TestData.SEARCH_DOMAINS,
- )
-
- assert result == mock_stuff
- mock_concept_factory.make_native_concept.assert_called_once_with(native_concept_code=NativeConceptCode.TEXT)
-
- def test_dict_with_native_concept(self, mocker: MockerFixture):
- """Test dictionary with native concept."""
- # Mock ConceptFactory to handle native concept creation
- mock_concept = mocker.Mock()
- mock_concept_factory = mocker.patch("pipelex.core.stuffs.stuff_factory.ConceptFactory")
- mock_concept_factory.make_native_concept.return_value = mock_concept
-
- # Mock the make_domain_and_concept_code method
- mock_domain_and_code = mocker.Mock()
- mock_domain_and_code.concept_code = "Text"
- mock_concept_factory.make_domain_and_concept_code_from_concept_string_or_code.return_value = mock_domain_and_code
-
- mock_content = mocker.Mock(spec=StuffContent)
- mock_content_factory = mocker.patch("pipelex.core.stuffs.stuff_factory.StuffContentFactory")
- mock_content_factory.make_stuff_content_from_concept_with_fallback.return_value = mock_content
-
- mock_stuff = mocker.Mock(spec=Stuff)
- mocker.patch.object(StuffFactory, "make_stuff", return_value=mock_stuff)
-
- result = StuffFactory.make_stuff_from_stuff_content_or_data(
- name=TestData.STUFF_NAME,
- stuff_content_or_data=TestData.NATIVE_TEXT_DICT,
- search_domains=TestData.SEARCH_DOMAINS,
- code=TestData.STUFF_CODE,
- )
-
- assert result == mock_stuff
- mock_concept_factory.make_native_concept.assert_called_once()
- mock_content_factory.make_stuff_content_from_concept_with_fallback.assert_called_once()
-
- def test_dict_with_custom_concept_and_stuffcontent_value(self, mocker: MockerFixture):
- """Test dictionary with custom concept and StuffContent as content value."""
- # Patch where it's used (stuff_factory imports from hub), not where it's defined
- mock_provider = mocker.patch("pipelex.core.stuffs.stuff_factory.get_concept_library").return_value
- mock_concept = mocker.Mock()
- mock_provider.get_required_concept.return_value = mock_concept
-
- test_content = TextContent(text="test")
- test_dict = {"concept": "test.CustomConcept", "content": test_content}
-
- mock_stuff = mocker.Mock(spec=Stuff)
- mocker.patch.object(StuffFactory, "make_stuff", return_value=mock_stuff)
-
- result = StuffFactory.make_stuff_from_stuff_content_or_data(
- name=TestData.STUFF_NAME,
- stuff_content_or_data=test_dict,
- search_domains=TestData.SEARCH_DOMAINS,
- code=TestData.STUFF_CODE,
- )
-
- assert result == mock_stuff
- mock_provider.get_required_concept.assert_called_once_with(concept_string="test.CustomConcept")
-
- def test_dict_with_custom_concept_and_dict_value(self, mocker: MockerFixture):
- """Test dictionary with custom concept and dict as content value."""
- # Patch where it's used (stuff_factory imports from hub), not where it's defined
- mock_provider = mocker.patch("pipelex.core.stuffs.stuff_factory.get_concept_library").return_value
- mock_concept = mocker.Mock()
- mock_provider.get_required_concept.return_value = mock_concept
-
- mock_content = mocker.Mock(spec=StuffContent)
- mock_content_factory = mocker.patch("pipelex.core.stuffs.stuff_factory.StuffContentFactory")
- mock_content_factory.make_stuff_content_from_concept_with_fallback.return_value = mock_content
-
- mock_stuff = mocker.Mock(spec=Stuff)
- mocker.patch.object(StuffFactory, "make_stuff", return_value=mock_stuff)
-
- result = StuffFactory.make_stuff_from_stuff_content_or_data(
- name=TestData.STUFF_NAME,
- stuff_content_or_data=TestData.CUSTOM_CONCEPT_DICT,
- search_domains=TestData.SEARCH_DOMAINS,
- code=TestData.STUFF_CODE,
- )
-
- assert result == mock_stuff
- mock_provider.get_required_concept.assert_called_with(concept_string="test.CustomConcept")
- mock_content_factory.make_stuff_content_from_concept_with_fallback.assert_called_once_with(
- concept=mock_concept,
- value={"title": "Test Title", "description": "Test Description"},
- )
-
- def test_dict_with_concept_code_field(self, mocker: MockerFixture):
- """Test dictionary with concept_code field instead of concept."""
- # Patch where it's used (stuff_factory imports from hub), not where it's defined
- mock_provider = mocker.patch("pipelex.core.stuffs.stuff_factory.get_concept_library").return_value
- mock_concept = mocker.Mock()
- mock_provider.get_required_concept.return_value = mock_concept
-
- mock_content = mocker.Mock(spec=StuffContent)
- mock_content_factory = mocker.patch("pipelex.core.stuffs.stuff_factory.StuffContentFactory")
- mock_content_factory.make_stuff_content_from_concept_with_fallback.return_value = mock_content
-
- mock_stuff = mocker.Mock(spec=Stuff)
- mocker.patch.object(StuffFactory, "make_stuff", return_value=mock_stuff)
-
- result = StuffFactory.make_stuff_from_stuff_content_or_data(
- name=TestData.STUFF_NAME,
- stuff_content_or_data=TestData.CUSTOM_CONCEPT_CODE_DICT,
- search_domains=TestData.SEARCH_DOMAINS,
- )
-
- assert result == mock_stuff
-
- def test_dict_missing_concept_raises_error(self):
- """Test dictionary missing concept field raises StuffFactoryError."""
- with pytest.raises(StuffFactoryError, match="Stuff content data dict is badly formed: no concept code"):
- StuffFactory.make_stuff_from_stuff_content_or_data(
- name=TestData.STUFF_NAME,
- stuff_content_or_data=TestData.MISSING_CONCEPT_DICT,
- search_domains=TestData.SEARCH_DOMAINS,
- )
-
- def test_dict_missing_content_raises_error(self):
- """Test dictionary missing content field raises StuffFactoryError."""
- with pytest.raises(StuffFactoryError, match="Stuff content data dict is badly formed: 'content'"):
- StuffFactory.make_stuff_from_stuff_content_or_data(
- name=TestData.STUFF_NAME,
- stuff_content_or_data=TestData.MISSING_CONTENT_DICT,
- search_domains=TestData.SEARCH_DOMAINS,
- )
-
- def test_default_parameters(self, mocker: MockerFixture):
- """Test function with default parameters (no stuff_code)."""
- mock_concept = mocker.Mock()
- mock_concept_factory = mocker.patch("pipelex.core.stuffs.stuff_factory.ConceptFactory")
- mock_concept_factory.make_native_concept.return_value = mock_concept
-
- mock_stuff = mocker.Mock(spec=Stuff)
- mocker.patch.object(StuffFactory, "make_stuff", return_value=mock_stuff)
-
- result = StuffFactory.make_stuff_from_stuff_content_or_data(
- name=TestData.STUFF_NAME,
- stuff_content_or_data=TestData.TEXT_STRING,
- search_domains=TestData.SEARCH_DOMAINS,
- )
-
- assert result == mock_stuff
-
- def test_empty_search_domains(self, mocker: MockerFixture):
- """Test function with empty search domains list."""
- list_content: ListContent[TextContent] = ListContent(items=TestData.TEXT_LIST_ITEMS)
-
- mock_stuff = mocker.Mock(spec=Stuff)
- mock_make = mocker.patch.object(StuffFactory, "make_stuff_using_concept_name_and_search_domains", return_value=mock_stuff)
-
- result = StuffFactory.make_stuff_from_stuff_content_or_data(
- name=TestData.STUFF_NAME,
- stuff_content_or_data=list_content,
- search_domains=[],
- )
-
- assert result == mock_stuff
- mock_make.assert_called_once_with(
- concept_name="TextContent",
- search_domains=[],
- content=list_content,
- name=TestData.STUFF_NAME,
- code=None,
- )