repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
InvokeAI
tests/backend/patches/lora_conversions/lora_state_dicts/flux_lora_diffusers_format.py
.py
# A sample state dict in the Diffusers FLUX LoRA format. # These keys are based on the LoRA model here: # https://civitai.com/models/200255/hands-xl-sd-15-flux1-dev?modelVersionId=781855 state_dict_keys = { "transformer.single_transformer_blocks.0.attn.to_k.lora_A.weight": [32, 3072], "transformer.single_transf...
994
81,699
InvokeAI
tests/backend/patches/lora_conversions/lora_state_dicts/flux_lokr_bfl_format.py
.py
# A sample state dict in the BFL LOKR format (FLUX.1 hidden_size=3072). # These keys represent a LOKR model using BFL internal key names with 'diffusion_model.' prefix. state_dict_keys = { "diffusion_model.double_blocks.0.img_attn.proj.lokr_w1": [32, 96], "diffusion_model.double_blocks.0.img_attn.proj.lokr_w2":...
23
1,363
InvokeAI
tests/backend/patches/lora_conversions/lora_state_dicts/anima_lora_kohya_with_te_format.py
.py
# A sample state dict in the Kohya Anima LoRA format with Qwen3 text encoder layers. # Contains both lora_unet_ (transformer) and lora_te_ (Qwen3 encoder) keys. state_dict_keys: dict[str, list[int]] = { # Transformer block 0 - cross attention "lora_unet_blocks_0_cross_attn_k_proj.lora_down.weight": [8, 2048], ...
35
2,006
InvokeAI
tests/backend/patches/lora_conversions/lora_state_dicts/flux_lora_aitoolkit_format.py
.py
state_dict_keys = { "diffusion_model.double_blocks.0.img_attn.proj.lora_A.weight": [16, 3072], "diffusion_model.double_blocks.0.img_attn.proj.lora_B.weight": [3072, 16], "diffusion_model.double_blocks.0.img_attn.qkv.lora_A.weight": [16, 3072], "diffusion_model.double_blocks.0.img_attn.qkv.lora_B.weight"...
459
34,858
InvokeAI
tests/backend/patches/lora_conversions/lora_state_dicts/qwen_image_lora_diffusers_format.py
.py
# Diffusers/PEFT-format Qwen Image LoRA state dict keys. # Keys use the pattern: transformer_blocks.{N}.{sub_module}.{param} state_dict_keys: dict[str, list[int]] = { # Block 0 - standard LoRA (lora_down/lora_up) "transformer_blocks.0.attn.to_k.lora_down.weight": [64, 3072], "transformer_blocks.0.attn.to_k...
17
774
InvokeAI
tests/backend/patches/lora_conversions/lora_state_dicts/flux_control_lora_format.py
.py
# A sample state dict in the FLUX Control LoRA format. # These keys are based on the LoRA model here: # https://huggingface.co/black-forest-labs/FLUX.1-Depth-dev-lora state_dict_keys = { "double_blocks.0.img_attn.norm.key_norm.scale": [128], "double_blocks.0.img_attn.norm.query_norm.scale": [128], "double_b...
1,100
64,758
InvokeAI
tests/backend/anima/test_scheduler_driver.py
.py
"""Tests for AnimaSchedulerDriver — the helper that hides per-scheduler API quirks (sigmas= vs num_inference_steps=, Heun's doubled timestep array, set_begin_index) behind a uniform iteration interface.""" import inspect import pytest import torch from invokeai.app.invocations.anima_denoise import loglinear_timestep...
196
7,581
InvokeAI
tests/backend/anima/test_control_net_lllite.py
.py
"""Tests for the Anima ControlNet-LLLite adapter — construction from a saved state dict, exact-passthrough guarantees, forward-swap binding/restore, multi-adapter composition, and the conditioning image preprocessing helpers.""" import os from pathlib import Path import pytest import torch import torch.nn.functional ...
765
31,036
InvokeAI
tests/backend/util/test_logging.py
.py
""" Test interaction of logging with configuration system. """ import io import logging import re from invokeai.app.services.config import InvokeAIAppConfig from invokeai.backend.util.logging import LOG_FORMATTERS, InvokeAILogger # test formatting # Would prefer to use the capfd/capsys fixture here, but it is broke...
59
1,877
InvokeAI
tests/backend/util/test_devices.py
.py
""" Test abstract device class. """ import ctypes import threading from types import SimpleNamespace from unittest.mock import patch import pytest import torch from invokeai.app.services.config import get_config from invokeai.backend.util.devices import TorchDevice, choose_precision, choose_torch_device, torch_dtype...
645
27,547
InvokeAI
tests/backend/util/test_build_line.py
.py
import math import pytest from invokeai.backend.util.build_line import build_line @pytest.mark.parametrize( ["x1", "y1", "x2", "y2", "x3", "y3"], [ (0, 0, 1, 1, 2, 2), # y = x (0, 1, 1, 2, 2, 3), # y = x + 1 (0, 0, 1, 2, 2, 4), # y = 2x (0, 1, 1, 0, 2, -1), # y = -x + 1 ...
20
526
InvokeAI
tests/backend/util/test_mask.py
.py
import pytest import torch from invokeai.backend.util.mask import to_standard_float_mask def test_to_standard_float_mask_wrong_ndim(): with pytest.raises(ValueError): to_standard_float_mask(mask=torch.zeros((1, 1, 5, 10)), out_dtype=torch.float32) def test_to_standard_float_mask_wrong_shape(): with...
89
2,893
InvokeAI
tests/backend/util/test_device_pool.py
.py
"""Tests for the idle generation-device arbiter used by text-encoder offload.""" import threading import time from collections.abc import Iterator import pytest import torch from invokeai.backend.util.device_pool import GENERATION_DEVICE_POOL @pytest.fixture(autouse=True) def reset_pool() -> Iterator[None]: ""...
194
8,529
InvokeAI
tests/backend/util/test_fp8.py
.py
"""Tests for `get_model_compute_dtype`. Regression coverage for the SDXL + fp8_storage crash: NotImplementedError: "pow_cuda" not implemented for 'Float8_e4m3fn' The legacy SD/SDXL denoise path derived every tensor dtype (latents, noise, conditioning, control images, LoRA patch weights) from `unet.dtype`. With f...
144
6,006
InvokeAI
tests/backend/image_util/test_color_conversion.py
.py
import pytest import torch from invokeai.backend.image_util import color_conversion from invokeai.invocation_api import ( hsl_from_linear_srgb, hsl_from_srgb, lab_from_linear_srgb, lab_from_srgb, lab_from_xyz, linear_srgb_from_hsl, linear_srgb_from_lab, linear_srgb_from_oklab, linea...
621
17,338
InvokeAI
tests/backend/image_util/test_vendor_mutable_defaults.py
.py
"""Tests for the mutable default argument fix in imwatermark/vendor.py and the bare except fix in sqlite_database.py.""" from logging import Logger from unittest import mock import pytest from invokeai.backend.image_util.imwatermark.vendor import EmbedMaxDct, WatermarkEncoder class TestSetByBitsNoSharedState: ...
107
3,618
InvokeAI
tests/backend/qwen3/test_qwen3_tokenizer.py
.py
"""Tests for the bundled Qwen3 tokenizer used by single-file / GGUF Qwen3 encoders. Single-file and GGUF Qwen3 encoder checkpoints (Z-Image, Anima) ship weights only. The tokenizer is vendored in the package so the encoder works fully offline instead of pulling ``Qwen/Qwen3-4B`` from HuggingFace on first use. """ fro...
56
2,015
InvokeAI
tests/backend/flux/test_anima_schedulers.py
.py
"""Tests for Anima scheduler registry.""" import typing import pytest from diffusers.schedulers.scheduling_utils import SchedulerMixin from invokeai.backend.flux.schedulers import ( ANIMA_SCHEDULER_LABELS, ANIMA_SCHEDULER_MAP, ANIMA_SCHEDULER_NAME_VALUES, ) def test_anima_scheduler_map_entries_are_clas...
320
14,294
InvokeAI
tests/backend/flux/test_denoise.py
.py
from types import SimpleNamespace import pytest import torch from invokeai.backend.flux.denoise import denoise from invokeai.backend.flux.schedulers import FLUX_SCHEDULER_MAP class _FakeFluxModel: def __call__( self, img: torch.Tensor, img_ids: torch.Tensor, txt: torch.Tensor, ...
250
8,450
InvokeAI
tests/backend/flux/test_sampling_utils.py
.py
import pytest import torch from invokeai.backend.flux.sampling_utils import clip_timestep_schedule, clip_timestep_schedule_fractional def float_lists_almost_equal(list1: list[float], list2: list[float], tol: float = 1e-6) -> bool: return all(abs(a - b) < tol for a, b in zip(list1, list2, strict=True)) @pytest....
77
3,454
InvokeAI
tests/backend/flux/redux/test_flux_redux_state_dict_utils.py
.py
# The state dict keys and shapes for a FLUX Redux model. # Model source: https://huggingface.co/black-forest-labs/FLUX.1-Redux-dev/blob/1282f955f706b5240161278f2ef261d2a29ad649/flux1-redux-dev.safetensors # The keys and shapes were extracted with extract_sd_keys_and_shapes.py. import torch from invokeai.backend.flux.r...
29
1,192
InvokeAI
tests/backend/flux/controlnet/test_state_dict_utils.py
.py
import sys import pytest import torch from invokeai.backend.flux.controlnet.instantx_controlnet_flux import InstantXControlNetFlux from invokeai.backend.flux.controlnet.state_dict_utils import ( convert_diffusers_instantx_state_dict_to_bfl_format, infer_flux_params_from_state_dict, infer_instantx_num_cont...
109
4,463
InvokeAI
tests/backend/flux/controlnet/instantx_flux_controlnet_state_dict.py
.py
# State dict keys and shapes for an InstantX FLUX ControlNet Union model. Intended to be used for unit tests. # These keys were extracted from: # https://huggingface.co/InstantX/FLUX.1-dev-Controlnet-Union/blob/4f32d6f2b220f8873d49bb8acc073e1df180c994/diffusion_pytorch_model.safetensors instantx_sd_shapes = { "cont...
375
21,670
InvokeAI
tests/backend/flux/controlnet/xlabs_flux_controlnet_state_dict.py
.py
# State dict keys and shapes for an XLabs FLUX ControlNet model. Intended to be used for unit tests. # These keys were extracted from: # https://huggingface.co/XLabs-AI/flux-controlnet-collections/blob/86ab1e915a389d5857135c00e0d350e9e38a9048/flux-canny-controlnet_v2.safetensors xlabs_sd_shapes = { "controlnet_bloc...
92
4,462
InvokeAI
tests/backend/flux/ip_adapter/xlabs_flux_ip_adapter_state_dict.py
.py
# State dict keys and shapes for an XLabs FLUX IP-Adapter model. Intended to be used for unit tests. # These keys were extracted from: # https://huggingface.co/XLabs-AI/flux-ip-adapter/resolve/main/ip_adapter.safetensors xlabs_flux_ip_adapter_sd_shapes = { "double_blocks.0.processor.ip_adapter_double_stream_k_proj....
86
6,726
InvokeAI
tests/backend/flux/ip_adapter/test_xlabs_ip_adapter_flux.py
.py
import sys import accelerate import pytest import torch from invokeai.backend.flux.ip_adapter.state_dict_utils import ( infer_xlabs_ip_adapter_params_from_state_dict, is_state_dict_xlabs_ip_adapter, ) from invokeai.backend.flux.ip_adapter.xlabs_ip_adapter_flux import ( XlabsIpAdapterFlux, XlabsIpAdapt...
79
2,793
InvokeAI
tests/backend/flux/ip_adapter/xlabs_flux_ip_adapter_v2_state_dict.py
.py
# State dict keys and shapes for an XLabs FLUX IP-Adapter V2 model. Intended to be used for unit tests. # These keys were extracted from: # https://huggingface.co/XLabs-AI/flux-ip-adapter-v2/blob/main/ip_adapter.safetensors xlabs_flux_ip_adapter_v2_sd_shapes = { "double_blocks.0.processor.ip_adapter_double_stream_k...
86
6,732
InvokeAI
tests/backend/flux/dype/test_dype.py
.py
"""Tests for DyPE (Dynamic Position Extrapolation) module.""" import torch from invokeai.backend.flux.dype.base import ( DyPEConfig, compute_vision_yarn_freqs, get_timestep_kappa, ) from invokeai.backend.flux.dype.embed import DyPEEmbedND from invokeai.backend.flux.dype.presets import ( DYPE_PRESET_4K...
500
15,080
InvokeAI
tests/backend/flux/modules/test_conditioner.py
.py
import torch from invokeai.backend.flux.modules.conditioner import HFEncoder class FakeTokenizer: def __call__( self, text, truncation, max_length, return_length, return_overflowing_tokens, padding, return_tensors, ): del text, truncatio...
61
2,293
InvokeAI
tests/app/test_subpath_middleware.py
.py
"""Tests for reverse-proxy sub-path support (`SubPathASGIMiddleware` + root_path-aware redirect). Exercises both proxy styles against a minimal FastAPI app so the subtle routing/redirect matrix (routing, trailing-slash 307s, and the `?__theme=dark` root redirect) is protected from regression. """ import pytest from f...
99
4,025
InvokeAI
tests/app/test_invocation_event_socketio.py
.py
"""Tests for socket routing of invocation events in multiuser mode. Invocation progress events drive personal UI (the global progress bar and progress image previews) and must be delivered only to the owner - admins receiving other users' progress would see their own progress display hijacked. The other invocation eve...
179
6,049
InvokeAI
tests/app/test_extract_metadata_from_image.py
.py
import json import logging from unittest.mock import MagicMock, patch import pytest from PIL import Image from invokeai.app.api.extract_metadata_from_image import ExtractedMetadata, extract_metadata_from_image @pytest.fixture def mock_logger(): return MagicMock(spec=logging.Logger) @pytest.fixture def valid_m...
224
8,518
InvokeAI
tests/app/test_workflow_socketio.py
.py
from types import SimpleNamespace from unittest.mock import ANY, AsyncMock import pytest from fastapi import FastAPI from invokeai.app.api.sockets import SocketIO @pytest.fixture def anyio_backend() -> str: return "asyncio" def _patch_multiuser_context(monkeypatch: pytest.MonkeyPatch, *, user_id: str, is_admi...
181
6,371
InvokeAI
tests/app/routers/test_utilities.py
.py
"""Router-level tests for /api/v1/utilities. Covers: - Auth gating (CurrentUserOrDefault on all three utility routes). - image-to-prompt: image read-access check must fire BEFORE the model is loaded, so non-owners can't probe stored images. - image-to-prompt: a missing image surfaces as 404, not 500. """ from typin...
174
7,036
InvokeAI
tests/app/routers/test_recall_parameters.py
.py
"""Tests for the recall parameters router. These tests monkey-patch the heavy-weight lookup helpers (``resolve_model_name_to_key``, ``load_image_file``, ``process_controlnet_image``) rather than wiring up a real model manager or image-files service. This keeps each test focused on the router's request-validation, reso...
835
34,014
InvokeAI
tests/app/routers/test_session_queue_workflow_call.py
.py
"""Tests for session queue API behavior with workflow-call queue items.""" import logging import uuid from typing import Any from unittest.mock import MagicMock import pytest from fastapi.testclient import TestClient from invokeai.app.api.dependencies import ApiDependencies from invokeai.app.api_app import app from ...
439
17,283
InvokeAI
tests/app/routers/test_model_manager.py
.py
import os from pathlib import Path from typing import Any import pytest from fastapi.testclient import TestClient from invokeai.app.api.dependencies import ApiDependencies from invokeai.app.api_app import app from invokeai.backend.model_manager.configs.external_api import ( ExternalApiModelConfig, ExternalMod...
283
11,191
InvokeAI
tests/app/routers/test_system_prompts_single_user.py
.py
"""Single-user tests for the /api/v1/system_prompts router. The multi-user tests cover the ownership checks. Single-user installs skip those checks entirely, which is exactly where the delete contract used to diverge: DELETE reported 200 for ids that GET 404s on, and deleting the same row twice succeeded twice. """ i...
136
5,958
InvokeAI
tests/app/routers/test_workflow_live_updates.py
.py
"""Tests for workflow CRUD live-update events with multiuser visibility rules.""" from typing import Any from fastapi.testclient import TestClient from tests.app.routers.test_workflows_multiuser import WORKFLOW_BODY pytest_plugins = ("tests.app.routers.test_workflows_multiuser",) def _auth(token: str) -> dict[str...
119
4,566
InvokeAI
tests/app/routers/test_style_presets.py
.py
"""Router-level tests for /api/v1/style_presets. Backed by a real SqliteStylePresetRecordsStorage from the shared conftest, so SQL filtering and ownership rules are exercised end-to-end. style_preset_image_files remains a MagicMock — file IO is not under test here. Covers: - Auth gating (CurrentUserOrDefault on CRUD/...
415
18,107
InvokeAI
tests/app/routers/test_app_info.py
.py
import os from pathlib import Path from typing import Any from unittest.mock import Mock import pytest from fastapi.testclient import TestClient from invokeai.app.api.dependencies import ApiDependencies from invokeai.app.api.routers import app_info from invokeai.app.api_app import app from invokeai.app.services.auth....
456
20,220
InvokeAI
tests/app/routers/test_auth.py
.py
"""Integration tests for authentication router endpoints.""" import os from pathlib import Path from typing import Any import pytest from fastapi.testclient import TestClient from invokeai.app.api.dependencies import ApiDependencies from invokeai.app.api_app import app from invokeai.app.services.auth.token_service i...
520
21,443
InvokeAI
tests/app/routers/test_model_relationships.py
.py
"""Router-level tests for /api/v1/model_relationships. Covers: - Auth gating (CurrentUserOrDefault on read/batch, AdminUserOrDefault on add/remove). - Bug regression: self-relationship checks must return 400 (not 500 — the previous broad `except Exception` swallowed the HTTPException and converted it). - Service exc...
157
6,079
InvokeAI
tests/app/routers/test_virtual_boards.py
.py
"""Router-level tests for /api/v1/virtual_boards. These routes already use CurrentUserOrDefault, but until now had no tests pinning the anonymous-rejection + per-user filtering behavior. """ from typing import Any from fastapi import status from fastapi.testclient import TestClient from invokeai.app.services.image_...
148
5,465
InvokeAI
tests/app/routers/test_image_moves.py
.py
import logging from unittest.mock import MagicMock import pytest from fastapi import status from fastapi.testclient import TestClient from invokeai.app.api.dependencies import ApiDependencies from invokeai.app.api_app import app from invokeai.app.services.auth.token_service import set_jwt_secret from invokeai.app.ser...
208
8,813
InvokeAI
tests/app/routers/test_update_model_record_cache_invalidation.py
.py
"""Tests for `_load_settings_changed` — the predicate that decides whether to evict cached model entries after an `update_model_record` call. Settings like `fp8_storage` and `cpu_only` are baked into the loaded nn.Module at load time, so toggling them silently has no effect until the cached entry is evicted. The predic...
54
2,597
InvokeAI
tests/app/routers/test_workflows_multiuser.py
.py
"""Tests for multiuser workflow library functionality.""" import logging from typing import Any from unittest.mock import MagicMock import pytest from fastapi import status from fastapi.testclient import TestClient from invokeai.app.api.dependencies import ApiDependencies from invokeai.app.api_app import app from in...
684
27,817
InvokeAI
tests/app/routers/test_custom_nodes.py
.py
"""Tests for the custom nodes router.""" import asyncio import json import sys from pathlib import Path from unittest.mock import MagicMock, patch from invokeai.app.api.routers.custom_nodes import ( PACK_MANIFEST_FILENAME, _extract_pack_name_from_source, _get_installed_packs, _import_workflows_from_pa...
568
24,397
InvokeAI
tests/app/routers/test_session_queue_image_move_maintenance.py
.py
from unittest.mock import MagicMock import pytest from fastapi import HTTPException from invokeai.app.api.dependencies import ApiDependencies from invokeai.app.api.routers.session_queue import enqueue_batch from invokeai.app.services.session_queue.session_queue_common import DEFAULT_QUEUE_ID, Batch from invokeai.app....
41
1,334
InvokeAI
tests/app/routers/test_client_state_multiuser.py
.py
"""Tests for multiuser client state functionality.""" from typing import Any import pytest from fastapi import status from fastapi.testclient import TestClient from invokeai.app.api.dependencies import ApiDependencies from invokeai.app.api_app import app from invokeai.app.services.invoker import Invoker from invokea...
445
17,507
InvokeAI
tests/app/routers/test_multiuser_authorization.py
.py
"""Tests for API-level authorization on board-image mutations, image mutations, workflow thumbnail access, and admin email leak prevention. These tests verify the security fixes for: 1. Shared-board write protection bypass via direct API calls 2. Image mutation endpoints lacking ownership checks 3. Private workflow th...
2,686
125,454
InvokeAI
tests/app/routers/test_system_prompts_multiuser.py
.py
"""Multi-user permission tests for the /api/v1/system_prompts router. Verifies: - list scopes to own + public for non-admins - non-owner PATCH/DELETE returns 403 - owner can flip is_public - admin sees and mutates everything """ import logging from typing import Any import pytest from fastapi import status from fast...
285
11,205
InvokeAI
tests/app/routers/test_session_queue_sanitization.py
.py
"""Tests for session queue item sanitization in multiuser mode.""" from datetime import datetime import pytest from invokeai.app.api.routers.session_queue import sanitize_queue_item_for_user from invokeai.app.invocations.baseinvocation import BaseInvocation, BaseInvocationOutput, invocation, invocation_output from i...
192
6,973
InvokeAI
tests/app/routers/test_boards_multiuser.py
.py
"""Tests for multiuser boards functionality.""" import inspect from contextlib import nullcontext from typing import Any from unittest.mock import MagicMock, patch import pytest from fastapi import status from fastapi.testclient import TestClient from invokeai.app.api.dependencies import ApiDependencies from invokea...
898
36,761
InvokeAI
tests/app/routers/test_model_manager_authorization.py
.py
"""Tests for API-level authorization on model-manager and app-info read endpoints. These cover the security fix for GH #9365: in multi-user mode a number of model-management and app-info read routes carried no auth dependency at all, so an unauthenticated network attacker could reach them. The highest impact was `GET ...
355
15,963
InvokeAI
tests/app/routers/test_video_range_header.py
.py
"""Tests for the video route's HTTP Range header parser.""" import pytest from invokeai.app.api.routers.videos import _parse_range_header FILE_SIZE = 1000 @pytest.mark.parametrize( "header,expected", [ ("bytes=0-499", (0, 499)), ("bytes=500-999", (500, 999)), ("bytes=500-", (500, 99...
48
1,622
InvokeAI
tests/app/routers/test_board_images_maintenance.py
.py
from unittest.mock import MagicMock import pytest from fastapi.testclient import TestClient from invokeai.app.api.auth_dependencies import get_current_user_or_default from invokeai.app.api.dependencies import ApiDependencies from invokeai.app.api_app import app from invokeai.app.services.auth.token_service import Tok...
155
6,365
InvokeAI
tests/app/routers/test_images.py
.py
import os from pathlib import Path from typing import Any from unittest.mock import MagicMock import pytest from fastapi import BackgroundTasks from fastapi.testclient import TestClient from invokeai.app.api.auth_dependencies import get_current_user_or_default from invokeai.app.api.dependencies import ApiDependencies...
223
9,086
InvokeAI
tests/app/routers/test_videos_multiuser.py
.py
"""Multiuser regression tests for the /v1/videos/ routes. Covers JPPhoto's code-review finding (PR #9163): the list endpoints accepted an explicit ``board_id`` with no read-access check, so a non-admin user could enumerate videos on someone else's private board if they happened to know its id. The fix added ``_assert_...
953
40,732
InvokeAI
tests/app/routers/conftest.py
.py
"""Shared fixtures and helpers for router-level multiuser/auth tests. Note: This conftest intentionally does NOT redefine `mock_services` / `mock_invoker` to avoid shadowing the project-level fixtures in `tests/conftest.py`. Instead, the `enable_multiuser` fixture below injects MagicMock services for the routers that ...
147
5,989
InvokeAI
tests/app/services/test_workflow_call_batch_runtime.py
.py
from tests.app.services import workflow_call_test_utils as workflow_call_tests def test_run_node_fails_cleanly_for_invalid_batch_child_workflow(monkeypatch) -> None: workflow_call_tests.test_run_node_fails_cleanly_for_invalid_batch_child_workflow(monkeypatch) def test_run_completes_call_saved_workflow_with_batc...
34
1,579
InvokeAI
tests/app/services/test_workflow_call_compatibility.py
.py
from typing import Any from invokeai.app.services.shared.workflow_call_compatibility import ( WorkflowCallCompatibilityReason, get_workflow_call_compatibility, ) def _invocation_node(node_id: str, invocation_type: str, inputs: dict[str, Any]) -> dict[str, Any]: return { "id": node_id, "ty...
614
20,156
InvokeAI
tests/app/services/test_system_prompt_records.py
.py
"""Storage-layer tests for system_prompt_records. Covers the per-user scoping semantics added on top of the original CRUD: - get_many returns own + public for a user_id, all rows for None (admin) - update/delete with a non-owner user_id raises NotFound and leaves the row untouched - the migration-seeded defaults (user...
157
5,424
InvokeAI
tests/app/services/test_workflow_graph_builder.py
.py
import pytest from invokeai.app.services.shared.graph import Graph from invokeai.app.services.shared.workflow_graph_builder import ( UnsupportedWorkflowNodeError, build_graph_from_workflow, ) def _build_workflow_node( node_id: str, invocation_type: str, inputs: dict[str, object], *, is_in...
271
8,732
InvokeAI
tests/app/services/test_image_move_startup_safety.py
.py
from unittest.mock import MagicMock from invokeai.app.services.invocation_services import InvocationServices from invokeai.app.services.invoker import Invoker from invokeai.app.services.session_processor.session_processor_default import DefaultSessionProcessor def _services(**overrides): services = { "bo...
83
2,967
InvokeAI
tests/app/services/test_session_processor_shutdown.py
.py
from tests.app.services import workflow_call_test_utils as workflow_call_tests def test_run_node_propagates_keyboard_interrupt(monkeypatch) -> None: workflow_call_tests.test_run_node_propagates_keyboard_interrupt(monkeypatch) def test_run_node_does_not_swallow_sigint_in_subprocess() -> None: workflow_call_t...
14
570
InvokeAI
tests/app/services/workflow_call_test_utils.py
.py
from contextlib import contextmanager from threading import Event from types import SimpleNamespace from typing import Any import pytest from invokeai.app.invocations.baseinvocation import BaseInvocation, BaseInvocationOutput, invocation, invocation_output from invokeai.app.invocations.call_saved_workflow import Call...
2,999
112,991
InvokeAI
tests/app/services/test_sql_injection_protection.py
.py
import pytest from invokeai.app.services.board_records.board_records_common import ( BoardRecordNotFoundException, BoardRecordOrderBy, ) from invokeai.app.services.board_records.board_records_sqlite import SqliteBoardRecordStorage from invokeai.app.services.config.config_default import InvokeAIAppConfig from i...
65
2,147
InvokeAI
tests/app/services/test_workflow_call_batch.py
.py
from typing import Any import pytest from invokeai.app.services.session_processor.workflow_call_batch import ( build_child_workflow_session_results, build_child_workflow_sessions, ) from invokeai.app.services.session_queue.session_queue_common import TooManySessionsError from invokeai.app.services.shared.grap...
1,423
47,880
InvokeAI
tests/app/services/test_workflow_call_runtime.py
.py
from tests.app.services import workflow_call_test_utils as workflow_call_tests def test_run_node_enters_waiting_state_without_executing_child_inline(monkeypatch) -> None: workflow_call_tests.test_run_node_enters_waiting_state_without_executing_child_inline(monkeypatch) def test_run_persists_waiting_session_with...
154
7,363
InvokeAI
tests/app/services/test_session_processor_callbacks.py
.py
from contextlib import nullcontext from threading import Event from types import SimpleNamespace from unittest.mock import Mock import pytest from invokeai.app.services.session_processor.session_processor_default import DefaultSessionRunner from invokeai.app.services.shared.graph import CollectInvocation, Graph, Grap...
48
1,953
InvokeAI
tests/app/services/external_generation/test_startup.py
.py
from unittest.mock import MagicMock from invokeai.app.services.external_generation.startup import sync_configured_external_starter_models from invokeai.backend.model_manager.configs.external_api import ExternalApiModelConfig, ExternalModelCapabilities def _build_installed_model(source: str) -> ExternalApiModelConfig...
57
2,339
InvokeAI
tests/app/services/external_generation/test_external_provider_adapters.py
.py
import io import logging import pytest from PIL import Image from invokeai.app.services.config.config_default import InvokeAIAppConfig from invokeai.app.services.external_generation.errors import ExternalProviderRequestError from invokeai.app.services.external_generation.external_generation_common import ( Extern...
394
14,766
InvokeAI
tests/app/services/external_generation/test_external_generation_service.py
.py
import logging import pytest from PIL import Image from invokeai.app.services.config.config_default import InvokeAIAppConfig from invokeai.app.services.external_generation.errors import ( ExternalProviderCapabilityError, ExternalProviderNotConfiguredError, ExternalProviderNotFoundError, ) from invokeai.ap...
278
10,685
InvokeAI
tests/app/services/external_generation/test_alibabacloud_provider.py
.py
import io import logging from typing import Any, Iterator import pytest from PIL import Image from invokeai.app.services.config.config_default import InvokeAIAppConfig from invokeai.app.services.external_generation.errors import ExternalProviderRequestError from invokeai.app.services.external_generation.external_gene...
312
11,086
InvokeAI
tests/app/services/external_generation/test_seedream_provider.py
.py
import logging import pytest from PIL import Image from invokeai.app.services.config.config_default import InvokeAIAppConfig from invokeai.app.services.external_generation.errors import ( ExternalProviderCapabilityError, ExternalProviderRequestError, ) from invokeai.app.services.external_generation.external_g...
355
13,770
InvokeAI
tests/app/services/session_processor/test_encoder_offload.py
.py
"""Tests for DefaultSessionRunner._maybe_offload_to_idle_gpu (idle-GPU text-encoder offload). These exercise the re-pinning + borrow-lock logic without needing real CUDA: the session device is a thread-local set via TorchDevice, and the device pool only manipulates locks keyed by device string. """ import logging imp...
305
13,624
InvokeAI
tests/app/services/session_processor/test_session_runner_cloning.py
.py
"""Tests for per-worker session-runner cloning in multi-GPU mode. Each worker needs its own runner instance because start() stores the worker's cancel event on the runner. Cloning must preserve the SessionRunnerBase contract: a DefaultSessionRunner subclass must not be silently downgraded to a plain DefaultSessionRunn...
64
2,283
InvokeAI
tests/app/services/session_processor/test_session_processor_cancel_guard.py
.py
"""Tests for the post-dequeue cancellation guard that closes the multi-GPU cancel-loss race. A cancellation can mark a queue item terminal in the window between dequeue claiming it and the worker recording `queue_item` (so the status-changed handler can't set the worker's cancel_event). `_is_queue_item_terminal` is th...
265
11,227
InvokeAI
tests/app/services/image_files/test_image_files_disk.py
.py
import hashlib import platform import zlib from pathlib import Path from unittest.mock import MagicMock, patch import pytest from PIL import Image from invokeai.app.services.image_files.image_files_common import ImageFileSaveException from invokeai.app.services.image_files.image_files_disk import DiskImageFileStorage...
382
15,303
InvokeAI
tests/app/services/image_records/test_image_records_sqlite.py
.py
"""DB-backed tests for SqliteImageRecordStorage. Verifies that image_subfolder round-trips correctly through save(), get(), get_many(), and delete_intermediates() against a real (in-memory) SQLite database, and that get_many()/get_image_names() enforce per-user ownership isolation. """ import pytest from invokeai.ap...
354
13,912
InvokeAI
tests/app/services/videos/test_videos_default.py
.py
"""Tests for VideoService (videos_default.py). Covers the board-cascade delete contract (JPPhoto PR #9163 follow-up). The old implementation silently swallowed per-file delete errors and then deleted every record anyway, which orphaned the file on disk while reporting success. """ from unittest.mock import MagicMock ...
287
14,292
InvokeAI
tests/app/services/images/test_images_default.py
.py
"""Tests for ImageService (images_default.py). Covers subfolder forwarding for all strategies and the delete_images_on_board silent-failure contract (Points 2 & 3 from PR review). """ from pathlib import Path from unittest.mock import MagicMock, patch import pytest from PIL import Image from invokeai.app.services.c...
362
15,418
InvokeAI
tests/app/services/boards/test_boards_default.py
.py
from datetime import datetime from types import SimpleNamespace from unittest.mock import MagicMock from invokeai.app.services.board_records.board_records_common import BoardRecordOrderBy from invokeai.app.services.invoker import Invoker from invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirection d...
125
5,804
InvokeAI
tests/app/services/events/test_progress_event_device.py
.py
"""Tests for the device reported by InvocationProgressEvent. The UI labels progress with the GPU executing the session. The queue item's persisted `device` is the authority: the worker thread's session device is temporarily re-pinned to a borrowed idle GPU during offloaded encoder nodes, and reporting that would make ...
99
3,663
InvokeAI
tests/app/services/users/test_user_service.py
.py
"""Tests for user service.""" from logging import Logger import pytest from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase from invokeai.app.services.users.users_common import UserCreateRequest, UserUpdateRequest from invokeai.app.services.users.users_default import USER_LOOKUP_CHUNK_SIZE,...
310
9,564
InvokeAI
tests/app/services/users/test_token_service.py
.py
"""Tests for token service.""" from datetime import timedelta from invokeai.app.services.auth.token_service import TokenData, create_access_token, verify_token def test_create_access_token(): """Test creating an access token.""" data = TokenData(user_id="test-user", email="test@example.com", is_admin=False)...
44
1,374
InvokeAI
tests/app/services/users/test_password_utils.py
.py
"""Tests for password utilities.""" from invokeai.app.services.auth.password_utils import hash_password, validate_password_strength, verify_password def test_hash_password(): """Test password hashing.""" password = "TestPassword123" hashed = hash_password(password) assert hashed != password asse...
57
1,717
InvokeAI
tests/app/services/shared/test_invocation_context_images.py
.py
from unittest.mock import MagicMock import pytest from invokeai.app.services.board_records.board_records_common import BoardVisibility from invokeai.app.services.shared.invocation_context import ImagesInterface def _make_interface(visibility: BoardVisibility, owner_id: str = "owner") -> tuple[ImagesInterface, Magic...
96
3,379
InvokeAI
tests/app/services/shared/test_graph_execution_performance.py
.py
"""Manual graph-execution performance benchmarks. These tests are marked slow and are excluded from normal pytest and CI runs. Run this benchmark with: pytest -m slow -s tests/app/services/shared/test_graph_execution_performance.py """ from __future__ import annotations import gc import json import time import ...
181
7,426
InvokeAI
tests/app/services/shared/test_invocation_context_videos.py
.py
from pathlib import Path from unittest.mock import MagicMock import pytest from invokeai.app.services.board_records.board_records_common import BoardVisibility from invokeai.app.services.shared.invocation_context import VideosInterface def _make_interface(visibility: BoardVisibility, owner_id: str = "owner") -> tup...
68
2,614
InvokeAI
tests/app/services/shared/sqlite_migrator/test_migration_loader.py
.py
import importlib from logging import Logger from pathlib import Path import pytest from invokeai.app.services.shared.sqlite_migrator.migration_loader import ( MigrationBuildContext, MigrationLoaderError, build_migrations, ) def _write_package(tmp_path: Path, package_name: str, modules: dict[str, str]) -...
253
9,102
InvokeAI
tests/app/services/download/test_download_queue.py
.py
"""Test the queued download facility""" import re import time from contextlib import contextmanager from pathlib import Path from typing import Any, Generator, Optional from unittest.mock import MagicMock, patch import pytest from pydantic.networks import AnyHttpUrl from requests import Response from requests.session...
690
25,143
InvokeAI
tests/app/services/auth/test_performance.py
.py
"""Performance tests for multiuser authentication system. These tests measure the performance overhead of authentication and ensure the system performs acceptably under load. """ import time from concurrent.futures import ThreadPoolExecutor, as_completed from logging import Logger import pytest from invokeai.app.se...
475
16,626
InvokeAI
tests/app/services/auth/test_security.py
.py
"""Security tests for multiuser authentication system. This module tests various security aspects including: - SQL injection prevention - Authorization bypass attempts - Session security - Input validation """ import os from pathlib import Path from typing import Any import pytest from fastapi.testclient import Test...
460
17,792
InvokeAI
tests/app/services/auth/test_token_service.py
.py
"""Unit tests for JWT token service.""" import time from datetime import timedelta import pytest from invokeai.app.services.auth.token_service import TokenData, create_access_token, set_jwt_secret, verify_token @pytest.fixture(scope="module", autouse=True) def setup_jwt_secret(): """Set up JWT secret for all t...
372
12,865
InvokeAI
tests/app/services/auth/test_password_utils.py
.py
"""Unit tests for password utilities.""" from invokeai.app.services.auth.password_utils import ( get_password_strength, hash_password, validate_password_strength, verify_password, ) class TestPasswordHashing: """Tests for password hashing functionality.""" def test_hash_password_returns_diff...
330
12,655
InvokeAI
tests/app/services/auth/test_data_isolation.py
.py
"""Integration tests for multi-user data isolation. Tests to ensure users can only access their own data and cannot access other users' data unless explicitly shared. """ import os from pathlib import Path from typing import Any import pytest from fastapi.testclient import TestClient from invokeai.app.api.dependenc...
412
16,189
InvokeAI
tests/app/services/auth/conftest.py
.py
import pytest from invokeai.app.services.auth.token_service import set_jwt_secret @pytest.fixture(autouse=True) def setup_jwt_secret() -> None: set_jwt_secret("test-secret-key-for-unit-tests-only-do-not-use-in-production")
9
230
InvokeAI
tests/app/services/video_files/test_video_files_disk.py
.py
"""Tests for DiskVideoFileStorage (video_files_disk.py). Covers the save-failure cleanup contract (JPPhoto PR #9163 follow-up): ``save()`` moves the source MP4 into permanent storage *before* writing the thumbnail and sidecar, so a failure in either of those later steps used to leave the moved MP4 (and any partial art...
180
6,527