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.

Chore/test pyramid (#110)

Louis Choquel7a93bc9bc713
diff --git a/.cursor/rules/pytest.mdc b/.cursor/rules/pytest.mdc
index 2b22e5bea..656cfe9fb 100644
--- a/.cursor/rules/pytest.mdc
+++ b/.cursor/rules/pytest.mdc
@@ -10,11 +10,11 @@ These rules apply when writing unit tests.
- Name test files with `test_` prefix
- Use descriptive names that match the functionality being tested
-- Place test files in the appropriate subdirectory of `tests/`:
- - `tests/tools/` for tests related to sub-package `pipelex.tools`
- - `tests/pipelex/` for tests related to `pipelex`and its sub-packages
- - `tests/pipelex/cogt/` for tests related to sub-package `pipelex.cogt`
-- More precisely, for `pipelex` and `pipelex.cogt` the async tests are placed inside subdirectories named `cogt_asynch` and `pipelex_asynch`
+- Place test files in the appropriate test category directory:
+ - `tests/unit/` - for unit tests that test individual functions/classes in isolation
+ - `tests/integration/` - for integration tests that test component interactions
+ - `tests/e2e/` - for end-to-end tests that test complete workflows
+ - `tests/test_pipelines/` - for test pipeline definitions (TOML files)
- Fixtures are defined in conftest.py modules at different levels of the hierarchy, their scope is handled by pytest
- Test data is placed inside test_data.py at different levels of the hierarchy, they must be imported with package paths from the root like `tests.pipelex.test_data`. Their content is all constants, regrouped inside classes to keep things tidy.
- Always put test inside Test classes.
@@ -55,7 +55,7 @@ class TestFooBar:
# Test implementation
```
-Sometimes it can be convenient to access the test's name in its body, for instance to include into a job_id. To achieve that, add the argument `request: FixtureRequest` into the signature and then you can get th test name using `cast(str, request.node.originalname), # type: ignore`.
+Sometimes it can be convenient to access the test's name in its body, for instance to include into a job_id. To achieve that, add the argument `request: FixtureRequest` into the signature and then you can get the test name using `cast(str, request.node.originalname), # type: ignore`.
# Pipe tests
diff --git a/.cursor/rules/standards.mdc b/.cursor/rules/standards.mdc
index 4c86f0e1e..4f768ea63 100644
--- a/.cursor/rules/standards.mdc
+++ b/.cursor/rules/standards.mdc
@@ -14,6 +14,7 @@ This document outlines the coding standards and quality control procedures that
Before finalizing a task, you must run the following command to check for linting issues, type errors, and code quality problems:
```bash
+make fix-unused-imports
make check
```
@@ -34,13 +35,7 @@ We have several make commands for running tests:
```
Use this for quick test runs that don't require LLM or image generation.
-2. `make ti`: Runs all tests with these markers:
- ```
- inference and not imgg
- ```
- Use this for testing LLM functionality without image generation.
-
-3. To run specific tests:
+2. To run specific tests:
```bash
make tp TEST=TestClassName
# or
@@ -48,6 +43,8 @@ We have several make commands for running tests:
```
It matches names, so `TEST=test_function_name` is going to run all test with the function name that STARTS with `test_function_name`.
+Note: never run `make ti`, `make test-inference`, `make to`, `make test-ocr`, `make tg`, or `make test-imgg`: these all use inference which is costly.
+
## Important Project Directories
### Pipelines Directory
diff --git a/Makefile b/Makefile
index 2a63b05ae..b759c9552 100644
--- a/Makefile
+++ b/Makefile
@@ -207,7 +207,7 @@ cleanall: cleanderived cleanenv cleanlibraries
codex-tests: env
$(call PRINT_TITLE,"Unit testing for Codex")
@echo "• Running unit tests for Codex (excluding inference and codex_disabled)"
- $(VENV_PYTEST) -n auto --exitfirst --quiet -m "(dry_runnable or not inference) and not (needs_output or pipelex_api or codex_disabled)" || [ $$? = 5 ]
+ $(VENV_PYTEST) --exitfirst -m "(dry_runnable or not inference) and not (needs_output or pipelex_api or codex_disabled)" || [ $$? = 5 ]
gha-tests: env
$(call PRINT_TITLE,"Unit testing for github actions")
@@ -318,6 +318,27 @@ test-pipelex-api: env
ta: test-pipelex-api
@echo "> done: ta = test-pipelex-api"
+cov: env
+ $(call PRINT_TITLE,"Unit testing with coverage")
+ @echo "• Running unit tests with coverage"
+ @if [ -n "$(TEST)" ]; then \
+ $(VENV_PYTEST) --cov=$(if $(PKG),$(PKG),pipelex) -k "$(TEST)" $(if $(filter 2,$(VERBOSE)),-vv,$(if $(filter 3,$(VERBOSE)),-vvv,-v)); \
+ else \
+ $(VENV_PYTEST) --cov=$(if $(PKG),$(PKG),pipelex) $(if $(filter 2,$(VERBOSE)),-vv,$(if $(filter 3,$(VERBOSE)),-vvv,-v)); \
+ fi
+
+cov-missing: env
+ $(call PRINT_TITLE,"Unit testing with coverage and missing lines")
+ @echo "• Running unit tests with coverage and missing lines"
+ @if [ -n "$(TEST)" ]; then \
+ $(VENV_PYTEST) --cov=$(if $(PKG),$(PKG),pipelex) --cov-report=term-missing -k "$(TEST)" $(if $(filter 2,$(VERBOSE)),-vv,$(if $(filter 3,$(VERBOSE)),-vvv,-v)); \
+ else \
+ $(VENV_PYTEST) --cov=$(if $(PKG),$(PKG),pipelex) --cov-report=term-missing $(if $(filter 2,$(VERBOSE)),-vv,$(if $(filter 3,$(VERBOSE)),-vvv,-v)); \
+ fi
+
+cm: cov-missing
+ @echo "> done: cm = cov-missing"
+
############################################################################################
############################ Linting ############################
############################################################################################
diff --git a/docs/pages/build-reliable-ai-workflows-with-pipelex/pipe-operators/PipeLLM.md b/docs/pages/build-reliable-ai-workflows-with-pipelex/pipe-operators/PipeLLM.md
index 93c1b8bf4..7fef68983 100644
--- a/docs/pages/build-reliable-ai-workflows-with-pipelex/pipe-operators/PipeLLM.md
+++ b/docs/pages/build-reliable-ai-workflows-with-pipelex/pipe-operators/PipeLLM.md
@@ -133,7 +133,6 @@ Analyze the document page shown in the image and explain how it relates to the p
2. **Fixed Multiple Outputs**: Use `nb_output = N` (where N is a positive integer) when you need exactly N outputs. For example, `nb_output = 3` will try to generate 3 results. The parameter `_nb_output` will be available in the prompt template, e.g. "Give me the names of $_nb_output flowers".
3. **Variable Multiple Outputs**: Use `multiple_output = true` when you need a variable-length list where the LLM determines how many outputs to generate based on the content and context.
-| `output_multiplicity` | string or integer | Defines the number of outputs. Use `"list"` for a variable-length list, or an integer (e.g., `3`) for a fixed-size list. | No |
## Examples
diff --git a/pipelex/core/stuff_factory.py b/pipelex/core/stuff_factory.py
index b01c9dbd5..eaaca9d8c 100644
--- a/pipelex/core/stuff_factory.py
+++ b/pipelex/core/stuff_factory.py
@@ -1,7 +1,7 @@
from typing import Any, Dict, List, Optional, Tuple
import shortuuid
-from pydantic import BaseModel, Field
+from pydantic import BaseModel, Field, ValidationError
from pipelex.config import get_config
from pipelex.core.concept import Concept
@@ -11,6 +11,7 @@ from pipelex.core.stuff import Stuff, StuffCreationRecord
from pipelex.core.stuff_content import StuffContent, StuffContentInitableFromStr
from pipelex.exceptions import ConceptError, PipelexError
from pipelex.hub import get_class_registry, get_required_concept
+from pipelex.tools.typing.pydantic_utils import format_pydantic_validation_error
class StuffFactoryError(PipelexError):
@@ -148,14 +149,22 @@ class StuffFactory:
return result
@classmethod
- def combine_stuffs(cls, concept_code: str, stuff_contents: Dict[str, StuffContent], name: Optional[str] = None) -> Stuff:
+ def combine_stuffs(
+ cls,
+ concept_code: str,
+ stuff_contents: Dict[str, StuffContent],
+ name: Optional[str] = None,
+ ) -> Stuff:
"""
Combine a dictionary of stuffs into a single stuff.
"""
the_concept = get_required_concept(concept_code=concept_code)
the_subclass_name = the_concept.structure_class_name
the_subclass = get_class_registry().get_required_subclass(name=the_subclass_name, base_class=StuffContent)
- the_stuff_content = the_subclass.model_validate(obj=stuff_contents)
+ try:
+ the_stuff_content = the_subclass.model_validate(obj=stuff_contents)
+ except ValidationError as exc:
+ raise StuffFactoryError(f"Error combining stuffs: {format_pydantic_validation_error(exc=exc)}") from exc
return cls.make_stuff(
concept_str=concept_code,
content=the_stuff_content,
diff --git a/pipelex/libraries/library_manager.py b/pipelex/libraries/library_manager.py
index f5be69c69..f4f8190dc 100644
--- a/pipelex/libraries/library_manager.py
+++ b/pipelex/libraries/library_manager.py
@@ -24,6 +24,7 @@ from pipelex.exceptions import (
StaticValidationError,
)
from pipelex.libraries.library_config import LibraryConfig
+from pipelex.tools.class_registry_utils import ClassRegistryUtils
from pipelex.tools.misc.file_utils import find_files_in_dir
from pipelex.tools.misc.json_utils import deep_update
from pipelex.tools.misc.toml_utils import load_toml_from_path
@@ -74,13 +75,13 @@ class LibraryManager:
def load_libraries(self):
log.debug("LibraryManager loading separate libraries")
- KajsonManager.get_class_registry().register_classes_in_folder(
+ ClassRegistryUtils.register_classes_in_folder(
folder_path=LibraryConfig.loaded_pipelines_path,
)
library_paths = [LibraryConfig.loaded_pipelines_path]
if runtime_manager.is_unit_testing:
log.debug("Registering test pipeline structures for unit testing")
- KajsonManager.get_class_registry().register_classes_in_folder(
+ ClassRegistryUtils.register_classes_in_folder(
folder_path=LibraryConfig.test_pipelines_path,
)
library_paths += [LibraryConfig.test_pipelines_path]
@@ -117,6 +118,7 @@ class LibraryManager:
pattern="*.toml",
is_recursive=True,
)
+ log.debug(f"Searching for TOML files in {libraries_path}, found '{found_file_paths}'")
if not found_file_paths:
log.warning(f"No TOML files found in library path: {libraries_path}")
toml_file_paths.extend(found_file_paths)
diff --git a/pipelex/pipe_operators/pipe_llm_factory.py b/pipelex/pipe_operators/pipe_llm_factory.py
index 95cca4c55..991d5c715 100644
--- a/pipelex/pipe_operators/pipe_llm_factory.py
+++ b/pipelex/pipe_operators/pipe_llm_factory.py
@@ -131,7 +131,7 @@ class PipeLLMFactory(PipeSpecificFactoryProtocol[PipeLLMBlueprint, PipeLLM]):
user_images=user_images or None,
)
- llm_settings = LLMSettingChoices(
+ llm_choices = LLMSettingChoices(
for_text=pipe_blueprint.llm,
for_object=pipe_blueprint.llm_to_structure,
for_object_direct=pipe_blueprint.llm_to_structure_direct,
@@ -152,7 +152,7 @@ class PipeLLMFactory(PipeSpecificFactoryProtocol[PipeLLMBlueprint, PipeLLM]):
inputs=PipeInputSpec(root=pipe_blueprint.inputs or {}),
output_concept_code=pipe_blueprint.output,
pipe_llm_prompt=pipe_llm_prompt,
- llm_choices=llm_settings,
+ llm_choices=llm_choices,
structuring_method=pipe_blueprint.structuring_method,
prompt_template_to_structure=pipe_blueprint.prompt_template_to_structure,
system_prompt_to_structure=pipe_blueprint.system_prompt_to_structure,
diff --git a/pipelex/plugins/openai/openai_factory.py b/pipelex/plugins/openai/openai_factory.py
index 35c653f9a..0cb832f8b 100644
--- a/pipelex/plugins/openai/openai_factory.py
+++ b/pipelex/plugins/openai/openai_factory.py
@@ -50,8 +50,8 @@ class OpenAIFactory:
base_url=endpoint,
)
case LLMPlatform.OPENAI:
- openai_openai_config = get_config().plugins.openai_config
- api_key = openai_openai_config.get_api_key(secrets_provider=get_secrets_provider())
+ openai_config = get_config().plugins.openai_config
+ api_key = openai_config.get_api_key(secrets_provider=get_secrets_provider())
the_client = openai.AsyncOpenAI(api_key=api_key)
case LLMPlatform.VERTEXAI:
vertexai_config = get_config().plugins.vertexai_config
diff --git a/pipelex/tools/class_registry_utils.py b/pipelex/tools/class_registry_utils.py
new file mode 100644
index 000000000..fca4ac202
--- /dev/null
+++ b/pipelex/tools/class_registry_utils.py
@@ -0,0 +1,83 @@
+import sys
+from pathlib import Path
+from typing import Any, List, Optional, Type
+
+from pipelex.hub import get_class_registry
+from pipelex.tools.typing.module_inspector import find_classes_in_module, import_module_from_file
+
+
+class ClassRegistryUtils:
+ @classmethod
+ def register_classes_in_file(
+ cls,
+ file_path: str,
+ base_class: Optional[Type[Any]],
+ is_include_imported: bool,
+ ) -> None:
+ """Processes a Python file to find and register classes."""
+ module = import_module_from_file(file_path)
+
+ # Find classes that match criteria
+ classes_to_register = find_classes_in_module(
+ module=module,
+ base_class=base_class,
+ include_imported=is_include_imported,
+ )
+
+ # Clean up sys.modules to prevent memory leaks
+ del sys.modules[module.__name__]
+
+ get_class_registry().register_classes(classes=classes_to_register)
+
+ @classmethod
+ def register_classes_in_folder(
+ cls,
+ folder_path: str,
+ base_class: Optional[Type[Any]] = None,
+ is_recursive: bool = True,
+ is_include_imported: bool = False,
+ ) -> None:
+ """
+ Registers all classes in Python files within folders that are subclasses of base_class.
+ If base_class is None, registers all classes.
+
+ Args:
+ folder_paths: List of paths to folders containing Python files
+ base_class: Optional base class to filter registerable classes
+ recursive: Whether to search recursively in subdirectories
+ exclude_files: List of filenames to exclude
+ exclude_dirs: List of directory names to exclude
+ include_imported: Whether to include classes imported from other modules
+ """
+
+ python_files = cls.find_files_in_dir(
+ dir_path=folder_path,
+ pattern="*.py",
+ is_recursive=is_recursive,
+ )
+
+ for python_file in python_files:
+ cls.register_classes_in_file(
+ file_path=str(python_file),
+ base_class=base_class,
+ is_include_imported=is_include_imported,
+ )
+
+ @classmethod
+ def find_files_in_dir(cls, dir_path: str, pattern: str, is_recursive: bool) -> List[Path]:
+ """
+ Find files matching a pattern in a directory.
+
+ Args:
+ dir_path: Directory path to search in
+ pattern: File pattern to match (e.g. "*.py")
+ recursive: Whether to search recursively in subdirectories
+
+ Returns:
+ List of matching Path objects
+ """
+ path = Path(dir_path)
+ if is_recursive:
+ return list(path.rglob(pattern))
+ else:
+ return list(path.glob(pattern))
diff --git a/pipelex/tools/typing/pydantic_utils.py b/pipelex/tools/typing/pydantic_utils.py
index fdcb995cb..ff269e7f7 100644
--- a/pipelex/tools/typing/pydantic_utils.py
+++ b/pipelex/tools/typing/pydantic_utils.py
@@ -27,6 +27,15 @@ def format_pydantic_validation_error(exc: ValidationError) -> str:
type_errors = [f"{'.'.join(map(str, err['loc']))}: expected {err['type']}" for err in exc.errors() if err["type"] == "type_error"]
value_errors = [f"{'.'.join(map(str, err['loc']))}: {err['msg']}" for err in exc.errors() if err["type"] == "value_error"]
enum_errors = [f"{'.'.join(map(str, err['loc']))}: invalid enum value" for err in exc.errors() if err["type"] == "enum"]
+ model_type_errors: List[str] = []
+ for err in exc.errors():
+ if err["type"] == "model_type":
+ field_path = ".".join(map(str, err["loc"]))
+ # Extract expected type from context if available
+ expected_type = err.get("ctx", {}).get("class_name", "unknown model type")
+ actual_input = err.get("input", "unknown")
+ actual_type = type(actual_input).__name__ if actual_input != "unknown" else "unknown"
+ model_type_errors.append(f"{field_path}: expected {expected_type}, got {actual_type}")
# Add each type of error to the message if present
if missing_fields:
@@ -39,9 +48,11 @@ def format_pydantic_validation_error(exc: ValidationError) -> str:
error_msg += f"\nValue errors: {value_errors}"
if enum_errors:
error_msg += f"\nEnum errors: {enum_errors}"
+ if model_type_errors:
+ error_msg += f"\nModel type errors: {model_type_errors}"
# If none of the specific error types were found, add the raw error messages
- if not any([missing_fields, extra_fields, type_errors, value_errors, enum_errors]):
+ if not any([missing_fields, extra_fields, type_errors, value_errors, enum_errors, model_type_errors]):
error_msg += "\nOther validation errors:"
for err in exc.errors():
error_msg += f"\n{'.'.join(map(str, err['loc']))}: {err['type']}: {err['msg']}"
diff --git a/pyproject.toml b/pyproject.toml
index cc8846d38..c6afa943d 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -24,7 +24,7 @@ dependencies = [
"instructor>=1.8.3",
"jinja2>=3.1.4",
"json2html>=1.3.0",
- "kajson==0.1.6",
+ "kajson==0.2.0",
"markdown>=3.6",
"networkx>=3.4.2",
"openai>=1.60.1",
@@ -71,6 +71,7 @@ dev = [
"pytest>=8.3.3",
"pytest-asyncio>=0.24.0",
"pytest-cov>=6.1.1",
+ "pytest-mock>=3.14.0",
"pytest-sugar>=1.0.0",
"pytest-xdist>= 3.6.1",
"ruff>=0.6.8",
@@ -217,6 +218,7 @@ markers = [
"pipelex_api: tests that require access to the Pipelex API",
]
minversion = "8.0"
+xfail_strict = true
[tool.coverage.run]
source = ["pipelex"]
diff --git a/tests/__init__.py b/tests/__init__.py
index 8b1378917..f7823efe4 100644
--- a/tests/__init__.py
+++ b/tests/__init__.py
@@ -1 +1,2 @@
-
+# tests package
+# Makes tests/ importable as a proper Python package
diff --git a/tests/cases/__init__.py b/tests/cases/__init__.py
new file mode 100644
index 000000000..f742bec03
--- /dev/null
+++ b/tests/cases/__init__.py
@@ -0,0 +1,22 @@
+"""Test case constants and data definitions.
+
+This package contains pure-Python test-case definitions without test logic.
+Each module exposes only data constants that can be imported cleanly.
+"""
+
+from .documents import Article, PDFTestCases
+from .images import ImageTestCases
+from .registry import ClassRegistryTestCases, FileHelperTestCases, Fruit
+from .templates import JINJA2TestCases
+from .urls import TestURLs
+
+__all__ = [
+ "Article",
+ "PDFTestCases",
+ "ImageTestCases",
+ "TestURLs",
+ "ClassRegistryTestCases",
+ "FileHelperTestCases",
+ "Fruit",
+ "JINJA2TestCases",
+]
diff --git a/tests/cases/documents.py b/tests/cases/documents.py
new file mode 100644
index 000000000..37b44ca91
--- /dev/null
+++ b/tests/cases/documents.py
@@ -0,0 +1,29 @@
+"""Document constants for testing."""
+
+from typing import ClassVar, List
+
+from pipelex.core.stuff_content import StructuredContent
+
+
+class PDFTestCases:
+ """PDF document test constants."""
+
+ # Directory paths
+ TEST_DOCUMENT_DIRECTORY = "tests/data/documents"
+
+ # Local file paths
+ DOCUMENT_FILE_PATHS: ClassVar[List[str]] = [
+ f"{TEST_DOCUMENT_DIRECTORY}/solar_system.pdf",
+ f"{TEST_DOCUMENT_DIRECTORY}/illustrated_train_article.pdf",
+ ]
+
+ # Remote URLs
+ DOCUMENT_URLS: ClassVar[List[str]] = ["https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"]
+
+
+class Article(StructuredContent):
+ """Test model for article data."""
+
+ title: str
+ description: str
+ date: str
diff --git a/tests/cases/images.py b/tests/cases/images.py
new file mode 100644
index 000000000..b4b6c4795
--- /dev/null
+++ b/tests/cases/images.py
@@ -0,0 +1,28 @@
+"""Image constants for testing."""
+
+from typing import ClassVar, List
+
+
+class ImageTestCases:
+ """Image test constants."""
+
+ # Directory paths
+ TEST_IMAGE_DIRECTORY = "tests/data/images"
+
+ # Individual file paths
+ IMAGE_FILE_PATH_PNG = f"{TEST_IMAGE_DIRECTORY}/ai_lympics.png"
+
+ # Remote URLs
+ IMAGE_URL_PNG = "https://www.python.org/static/community_logos/python-logo-master-v3-TM.png"
+
+ # File path collections
+ IMAGE_FILE_PATHS: ClassVar[List[str]] = [
+ f"{TEST_IMAGE_DIRECTORY}/ai_lympics.png",
+ f"{TEST_IMAGE_DIRECTORY}/animal_lympics.jpg",
+ ]
+
+ # URL collections
+ IMAGE_URLS: ClassVar[List[str]] = [
+ "https://www.w3.org/People/mimasa/test/imgformat/img/w3c_home.png",
+ "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png",
+ ]
diff --git a/tests/cases/registry.py b/tests/cases/registry.py
new file mode 100644
index 000000000..2b90d6852
--- /dev/null
+++ b/tests/cases/registry.py
@@ -0,0 +1,41 @@
+"""Registry and model constants for testing."""
+
+from typing import ClassVar, List
+
+from pydantic import BaseModel
+from typing_extensions import override
+
+
+class ClassRegistryTestCases:
+ """Class registry test constants."""
+
+ MODEL_FOLDER_PATH = "tests/data/tools_data/mock_folder_with_classes"
+
+ CLASSES_TO_REGISTER: ClassVar[List[str]] = [
+ "Class1",
+ "Class2",
+ "Class3",
+ "Class4",
+ ]
+
+ CLASSES_NOT_TO_REGISTER: ClassVar[List[str]] = [
+ "ClassA",
+ "ClassB",
+ ]
+
+
+class FileHelperTestCases:
+ """File helper test constants."""
+
+ TEST_IMAGE = "tests/data/tools_data/images/white_square.png"
+
+
+class Fruit(BaseModel):
+ """Test model for fruit data."""
+
+ name: str
+ color: str
+
+ @override
+ def __str__(self) -> str:
+ return self.name
diff --git a/tests/cases/templates.py b/tests/cases/templates.py
new file mode 100644
index 000000000..de891ea42
--- /dev/null
+++ b/tests/cases/templates.py
@@ -0,0 +1,134 @@
+"""Template constants for testing."""
+
+from typing import Any, ClassVar, List, Tuple
+
+from pipelex.tools.templating.templating_models import PromptingStyle, TagStyle, TextFormat
+
+from .registry import Fruit
+
+
+class JINJA2TestCases:
+ """Jinja2 template test constants."""
+
+ # Template names
+ JINJA2_NAME: ClassVar[List[str]] = [
+ "jinja2_test_template",
+ ]
+
+ # Basic templates
+ JINJA2_FOR_ANY: ClassVar[List[str]] = [
+ "I want a {{ place_holder }} cocktail.",
+ ]
+
+ # Filter templates
+ JINJA2_FILTER_TAG = """
+Tag filter:
+{{ place_holder | tag("some stuff") }}
+"""
+
+ JINJA2_FILTER_FORMAT = """
+Format filter:
+{{ place_holder | format }}
+"""
+
+ JINJA2_FILTER_FORMAT_PLAIN = """
+Format filter plain:
+{{ place_holder | format("plain") }}
+"""
+
+ JINJA2_FILTER_FORMAT_JSON = """
+Format filter json:
+{{ place_holder | format("json") }}
+"""
+
+ JINJA2_FILTER_FORMAT_MARKDOWN = """
+Format filter markdown:
+{{ place_holder | format("markdown") }}
+"""
+
+ JINJA2_FILTER_FORMAT_HTML = """
+Format filter html:
+{{ place_holder | format("html") }}
+"""
+
+ JINJA2_FILTER_FORMAT_SPREADSHEET = """
+Format filter spreadsheet:
+{{ place_holder | format("spreadsheet") }}
+"""
+
+ JINJA2_ALL_METHODS = """
+Direct (no filter):
+{{ place_holder }}
+
+Format filter:
+{{ place_holder | format }}
+
+Tag filter:
+{{ place_holder | tag("some stuff") }}
+
+Format filter json:
+{{ place_holder | format("json") }}
+
+Format filter markdown:
+{{ place_holder | format("markdown") }}
+
+Format filter html:
+{{ place_holder | format("html") }}
+
+"""
+
+ # Template collections
+ JINJA2_FOR_STUFF: ClassVar[List[str]] = [
+ JINJA2_FILTER_TAG,
+ JINJA2_FILTER_FORMAT,
+ JINJA2_FILTER_FORMAT_PLAIN,
+ JINJA2_FILTER_FORMAT_JSON,
+ JINJA2_FILTER_FORMAT_MARKDOWN,
+ JINJA2_FILTER_FORMAT_HTML,
+ JINJA2_FILTER_FORMAT_SPREADSHEET,
+ JINJA2_ALL_METHODS,
+ ]
+
+ # Style configurations
+ STYLE: ClassVar[List[PromptingStyle]] = [
+ PromptingStyle(
+ tag_style=TagStyle.NO_TAG,
+ text_format=TextFormat.PLAIN,
+ ),
+ PromptingStyle(
+ tag_style=TagStyle.TICKS,
+ text_format=TextFormat.MARKDOWN,
+ ),
+ PromptingStyle(
+ tag_style=TagStyle.XML,
+ text_format=TextFormat.HTML,
+ ),
+ PromptingStyle(
+ tag_style=TagStyle.SQUARE_BRACKETS,
+ text_format=TextFormat.JSON,
+ ),
+ ]
+
+ # Test data
+ COLOR: ClassVar[List[str]] = [
+ "red",
+ "blue",
+ "green",
+ ]
+
+ FRUIT: ClassVar[List[Fruit]] = [
+ Fruit(color="red", name="cherry"),
+ Fruit(color="blue", name="blueberry"),
+ Fruit(color="green", name="grape"),
+ ]
+
+ # Mixed object types for comprehensive testing
+ ANY_OBJECT: ClassVar[List[Tuple[str, Any]]] = [ # topic, any_object
+ ("string", "test_string"),
+ ("integer", 42),
+ ("float", 3.14),
+ ("boolean", True),
+ ("list", ["item1", "item2", "item3"]),
+ ("dict", {"key1": "value1", "key2": "value2"}),
+ ("fruit_object", Fruit(color="red", name="apple")),
+ ]
diff --git a/tests/cases/urls.py b/tests/cases/urls.py
new file mode 100644
index 000000000..173768f0b
--- /dev/null
+++ b/tests/cases/urls.py
@@ -0,0 +1,15 @@
+"""URL constants for testing."""
+
+from typing import ClassVar, List
+
+
+class TestURLs:
+ """Test URL constants."""
+
+ GCP_PUBLIC = "https://storage.googleapis.com/public_test_files_7fa6_4277_9ab/diagrams/gantt_tree_house.png"
+ WIKIPEDIA = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Olympic_rings_on_the_Eiffel_Tower_2024_%2819%29.jpg/440px-Olympic_rings_on_the_Eiffel_Tower_2024_%2819%29.jpg"
+
+ PUBLIC_URLS: ClassVar[List[str]] = [
+ GCP_PUBLIC,
+ WIKIPEDIA,
+ ]
diff --git a/tests/conftest.py b/tests/conftest.py
index c3eb111e5..c0857935b 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -9,6 +9,7 @@ import pipelex.config
import pipelex.pipelex
from pipelex import log
from pipelex.config import get_config
+from tests.cases.registry import Fruit
pytest_plugins = [
"pipelex.test_extras.shared_pytest_plugins",
@@ -48,3 +49,22 @@ def pretty():
@pytest.fixture(scope="session", autouse=True) # pyright: ignore[reportUntypedFunctionDecorator, reportUnknownMemberType]
def apply_manage_pipelex_libraries(manage_pipelex_libraries_with_overwrite: Any): # pyright: ignore[reportUnknownParameterType]
return
+
+
+# Test data fixtures
[email protected](scope="session")
+def apple() -> Fruit:
+ """Apple fruit fixture."""
+ return Fruit(name="apple", color="red")
+
+
[email protected](scope="session")
+def cherry() -> Fruit:
+ """Cherry fruit fixture."""
+ return Fruit(name="cherry", color="red")
+
+
[email protected](scope="session")
+def blueberry() -> Fruit:
+ """Blueberry fruit fixture."""
+ return Fruit(name="blueberry", color="blue")
diff --git a/tests/tools/data/images/white_square.png b/tests/data/tools_data/images/white_square.png
similarity index 100%
rename from tests/tools/data/images/white_square.png
rename to tests/data/tools_data/images/white_square.png
diff --git a/tests/tools/data/mock_folder_with_classes/subfolder/test_model_c.py b/tests/data/tools_data/mock_folder_with_classes/subfolder/test_model_c.py
similarity index 100%
rename from tests/tools/data/mock_folder_with_classes/subfolder/test_model_c.py
rename to tests/data/tools_data/mock_folder_with_classes/subfolder/test_model_c.py
diff --git a/tests/tools/data/mock_folder_with_classes/test_model_a.py b/tests/data/tools_data/mock_folder_with_classes/test_model_a.py
similarity index 100%
rename from tests/tools/data/mock_folder_with_classes/test_model_a.py
rename to tests/data/tools_data/mock_folder_with_classes/test_model_a.py
diff --git a/tests/tools/data/mock_folder_with_classes/test_model_b.py b/tests/data/tools_data/mock_folder_with_classes/test_model_b.py
similarity index 100%
rename from tests/tools/data/mock_folder_with_classes/test_model_b.py
rename to tests/data/tools_data/mock_folder_with_classes/test_model_b.py
diff --git a/tests/helpers/__init__.py b/tests/helpers/__init__.py
new file mode 100644
index 000000000..4135a9df5
--- /dev/null
+++ b/tests/helpers/__init__.py
@@ -0,0 +1 @@
+"""Test helper utilities package."""
diff --git a/tests/helpers/paths.py b/tests/helpers/paths.py
new file mode 100644
index 000000000..45011de38
--- /dev/null
+++ b/tests/helpers/paths.py
@@ -0,0 +1,21 @@
+"""Path helpers for accessing test data files."""
+
+from importlib import resources
+from pathlib import Path
+
+
+def data_path(relative: str) -> Path:
+ """Get the absolute path to a test data file.
+
+ Args:
+ relative: Relative path from tests/data directory
+
+ Returns:
+ Absolute path to the data file
+
+ Example:
+ >>> img = data_path("images/white_square.png")
+ >>> doc = data_path("documents/solar_system.pdf")
+ """
+ data_dir = resources.files("tests.data")
+ return Path(str(data_dir)) / relative
diff --git a/tests/pipelex/pipelex_asynch/test_client.py b/tests/integration/pipelex/client/test_client.py
similarity index 100%
rename from tests/pipelex/pipelex_asynch/test_client.py
rename to tests/integration/pipelex/client/test_client.py
diff --git a/tests/pipelex/cogt_asynch/test_content_generator.py b/tests/integration/pipelex/cogt/test_content_generator.py
similarity index 98%
rename from tests/pipelex/cogt_asynch/test_content_generator.py
rename to tests/integration/pipelex/cogt/test_content_generator.py
index 735895f4f..57c2b884e 100644
--- a/tests/pipelex/cogt_asynch/test_content_generator.py
+++ b/tests/integration/pipelex/cogt/test_content_generator.py
@@ -16,8 +16,8 @@ from pipelex.cogt.ocr.ocr_job_components import OcrJobConfig, OcrJobParams
from pipelex.cogt.ocr.ocr_output import OcrOutput
from pipelex.hub import get_content_generator, get_llm_deck
from pipelex.pipeline.job_metadata import JobMetadata
-from tests.pipelex.cogt.test_data import Employee
-from tests.test_data import ImageTestCases
+from tests.cases import ImageTestCases
+from tests.integration.pipelex.cogt.test_data import Employee
USER_TEXT_FOR_BASE = """
Write a detailed description of a woman's clothing in the style of a 19th-century novel.
diff --git a/tests/pipelex/cogt/test_data.py b/tests/integration/pipelex/cogt/test_data.py
similarity index 99%
rename from tests/pipelex/cogt/test_data.py
rename to tests/integration/pipelex/cogt/test_data.py
index 5bf12186a..c83ff3f78 100644
--- a/tests/pipelex/cogt/test_data.py
+++ b/tests/integration/pipelex/cogt/test_data.py
@@ -7,7 +7,7 @@ from pipelex.cogt.llm.llm_prompt import LLMPrompt
from pipelex.cogt.llm.llm_prompt_template import LLMPromptTemplate
from pipelex.cogt.llm.llm_prompt_template_inputs import LLMPromptTemplateInputs
from pipelex.types import StrEnum
-from tests.pipelex.test_data import PipeTestCases
+from tests.integration.pipelex.test_data import PipeTestCases
class Person(BaseModel):
diff --git a/tests/pipelex/cogt_asynch/test_image_gen.py b/tests/integration/pipelex/cogt/test_image_gen.py
similarity index 93%
rename from tests/pipelex/cogt_asynch/test_image_gen.py
rename to tests/integration/pipelex/cogt/test_image_gen.py
index 510488aa5..86a83790a 100644
--- a/tests/pipelex/cogt_asynch/test_image_gen.py
+++ b/tests/integration/pipelex/cogt/test_image_gen.py
@@ -3,7 +3,7 @@ import pytest
from pipelex import pretty_print
from pipelex.cogt.imgg.imgg_job_factory import ImggJobFactory
from pipelex.hub import get_imgg_worker
-from tests.pipelex.test_data import IMGGTestCases
+from tests.integration.pipelex.test_data import IMGGTestCases
@pytest.mark.imgg
diff --git a/tests/pipelex/cogt_asynch/test_llm_engines.py b/tests/integration/pipelex/cogt/test_llm_engines.py
similarity index 98%
rename from tests/pipelex/cogt_asynch/test_llm_engines.py
rename to tests/integration/pipelex/cogt/test_llm_engines.py
index d58fcf149..b304f2cff 100644
--- a/tests/pipelex/cogt_asynch/test_llm_engines.py
+++ b/tests/integration/pipelex/cogt/test_llm_engines.py
@@ -11,7 +11,7 @@ from pipelex.cogt.llm.llm_models.llm_platform import LLMPlatform
from pipelex.cogt.llm.llm_worker_abstract import LLMWorkerAbstract
from pipelex.cogt.llm.llm_worker_factory import LLMWorkerFactory
from pipelex.hub import get_inference_manager, get_llm_deck, get_llm_models_provider, get_report_delegate
-from tests.pipelex.cogt.test_data import LLMTestConstants, Person
+from tests.integration.pipelex.cogt.test_data import LLMTestConstants, Person
@pytest.mark.llm
diff --git a/tests/pipelex/cogt_asynch/test_llm_gen_object.py b/tests/integration/pipelex/cogt/test_llm_gen_object.py
similarity index 98%
rename from tests/pipelex/cogt_asynch/test_llm_gen_object.py
rename to tests/integration/pipelex/cogt/test_llm_gen_object.py
index 2b15c7065..5fb151c35 100644
--- a/tests/pipelex/cogt_asynch/test_llm_gen_object.py
+++ b/tests/integration/pipelex/cogt/test_llm_gen_object.py
@@ -8,7 +8,7 @@ from pipelex import pretty_print
from pipelex.cogt.llm.llm_job_components import LLMJobParams
from pipelex.cogt.llm.llm_job_factory import LLMJobFactory
from pipelex.hub import get_llm_deck, get_llm_worker
-from tests.pipelex.cogt.test_data import LLMTestCases
+from tests.integration.pipelex.cogt.test_data import LLMTestCases
def get_async_worker_and_job(llm_preset_id: str, user_text: str):
diff --git a/tests/pipelex/cogt_asynch/test_llm_gen_text.py b/tests/integration/pipelex/cogt/test_llm_gen_text.py
similarity index 98%
rename from tests/pipelex/cogt_asynch/test_llm_gen_text.py
rename to tests/integration/pipelex/cogt/test_llm_gen_text.py
index 0f077a3a2..66f9f231a 100644
--- a/tests/pipelex/cogt_asynch/test_llm_gen_text.py
+++ b/tests/integration/pipelex/cogt/test_llm_gen_text.py
@@ -8,7 +8,7 @@ from pipelex.cogt.llm.llm_job_components import LLMJobParams
from pipelex.cogt.llm.llm_job_factory import LLMJobFactory
from pipelex.cogt.llm.llm_models.llm_family import LLMFamily
from pipelex.hub import get_llm_deck, get_llm_worker, get_report_delegate
-from tests.pipelex.cogt.test_data import LLMTestCases
+from tests.integration.pipelex.cogt.test_data import LLMTestCases
def get_async_worker_and_job(llm_preset_id: str, user_text: str):
diff --git a/tests/pipelex/cogt_asynch/test_llm_job_async_factory.py b/tests/integration/pipelex/cogt/test_llm_job_async_factory.py
similarity index 97%
rename from tests/pipelex/cogt_asynch/test_llm_job_async_factory.py
rename to tests/integration/pipelex/cogt/test_llm_job_async_factory.py
index cd40e8aa3..0b1ed2920 100644
--- a/tests/pipelex/cogt_asynch/test_llm_job_async_factory.py
+++ b/tests/integration/pipelex/cogt/test_llm_job_async_factory.py
@@ -7,7 +7,7 @@ from pipelex.cogt.llm.llm_job import LLMJobParams
from pipelex.cogt.llm.llm_job_factory import LLMJobFactory
from pipelex.cogt.llm.llm_prompt_template import LLMPromptTemplate
from pipelex.hub import get_llm_worker
-from tests.pipelex.cogt.test_data import LLMTestConstants
+from tests.integration.pipelex.cogt.test_data import LLMTestConstants
@pytest.mark.asyncio(loop_scope="class")
diff --git a/tests/pipelex/cogt/test_llm_models_library.py b/tests/integration/pipelex/cogt/test_llm_models_library.py
similarity index 100%
rename from tests/pipelex/cogt/test_llm_models_library.py
rename to tests/integration/pipelex/cogt/test_llm_models_library.py
diff --git a/tests/pipelex/cogt_asynch/test_llm_report.py b/tests/integration/pipelex/cogt/test_llm_report.py
similarity index 97%
rename from tests/pipelex/cogt_asynch/test_llm_report.py
rename to tests/integration/pipelex/cogt/test_llm_report.py
index 77caef5c7..d3a9af4ca 100644
--- a/tests/pipelex/cogt_asynch/test_llm_report.py
+++ b/tests/integration/pipelex/cogt/test_llm_report.py
@@ -6,7 +6,7 @@ import pytest
from pipelex import pretty_print
from pipelex.cogt.llm.llm_job_factory import LLMJobFactory
from pipelex.hub import get_llm_deck, get_llm_worker, get_report_delegate
-from tests.pipelex.cogt.test_data import LLMTestCases
+from tests.integration.pipelex.cogt.test_data import LLMTestCases
@pytest.mark.asyncio
diff --git a/tests/pipelex/cogt_asynch/test_llm_vision.py b/tests/integration/pipelex/cogt/test_llm_vision.py
similarity index 98%
rename from tests/pipelex/cogt_asynch/test_llm_vision.py
rename to tests/integration/pipelex/cogt/test_llm_vision.py
index 09f437db7..924dcc22f 100644
--- a/tests/pipelex/cogt_asynch/test_llm_vision.py
+++ b/tests/integration/pipelex/cogt/test_llm_vision.py
@@ -10,7 +10,7 @@ from pipelex.cogt.llm.llm_job import LLMJobParams
from pipelex.cogt.llm.llm_job_factory import LLMJobFactory
from pipelex.hub import get_llm_worker
from pipelex.tools.misc.base_64_utils import load_binary_as_base64
-from tests.pipelex.cogt.test_data import LLMVisionTestCases
+from tests.integration.pipelex.cogt.test_data import LLMVisionTestCases
@pytest.mark.llm
diff --git a/tests/pipelex/cogt_asynch/test_ocr.py b/tests/integration/pipelex/cogt/test_ocr.py
similarity index 98%
rename from tests/pipelex/cogt_asynch/test_ocr.py
rename to tests/integration/pipelex/cogt/test_ocr.py
index 4e42f0f7b..74bc9d478 100644
--- a/tests/pipelex/cogt_asynch/test_ocr.py
+++ b/tests/integration/pipelex/cogt/test_ocr.py
@@ -8,7 +8,7 @@ from pipelex.cogt.ocr.ocr_job_factory import OcrJobFactory
from pipelex.config import get_config
from pipelex.hub import get_ocr_worker
from pipelex.tools.misc.file_utils import get_incremental_directory_path
-from tests.test_data import ImageTestCases, PDFTestCases
+from tests.cases import ImageTestCases, PDFTestCases
@pytest.mark.ocr
diff --git a/tests/pipelex/cogt/test_serde_llm_classes.py b/tests/integration/pipelex/cogt/test_serde_llm_classes.py
similarity index 97%
rename from tests/pipelex/cogt/test_serde_llm_classes.py
rename to tests/integration/pipelex/cogt/test_serde_llm_classes.py
index a89f0e824..532830be3 100644
--- a/tests/pipelex/cogt/test_serde_llm_classes.py
+++ b/tests/integration/pipelex/cogt/test_serde_llm_classes.py
@@ -6,7 +6,7 @@ from pydantic import BaseModel
from pipelex import pretty_print
from pipelex.cogt.llm.llm_prompt_template import LLMPromptTemplate
-from tests.pipelex.cogt.test_data import SerDeTestLLMCases
+from tests.integration.pipelex.cogt.test_data import SerDeTestLLMCases
class TestSerDeLLMClasses:
diff --git a/tests/pipelex/cogt/test_setup_inference_workers.py b/tests/integration/pipelex/cogt/test_setup_inference_workers.py
similarity index 100%
rename from tests/pipelex/cogt/test_setup_inference_workers.py
rename to tests/integration/pipelex/cogt/test_setup_inference_workers.py
diff --git a/tests/pipelex/conftest.py b/tests/integration/pipelex/conftest.py
similarity index 100%
rename from tests/pipelex/conftest.py
rename to tests/integration/pipelex/conftest.py
diff --git a/tests/pipelex/pipelex_asynch/conftest.py b/tests/integration/pipelex/pipes/conftest.py
similarity index 100%
rename from tests/pipelex/pipelex_asynch/conftest.py
rename to tests/integration/pipelex/pipes/conftest.py
diff --git a/tests/pipelex/pipelex_asynch/test_image_inputs.py b/tests/integration/pipelex/pipes/test_image_inputs.py
similarity index 97%
rename from tests/pipelex/pipelex_asynch/test_image_inputs.py
rename to tests/integration/pipelex/pipes/test_image_inputs.py
index 6fd39e055..a958e4e0d 100644
--- a/tests/pipelex/pipelex_asynch/test_image_inputs.py
+++ b/tests/integration/pipelex/pipes/test_image_inputs.py
@@ -12,8 +12,7 @@ from pipelex.core.stuff_factory import StuffFactory
from pipelex.core.working_memory_factory import WorkingMemoryFactory
from pipelex.hub import get_pipe_router, get_report_delegate
from pipelex.pipeline.job_metadata import JobMetadata
-from tests.test_data import ImageTestCases
-from tests.test_pipelines.misc_tests.tests import Article
+from tests.cases import Article, ImageTestCases
@pytest.mark.dry_runnable
diff --git a/tests/pipelex/pipelex_asynch/test_pipe_batch.py b/tests/integration/pipelex/pipes/test_pipe_batch.py
similarity index 100%
rename from tests/pipelex/pipelex_asynch/test_pipe_batch.py
rename to tests/integration/pipelex/pipes/test_pipe_batch.py
diff --git a/tests/pipelex/pipelex_asynch/test_pipe_imgg.py b/tests/integration/pipelex/pipes/test_pipe_imgg.py
similarity index 96%
rename from tests/pipelex/pipelex_asynch/test_pipe_imgg.py
rename to tests/integration/pipelex/pipes/test_pipe_imgg.py
index 3ef3e5f71..82ed87fee 100644
--- a/tests/pipelex/pipelex_asynch/test_pipe_imgg.py
+++ b/tests/integration/pipelex/pipes/test_pipe_imgg.py
@@ -8,7 +8,7 @@ from pipelex.core.pipe_run_params_factory import PipeRunParamsFactory
from pipelex.hub import get_pipe_router
from pipelex.pipe_operators.pipe_img_gen import PipeImgGen, PipeImgGenOutput
from pipelex.pipe_works.pipe_job_factory import PipeJobFactory
-from tests.pipelex.test_data import IMGGTestCases
+from tests.integration.pipelex.test_data import IMGGTestCases
@pytest.mark.dry_runnable
diff --git a/tests/pipelex/pipelex_asynch/test_pipe_jinja2.py b/tests/integration/pipelex/pipes/test_pipe_jinja2.py
similarity index 97%
rename from tests/pipelex/pipelex_asynch/test_pipe_jinja2.py
rename to tests/integration/pipelex/pipes/test_pipe_jinja2.py
index 3a175d071..438b01219 100644
--- a/tests/pipelex/pipelex_asynch/test_pipe_jinja2.py
+++ b/tests/integration/pipelex/pipes/test_pipe_jinja2.py
@@ -8,9 +8,10 @@ from pipelex.hub import get_pipe_router
from pipelex.pipe_operators.pipe_jinja2 import PipeJinja2, PipeJinja2Output
from pipelex.pipe_works.pipe_job_factory import PipeJobFactory
from pipelex.tools.templating.templating_models import PromptingStyle, TagStyle, TextFormat
-from tests.pipelex.test_data import JINJA2TestCases
+from tests.cases import JINJA2TestCases
@pytest.mark.asyncio(loop_scope="class")
class TestPipeJinja2:
@pytest.mark.parametrize("jinja2", JINJA2TestCases.JINJA2_FOR_ANY)
diff --git a/tests/pipelex/pipelex_asynch/test_pipe_llm.py b/tests/integration/pipelex/pipes/test_pipe_llm.py
similarity index 98%
rename from tests/pipelex/pipelex_asynch/test_pipe_llm.py
rename to tests/integration/pipelex/pipes/test_pipe_llm.py
index 6dcfe0d47..7c6ba21ab 100644
--- a/tests/pipelex/pipelex_asynch/test_pipe_llm.py
+++ b/tests/integration/pipelex/pipes/test_pipe_llm.py
@@ -13,7 +13,7 @@ from pipelex.hub import get_pipe_router, get_report_delegate
from pipelex.pipe_operators.pipe_llm import PipeLLM, PipeLLMOutput
from pipelex.pipe_operators.pipe_llm_prompt import PipeLLMPrompt
from pipelex.pipe_works.pipe_job_factory import PipeJobFactory
-from tests.pipelex.test_data import PipeTestCases
+from tests.integration.pipelex.test_data import PipeTestCases
@pytest.mark.dry_runnable
diff --git a/tests/pipelex/pipelex_asynch/test_pipe_llm_prompt.py b/tests/integration/pipelex/pipes/test_pipe_llm_prompt.py
similarity index 99%
rename from tests/pipelex/pipelex_asynch/test_pipe_llm_prompt.py
rename to tests/integration/pipelex/pipes/test_pipe_llm_prompt.py
index a86d46cd3..be5872265 100644
--- a/tests/pipelex/pipelex_asynch/test_pipe_llm_prompt.py
+++ b/tests/integration/pipelex/pipes/test_pipe_llm_prompt.py
@@ -11,7 +11,7 @@ from pipelex.hub import get_pipe_router
from pipelex.pipe_operators.pipe_llm_prompt import PipeLLMPrompt, PipeLLMPromptOutput
from pipelex.pipe_works.pipe_job_factory import PipeJobFactory
from pipelex.tools.templating.templating_models import PromptingStyle, TagStyle, TextFormat
-from tests.pipelex.test_data import PipeTestCases
+from tests.integration.pipelex.test_data import PipeTestCases
from tests.test_pipelines.pipe_llm_prompt import (
ComplexListContent,
DocumentTypeContent,
diff --git a/tests/pipelex/pipelex_asynch/test_pipe_ocr.py b/tests/integration/pipelex/pipes/test_pipe_ocr.py
similarity index 98%
rename from tests/pipelex/pipelex_asynch/test_pipe_ocr.py
rename to tests/integration/pipelex/pipes/test_pipe_ocr.py
index 7da9bfae7..0b83b8d3e 100644
--- a/tests/pipelex/pipelex_asynch/test_pipe_ocr.py
+++ b/tests/integration/pipelex/pipes/test_pipe_ocr.py
@@ -10,7 +10,7 @@ from pipelex.core.working_memory_factory import WorkingMemoryFactory
from pipelex.hub import get_pipe_router
from pipelex.pipe_operators.pipe_ocr import PipeOcr, PipeOcrOutput
from pipelex.pipe_works.pipe_job_factory import PipeJobFactory
-from tests.pipelex.test_data import PipeOcrTestCases
+from tests.integration.pipelex.test_data import PipeOcrTestCases
@pytest.mark.dry_runnable
diff --git a/tests/pipelex/pipelex_asynch/test_pipe_running_variants.py b/tests/integration/pipelex/pipes/test_pipe_running_variants.py
similarity index 99%
rename from tests/pipelex/pipelex_asynch/test_pipe_running_variants.py
rename to tests/integration/pipelex/pipes/test_pipe_running_variants.py
index 023a733e7..4cf432173 100644
--- a/tests/pipelex/pipelex_asynch/test_pipe_running_variants.py
+++ b/tests/integration/pipelex/pipes/test_pipe_running_variants.py
@@ -14,7 +14,7 @@ from pipelex.core.working_memory_factory import WorkingMemoryFactory
from pipelex.hub import get_pipe_router, get_pipeline_tracker, get_report_delegate
from pipelex.pipeline.activity.activity_handler import ActivityHandlerForResultFiles
from pipelex.pipeline.job_metadata import JobMetadata
-from tests.pipelex.test_data import PipeTestCases
+from tests.integration.pipelex.test_data import PipeTestCases
@pytest.mark.dry_runnable
diff --git a/tests/pipelex/plugins/conftest.py b/tests/integration/pipelex/plugins/conftest.py
similarity index 100%
rename from tests/pipelex/plugins/conftest.py
rename to tests/integration/pipelex/plugins/conftest.py
diff --git a/tests/pipelex/plugins/test_anthropic.py b/tests/integration/pipelex/plugins/test_anthropic.py
similarity index 100%
rename from tests/pipelex/plugins/test_anthropic.py
rename to tests/integration/pipelex/plugins/test_anthropic.py
diff --git a/tests/pipelex/plugins/test_bedrock.py b/tests/integration/pipelex/plugins/test_bedrock.py
similarity index 100%
rename from tests/pipelex/plugins/test_bedrock.py
rename to tests/integration/pipelex/plugins/test_bedrock.py
diff --git a/tests/pipelex/plugins/test_mistral.py b/tests/integration/pipelex/plugins/test_mistral.py
similarity index 100%
rename from tests/pipelex/plugins/test_mistral.py
rename to tests/integration/pipelex/plugins/test_mistral.py
diff --git a/tests/pipelex/plugins/test_openai.py b/tests/integration/pipelex/plugins/test_openai.py
similarity index 88%
rename from tests/pipelex/plugins/test_openai.py
rename to tests/integration/pipelex/plugins/test_openai.py
index 0cf4f917c..a85e485fa 100644
--- a/tests/pipelex/plugins/test_openai.py
+++ b/tests/integration/pipelex/plugins/test_openai.py
@@ -14,8 +14,8 @@ from pipelex.plugins.openai.openai_llms import openai_list_available_models
@pytest.mark.asyncio(loop_scope="class")
class TestOpenAI:
async def test_openai_api_key(self):
- openai_openai_config = get_config().plugins.openai_config
- assert openai_openai_config.get_api_key(secrets_provider=get_secrets_provider())
+ openai_config = get_config().plugins.openai_config
+ assert openai_config.get_api_key(secrets_provider=get_secrets_provider())
# pytest -k test_openai_list_available_models -s -vv
async def test_openai_list_available_models(
diff --git a/tests/pipelex/plugins/test_openai_image_gen.py b/tests/integration/pipelex/plugins/test_openai_image_gen.py
similarity index 96%
rename from tests/pipelex/plugins/test_openai_image_gen.py
rename to tests/integration/pipelex/plugins/test_openai_image_gen.py
index 520eb743c..d539254ca 100644
--- a/tests/pipelex/plugins/test_openai_image_gen.py
+++ b/tests/integration/pipelex/plugins/test_openai_image_gen.py
@@ -6,7 +6,7 @@ from pipelex.plugins.openai.openai_factory import OpenAIFactory
from pipelex.tools.misc.base_64_utils import save_base64_to_binary_file
from pipelex.tools.misc.file_utils import ensure_path, get_incremental_file_path
from tests.conftest import TEST_OUTPUTS_DIR
-from tests.pipelex.test_data import IMGGTestCases
+from tests.integration.pipelex.test_data import IMGGTestCases
@pytest.mark.imgg
diff --git a/tests/test_boot.py b/tests/integration/pipelex/test_boot.py
similarity index 100%
rename from tests/test_boot.py
rename to tests/integration/pipelex/test_boot.py
diff --git a/tests/pipelex/test_data.py b/tests/integration/pipelex/test_data.py
similarity index 72%
rename from tests/pipelex/test_data.py
rename to tests/integration/pipelex/test_data.py
index ab53765fe..0d7321877 100644
--- a/tests/pipelex/test_data.py
+++ b/tests/integration/pipelex/test_data.py
@@ -1,15 +1,11 @@
-from typing import Any, ClassVar, List, Optional, Tuple, Type
-
-from pydantic import BaseModel
-from typing_extensions import override
+from typing import ClassVar, List, Optional, Tuple, Type
from pipelex.core.pipe_run_params import PipeOutputMultiplicity
from pipelex.core.stuff import Stuff
from pipelex.core.stuff_content import ImageContent, ListContent, PDFContent, StructuredContent, TextContent
from pipelex.core.stuff_factory import StuffBlueprint, StuffFactory
from pipelex.exceptions import PipeStackOverflowError
-from pipelex.tools.templating.templating_models import PromptingStyle, TagStyle, TextFormat
-from tests.test_data import ImageTestCases, PDFTestCases
+from tests.cases import ImageTestCases, PDFTestCases
class SomeContentWithImageAttribute(StructuredContent):
@@ -179,114 +175,6 @@ class PipeTestCases:
]
-class Fruit(BaseModel):
- name: str
- color: str
-
- @override
- def __str__(self) -> str:
- return self.name
-
-
-class JINJA2TestCases:
- JINJA2_NAME: ClassVar[List[str]] = [
- "jinja2_test_template",
- ]
- JINJA2_FOR_ANY: ClassVar[List[str]] = [
- "I want a {{ place_holder }} cocktail.",
- ]
- JINJA2_FILTER_TAG = """
-Tag filter:
-{{ place_holder | tag("some stuff") }}
-"""
- JINJA2_FILTER_FORMAT = """
-Format filter:
-{{ place_holder | format }}
-"""
- JINJA2_FILTER_FORMAT_PLAIN = """
-Format filter plain:
-{{ place_holder | format("plain") }}
-"""
- JINJA2_FILTER_FORMAT_JSON = """
-Format filter json:
-{{ place_holder | format("json") }}
-"""
- JINJA2_FILTER_FORMAT_MARKDOWN = """
-Format filter markdown:
-{{ place_holder | format("markdown") }}
-"""
- JINJA2_FILTER_FORMAT_HTML = """
-Format filter html:
-{{ place_holder | format("html") }}
-"""
- JINJA2_FILTER_FORMAT_SPREADSHEET = """
-Format filter spreadsheet:
-{{ place_holder | format("spreadsheet") }}
-"""
- JINJA2_ALL_METHODS = """
-Direct (no filter):
-{{ place_holder }}
-
-Format filter:
-{{ place_holder | format }}
-
-Tag filter:
-{{ place_holder | tag("some stuff") }}
-
-Format filter json:
-{{ place_holder | format("json") }}
-
-Format filter markdown:
-{{ place_holder | format("markdown") }}
-
-Format filter html:
-{{ place_holder | format("html") }}
-
-"""
- JINJA2_FOR_STUFF: ClassVar[List[str]] = [
- JINJA2_FILTER_TAG,
- JINJA2_FILTER_FORMAT,
- JINJA2_FILTER_FORMAT_PLAIN,
- JINJA2_FILTER_FORMAT_JSON,
- JINJA2_FILTER_FORMAT_MARKDOWN,
- JINJA2_FILTER_FORMAT_HTML,
- JINJA2_FILTER_FORMAT_SPREADSHEET,
- JINJA2_ALL_METHODS,
- ]
- STYLE: ClassVar[List[PromptingStyle]] = [
- PromptingStyle(
- tag_style=TagStyle.NO_TAG,
- text_format=TextFormat.PLAIN,
- ),
- PromptingStyle(
- tag_style=TagStyle.TICKS,
- text_format=TextFormat.MARKDOWN,
- ),
- PromptingStyle(
- tag_style=TagStyle.XML,
- text_format=TextFormat.HTML,
- ),
- PromptingStyle(
- tag_style=TagStyle.SQUARE_BRACKETS,
- text_format=TextFormat.JSON,
- ),
- ]
- COLOR: ClassVar[List[str]] = [
- "red",
- "blue",
- "green",
- ]
- FRUIT: ClassVar[List[Fruit]] = [
- (Fruit(color="red", name="cherry")),
- (Fruit(color="blue", name="blueberry")),
- (Fruit(color="green", name="grape")),
- ]
- ANY_OBJECT: ClassVar[List[Tuple[str, Any]]] = [
- ("cherry", PipeTestCases.SIMPLE_STUFF_TEXT),
- # ("complex", PipeTestCases.COMPLEX_STUFF),
- ]
-
-
class LibraryTestCases:
KNOWN_CONCEPTS_AND_PIPES: ClassVar[List[Tuple[str, str]]] = [ # concept, pipe
("cars.CarDescription", "generate_car_description"),
diff --git a/tests/pipelex/test_libraries.py b/tests/integration/pipelex/test_libraries.py
similarity index 98%
rename from tests/pipelex/test_libraries.py
rename to tests/integration/pipelex/test_libraries.py
index 3c8cfb78a..fc5cd1b49 100644
--- a/tests/pipelex/test_libraries.py
+++ b/tests/integration/pipelex/test_libraries.py
@@ -13,7 +13,7 @@ from pipelex import pretty_print
from pipelex.core.concept_library import ConceptLibrary
from pipelex.core.pipe_library import PipeLibrary
from pipelex.libraries.library_manager import LibraryManager
-from tests.pipelex.test_data import LibraryTestCases
+from tests.integration.pipelex.test_data import LibraryTestCases
def pretty_print_all_pipes(
diff --git a/tests/tools/aws/test_aws.py b/tests/integration/pipelex/tools/aws/test_aws.py
similarity index 100%
rename from tests/tools/aws/test_aws.py
rename to tests/integration/pipelex/tools/aws/test_aws.py
diff --git a/tests/integration/pipelex/tools/class_registry/test_class_registry_utils.py b/tests/integration/pipelex/tools/class_registry/test_class_registry_utils.py
new file mode 100644
index 000000000..6e42f5fa9
--- /dev/null
+++ b/tests/integration/pipelex/tools/class_registry/test_class_registry_utils.py
@@ -0,0 +1,67 @@
+from pathlib import Path
+
+import pytest
+
+from pipelex.core.stuff_content import StuffContent
+from pipelex.hub import get_class_registry
+from pipelex.tools.class_registry_utils import ClassRegistryUtils
+from tests.cases import ClassRegistryTestCases
+
+
+class TestClassRegistryUtilsIntegration:
+ """Integration tests for ClassRegistryUtils using real file operations."""
+
+ @pytest.mark.asyncio
+ async def test_register_classes_in_folder_integration_stuffcontent_recursive(self) -> None:
+ """Integration test for registering StuffContent classes recursively."""
+ class_registry = get_class_registry()
+ ClassRegistryUtils.register_classes_in_folder(
+ folder_path=ClassRegistryTestCases.MODEL_FOLDER_PATH, base_class=StuffContent, is_recursive=True
+ )
+
+ # Should register classes that inherit from StuffContent
+ for class_name in ClassRegistryTestCases.CLASSES_TO_REGISTER:
+ assert class_registry.get_class(class_name) is not None, f"Expected {class_name} to be registered"
+
+ @pytest.mark.asyncio
+ async def test_register_classes_in_folder_integration_stuffcontent_non_recursive(self) -> None:
+ """Integration test for registering StuffContent classes non-recursively."""
+ class_registry = get_class_registry()
+ ClassRegistryUtils.register_classes_in_folder(
+ folder_path=ClassRegistryTestCases.MODEL_FOLDER_PATH, base_class=StuffContent, is_recursive=False
+ )
+
+ # Should register only top-level StuffContent classes
+ for class_name in ["Class1", "Class2", "Class4"]: # Only from top-level files
+ assert class_registry.get_class(class_name) is not None, f"Expected {class_name} to be registered"
+
+ @pytest.mark.asyncio
+ async def test_register_classes_in_folder_integration_no_base_class(self) -> None:
+ """Integration test for registering all classes when no base class is specified."""
+ class_registry = get_class_registry()
+
+ # Record classes before registration to check for new registrations
+ classes_before: set[str] = set()
+ for class_name in ["Class1", "Class2", "Class3", "Class4", "ClassA", "ClassB"]:
+ if class_registry.has_class(class_name):
+ classes_before.add(class_name)
+
+ ClassRegistryUtils.register_classes_in_folder(folder_path=ClassRegistryTestCases.MODEL_FOLDER_PATH, base_class=None, is_recursive=True)
+
+ # Should register all classes
+ for class_name in ["Class1", "Class2", "Class3", "Class4", "ClassA", "ClassB"]:
+ assert class_registry.get_class(class_name) is not None, f"Expected {class_name} to be registered"
+
+ @pytest.mark.asyncio
+ async def test_register_classes_in_folder_empty_directory_integration(self, tmp_path: Path) -> None:
+ """Integration test for registering classes from an empty folder."""
+ # Create an empty directory
+ empty_dir = tmp_path / "empty_folder"
+ empty_dir.mkdir()
+
+ # This should not raise an error and should not register any classes
+ ClassRegistryUtils.register_classes_in_folder(folder_path=str(empty_dir), base_class=StuffContent, is_recursive=True)
+
+ # Verify no new classes were registered (we can't easily check the exact count,
+ # but the operation should complete without error)
+ assert True # If we get here without exception, the test passed
diff --git a/tests/tools/misc/test_httpx_fetching.py b/tests/integration/pipelex/tools/httpx/test_httpx_fetching.py
similarity index 95%
rename from tests/tools/misc/test_httpx_fetching.py
rename to tests/integration/pipelex/tools/httpx/test_httpx_fetching.py
index e4cef8600..8374b460d 100644
--- a/tests/tools/misc/test_httpx_fetching.py
+++ b/tests/integration/pipelex/tools/httpx/test_httpx_fetching.py
@@ -1,7 +1,7 @@
import pytest
from pipelex.tools.misc.file_fetch_utils import fetch_file_from_url_httpx, fetch_file_from_url_httpx_async
-from tests.tools.test_data import TestURLs
+from tests.cases import TestURLs
@pytest.mark.codex_disabled
diff --git a/tests/tools/pdf/test_pdf_render.py b/tests/integration/pipelex/tools/pdf/test_pdf_render.py
similarity index 90%
rename from tests/tools/pdf/test_pdf_render.py
rename to tests/integration/pipelex/tools/pdf/test_pdf_render.py
index d34175c81..7a37d4312 100644
--- a/tests/tools/pdf/test_pdf_render.py
+++ b/tests/integration/pipelex/tools/pdf/test_pdf_render.py
@@ -1,7 +1,7 @@
import pytest
from pipelex.tools.pdf.pypdfium2_renderer import pypdfium2_renderer
-from tests.test_data import PDFTestCases
+from tests.cases import PDFTestCases
@pytest.mark.asyncio(loop_scope="class")
diff --git a/tests/pipelex/__init__.py b/tests/pipelex/__init__.py
deleted file mode 100644
index 8b1378917..000000000
--- a/tests/pipelex/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/tests/pipelex/cogt/__init__.py b/tests/pipelex/cogt/__init__.py
deleted file mode 100644
index 8b1378917..000000000
--- a/tests/pipelex/cogt/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/tests/pipelex/cogt_asynch/__init__.py b/tests/pipelex/cogt_asynch/__init__.py
deleted file mode 100644
index 8b1378917..000000000
--- a/tests/pipelex/cogt_asynch/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/tests/pipelex/pipelex_asynch/__init__.py b/tests/pipelex/pipelex_asynch/__init__.py
deleted file mode 100644
index 8b1378917..000000000
--- a/tests/pipelex/pipelex_asynch/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/tests/pipelex/plugins/__init__.py b/tests/pipelex/plugins/__init__.py
deleted file mode 100644
index 8b1378917..000000000
--- a/tests/pipelex/plugins/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/tests/test_data.py b/tests/test_data.py
deleted file mode 100644
index babdbbe0c..000000000
--- a/tests/test_data.py
+++ /dev/null
@@ -1,27 +0,0 @@
-from typing import ClassVar, List
-
-
-class PDFTestCases:
- DOCUMENT_FILE_PATHS: ClassVar[List[str]] = [
- # "tests/data/documents/solar_system.pdf",
- "tests/data/documents/illustrated_train_article.pdf",
- ]
- DOCUMENT_URLS: ClassVar[List[str]] = [
- "https://storage.googleapis.com/public_test_files_7fa6_4277_9ab/documents/solar_system.pdf",
- ]
-
-
-# TODO: move the other shared test images here from other test_data.py files
-class ImageTestCases:
- IMAGE_FILE_PATH_PNG = "tests/data/documents/solar_system.png"
- IMAGE_FILE_PATH_JPG = "tests/data/documents/solar_system.jpg"
- IMAGE_FILE_PATHS: ClassVar[List[str]] = [
- IMAGE_FILE_PATH_PNG,
- IMAGE_FILE_PATH_JPG,
- ]
- IMAGE_URL_PNG = "https://storage.googleapis.com/public_test_files_7fa6_4277_9ab/documents/solar_system.png"
- IMAGE_URL_JPG = "https://storage.googleapis.com/public_test_files_7fa6_4277_9ab/documents/solar_system.jpg"
- IMAGE_URLS: ClassVar[List[str]] = [
- IMAGE_URL_PNG,
- IMAGE_URL_JPG,
- ]
diff --git a/tests/test_pipelines/__init__.py b/tests/test_pipelines/__init__.py
deleted file mode 100644
index e69de29bb..000000000
diff --git a/tests/test_pipelines/misc_tests/__init__.py b/tests/test_pipelines/misc_tests/__init__.py
deleted file mode 100644
index e69de29bb..000000000
diff --git a/tests/test_pipelines/misc_tests/tests.py b/tests/test_pipelines/misc_tests/tests.py
index cc36b393a..e648f6c2b 100644
--- a/tests/test_pipelines/misc_tests/tests.py
+++ b/tests/test_pipelines/misc_tests/tests.py
@@ -1,11 +1,5 @@
-from pipelex.core.stuff_content import ListContent, StructuredContent, TextContent
+from pipelex.core.stuff_content import ListContent, TextContent
class RandomListContent(ListContent[TextContent]):
pass
-
-
-class Article(StructuredContent):
- title: str
- description: str
- date: str
diff --git a/tests/tools/__init__.py b/tests/tools/__init__.py
deleted file mode 100644
index 8b1378917..000000000
--- a/tests/tools/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/tests/tools/aws/__init__.py b/tests/tools/aws/__init__.py
deleted file mode 100644
index 8b1378917..000000000
--- a/tests/tools/aws/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/tests/tools/class_registry/__init__.py b/tests/tools/class_registry/__init__.py
deleted file mode 100644
index 8b1378917..000000000
--- a/tests/tools/class_registry/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/tests/tools/class_registry/test_class_registry.py b/tests/tools/class_registry/test_class_registry.py
deleted file mode 100644
index 3ade36f4e..000000000
--- a/tests/tools/class_registry/test_class_registry.py
+++ /dev/null
@@ -1,35 +0,0 @@
-from typing import List
-
-import pytest
-
-from pipelex.core.stuff_content import StuffContent
-from pipelex.hub import get_class_registry
-from tests.tools.test_data import ClassRegistryTestCases
-
-
-class TestClassRegistry:
- @pytest.mark.asyncio
- @pytest.mark.parametrize(
- "folder, classes_to_register, classes_not_to_register",
- [
- (
- ClassRegistryTestCases.MODEL_FOLDER_PATH,
- ClassRegistryTestCases.CLASSES_TO_REGISTER,
- ClassRegistryTestCases.CLASSES_NOT_TO_REGISTER,
- ),
- ],
- )
- async def test_register_classes_in_folder(
- self,
- folder: str,
- classes_to_register: List[str],
- classes_not_to_register: List[str],
- ) -> None:
- class_registry = get_class_registry()
- class_registry.register_classes_in_folder(folder_path=folder, base_class=StuffContent)
-
- for class_name in classes_to_register:
- assert class_registry.get_class(class_name) is not None
-
- for class_name in classes_not_to_register:
- assert class_registry.get_class(class_name) is None
diff --git a/tests/tools/config/__init__.py b/tests/tools/config/__init__.py
deleted file mode 100644
index 8b1378917..000000000
--- a/tests/tools/config/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/tests/tools/misc/__init__.py b/tests/tools/misc/__init__.py
deleted file mode 100644
index 8b1378917..000000000
--- a/tests/tools/misc/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/tests/tools/pdf/__init__.py b/tests/tools/pdf/__init__.py
deleted file mode 100644
index 8b1378917..000000000
--- a/tests/tools/pdf/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/tests/tools/templating/__init__.py b/tests/tools/templating/__init__.py
deleted file mode 100644
index 8b1378917..000000000
--- a/tests/tools/templating/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/tests/tools/test_data.py b/tests/tools/test_data.py
deleted file mode 100644
index adcd93905..000000000
--- a/tests/tools/test_data.py
+++ /dev/null
@@ -1,29 +0,0 @@
-from typing import ClassVar, List
-
-
-class TestURLs:
- URL_GCP_PUBLIC = "https://storage.googleapis.com/public_test_files_7fa6_4277_9ab/diagrams/gantt_tree_house.png"
- URL_WIKIPEDIA = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Olympic_rings_on_the_Eiffel_Tower_2024_%2819%29.jpg/440px-Olympic_rings_on_the_Eiffel_Tower_2024_%2819%29.jpg"
-
- PUBLIC_URLS: ClassVar[List[str]] = [
- URL_GCP_PUBLIC,
- URL_WIKIPEDIA,
- ]
-
-
-class ClassRegistryTestCases:
- MODEL_FOLDER_PATH = "tests/tools/data/mock_folder_with_classes"
- CLASSES_TO_REGISTER: ClassVar[List[str]] = [
- "Class1",
- "Class2",
- "Class3",
- "Class4",
- ]
- CLASSES_NOT_TO_REGISTER: ClassVar[List[str]] = [
- "ClassA",
- "ClassB",
- ]
-
-
-class FileHelperTestCases:
- TEST_IMAGE = "tests/tools/data/images/white_square.png"
diff --git a/tests/tools/typing/__init__.py b/tests/tools/typing/__init__.py
deleted file mode 100644
index 8b1378917..000000000
--- a/tests/tools/typing/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/tests/core/test_concept_pydantic_validation.py b/tests/unit/pipelex/core/test_concept_pydantic_validation.py
similarity index 100%
rename from tests/core/test_concept_pydantic_validation.py
rename to tests/unit/pipelex/core/test_concept_pydantic_validation.py
diff --git a/tests/core/test_concept_refines.py b/tests/unit/pipelex/core/test_concept_refines.py
similarity index 100%
rename from tests/core/test_concept_refines.py
rename to tests/unit/pipelex/core/test_concept_refines.py
diff --git a/tests/tools/config/test_config_manager.py b/tests/unit/pipelex/tools/config/test_config_manager.py
similarity index 100%
rename from tests/tools/config/test_config_manager.py
rename to tests/unit/pipelex/tools/config/test_config_manager.py
diff --git a/tests/tools/misc/test_base_64_utils.py b/tests/unit/pipelex/tools/misc/test_base_64_utils.py
similarity index 97%
rename from tests/tools/misc/test_base_64_utils.py
rename to tests/unit/pipelex/tools/misc/test_base_64_utils.py
index aac7f2712..b63b9092e 100644
--- a/tests/tools/misc/test_base_64_utils.py
+++ b/tests/unit/pipelex/tools/misc/test_base_64_utils.py
@@ -10,7 +10,7 @@ from pipelex.tools.misc.base_64_utils import (
load_binary_as_base64_async,
save_base64_to_binary_file,
)
-from tests.tools.test_data import FileHelperTestCases
+from tests.cases import FileHelperTestCases
class TestBase64Utils:
diff --git a/tests/unit/pipelex/tools/misc/test_find_files_in_dir.py b/tests/unit/pipelex/tools/misc/test_find_files_in_dir.py
new file mode 100644
index 000000000..5473b60f5
--- /dev/null
+++ b/tests/unit/pipelex/tools/misc/test_find_files_in_dir.py
@@ -0,0 +1,67 @@
+import tempfile
+from pathlib import Path
+
+from pipelex.tools.misc.file_utils import find_files_in_dir
+
+
+class TestFindFilesInDir:
+ """Test the find_files_in_dir helper function."""
+
+ def test_find_files_non_recursive(self):
+ """Test finding files non-recursively."""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ # Create files
+ (Path(temp_dir) / "file1.py").touch()
+ (Path(temp_dir) / "file2.py").touch()
+ (Path(temp_dir) / "file3.txt").touch()
+
+ # Create subdirectory with files
+ sub_dir = Path(temp_dir) / "subdir"
+ sub_dir.mkdir()
+ (sub_dir / "file4.py").touch()
+
+ # Find Python files non-recursively
+ files = find_files_in_dir(temp_dir, "*.py", is_recursive=False)
+
+ assert len(files) == 2
+ file_names = [f.name for f in files]
+ assert "file1.py" in file_names
+ assert "file2.py" in file_names
+ assert "file4.py" not in file_names
+
+ def test_find_files_recursive(self):
+ """Test finding files recursively."""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ # Create files
+ (Path(temp_dir) / "file1.py").touch()
+ (Path(temp_dir) / "file2.py").touch()
+ (Path(temp_dir) / "file3.txt").touch()
+
+ # Create subdirectory with files
+ sub_dir = Path(temp_dir) / "subdir"
+ sub_dir.mkdir()
+ (sub_dir / "file4.py").touch()
+
+ # Find Python files recursively
+ files = find_files_in_dir(temp_dir, "*.py", is_recursive=True)
+
+ assert len(files) == 3
+ file_names = [f.name for f in files]
+ assert "file1.py" in file_names
+ assert "file2.py" in file_names
+ assert "file4.py" in file_names
+
+ def test_find_files_empty_directory(self):
+ """Test finding files in empty directory."""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ files = find_files_in_dir(temp_dir, "*.py", is_recursive=False)
+ assert len(files) == 0
+
+ def test_find_files_no_matches(self):
+ """Test finding files with no matches."""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ (Path(temp_dir) / "file1.txt").touch()
+ (Path(temp_dir) / "file2.md").touch()
+
+ files = find_files_in_dir(temp_dir, "*.py", is_recursive=False)
+ assert len(files) == 0
diff --git a/tests/tools/misc/test_markdown.py b/tests/unit/pipelex/tools/misc/test_markdown.py
similarity index 100%
rename from tests/tools/misc/test_markdown.py
rename to tests/unit/pipelex/tools/misc/test_markdown.py
diff --git a/tests/tools/misc/test_pretty.py b/tests/unit/pipelex/tools/misc/test_pretty.py
similarity index 100%
rename from tests/tools/misc/test_pretty.py
rename to tests/unit/pipelex/tools/misc/test_pretty.py
diff --git a/tests/tools/misc/test_string_utils.py b/tests/unit/pipelex/tools/misc/test_string_utils.py
similarity index 100%
rename from tests/tools/misc/test_string_utils.py
rename to tests/unit/pipelex/tools/misc/test_string_utils.py
diff --git a/tests/tools/misc/test_text.py b/tests/unit/pipelex/tools/misc/test_text.py
similarity index 100%
rename from tests/tools/misc/test_text.py
rename to tests/unit/pipelex/tools/misc/test_text.py
diff --git a/tests/tools/templating/test_jinja2.py b/tests/unit/pipelex/tools/templating/test_jinja2.py
similarity index 98%
rename from tests/tools/templating/test_jinja2.py
rename to tests/unit/pipelex/tools/templating/test_jinja2.py
index 8f2e7a07d..cf77e92f0 100644
--- a/tests/tools/templating/test_jinja2.py
+++ b/tests/unit/pipelex/tools/templating/test_jinja2.py
@@ -7,7 +7,7 @@ from pipelex.hub import get_template_provider
from pipelex.tools.templating.jinja2_rendering import render_jinja2
from pipelex.tools.templating.jinja2_template_category import Jinja2TemplateCategory
from pipelex.tools.templating.templating_models import PromptingStyle, TagStyle, TextFormat
-from tests.pipelex.test_data import Fruit, JINJA2TestCases
+from tests.cases import Fruit, JINJA2TestCases
PLACE_HOLDER = "place_holder"
diff --git a/tests/tools/templating/test_template_preprocessor.py b/tests/unit/pipelex/tools/templating/test_template_preprocessor.py
similarity index 100%
rename from tests/tools/templating/test_template_preprocessor.py
rename to tests/unit/pipelex/tools/templating/test_template_preprocessor.py
diff --git a/tests/unit/pipelex/tools/test_class_registry_utils.py b/tests/unit/pipelex/tools/test_class_registry_utils.py
new file mode 100644
index 000000000..a27dd04e8
--- /dev/null
+++ b/tests/unit/pipelex/tools/test_class_registry_utils.py
@@ -0,0 +1,56 @@
+from pathlib import Path
+
+from pydantic import BaseModel
+from pytest_mock import MockerFixture
+
+from pipelex.tools.class_registry_utils import ClassRegistryUtils
+
+
+class TestClassRegistryUtilsUnit:
+ """Unit tests for ClassRegistryUtils using mocks."""
+
+ def test_register_classes_in_file(self, mocker: MockerFixture):
+ """Test registering classes from a Python file."""
+ # Mock the module utilities to avoid complex file operations
+ mock_module = mocker.MagicMock()
+ mock_module.__name__ = "test_module"
+
+ # Mock the functions at the location where they're imported in ClassRegistryUtils
+ mock_import = mocker.patch("pipelex.tools.class_registry_utils.import_module_from_file", return_value=mock_module)
+ mock_find = mocker.patch("pipelex.tools.class_registry_utils.find_classes_in_module", return_value=[str, int])
+
+ # Mock the global class registry
+ mock_registry = mocker.MagicMock()
+ mocker.patch("pipelex.tools.class_registry_utils.get_class_registry", return_value=mock_registry)
+
+ # Mock sys.modules for cleanup verification
+ mock_sys_modules = mocker.patch("pipelex.tools.class_registry_utils.sys.modules", spec=dict)
+
+ ClassRegistryUtils.register_classes_in_file(file_path="/fake/path.py", base_class=None, is_include_imported=False)
+
+ # Verify the mocked functions were called correctly
+ mock_import.assert_called_once_with("/fake/path.py")
+ mock_find.assert_called_once_with(module=mock_module, base_class=None, include_imported=False)
+
+ # Verify sys.modules cleanup
+ mock_sys_modules.__delitem__.assert_called_once_with("test_module")
+
+ # Verify classes were registered with the global registry
+ mock_registry.register_classes.assert_called_once_with(classes=[str, int])
+
+ def test_register_classes_in_folder_unit(self, mocker: MockerFixture):
+ """Unit test for registering classes from a folder using mocks."""
+ # Mock the file finding and registration
+ mock_files = [Path("/fake/file1.py"), Path("/fake/file2.py")]
+ mock_find_files = mocker.patch.object(ClassRegistryUtils, "find_files_in_dir", return_value=mock_files)
+ mock_register_file = mocker.patch.object(ClassRegistryUtils, "register_classes_in_file")
+
+ ClassRegistryUtils.register_classes_in_folder(folder_path="/fake/folder", base_class=BaseModel, is_recursive=True, is_include_imported=False)
+
+ # Verify find_files_in_dir was called correctly
+ mock_find_files.assert_called_once_with(dir_path="/fake/folder", pattern="*.py", is_recursive=True)
+
+ # Verify register_classes_in_file was called for each file
+ assert mock_register_file.call_count == 2
+ mock_register_file.assert_any_call(file_path="/fake/file1.py", base_class=BaseModel, is_include_imported=False)
+ mock_register_file.assert_any_call(file_path="/fake/file2.py", base_class=BaseModel, is_include_imported=False)
diff --git a/tests/unit/pipelex/tools/test_func_registry.py b/tests/unit/pipelex/tools/test_func_registry.py
new file mode 100644
index 000000000..698701df0
--- /dev/null
+++ b/tests/unit/pipelex/tools/test_func_registry.py
@@ -0,0 +1,166 @@
+import logging
+from typing import Any, Callable, Dict, List
+
+import pytest
+from pytest import LogCaptureFixture
+
+from pipelex.tools.func_registry import FuncRegistry, FuncRegistryError
+
+
+def sample_function():
+ return "sample"
+
+
+def another_function(x: int):
+ return x * 2
+
+
+def registry():
+ # Create a new registry for each test
+ reg = FuncRegistry()
+ yield reg
+ # Teardown: clear the registry after each test
+ reg.teardown()
+
+
+class TestFuncRegistry:
+ def test_register_and_get_function(self, registry: FuncRegistry):
+ registry.register_function(sample_function)
+ assert registry.get_function("sample_function") is sample_function
+
+ def test_register_function_with_custom_name(self, registry: FuncRegistry):
+ registry.register_function(sample_function, name="custom_name")
+ assert registry.get_function("custom_name") is sample_function
+ assert registry.get_function("sample_function") is None
+
+ def test_has_function(self, registry: FuncRegistry):
+ registry.register_function(sample_function)
+ assert registry.has_function("sample_function")
+ assert not registry.has_function("non_existent_function")
+
+ def test_get_required_function(self, registry: FuncRegistry):
+ registry.register_function(sample_function)
+ assert registry.get_required_function("sample_function") is sample_function
+
+ def test_get_required_function_not_found(self, registry: FuncRegistry):
+ with pytest.raises(FuncRegistryError, match="not found in registry"):
+ registry.get_required_function("non_existent_function")
+
+ def test_unregister_function(self, registry: FuncRegistry):
+ registry.register_function(sample_function)
+ assert registry.has_function("sample_function")
+ registry.unregister_function(sample_function)
+ assert not registry.has_function("sample_function")
+
+ def test_unregister_function_not_found(self, registry: FuncRegistry):
+ with pytest.raises(FuncRegistryError, match="not found in registry"):
+ registry.unregister_function(sample_function)
+
+ def test_unregister_function_by_name(self, registry: FuncRegistry):
+ registry.register_function(sample_function, name="custom")
+ registry.unregister_function_by_name("custom")
+ assert not registry.has_function("custom")
+
+ def test_unregister_function_by_name_not_found(self, registry: FuncRegistry):
+ with pytest.raises(FuncRegistryError, match="not found in registry"):
+ registry.unregister_function_by_name("non_existent")
+
+ def test_register_functions_dict(self, registry: FuncRegistry):
+ functions: Dict[str, Callable[..., Any]] = {"func1": sample_function, "func2": another_function}
+ registry.register_functions_dict(functions)
+ assert registry.get_function("func1") is sample_function
+ assert registry.get_function("func2") is another_function
+
+ def test_register_functions_list(self, registry: FuncRegistry):
+ functions: List[Callable[..., Any]] = [sample_function, another_function]
+ registry.register_functions(functions)
+ assert registry.get_function("sample_function") is sample_function
+ assert registry.get_function("another_function") is another_function
+
+ def test_register_functions_empty_list(self, registry: FuncRegistry):
+ registry.register_functions([])
+ assert len(registry.root) == 0
+
+ def test_register_existing_function_with_warning(self, registry: FuncRegistry, caplog: LogCaptureFixture):
+ registry.register_function(sample_function)
+ with caplog.at_level("DEBUG"):
+ registry.register_function(sample_function)
+ assert "already exists in registry" in caplog.text
+
+ def test_register_existing_function_no_warning(self, registry: FuncRegistry, caplog: LogCaptureFixture):
+ registry.register_function(sample_function)
+ with caplog.at_level("DEBUG"):
+ registry.register_function(sample_function, should_warn_if_already_registered=False)
+ assert "already exists in registry" not in caplog.text
+
+ def test_teardown(self, registry: FuncRegistry):
+ registry.register_function(sample_function)
+ assert registry.has_function("sample_function")
+ registry.teardown()
+ assert not registry.has_function("sample_function")
+
+ def test_get_required_function_with_signature(self, registry: FuncRegistry):
+ registry.register_function(another_function)
+ func = registry.get_required_function_with_signature("another_function", another_function)
+ assert func is another_function
+
+ def test_get_required_function_with_signature_not_found(self, registry: FuncRegistry):
+ with pytest.raises(FuncRegistryError, match="not found in registry"):
+ registry.get_required_function_with_signature("non_existent", sample_function)
+
+ def test_get_required_function_with_signature_not_callable(self, registry: FuncRegistry):
+ registry.root["not_a_function"] = "a string" # type: ignore
+ with pytest.raises(FuncRegistryError, match="is not a callable function"):
+ registry.get_required_function_with_signature("not_a_function", sample_function)
+
+ def test_register_function_without_warning_when_already_exists(self, registry: FuncRegistry, caplog: LogCaptureFixture):
+ """Test that no 'already exists' log is generated when should_warn_if_already_registered=False and function doesn't exist yet"""
+ with caplog.at_level("DEBUG"):
+ registry.register_function(sample_function, should_warn_if_already_registered=False)
+ # This covers line 28 - the else branch when function doesn't exist yet
+ assert "Registered new single function" in caplog.text
+
+ def test_register_functions_dict_single_function(self, registry: FuncRegistry, caplog: LogCaptureFixture):
+ """Test registering a single function via dict - covers line 72"""
+ functions: Dict[str, Callable[..., Any]] = {"single_func": sample_function}
+ with caplog.at_level("DEBUG"):
+ registry.register_functions_dict(functions)
+ assert "Registered single function 'sample_function' in registry" in caplog.text
+ assert registry.get_function("single_func") is sample_function
+
+ def test_register_functions_skip_existing(self, registry: FuncRegistry, caplog: LogCaptureFixture):
+ """Test that existing functions are skipped when registering multiple functions - covers lines 83-84"""
+ # First register a function
+ registry.register_function(sample_function)
+
+ # Now try to register a list that includes the existing function
+ functions: List[Callable[..., Any]] = [sample_function, another_function]
+ with caplog.at_level("DEBUG"):
+ registry.register_functions(functions)
+
+ # Should log that existing function was skipped
+ assert "already exists in registry, skipping" in caplog.text
+ # But should still register the new function
+ assert registry.get_function("another_function") is another_function
+
+ def test_register_functions_single_function_in_list(self, registry: FuncRegistry, caplog: LogCaptureFixture):
+ """Test registering a single function via list - covers line 93"""
+ functions: List[Callable[..., Any]] = [sample_function]
+ with caplog.at_level("DEBUG"):
+ registry.register_functions(functions)
+ assert "Registered single function 'sample_function' in registry" in caplog.text
+ assert registry.get_function("sample_function") is sample_function
+
+ def test_set_logger(self, registry: FuncRegistry, caplog: LogCaptureFixture):
+ """Test setting a custom logger - covers line 28"""
+ custom_logger = logging.getLogger("custom_test_logger")
+ registry.set_logger(custom_logger)
+
+ # Test that the custom logger is being used by triggering a log message
+ with caplog.at_level("DEBUG", logger="custom_test_logger"):
+ registry.register_function(sample_function)
+
+ # Verify the log message was captured by our custom logger
+ assert len(caplog.records) > 0
+ assert any("Registered new single function" in record.message for record in caplog.records)
diff --git a/tests/tools/test_testing.py b/tests/unit/pipelex/tools/test_testing.py
similarity index 100%
rename from tests/tools/test_testing.py
rename to tests/unit/pipelex/tools/test_testing.py
diff --git a/tests/unit/pipelex/tools/typing/test_module_inspector.py b/tests/unit/pipelex/tools/typing/test_module_inspector.py
new file mode 100644
index 000000000..346fed801
--- /dev/null
+++ b/tests/unit/pipelex/tools/typing/test_module_inspector.py
@@ -0,0 +1,315 @@
+# SPDX-FileCopyrightText: © 2025 Evotis S.A.S.
+# SPDX-License-Identifier: Apache-2.0
+
+import os
+import shutil
+import sys
+from pathlib import Path
+
+import pytest
+
+from pipelex.tools.typing.module_inspector import ModuleFileError, find_classes_in_module, import_module_from_file
+
+
+class TestModuleFileError:
+ def test_exception_inheritance(self):
+ """Test that ModuleFileError inherits from Exception."""
+ error = ModuleFileError("test message")
+ assert isinstance(error, Exception)
+ assert str(error) == "test message"
+
+
+class TestImportModuleFromFile:
+ @pytest.fixture(autouse=True)
+ def cleanup_test_files(self):
+ """Clean up test files and sys.modules after each test."""
+ yield
+ # Clean up test files
+ test_files = ["test_module.py", "test_file.txt", "syntax_error.py", "import_error.py", "nested/subdir/test_module.py"]
+ for file_path in test_files:
+ if os.path.exists(file_path):
+ os.remove(file_path)
+
+ # Clean up nested directories and __pycache__ directories
+ directories_to_remove = ["nested/subdir", "nested", "__pycache__", "nested/__pycache__", "nested/subdir/__pycache__"]
+ for dir_path in directories_to_remove:
+ if os.path.exists(dir_path):
+ shutil.rmtree(dir_path)
+
+ # Clean up sys.modules entries for test modules
+ modules_to_remove = [name for name in sys.modules.keys() if name.startswith("test_module")]
+ for module_name in modules_to_remove:
+ del sys.modules[module_name]
+
+ def test_import_valid_python_file(self):
+ """Test importing a valid Python file."""
+ test_file_path = "test_module.py"
+ with open(test_file_path, "w") as test_file:
+ test_file.write("""
+def test_function():
+ return "test_value"
+
+class TestClass:
+ pass
+""")
+ module = import_module_from_file(test_file_path)
+ assert hasattr(module, "test_function")
+ assert hasattr(module, "TestClass")
+ assert module.test_function() == "test_value"
+
+ def test_import_non_python_file_raises_error(self, tmp_path: Path):
+ """Test that importing a non-Python file raises ModuleFileError."""
+ test_file_path = "test_file.txt"
+ with open(test_file_path, "w") as test_file:
+ test_file.write("This is not Python code")
+ with pytest.raises(ModuleFileError) as excinfo:
+ import_module_from_file(test_file_path)
+ assert "is not a Python file" in str(excinfo.value)
+
+ def test_import_nonexistent_file_raises_error(self, tmp_path: Path):
+ """Test that importing a nonexistent file raises FileNotFoundError."""
+ nonexistent_file_path = "nonexistent.py"
+ with pytest.raises(ModuleNotFoundError):
+ import_module_from_file(nonexistent_file_path)
+
+ def test_import_file_with_syntax_error_raises_error(self, tmp_path: Path):
+ """Test that importing a file with syntax errors raises SyntaxError."""
+ test_file_path = "syntax_error.py"
+ with open(test_file_path, "w") as test_file:
+ test_file.write("""
+def test_function(
+ return "missing closing parenthesis"
+""")
+ with pytest.raises(SyntaxError):
+ import_module_from_file(test_file_path)
+
+ def test_import_file_with_import_error_raises_error(self, tmp_path: Path):
+ """Test that importing a file with import errors raises ImportError."""
+ test_file_path = "import_error.py"
+ with open(test_file_path, "w") as test_file:
+ test_file.write("""
+import nonexistent_module
+""")
+ with pytest.raises(ImportError):
+ import_module_from_file(test_file_path)
+
+ def test_module_added_to_sys_modules(self, tmp_path: Path):
+ """Test that imported module is added to sys.modules."""
+ test_file_path = "test_module.py"
+ with open(test_file_path, "w") as test_file:
+ test_file.write("""
+def test_function():
+ return "test_value"
+""")
+ module = import_module_from_file(test_file_path)
+ expected_module_name = "test_module"
+ assert expected_module_name in sys.modules
+ assert sys.modules[expected_module_name] is module
+
+ def test_module_name_with_path_separators(self, tmp_path: Path):
+ """Test that module name is correctly formatted with path separators (should use file basename)."""
+ test_file_path = "nested/subdir/test_module.py"
+ # Create nested directories
+ os.makedirs("nested/subdir", exist_ok=True)
+ with open(test_file_path, "w") as test_file:
+ test_file.write("""
+def test_function():
+ return "test_value"
+""")
+ module = import_module_from_file(test_file_path)
+ assert hasattr(module, "test_function")
+ assert module.test_function() == "test_value"
+
+
+class TestFindClassesInModule:
+ def test_find_all_classes_no_base_class(self):
+ """Test finding all classes when no base class is specified."""
+ import types
+
+ test_module = types.ModuleType("test_module")
+
+ class ClassA:
+ pass
+
+ class ClassB:
+ pass
+
+ # Set __module__ so inspect.getmembers finds them
+ ClassA.__module__ = test_module.__name__
+ ClassB.__module__ = test_module.__name__
+ setattr(test_module, "ClassA", ClassA)
+ setattr(test_module, "ClassB", ClassB)
+ setattr(test_module, "some_function", lambda: None)
+ classes = find_classes_in_module(test_module, base_class=None, include_imported=False)
+ assert len(classes) == 2
+ assert ClassA in classes
+ assert ClassB in classes
+
+ def test_find_classes_with_base_class(self):
+ """Test finding classes that inherit from a specific base class."""
+ import types
+
+ test_module = types.ModuleType("test_module")
+
+ class BaseClass:
+ pass
+
+ class SubClass(BaseClass):
+ pass
+
+ class UnrelatedClass:
+ pass
+
+ # Set __module__
+ BaseClass.__module__ = test_module.__name__
+ SubClass.__module__ = test_module.__name__
+ UnrelatedClass.__module__ = test_module.__name__
+ setattr(test_module, "BaseClass", BaseClass)
+ setattr(test_module, "SubClass", SubClass)
+ setattr(test_module, "UnrelatedClass", UnrelatedClass)
+ classes = find_classes_in_module(test_module, base_class=BaseClass, include_imported=False)
+ assert len(classes) == 2 # BaseClass and SubClass
+ assert BaseClass in classes
+ assert SubClass in classes
+ assert UnrelatedClass not in classes
+
+ def test_find_classes_exclude_imported(self):
+ """Test that imported classes are excluded when include_imported=False."""
+ import types
+
+ test_module = types.ModuleType("test_module")
+
+ class LocalClass:
+ pass
+
+ class ImportedClass:
+ pass
+
+ LocalClass.__module__ = test_module.__name__
+ ImportedClass.__module__ = "other_module"
+ setattr(test_module, "LocalClass", LocalClass)
+ setattr(test_module, "ImportedClass", ImportedClass)
+ classes = find_classes_in_module(test_module, base_class=None, include_imported=False)
+ assert len(classes) == 1
+ assert LocalClass in classes
+ assert ImportedClass not in classes
+
+ def test_find_classes_include_imported(self):
+ """Test that imported classes are included when include_imported=True."""
+ import types
+
+ test_module = types.ModuleType("test_module")
+
+ class LocalClass:
+ pass
+
+ class ImportedClass:
+ pass
+
+ LocalClass.__module__ = test_module.__name__
+ ImportedClass.__module__ = "other_module"
+ setattr(test_module, "LocalClass", LocalClass)
+ setattr(test_module, "ImportedClass", ImportedClass)
+ classes = find_classes_in_module(test_module, base_class=None, include_imported=True)
+ assert len(classes) == 2
+ assert LocalClass in classes
+ assert ImportedClass in classes
+
+ def test_find_classes_empty_module(self):
+ """Test finding classes in an empty module."""
+ import types
+
+ test_module = types.ModuleType("test_module")
+ classes = find_classes_in_module(test_module, base_class=None, include_imported=False)
+ assert len(classes) == 0
+
+ def test_find_classes_with_functions_and_variables(self):
+ """Test that functions and variables are not included in class search."""
+ import types
+
+ test_module = types.ModuleType("test_module")
+
+ class TestClass:
+ pass
+
+ TestClass.__module__ = test_module.__name__
+
+ def test_function():
+ pass
+
+ setattr(test_module, "TestClass", TestClass)
+ setattr(test_module, "test_function", test_function)
+ setattr(test_module, "some_variable", 42)
+ setattr(test_module, "some_string", "hello")
+ classes = find_classes_in_module(test_module, base_class=None, include_imported=False)
+ assert len(classes) == 1
+ assert TestClass in classes
+
+ def test_find_classes_with_nested_classes(self):
+ """Test finding classes including nested classes."""
+ import types
+
+ test_module = types.ModuleType("test_module")
+
+ class OuterClass:
+ class InnerClass:
+ pass
+
+ OuterClass.__module__ = test_module.__name__
+ setattr(test_module, "OuterClass", OuterClass)
+ classes = find_classes_in_module(test_module, base_class=None, include_imported=False)
+ assert len(classes) == 1
+ assert OuterClass in classes
+
+ def test_find_classes_with_builtin_types(self):
+ """Test finding classes including user-defined types (not builtins, which can't be assigned __module__)."""
+ import types
+
+ test_module = types.ModuleType("test_module")
+
+ class MyClassA:
+ pass
+
+ class MyClassB:
+ pass
+
+ MyClassA.__module__ = test_module.__name__
+ MyClassB.__module__ = test_module.__name__
+ setattr(test_module, "MyClassA", MyClassA)
+ setattr(test_module, "MyClassB", MyClassB)
+ classes = find_classes_in_module(test_module, base_class=None, include_imported=False)
+ assert len(classes) == 2
+ assert MyClassA in classes
+ assert MyClassB in classes
+
+ def test_find_classes_with_base_class_and_imported(self):
+ """Test finding classes with base class filter and imported classes."""
+ import types
+
+ test_module = types.ModuleType("test_module")
+
+ class BaseClass:
+ pass
+
+ class LocalSubClass(BaseClass):
+ pass
+
+ class ImportedSubClass(BaseClass):
+ pass
+
+ BaseClass.__module__ = test_module.__name__
+ LocalSubClass.__module__ = test_module.__name__
+ ImportedSubClass.__module__ = "other_module"
+ setattr(test_module, "BaseClass", BaseClass)
+ setattr(test_module, "LocalSubClass", LocalSubClass)
+ setattr(test_module, "ImportedSubClass", ImportedSubClass)
+ classes = find_classes_in_module(test_module, base_class=BaseClass, include_imported=False)
+ assert len(classes) == 2 # BaseClass and LocalSubClass
+ assert BaseClass in classes
+ assert LocalSubClass in classes
+ assert ImportedSubClass not in classes
+ classes = find_classes_in_module(test_module, base_class=BaseClass, include_imported=True)
+ assert len(classes) == 3 # BaseClass, LocalSubClass, and ImportedSubClass
+ assert BaseClass in classes
+ assert LocalSubClass in classes
+ assert ImportedSubClass in classes
diff --git a/tests/tools/typing/test_pydantic_utils.py b/tests/unit/pipelex/tools/typing/test_pydantic_utils.py
similarity index 86%
rename from tests/tools/typing/test_pydantic_utils.py
rename to tests/unit/pipelex/tools/typing/test_pydantic_utils.py
index 42920d767..0ed7b8d90 100644
--- a/tests/tools/typing/test_pydantic_utils.py
+++ b/tests/unit/pipelex/tools/typing/test_pydantic_utils.py
@@ -95,6 +95,22 @@ def test_format_pydantic_validation_error() -> None:
assert "Extra forbidden fields: ['c: 1']" in formatted
+def test_format_pydantic_validation_error_model_type() -> None:
+ class InnerModel(BaseModel):
+ value: int
+
+ class OuterModel(BaseModel):
+ inner: InnerModel
+
+ # Try to pass a dict where a specific model type is expected
+ with pytest.raises(ValidationError) as exc:
+ OuterModel.model_validate({"inner": "not_a_model"})
+
+ formatted = format_pydantic_validation_error(exc.value)
+ assert "Model type errors:" in formatted
+ assert "expected InnerModel, got str" in formatted
+
+
def test_custom_base_model_truncates_repr() -> None:
class TestModel(CustomBaseModel):
base_64: str
diff --git a/tests/tools/typing/test_type_inspector.py b/tests/unit/pipelex/tools/typing/test_type_inspector.py
similarity index 100%
rename from tests/tools/typing/test_type_inspector.py
rename to tests/unit/pipelex/tools/typing/test_type_inspector.py
diff --git a/uv.lock b/uv.lock
index fc3eed5d1..46e72f85e 100644
--- a/uv.lock
+++ b/uv.lock
@@ -889,14 +889,14 @@ wheels = [
[[package]]
name = "kajson"
-version = "0.1.6"
+version = "0.2.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "pydantic" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/40/cf/eb2cc86fc0f56b982692d2a2401d3464e8143dfc7e6549afa0eaf3613053/kajson-0.1.6.tar.gz", hash = "sha256:163abcfe8c376adb351d4e7acdc82744e2ddcb7ae4082803284318cc4d240f06", size = 15236, upload-time = "2025-06-19T10:18:00.314Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/8a/b5/404dda6ea283cba04e408d4447466a14863586f6872f87d70883e32ac48a/kajson-0.2.0.tar.gz", hash = "sha256:1dbe9595ef70a6cb1e3fdfc28fa6f1f3e361bbdfb03b0a4ca525f3f6f6100b92", size = 18178, upload-time = "2025-06-23T09:05:15.665Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/22/75/53cc71d915c4269c624f8e76f10e0aff9f1112d6b568ac1b987d1b5df4b1/kajson-0.1.6-py3-none-any.whl", hash = "sha256:93ddca59dd225a79d8ffb9b54170e98b4b6c8a1f999bcf2d5981d919e132538d", size = 21594, upload-time = "2025-06-19T10:17:58.919Z" },
+ { url = "https://files.pythonhosted.org/packages/1e/da/8942c19fb6806d29d8769059a2f5f0a19bd9cbaadaaad725dd1aae8efa78/kajson-0.2.0-py3-none-any.whl", hash = "sha256:1221d4d3be54033f97642c4df9a7144d086a49d95f1f2adeb975308e671c5ac9", size = 24219, upload-time = "2025-06-23T09:05:14.193Z" },
]
[[package]]
@@ -1668,6 +1668,7 @@ dev = [
{ name = "pytest" },
{ name = "pytest-asyncio" },
{ name = "pytest-cov" },
+ { name = "pytest-mock" },
{ name = "pytest-sugar" },
{ name = "pytest-xdist" },
{ name = "ruff" },
@@ -1712,7 +1713,7 @@ requires-dist = [
{ name = "instructor", specifier = ">=1.8.3" },
{ name = "jinja2", specifier = ">=3.1.4" },
{ name = "json2html", specifier = ">=1.3.0" },
- { name = "kajson", specifier = "==0.1.6" },
+ { name = "kajson", specifier = "==0.2.0" },
{ name = "markdown", specifier = ">=3.6" },
{ name = "mistralai", marker = "extra == 'mistralai'", specifier = "==1.5.2" },
{ name = "mkdocs", marker = "extra == 'docs'", specifier = "==1.6.1" },
@@ -1733,6 +1734,7 @@ requires-dist = [
{ name = "pytest", marker = "extra == 'dev'", specifier = ">=8.3.3" },
{ name = "pytest-asyncio", marker = "extra == 'dev'", specifier = ">=0.24.0" },
{ name = "pytest-cov", marker = "extra == 'dev'", specifier = ">=6.1.1" },
+ { name = "pytest-mock", marker = "extra == 'dev'", specifier = ">=3.14.0" },
{ name = "pytest-sugar", marker = "extra == 'dev'", specifier = ">=1.0.0" },
{ name = "pytest-xdist", marker = "extra == 'dev'", specifier = ">=3.6.1" },
{ name = "python-dotenv", specifier = ">=1.0.1" },
@@ -2085,6 +2087,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/bc/16/4ea354101abb1287856baa4af2732be351c7bee728065aed451b678153fd/pytest_cov-6.2.1-py3-none-any.whl", hash = "sha256:f5bc4c23f42f1cdd23c70b1dab1bbaef4fc505ba950d53e0081d0730dd7e86d5", size = 24644, upload-time = "2025-06-12T10:47:45.932Z" },
]
+[[package]]
+name = "pytest-mock"
+version = "3.14.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "pytest" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/71/28/67172c96ba684058a4d24ffe144d64783d2a270d0af0d9e792737bddc75c/pytest_mock-3.14.1.tar.gz", hash = "sha256:159e9edac4c451ce77a5cdb9fc5d1100708d2dd4ba3c3df572f14097351af80e", size = 33241, upload-time = "2025-05-26T13:58:45.167Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b2/05/77b60e520511c53d1c1ca75f1930c7dd8e971d0c4379b7f4b3f9644685ba/pytest_mock-3.14.1-py3-none-any.whl", hash = "sha256:178aefcd11307d874b4cd3100344e7e2d888d9791a6a1d9bfe90fbc1b74fd1d0", size = 9923, upload-time = "2025-05-26T13:58:43.487Z" },
+]
+
[[package]]
name = "pytest-sugar"
version = "1.0.0"