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/app/services/session_queue/test_session_queue_bulk_cancel_events.py
.py
"""Tests that bulk cancel/delete operations emit queue_items_canceled. A bulk cancel (e.g. cancel-all-except-current) updates rows in a single SQL statement and emits no per-item queue_item_status_changed events. Without a bulk event, other connected clients never learn that pending items left the queue — an owner's b...
223
9,690
InvokeAI
tests/app/services/session_queue/test_session_queue_dequeue.py
.py
"""Tests for session queue dequeue() ordering: FIFO and round-robin modes.""" import json import uuid from typing import Optional import pytest from pydantic_core import to_jsonable_python from invokeai.app.services.config.config_default import InvokeAIAppConfig from invokeai.app.services.invoker import Invoker from...
480
21,709
InvokeAI
tests/app/services/session_queue/test_session_queue_dequeue_concurrency.py
.py
"""Tests that concurrent dequeue() calls (multi-GPU session workers) never claim the same item twice.""" import threading import uuid import pytest from invokeai.app.services.invoker import Invoker from invokeai.app.services.session_queue.session_queue_sqlite import SqliteSessionQueue from invokeai.app.services.shar...
91
3,156
InvokeAI
tests/app/services/session_queue/test_session_queue_workflow_call_metadata.py
.py
"""Tests for workflow-call relationship metadata on session_queue items.""" import uuid import pytest from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocation from invokeai.app.services.events.events_common import QueueItemsRetriedEvent, QueueItemStatusChangedEvent from invokeai.app.servi...
1,365
49,144
InvokeAI
tests/app/services/session_queue/test_session_queue_status_sequence.py
.py
import uuid import pytest from invokeai.app.services.events.events_common import QueueItemStatusChangedEvent from invokeai.app.services.invoker import Invoker from invokeai.app.services.session_queue.session_queue_sqlite import SqliteSessionQueue from invokeai.app.services.shared.graph import Graph, GraphExecutionSta...
104
3,873
InvokeAI
tests/app/services/session_queue/test_session_queue_status_event_isolation.py
.py
"""Regression tests for the cross-user identifier leak in QueueItemStatusChangedEvent. When user A's queue item changes status while user B's item is currently in_progress, the embedded SessionQueueStatus inside the event must NOT expose B's item_id, session_id, or batch_id. The full event ships to user:{A.user_id} an...
299
13,323
InvokeAI
tests/app/services/session_queue/test_session_queue_status_user_scoping.py
.py
"""Regression tests for multiuser queue status / list scoping. The queue badge in multiuser mode shows "X/Y" where X is the requesting user's own pending+in_progress jobs and Y is the global total across all users. For this to work, get_queue_status must report GLOBAL aggregate counts and ADDITIONALLY return the reque...
146
6,426
InvokeAI
tests/app/services/session_queue/test_session_queue_workflow_call_retry.py
.py
"""Tests for workflow-call retry semantics in the session queue.""" from datetime import datetime import pytest from invokeai.app.services.events.events_common import QueueItemsRetriedEvent from invokeai.app.services.invoker import Invoker from invokeai.app.services.session_queue.session_queue_common import SessionQ...
134
4,888
InvokeAI
tests/app/services/session_queue/test_session_queue_multigpu_cancel.py
.py
"""Regression tests for multi-GPU bulk cancellation. With one session-processor worker per device, several queue items can be `in_progress` at the same time. The bulk-cancel APIs must cancel ALL matching in-progress items (each emitting a cancel event so its worker stops), not just the single `get_current()` item. See...
293
13,206
InvokeAI
tests/app/services/session_queue/test_session_queue_clear.py
.py
"""Tests for session queue clear() user_id scoping.""" import uuid import pytest from invokeai.app.services.events.events_common import QueueClearedEvent, QueueItemStatusChangedEvent from invokeai.app.services.invoker import Invoker from invokeai.app.services.session_queue.session_queue_sqlite import SqliteSessionQu...
192
7,901
InvokeAI
tests/app/services/model_records/test_model_records_sql.py
.py
""" Test the refactored model config classes. """ from hashlib import sha256 from typing import Any, Optional import pytest from pydantic import ValidationError from invokeai.app.services.config import InvokeAIAppConfig from invokeai.app.services.model_records import ( DuplicateModelException, ModelRecordOrd...
470
16,356
InvokeAI
tests/app/services/config/test_config_device.py
.py
"""Validation tests for the `device` config field. Note these construct the config rather than assigning to an existing instance: the model does not enable `validate_assignment`, so `config.device = ...` bypasses the pattern entirely. """ import pytest from pydantic import ValidationError from invokeai.app.services....
28
826
InvokeAI
tests/app/services/config/test_config_generation_devices.py
.py
"""Validation tests for the multi-GPU `generation_devices` config field.""" import pytest from pydantic import ValidationError from invokeai.app.services.config.config_default import InvokeAIAppConfig @pytest.mark.parametrize( "value", [ "auto", ["cuda:0"], ["cuda:0", "cuda:1"], ...
78
2,906
InvokeAI
tests/app/services/image_moves/test_image_moves_default.py
.py
import os import threading from pathlib import Path from shutil import copy2 from unittest.mock import MagicMock, patch import pytest from PIL import Image from invokeai.app.services.config.config_default import InvokeAIAppConfig from invokeai.app.services.image_files.image_files_disk import DiskImageFileStorage from...
784
31,453
InvokeAI
tests/app/services/gallery/test_gallery_default.py
.py
"""Regression tests for SqliteGalleryService multiuser isolation and date-based virtual boards. Covers JPPhoto's code-review findings (PR #9163): 1. The gallery /items/ and /items/names endpoints returned every user's items when ``board_id`` was omitted, because ``_build_half`` only applied a user filter for th...
520
22,629
InvokeAI
tests/app/services/model_load/test_model_load_device_routing.py
.py
"""Tests that ModelLoadService routes to the per-device cache for the calling thread (multi-GPU).""" import threading from collections.abc import Iterator import pytest import torch from invokeai.app.services.config.config_default import InvokeAIAppConfig, get_config from invokeai.app.services.model_load.model_load_...
97
3,027
InvokeAI
tests/app/services/model_load/test_load_api.py
.py
from pathlib import Path import pytest import torch from diffusers import AutoencoderTiny from invokeai.app.invocations.model import ModelIdentifierField from invokeai.app.services.invocation_services import InvocationServices from invokeai.app.services.model_manager import ModelManagerServiceBase from invokeai.app.s...
116
4,987
InvokeAI
tests/app/services/workflow_records/test_default_workflows_registry.py
.py
"""Verify the bundled Wan/video workflows agree with the invocation registry. The pre-existing default workflows (SD1.5/SDXL/FLUX...) carry stale node versions and even removed node types — the editor tolerates this with "node needs update" badges, so they are deliberately NOT checked here. The workflows this PR ships...
54
2,377
InvokeAI
tests/app/services/model_install/test_model_install.py
.py
""" Test the model installer """ import gc import platform import shutil import threading import time import uuid from pathlib import Path from types import SimpleNamespace from typing import Any, Dict import pytest from pydantic_core import Url from invokeai.app.services.config import InvokeAIAppConfig from invokea...
1,081
41,534
InvokeAI
tests/app/services/model_install/test_missing_models.py
.py
""" Tests for missing model detection (_scan_for_missing_models) and bulk deletion. """ import gc from pathlib import Path import pytest from invokeai.app.services.config import InvokeAIAppConfig from invokeai.app.services.model_install import ModelInstallServiceBase from invokeai.app.services.model_records import U...
221
8,765
InvokeAI
tests/app/services/model_install/test_orphan_scan.py
.py
"""The startup orphan scan must survive a model file it cannot register. `_register_orphaned_models` runs inside `ModelInstallService.start()`, which stores and re-raises anything that escapes it. Identification can now reject a file outright — a checkpoint recognised as a PiD decoder and found unusable, or anything a...
58
2,591
InvokeAI
tests/app/services/video_records/test_video_records_sqlite.py
.py
"""Regression tests for SqliteVideoRecordStorage multiuser isolation. Covers JPPhoto's code-review finding (PR #9163): when ``board_id`` was omitted from /v1/videos/ and /v1/videos/names, the SQL builder applied no user filter and a non-admin caller saw every user's videos. The fix added an ``elif user_id is not None ...
210
9,255
InvokeAI
tests/app/services/bulk_download/test_bulk_download.py
.py
import os from pathlib import Path from tempfile import TemporaryDirectory from typing import Any from zipfile import ZipFile import pytest from invokeai.app.services.board_records.board_records_common import BoardRecord, BoardRecordNotFoundException from invokeai.app.services.bulk_download.bulk_download_common impor...
399
14,814
InvokeAI
tests/app/api/test_sliding_window_token.py
.py
"""Tests for SlidingWindowTokenMiddleware and token refresh behavior.""" from datetime import timedelta from types import SimpleNamespace import pytest from fastapi import FastAPI, Request, Response from fastapi.testclient import TestClient from invokeai.app.services.auth.token_service import TokenData, create_acces...
313
12,976
InvokeAI
tests/app/api/test_video_upload_limits.py
.py
"""Tests for VideoUploadLimitASGIMiddleware (PR #9163 review fix). The upload route's MAX_UPLOAD_SIZE check runs only after FastAPI has parsed (and spooled) the entire multipart body, so oversized/chunked/concurrent requests could exhaust temp storage before rejection. The middleware bounds ingress before the parser r...
553
19,771
InvokeAI
tests/app/util/test_video_thumbnails.py
.py
"""Tests for the subprocess-bounded video decode helpers (PR #9163 review). The bug: ``probe_video`` / ``extract_video_frame`` decoded untrusted uploads in-process with no timeout, despite the module itself noting that cv2 has historically hung on some containers. A crafted MP4 that makes the imageio probe fail and th...
699
29,713
InvokeAI
tests/app/util/test_controlnet_utils.py
.py
import numpy as np import pytest from PIL import Image from invokeai.app.util.controlnet_utils import prepare_control_image from invokeai.backend.image_util.util import nms @pytest.mark.parametrize("num_channels", [1, 2, 3]) def test_prepare_control_image_num_channels(num_channels): """Test that the `num_channel...
51
1,765
InvokeAI
tests/app/util/test_dynamicprompts.py
.py
from __future__ import annotations import pytest from invokeai.app.util.dynamicprompts import find_missing_wildcards def test_find_missing_wildcards_detects_unknown_wildcard_in_variant() -> None: # Regression: `__random__` inside a variant is parsed as a wildcard reference. Left unchecked it # sends the com...
32
1,462
InvokeAI
tests/app/util/test_ssrf.py
.py
"""Unit tests for the download-URL SSRF guard.""" import http.server import ipaddress import logging import threading from typing import Any, Generator import pytest import requests from requests import Request from requests.models import PreparedRequest from requests.utils import select_proxy from invokeai.app.util...
347
13,894
InvokeAI
tests/app/util/test_custom_openapi.py
.py
from fastapi import FastAPI from pydantic import create_model from invokeai.app.invocations.baseinvocation import InvocationRegistry from invokeai.app.util.custom_openapi import get_openapi_func class _FakeOutput: pass class _InvocationB: __name__ = "InvocationB" @classmethod def model_json_schema...
62
1,943
InvokeAI
tests/app/util/test_step_callback.py
.py
"""Tests for diffusion step callback preview image generation.""" import torch from PIL import Image from invokeai.app.util.step_callback import ( QWEN_IMAGE_LATENT_RGB_BIAS, QWEN_IMAGE_LATENT_RGB_FACTORS, sample_to_lowres_estimated_image, ) class TestSampleToLowresEstimatedImage: """Test the latent...
120
5,082
InvokeAI
tests/app/util/test_video_encoding.py
.py
"""Regression tests for make_mp4_writer (PR #9163 review). The bug: the production encoders relied on imageio's default ``macro_block_size=16``, which makes ffmpeg silently *rescale* frames to the next multiple of 16 — a 1920x1080 upload trimmed by Frame Range from Video came back as 1920x1088 while the DTO recorded 1...
47
1,773
InvokeAI
tests/app/util/test_torch_cuda_allocator.py
.py
import pytest import torch from tests.dangerously_run_function_in_subprocess import dangerously_run_function_in_subprocess # These tests are a bit fiddly, because the depend on the import behaviour of torch. They use subprocesses to isolate # the import behaviour of torch, and then check that the function behaves as ...
128
5,056
InvokeAI
tests/app/invocations/test_anima_denoise_er_sde_dispatch.py
.py
"""Dispatch wiring and sigma-contract tests for Anima ER-SDE. Verifies that ANIMA_SCHEDULER_MAP['er_sde'] produces a correctly configured ERSDEScheduler, that set_timesteps accepts sigmas= (the contract Anima relies on to pass its pre-shifted schedule), and that the sigma state is set up as expected after set_timestep...
56
2,397
InvokeAI
tests/app/invocations/test_flux2_klein_model_loader.py
.py
"""Tests for Flux2KleinModelLoaderInvocation submodel-source resolution. Focus: a partial SDNQ FLUX.2 pipeline (format=sdnq_quantized whose submodels contains only the transformer) must NOT be treated as a self-contained source. Otherwise the invocation sets main_is_diffusers=True, skips the standalone VAE/Qwen3 requi...
69
3,008
InvokeAI
tests/app/invocations/test_wan_latents_to_video_encoding.py
.py
from unittest.mock import MagicMock import numpy as np import pytest import torch from invokeai.app.invocations.wan_latents_to_video import ( WanLatentsToVideoInvocation, _iter_decoded_frames, _validate_video_latent_batch, _write_video_frames, ) from invokeai.app.services.session_processor.session_pro...
83
2,619
InvokeAI
tests/app/invocations/test_ernie_image_model_loader.py
.py
"""Tests for the ERNIE-Image prompt-enhancer availability gate. `use_prompt_enhancer` defaults to true, so whatever this gate reports is the default experience. `GenericDiffusersLoader.get_hf_load_class` resolves each submodel's class from `model_index.json` and raises "the ... submodel is not available for this model...
96
4,220
InvokeAI
tests/app/invocations/test_video_primitive.py
.py
from unittest.mock import MagicMock, patch import pytest from invokeai.app.invocations.fields import VideoField from invokeai.app.invocations.primitives import VideoInvocation @pytest.mark.parametrize("decoded_count,expected", [(7, 7), (None, 8)]) def test_video_primitive_prefers_exact_decoder_frame_count(decoded_c...
20
827
InvokeAI
tests/app/invocations/test_cogview4_text_encoder.py
.py
from contextlib import contextmanager from types import SimpleNamespace from unittest.mock import MagicMock import torch from invokeai.app.invocations.cogview4_text_encoder import CogView4TextEncoderInvocation class FakeGlmModel(torch.nn.Module): def __init__(self): super().__init__() self.regis...
86
3,051
InvokeAI
tests/app/invocations/test_anima_text_encoder.py
.py
from contextlib import contextmanager, nullcontext from types import SimpleNamespace from unittest.mock import MagicMock import torch from invokeai.app.invocations.anima_text_encoder import AnimaTextEncoderInvocation class FakeQwen3Encoder(torch.nn.Module): """Mimics the Qwen3 0.6B encoder. Its `.device` p...
108
4,165
InvokeAI
tests/app/invocations/test_sd3_text_encoder.py
.py
from contextlib import contextmanager, nullcontext from types import SimpleNamespace from unittest.mock import MagicMock import torch from invokeai.app.invocations.sd3_text_encoder import Sd3TextEncoderInvocation from invokeai.backend.model_manager.taxonomy import ModelFormat class FakeSd3ClipTextEncoder(torch.nn.M...
167
6,521
InvokeAI
tests/app/invocations/test_krea2_denoise.py
.py
import math from contextlib import contextmanager, nullcontext from types import SimpleNamespace import pytest import torch from invokeai.app.invocations.fields import DenoiseMaskField, Krea2ConditioningField, LatentsField, TensorField from invokeai.app.invocations.krea2_denoise import KREA2_LATENT_CHANNELS, Krea2Den...
760
33,430
InvokeAI
tests/app/invocations/test_krea2_text_encoder.py
.py
from contextlib import contextmanager, nullcontext from types import SimpleNamespace import pytest import torch from invokeai.app.invocations.fields import TensorField from invokeai.app.invocations.krea2_text_encoder import Krea2TextEncoderInvocation from invokeai.app.invocations.model import LoRAField, ModelIdentifi...
348
13,341
InvokeAI
tests/app/invocations/test_ernie_image_prompt_enhancer.py
.py
"""`ernie_image_prompt_enhancer` exists to keep long, per-execution work *off* a borrowed idle GPU. It was split out of `ernie_image_text_encoder`, which is `idle_gpu_offloadable`: the offload holds the lent GPU's exclusive-use lock for the whole node, so a session dequeued onto that GPU blocks until it returns. An en...
132
5,974
InvokeAI
tests/app/invocations/test_latent_noise.py
.py
from unittest.mock import MagicMock import pytest import torch @pytest.mark.parametrize( ("noise_type", "width", "height", "expected_shape"), [ ("SD", 64, 64, (1, 4, 8, 8)), ("FLUX", 64, 64, (1, 16, 8, 8)), ("FLUX.2", 64, 64, (1, 32, 8, 8)), ("SD3", 64, 64, (1, 16, 8, 8)), ...
102
3,435
InvokeAI
tests/app/invocations/test_anima_denoise.py
.py
from types import SimpleNamespace import pytest import torch from invokeai.app.invocations.anima_denoise import ( ANIMA_LATENT_CHANNELS, ANIMA_LATENT_SCALE_FACTOR, ANIMA_SHIFT, AnimaDenoiseInvocation, inverse_loglinear_timestep_shift, loglinear_timestep_shift, ) from invokeai.backend.anima.ani...
210
8,879
InvokeAI
tests/app/invocations/test_krea2_model_loader.py
.py
from types import SimpleNamespace import pytest from invokeai.app.invocations.krea2_model_loader import Krea2ModelLoaderInvocation from invokeai.app.invocations.model import ModelIdentifierField from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType def _model(key: str, base: Base...
71
3,303
InvokeAI
tests/app/invocations/test_wan_working_memory.py
.py
"""Wan VAE invocations: working-memory estimation and cpu_only device handling.""" from unittest.mock import MagicMock, patch import PIL.Image import torch from diffusers.models.autoencoders import AutoencoderKLWan from invokeai.app.invocations.wan_image_to_latents import WanImageToLatentsInvocation from invokeai.ap...
320
14,114
InvokeAI
tests/app/invocations/test_is_optional.py
.py
from typing import Any, Literal, Optional, Union import pytest from pydantic import BaseModel class TestModel(BaseModel): foo: Literal["bar"] = "bar" @pytest.mark.parametrize( "input_type, expected", [ (str, False), (list[str], False), (list[dict[str, Any]], False), (lis...
47
1,267
InvokeAI
tests/app/invocations/test_flux2_klein_output_device.py
.py
"""Flux2KleinTextEncoderInvocation is idle_gpu_offloadable: it may run on a borrowed idle GPU whose device-pool lock is released the moment the node returns. Like the other offloadable encoders (flux_text_encoder, flux_redux), its saved conditioning must be detached and moved to the CPU — otherwise the embeddings stay ...
40
1,765
InvokeAI
tests/app/invocations/test_z_image_working_memory.py
.py
"""Test that Z-Image VAE invocations properly estimate and request working memory.""" from unittest.mock import MagicMock, patch import pytest import torch from diffusers.models.autoencoders.autoencoder_kl import AutoencoderKL from invokeai.app.invocations.z_image_image_to_latents import ZImageImageToLatentsInvocati...
143
6,340
InvokeAI
tests/app/invocations/test_flux2_model_loader_source_guards.py
.py
"""The FLUX.2 loaders' cross-variant guard must gate the *encoder* extraction path only. Klein and [dev] share the same 32-channel `AutoencoderKLFlux2` — the repo ships the Klein-sourced `flux2_vae` as a dependency of every [dev] GGUF starter model — so a cross-variant pipeline is a legitimate VAE source. In the *Klei...
306
12,075
InvokeAI
tests/app/invocations/test_external_image_generation.py
.py
from types import SimpleNamespace from unittest.mock import MagicMock import pytest from PIL import Image from invokeai.app.invocations.external_image_generation import OpenAIImageGenerationInvocation from invokeai.app.invocations.fields import ImageField from invokeai.app.invocations.model import ModelIdentifierFiel...
112
3,897
InvokeAI
tests/app/invocations/test_text_llm_with_preset.py
.py
"""Tests for TextLLMWithPresetInvocation. The model-loading and pipeline-run code paths are exercised by the existing TextLLMInvocation node. What is unique to TextLLMWithPresetInvocation is that the system prompt is fetched from system_prompt_records by id -- and that this lookup must enforce the same own/public/defa...
194
7,811
InvokeAI
tests/app/invocations/test_flux_denoise.py
.py
import pytest from invokeai.app.invocations.flux_denoise import FluxDenoiseInvocation TIMESTEPS = [1.0, 0.75, 0.5, 0.25, 0.0] @pytest.mark.parametrize( ["cfg_scale", "timesteps", "cfg_scale_start_step", "cfg_scale_end_step", "expected"], [ # Test scalar cfg_scale. (2.0, TIMESTEPS, 0, -1, [2....
63
2,432
InvokeAI
tests/app/invocations/test_save_image_to_file.py
.py
"""Tests for SaveImageToFileInvocation.""" from pathlib import Path from unittest.mock import MagicMock import pytest from PIL import Image from pydantic import ValidationError from invokeai.app.invocations.image import SaveImageToFileInvocation def _make_context(tmp_path: Path, pil_image: Image.Image, gallery_uui...
198
6,299
InvokeAI
tests/app/invocations/test_video_frame_extract_range.py
.py
"""Regression tests for ExtractVideoRangeInvocation streaming (PR #9163 review). The bug: the node collected every selected frame into a list before encoding, so the default ``start_frame=0, end_frame=-1`` materialized the whole source in RAM — and the upload API admits 1 GB compressed files whose decoded frames can r...
114
5,041
InvokeAI
tests/app/invocations/test_denoise_noise_inputs.py
.py
import inspect from types import SimpleNamespace from unittest.mock import MagicMock, patch import pytest import torch from invokeai.app.invocations.anima_denoise import AnimaDenoiseInvocation from invokeai.app.invocations.cogview4_denoise import CogView4DenoiseInvocation from invokeai.app.invocations.flux2_denoise i...
700
28,380
InvokeAI
tests/app/invocations/test_z_image_model_loader.py
.py
"""Tests for ZImageModelLoaderInvocation submodel-source resolution. Focus: a freshly installed SDNQ Z-Image pipeline (format=sdnq_quantized with submodels) is self-contained and must generate without the user manually selecting a VAE / Qwen3 component source. In that case the loader must fall back to the main model i...
154
7,211
InvokeAI
tests/app/invocations/test_image.py
.py
import importlib.util from pathlib import Path from types import SimpleNamespace from unittest.mock import MagicMock import numpy import torch from PIL import Image, ImageFilter from invokeai.app.invocations.image import ImageField, OklabUnsharpMaskInvocation, OklchImageHueAdjustmentInvocation from invokeai.app.invoc...
436
15,929
InvokeAI
tests/app/invocations/test_idle_offload_encoder_output_devices.py
.py
"""The Wan, Krea-2, Ideogram 4 and ERNIE-Image text encoders are idle_gpu_offloadable: each may run on a borrowed idle GPU whose device-pool lock is released the moment the node returns. Like the other offloadable encoders (see test_flux2_klein_output_device.py, test_flux_redux_output_device.py), their saved conditioni...
153
6,690
InvokeAI
tests/app/invocations/test_ernie_image_denoise.py
.py
"""Tests for `ErnieImageDenoiseInvocation`'s initial-latent handling. ERNIE denoises on the rectified-flow path, so the loop assumes its input already sits at the first sigma of the schedule. Both directions of that contract are easy to get silently wrong: - clean init latents passed through *unnoised* tell the model...
89
3,681
InvokeAI
tests/app/invocations/test_wan_denoise.py
.py
"""CPU-only integration tests for ``WanDenoiseInvocation``. These tests substitute a synthetic transformer (no weights) for the real ``WanTransformer3DModel`` so the denoise loop's shape-handling, scheduler integration, CFG branch, and step-callback wiring can be exercised on a CPU runner. End-to-end tests against rea...
1,337
51,920
InvokeAI
tests/app/invocations/test_qwen_image_text_encoder.py
.py
"""Tests for the Qwen Image text encoder prompt building and image resizing.""" from PIL import Image from invokeai.app.invocations.qwen_image_text_encoder import ( QwenImageTextEncoderInvocation, _build_prompt, ) class TestBuildPrompt: """Test the _build_prompt function for edit vs generate modes.""" ...
125
5,689
InvokeAI
tests/app/invocations/test_video_frame_extract.py
.py
"""Regression tests for VideoFrameExtractInvocation negative-index resolution. Covers JPPhoto's code-review finding (PR #9163): the old code computed ``n_frames = round(duration * fps)`` to resolve ``frame_index=-1``. For uploads with inexact metadata that can overshoot the decoded frame count, requesting the last fra...
49
1,990
InvokeAI
tests/app/invocations/test_pid_memory_optimization_wiring.py
.py
"""Every PiD node must forward `pid_memory_optimization` — to the decode *and* to the memory estimate. Two things go wrong silently here, so both are pinned structurally rather than per-node: 1. A new PiD node that forgets `pid_memory_optimization=` on its `PiDDecodeConfig` decodes unoptimized while the user belie...
83
3,871
InvokeAI
tests/app/invocations/test_wan_ti2v_ideal_dimensions.py
.py
"""Unit tests for WanTI2VIdealDimensionsInvocation. Mirrors ``test_wan_ideal_dimensions.py`` but for the TI2V-5B variant, which snaps to a multiple of 32 (16x Wan 2.2-VAE × 2x transformer patch) instead of 16. The node is a pure math transform — no context dependencies — so we can call ``invoke`` with ``None`` directl...
155
6,030
InvokeAI
tests/app/invocations/test_flux2_dev_output_device.py
.py
"""Flux2DevTextEncoderInvocation is idle_gpu_offloadable: it may run on a borrowed idle GPU whose device-pool lock is released the moment the node returns. Like the other offloadable encoders (flux_text_encoder, flux2_klein_text_encoder), its saved conditioning must be detached and moved to the CPU — otherwise the embe...
37
1,624
InvokeAI
tests/app/invocations/test_krea2_enhancers.py
.py
"""Tests for the optional Krea-2 conditioning enhancers (rebalance + seed variance). Both operate on the 4D ``prompt_embeds (B, seq, 12, hidden)`` conditioning between the text encoder and denoise. The load-bearing logic - the per-layer gain broadcast, the exact-count weight validation, and the seeded-noise determinis...
255
10,372
InvokeAI
tests/app/invocations/test_qwen_image_working_memory.py
.py
"""Test that Qwen Image VAE invocations properly estimate and request working memory.""" from contextlib import nullcontext from unittest.mock import MagicMock, patch import pytest import torch from diffusers.models.autoencoders.autoencoder_kl_qwenimage import AutoencoderKLQwenImage from invokeai.app.invocations.qwe...
181
8,325
InvokeAI
tests/app/invocations/test_wan_lora_loader.py
.py
"""Tests for ``WanLoRALoaderInvocation`` target resolution and routing.""" from unittest.mock import MagicMock import pytest from invokeai.app.invocations.model import LoRAField, ModelIdentifierField, WanTransformerField from invokeai.app.invocations.wan_lora_loader import ( WanLoRACollectionLoader, WanLoRAL...
463
20,099
InvokeAI
tests/app/invocations/test_wan_ideal_dimensions.py
.py
"""Unit tests for WanI2VIdealDimensionsInvocation. The node is a pure math transform — no context dependencies — so we can call ``invoke`` with ``None`` directly. """ import pytest from invokeai.app.invocations.wan_ideal_dimensions import ( WAN_TARGET_RESOLUTION_PX, WanI2VIdealDimensionsInvocation, ) def _...
145
5,499
InvokeAI
tests/app/invocations/test_qwen_image_denoise.py
.py
"""Tests for the Qwen Image denoise invocation.""" import pytest from invokeai.app.invocations.qwen_image_denoise import QwenImageDenoiseInvocation class TestPrepareCfgScale: """Test _prepare_cfg_scale utility method.""" def test_scalar_cfg_scale(self): inv = QwenImageDenoiseInvocation.model_constr...
198
8,658
InvokeAI
tests/app/invocations/test_qwen_image_model_loader.py
.py
"""Tests for the Qwen Image model loader invocation.""" from unittest.mock import MagicMock import pytest from invokeai.app.invocations.model import ModelIdentifierField from invokeai.app.invocations.qwen_image_model_loader import QwenImageModelLoaderInvocation from invokeai.backend.model_manager.taxonomy import Mod...
114
5,150
InvokeAI
tests/app/invocations/test_anima_vae.py
.py
"""Tests for the Anima VAE invocations: working-memory estimation, the tiled-decode decision, and the tiled retry on out-of-memory.""" import math from unittest.mock import MagicMock, patch import pytest import torch from diffusers.models.autoencoders import AutoencoderKLWan from invokeai.app.invocations.anima_image...
223
10,317
InvokeAI
tests/app/invocations/test_video_concat.py
.py
"""Regression tests for VideoConcatInvocation._iter_joined_frames. Covers two JPPhoto code-review findings (PR #9163): 1. ``fade_through_black`` claimed to emit ``transition_frames`` frames per boundary but used a symmetric ``tf // 2`` split, dropping one frame for odd ``tf``. The fix splits asymmetrically: ``t...
231
10,408
InvokeAI
tests/app/invocations/test_wan_latents_to_image.py
.py
"""Tests for ``WanLatentsToImageInvocation`` input validation (JPPhoto review 2026-07-21). The bug: the node accepted any 5D latent tensor. Multi-frame video latents ran the full multi-frame VAE decode (under a working-memory estimate that assumed one frame) and then died in an opaque einops rank error at the final re...
89
3,221
InvokeAI
tests/app/invocations/test_flux_redux_output_device.py
.py
"""FluxReduxInvocation is idle_gpu_offloadable: it may run on a borrowed idle GPU while its consumer (FLUX denoise) runs on the session's GPU. Like the other offloadable encoders, its saved conditioning must be moved to the CPU — otherwise the embeddings stay resident on the borrowed device and downstream concatenation...
34
1,472
InvokeAI
tests/app/invocations/test_wan_expert_swapper.py
.py
"""Tests for ``_ExpertSwapper``'s LoRA-context lifecycle. The swapper is responsible for entering and exiting both the ``model_on_device`` context and the ``LayerPatcher.apply_smart_model_patches`` context in the right order across an expert swap: enter HIGH: enter device(HIGH) -> enter lora(HIGH) swap: ...
655
24,396
InvokeAI
tests/app/invocations/test_flux_model_loader_self_contained.py
.py
"""The FLUX.1 model loader must accept a complete SDNQ pipeline on its own. `docs/.../sdnq-quantization.mdx` promises "one install pulls everything you need (transformer + encoders + VAE)", but the node required separate T5, CLIP and VAE identifiers regardless, forcing users to install duplicates of components the pip...
120
4,673
InvokeAI
tests/app/invocations/test_compel.py
.py
from contextlib import contextmanager, nullcontext from types import SimpleNamespace from unittest.mock import MagicMock import torch from invokeai.app.invocations.compel import SDXLPromptInvocationBase class FakeClipTextEncoder(torch.nn.Module): def __init__(self, effective_device: torch.device): super...
153
5,979
InvokeAI
tests/app/invocations/test_krea2_lora_loader.py
.py
from types import SimpleNamespace import pytest from invokeai.app.invocations.krea2_lora_loader import Krea2LoRACollectionLoader, Krea2LoRALoaderInvocation from invokeai.app.invocations.model import LoRAField, ModelIdentifierField, Qwen3VLEncoderField, TransformerField from invokeai.backend.model_manager.taxonomy imp...
146
5,682
InvokeAI
tests/app/invocations/test_call_saved_workflows.py
.py
from types import SimpleNamespace from unittest.mock import Mock import pytest from invokeai.app.services.users.users_common import UserDTO from invokeai.app.services.workflow_records.workflow_records_common import ( Workflow, WorkflowCategory, WorkflowMeta, WorkflowNotFoundError, WorkflowRecordDT...
422
14,892
InvokeAI
tests/app/invocations/test_flux_vae_decode.py
.py
"""Tests for the FLUX VAE decode path's handling of the diffusers ``AutoencoderKL`` config. ``shift_factor`` is optional on ``AutoencoderKL``. The FLUX VAE sets one, but a plain SD-style config leaves it ``None``, and the decode used to add it to the latents unconditionally. """ from contextlib import contextmanager ...
69
2,747
InvokeAI
tests/app/invocations/test_wan_model_loader.py
.py
from types import SimpleNamespace from unittest.mock import MagicMock import pytest from invokeai.app.invocations.model import ModelIdentifierField from invokeai.app.invocations.wan_model_loader import WanModelLoaderInvocation from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType, ...
415
15,293
InvokeAI
scripts/get_external_contributions.py
.py
import re from argparse import ArgumentParser, RawTextHelpFormatter from typing import Any import requests from attr import dataclass from tqdm import tqdm def get_author(commit: dict[str, Any]) -> str: """Gets the author of a commit. If the author is not present, the committer is used instead and an asteri...
123
4,564
InvokeAI
scripts/check_pins.py
.py
"""Check that pins.json is consistent with pyproject.toml. ``pins.json`` is not used anywhere in this repo — it is fetched (at the release tag) by the Invoke Launcher (https://github.com/invoke-ai/launcher), which uses its ``torchIndexUrl`` entries to pick the torch wheel index for legacy (pre-6.14.0) installs. Becaus...
365
17,247
InvokeAI
scripts/classify-model.py
.py
#!/bin/env python """Little command-line utility for probing a model on disk.""" import argparse from pathlib import Path from typing import get_args from invokeai.backend.model_hash.model_hash import HASHING_ALGORITHMS from invokeai.backend.model_manager import InvalidModelConfigException, ModelProbe from invokeai....
46
1,291
InvokeAI
scripts/generate_openapi_schema.py
.py
import json import os import sys def main(): # Change working directory to the repo root repo_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) os.chdir(repo_root) # When invoked as a script, sys.path[0] is this script's directory rather than the repo # root, so ``import invok...
28
951
InvokeAI
scripts/extract_sd_keys_and_shapes.py
.py
import argparse import json from safetensors.torch import load_file def extract_sd_keys_and_shapes(safetensors_file: str): sd = load_file(safetensors_file) keys_to_shapes = {k: v.shape for k, v in sd.items()} out_file = "keys_and_shapes.json" with open(out_file, "w") as f: json.dump(keys_to...
31
843
InvokeAI
scripts/check_aarch64_lock.py
.py
"""Assert that `uv.lock` gives linux/aarch64 an installable torch and torchvision. Nothing else in CI covers aarch64. Three separate mechanisms in `pyproject.toml` conspire to make torch resolve from PyPI there instead of from the PyTorch WHL indexes (which ship no aarch64 torchvision wheel): `tool.uv.environments`, t...
178
8,748
InvokeAI
scripts/generate_vae_linear_approximation.py
.py
"""A script to generate a linear approximation of the VAE decode operation. The resultant matrix can be used to quickly visualize intermediate states of the denoising process. """ import argparse from pathlib import Path import einops import torch import torchvision.transforms as T from diffusers import AutoencoderKL...
185
6,380
InvokeAI
scripts/remove_orphaned_models.py
.py
#!/usr/bin/env python """Script to remove orphaned model files from INVOKEAI_ROOT directory. Orphaned models are ones that appear in the INVOKEAI_ROOT/models directory, but which are not referenced in the database `models` table. """ import argparse import datetime import json import locale import os import shutil im...
465
17,679
InvokeAI
scripts/multigpu_ram_driver.py
.py
#!/usr/bin/env python """Driver to exercise the multi-GPU shared-RAM model cache under real, concurrent generations. It repeatedly enqueues N batches at once (so the multi-GPU session processor runs them in parallel across devices), polls the queue until each round drains, and samples the InvokeAI server process's RAM...
292
13,072
InvokeAI
scripts/invokeai-web.py
.py
#!/usr/bin/env python # Copyright (c) 2022 Kyle Schouviller (https://github.com/kyle0654) import logging import os from invokeai.app.run_app import run_app logging.getLogger("xformers").addFilter(lambda record: "A matching Triton is not available" not in record.getMessage()) def main(): # Change working direc...
21
473
InvokeAI
scripts/gallery_maintenance.py
.py
#!/usr/bin/env python3 """ gallery_maintenance.py Remove orphan images from the gallery directory. Remove orphan database entries for images that no longer exist in the gallery directory. Regenerate missing thumbnail images. """ from invokeai.backend.util.gallery_maintenance import main main()
13
298
InvokeAI
scripts/calibrate_qwen_vae_working_memory.py
.py
"""Calibrate the Qwen Image VAE working-memory estimate against measured peak CUDA/HIP memory. Background ---------- ``estimate_vae_working_memory_qwen_image`` models peak working memory as a linear function of spatial area:: working_memory = h * w * element_size * scaling_constant This script measures the *actu...
306
12,267
InvokeAI
scripts/allocate_vram.py
.py
import argparse import torch def display_vram_usage(): """Displays the total, allocated, and free VRAM on the current CUDA device.""" assert torch.cuda.is_available(), "CUDA is not available" device = torch.device("cuda") total_vram = torch.cuda.get_device_properties(device).total_memory alloca...
64
2,661
InvokeAI
scripts/generate_docs_json.py
.py
from __future__ import annotations import inspect import json import os import re from pathlib import Path from typing import Any, Literal, cast, get_args, get_origin, get_type_hints from pydantic.fields import FieldInfo from invokeai.app.services.config.config_default import InvokeAIAppConfig from invokeai.app.serv...
324
11,622
InvokeAI
scripts/check_classifiers.py
.py
import re import sys import urllib.request from pathlib import Path # This script checks the classifiers in a pyproject.toml file against the official Trove classifier list. # If the classifiers are invalid, PyPI will reject the package upload. # Step 1: Get pyproject.toml path from args if len(sys.argv) != 2: pr...
49
1,564