Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

3.7 KB
Raw Blame
from fastapi import FastAPI
from pydantic import create_model

from invokeai.app.invocations.baseinvocation import InvocationRegistry
from invokeai.app.services.config.config_default import InvokeAIAppConfig
from invokeai.app.util.custom_openapi import (
    get_openapi_func,
    normalize_path_defaults,
    remove_unreferenced_internal_execution_schemas,
)


class _FakeOutput:
    pass


class _InvocationB:
    __name__ = "InvocationB"

    @classmethod
    def model_json_schema(cls, mode: str, ref_template: str) -> dict:
        return {"type": "object", "properties": {}}

    @classmethod
    def get_output_annotation(cls) -> type:
        return _FakeOutput

    @classmethod
    def get_type(cls) -> str:
        return "b_type"


class _InvocationA:
    __name__ = "InvocationA"

    @classmethod
    def model_json_schema(cls, mode: str, ref_template: str) -> dict:
        return {"type": "object", "properties": {}}

    @classmethod
    def get_output_annotation(cls) -> type:
        return _FakeOutput

    @classmethod
    def get_type(cls) -> str:
        return "a_type"


def test_invocation_output_map_required_is_sorted(monkeypatch: object) -> None:
    """The 'required' list in InvocationOutputMap must be sorted so that the
    generated openapi.json is deterministic regardless of set-iteration order."""

    # A FastAPI app needs at least one route to produce a schema with 'components'.
    DummyResponse = create_model("DummyResponse", ok=(bool, ...))
    app = FastAPI(title="test")
    app.get("/healthz", response_model=DummyResponse)(lambda: DummyResponse(ok=True))

    monkeypatch.setattr(InvocationRegistry, "get_output_classes", classmethod(lambda cls: []))  # type: ignore[arg-type]
    monkeypatch.setattr(  # type: ignore[arg-type]
        InvocationRegistry, "get_invocation_classes", classmethod(lambda cls: [_InvocationB, _InvocationA])
    )

    schema = get_openapi_func(app)()
    required = schema["components"]["schemas"]["InvocationOutputMap"]["required"]

    assert required == ["a_type", "b_type"], f"Expected sorted required list, got: {required}"


def test_path_defaults_are_normalized_to_forward_slashes() -> None:
    schema = InvokeAIAppConfig.model_json_schema()
    schema["properties"]["convert_cache_dir"]["default"] = "models\\.convert_cache"
    schema["properties"]["download_cache_dir"]["default"] = "models\\.download_cache"
    schema["properties"]["nested_path"] = {
        "oneOf": [
            {
                "type": "object",
                "properties": {
                    "cache_dir": {
                        "type": "string",
                        "format": "path",
                        "default": "models\\.nested_cache",
                    }
                },
            }
        ]
    }

    normalize_path_defaults(schema)

    assert schema["properties"]["convert_cache_dir"]["default"] == "models/.convert_cache"
    assert schema["properties"]["download_cache_dir"]["default"] == "models/.download_cache"
    assert (
        schema["properties"]["nested_path"]["oneOf"][0]["properties"]["cache_dir"]["default"] == "models/.nested_cache"
    )


def test_internal_execution_schemas_are_retained_when_publicly_referenced() -> None:
    schema = {
        "paths": {},
        "components": {
            "schemas": {
                "Public": {"properties": {"reference": {"$ref": "#/components/schemas/ExecutionReference"}}},
                "ExecutionReference": {"properties": {"frame": {"$ref": "#/components/schemas/ExecutionFrame"}}},
                "ExecutionFrame": {},
                "ExecutionToken": {},
            }
        },
    }

    remove_unreferenced_internal_execution_schemas(schema)

    assert set(schema["components"]["schemas"]) == {"Public", "ExecutionReference", "ExecutionFrame"}