Blender add-on: glTF export checked against real Blender, atomic export, a render refusal that holds (#17)

This commit is contained in:
Eureka 2026-11-28 01:13:22 +00:00
commit 282d9eff7a
11 changed files with 904 additions and 81 deletions

View file

@ -3379,6 +3379,42 @@ mod tests {
Ok(())
}
#[test]
fn sync_once_writes_an_inactive_unity_object_as_hidden_in_blender() -> Result<()> {
let temp = tempfile::tempdir()?;
let unity_path = temp.path().join("unity.ccmp");
let blender_path = temp.path().join("blender.ccmp");
seed_component_property_stores(&unity_path, &blender_path, "active-state")?;
MirrorStore::open(&unity_path)?.put_messagepack_document(
"brokkr.unity.host_snapshot.v0",
"unity/host/current",
&json!({
"sceneObjects": [{
"objectId": "unity-cube",
"name": "Cube",
"path": "/Cube",
"activeSelf": false
}]
}),
)?;
let report = run_sync_once(&SyncArgs {
unity_cache: unity_path,
blender_cache: blender_path.clone(),
dry_run: false,
})?;
assert_eq!(report.blender_commands_written, 1, "{report:#?}");
let command = MirrorStore::open(&blender_path)?
.documents()?
.into_iter()
.find(|document| document.key.starts_with("blender/commands/"))
.expect("Brokkr should emit a Blender visibility command");
assert_eq!(command.value["action"], "setObjectVisibility");
assert_eq!(command.value["visible"], false);
Ok(())
}
#[test]
fn dry_run_counts_active_state_command_but_writes_none() -> Result<()> {
let temp = tempfile::tempdir()?;

View file

@ -216,6 +216,7 @@ All Blender writes use `brokkr.blender.command_intent.v0` and receive
- `selectObject`
- `assignMaterial`
- `importGltf`
- `exportGltf` (writes under the add-on preference Render Output Directory, never overwriting)
- `setCamera`
- `setLight`
- `setWorld`

View file

@ -88,7 +88,7 @@ class BrokkrPreferences(bpy.types.AddonPreferences):
name="Render Output Directory",
subtype="DIR_PATH",
default="",
description="renderStill may only write files inside this directory; empty disables renderStill",
description="renderStill and exportGltf may only write files inside this directory; empty disables both",
)
auto_capture: bpy.props.BoolProperty(

View file

@ -6,8 +6,12 @@ import json
import math
import os
import re
import shutil
import signal
import struct
import subprocess
import sys
import tempfile
import uuid
import zlib
from array import array
@ -16,6 +20,11 @@ from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any, Iterable
if os.name == "nt":
import msvcrt
else:
import fcntl
from . import node_actions as na
from . import scene_actions as sa
from .server_guard import BindRefused, SessionGuard, check_bind, guarded_server_class, is_loopback_host, stop_pending
@ -42,10 +51,14 @@ SYNC_RECEIPT_SCHEMA = "brokkr.sync.receipt.v0"
CREATABLE_OBJECT_TYPES = ("MESH", "LIGHT", "CAMERA", "EMPTY")
# Engines that draw through the GL stack. A headless Linux Blender without libEGL aborts the whole
# process inside bpy.ops.render.render for these (no receipt); CYCLES renders on the CPU.
# Engines that draw through the GL stack. A headless Blender with no usable GL device aborts the whole
# process inside bpy.ops.render.render for these (no receipt); CYCLES renders on the CPU. Whether it
# will is found by rendering one pixel in a child Blender (gl_render_failure), not by guessing at libraries.
GL_RENDER_ENGINES = ("BLENDER_WORKBENCH", "BLENDER_EEVEE", "BLENDER_EEVEE_NEXT")
GL_RUNTIME_LIBRARY = "libEGL.so.1"
GL_PROBE_TIMEOUT_SECONDS = 120
EXPORT_STAGE_PREFIX = ".brokkr-export-"
STAGE_LOCK = ".brokkr-lock"
STAGE_JOURNAL = ".brokkr-journal"
# Actions that only read the scene and so push no undo step.
READ_ACTIONS = ("look",)
@ -732,8 +745,9 @@ class BrokkrBlenderTarget:
raise sa.ActionRefused(
f"objectType {shown!r} cannot be created; allowed: {', '.join(CREATABLE_OBJECT_TYPES)}.")
mesh_type = command.get("meshType")
if object_type == "MESH" and mesh_type is not None and (
not isinstance(mesh_type, str) or mesh_type.upper() != "CUBE"):
if mesh_type is not None and object_type != "MESH":
raise sa.ActionRefused(f"meshType applies only to objectType MESH, not {object_type}.")
if mesh_type is not None and (not isinstance(mesh_type, str) or mesh_type.upper() != "CUBE"):
raise sa.ActionRefused(f"meshType {mesh_type!r} is not available; a MESH is a CUBE.")
name = command.get("name") or f"Brokkr {object_type.title()}"
location = _vector(command.get("location"), 3, (0.0, 0.0, 0.0))
@ -868,6 +882,8 @@ class BrokkrBlenderTarget:
name = command.get("filepath")
if not isinstance(name, str):
raise sa.ActionRefused("filepath must be a string.")
if self.output_dir:
_sweep_stale_stages(Path(self.output_dir).resolve())
path = sa.resolve_inside(self.output_dir, name, "output", new_file=True)
suffix = path.suffix.lower()
if suffix not in sa.GLTF_EXTENSIONS:
@ -892,30 +908,90 @@ class BrokkrBlenderTarget:
off_layer = [o.name for o in chosen if o.name not in context.view_layer.objects]
if off_layer:
raise sa.ActionRefused(f"Selection object is not in the active view layer: {off_layer[0]}")
binary = path.with_suffix(".bin")
if suffix == ".gltf" and os.path.lexists(binary):
raise sa.ActionRefused("output path already exists; output actions never overwrite: " + binary.name)
path.parent.mkdir(parents=True, exist_ok=True)
# Re-check after the folders exist and just before use (residual TOCTOU as in renderStill).
if sa.resolve_inside(self.output_dir, name, "output", new_file=True) != path:
raise sa.ActionRefused("Output path changed while it was being checked.")
# The selection is touched only when one was asked for, and only on view-layer objects.
objects = list(context.view_layer.objects.values()) if chosen else []
saved = [(obj, obj.select_get()) for obj in objects]
# The exporter writes into a fresh staging folder beside the target, never onto the output
# directory: it may also write a .bin and texture files whose names Brokkr does not choose. Only
# after it finishes does every file move into place, each refused if its name is taken, so no
# existing file is overwritten and a failed export leaves nothing behind (not even new folders).
made = []
for folder in (path.parent, *path.parent.parents):
if folder.exists() or folder == Path(self.output_dir).resolve():
break
made.append(folder)
stage = None
lock_fd = None
moved: list[tuple[Path, Path]] = []
new_dirs: list[Path] = []
try:
for obj in objects:
obj.select_set(obj in chosen)
result = self.bpy.ops.export_scene.gltf("EXEC_DEFAULT", False,
filepath=str(path), export_format="GLB" if suffix == ".glb" else "GLTF_SEPARATE",
use_selection=bool(chosen), **options)
finally:
for obj, state in saved:
if obj.name in self.bpy.data.objects:
obj.select_set(state)
if "FINISHED" not in result:
raise sa.ActionRefused(f"glTF export did not finish: {sorted(result)}")
if not path.is_file():
raise sa.ActionRefused("glTF export wrote no file.")
path.parent.mkdir(parents=True, exist_ok=True)
# Re-check after the folders exist and just before use (residual TOCTOU as in renderStill).
if sa.resolve_inside(self.output_dir, name, "output", new_file=True) != path:
raise sa.ActionRefused("Output path changed while it was being checked.")
stage, lock_fd = _open_stage(path.parent)
staged = stage / path.name
# The selection is touched only when one was asked for, and only on view-layer objects.
objects = list(context.view_layer.objects.values()) if chosen else []
saved = [(obj, obj.select_get()) for obj in objects]
try:
for obj in objects:
obj.select_set(obj in chosen)
result = self.bpy.ops.export_scene.gltf("EXEC_DEFAULT", False,
filepath=str(staged), export_format="GLB" if suffix == ".glb" else "GLTF_SEPARATE",
use_selection=bool(chosen), **options)
finally:
for obj, state in saved:
if obj.name in self.bpy.data.objects:
obj.select_set(state)
if "FINISHED" not in result:
raise sa.ActionRefused(f"glTF export did not finish: {sorted(result)}")
if not staged.is_file():
raise sa.ActionRefused("glTF export wrote no file.")
written = sorted(f.relative_to(stage) for f in stage.rglob("*") if f.is_file() and f != stage / STAGE_LOCK)
taken = [str(f) for f in written if os.path.lexists(path.parent / f)]
if taken:
raise sa.ActionRefused("output path already exists; output actions never overwrite: " + taken[0])
for relative in written:
target = path.parent / relative
for folder in (target.parent, *target.parent.parents):
if folder.exists() or folder == path.parent:
break
new_dirs.append(folder)
target.parent.mkdir(parents=True, exist_ok=True)
os.rename(stage / relative, target)
moved.append((stage / relative, target))
except BaseException as failure:
# A move that fails partway is rolled back: the target is the whole new export or untouched.
stuck = []
for source, target in reversed(moved):
try:
os.rename(target, source)
except OSError:
stuck.append(target)
if lock_fd is not None:
os.close(lock_fd)
if stage is not None and stuck:
# The rollback itself failed: keep the stage with a journal of the files left in the
# target. Its lock is released, so the next export's sweep removes them and the retry works.
(stage / STAGE_JOURNAL).write_text(
"\n".join(t.relative_to(path.parent).as_posix() for t in stuck), encoding="utf-8")
raise sa.ActionRefused(
"glTF export failed and could not be rolled back; files left in the output directory: "
+ ", ".join(t.relative_to(Path(self.output_dir).resolve()).as_posix() for t in stuck)
+ ". The next export removes them.") from failure
if stage is not None:
shutil.rmtree(stage, ignore_errors=True)
for folder in sorted(set(new_dirs), key=lambda f: -len(f.parts)):
try:
folder.rmdir()
except OSError:
pass
for folder in made: # deepest first: only the folders this call made, only if still empty
try:
folder.rmdir()
except OSError:
pass
raise
os.close(lock_fd)
shutil.rmtree(stage, ignore_errors=True)
return self._receipt(command, "accepted", f"Exported glTF to {path} ({path.stat().st_size} bytes).", "")
def _resolve_typed(self, command: dict[str, Any], object_type: str) -> Any:
@ -1024,11 +1100,11 @@ class BrokkrBlenderTarget:
except TypeError:
raise sa.ActionRefused(f"engine {engine} is not available in this Blender.") from None
if render.engine in GL_RENDER_ENGINES and getattr(getattr(self.bpy, "app", None), "background", False):
missing = missing_gl_library()
if missing:
failure = gl_render_failure(getattr(self.bpy.app, "binary_path", ""), render.engine)
if failure:
raise sa.ActionRefused(
f"engine {render.engine} needs {missing}, which this headless Blender cannot load "
"(rendering would abort the process); use engine CYCLES.")
f"engine {render.engine} cannot render in this headless Blender ({failure}); "
"rendering would abort the process; use engine CYCLES.")
if width is not None:
render.resolution_x = width
if height is not None:
@ -1515,17 +1591,123 @@ def _load_cultmesh(cultlib_py_src: str) -> tuple[Any, Any]:
return cultmesh_py, cultcache_py
@functools.lru_cache(maxsize=None)
def missing_gl_library() -> str | None:
"""The GL runtime library this host cannot load, or None. Probed once, on Linux only: on
Windows and macOS a failed GPU render is not a headless-EGL abort."""
if not sys.platform.startswith("linux"):
return None
GL_PROBE_SCRIPT = Path(__file__).with_name("gl_probe.py") # runs inside the child Blender
def _try_lock(fd: int) -> bool:
"""Take an exclusive lock on the file, without waiting; the OS drops it when the holder dies."""
try:
ctypes.CDLL(GL_RUNTIME_LIBRARY)
if os.name == "nt":
os.lseek(fd, 0, os.SEEK_SET)
msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
else:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError:
return GL_RUNTIME_LIBRARY
return None
return False
return True
def _open_stage(parent: Path) -> tuple[Path, int]:
"""A fresh staging folder in parent whose lock file this export holds, locked, until it closes the
descriptor or dies: a held lock is how a sweep knows the stage is live."""
stage = Path(tempfile.mkdtemp(prefix=EXPORT_STAGE_PREFIX, dir=parent))
fd = os.open(stage / STAGE_LOCK, os.O_RDWR | os.O_CREAT)
if not _try_lock(fd):
os.close(fd)
raise OSError(f"could not lock staging folder {stage}")
return stage, fd
def _sweep_stale_stages(top: Path) -> None:
"""Remove every staging folder under top whose lock can be taken: its export is over or its Blender
died. A held lock (an export running now, in any process) leaves the folder alone, and so does a
folder with no lock file yet (an export between creating it and locking it)."""
for root, dirs, _ in os.walk(top):
for name in [d for d in dirs if d.startswith(EXPORT_STAGE_PREFIX)]:
dirs.remove(name)
_sweep_stage(Path(root) / name)
def _sweep_stage(stage: Path) -> None:
try:
fd = os.open(stage / STAGE_LOCK, os.O_RDWR)
except OSError:
return
try:
if not _try_lock(fd):
return
journal = stage / STAGE_JOURNAL
if journal.is_file(): # a failed rollback's leftovers in the target
for line in journal.read_text(encoding="utf-8").splitlines():
relative = Path(line)
if not line or relative.is_absolute() or ".." in relative.parts:
continue
target = stage.parent / relative
if target.is_file() and not target.is_symlink():
target.unlink(missing_ok=True)
for folder in target.parents:
if folder == stage.parent:
break
try:
folder.rmdir()
except OSError:
break
finally:
os.close(fd)
shutil.rmtree(stage, ignore_errors=True)
def _kill_tree(process: "subprocess.Popen[str]") -> None:
"""Kill process and everything it started, so none keeps its output pipe open."""
if os.name == "nt":
subprocess.run(["taskkill", "/F", "/T", "/PID", str(process.pid)], capture_output=True, check=False)
else:
try:
os.killpg(process.pid, signal.SIGKILL)
except OSError:
pass
process.kill()
_GL_PROBES: dict[tuple[str, str], str | None] = {}
def gl_render_failure(binary: str, engine: str) -> str | None:
"""Why a headless render with this engine would not survive on this host, or None when it does.
Renders one pixel in a child process of the same Blender binary: the render aborts the process
it runs in, so only a child can find out. A definite outcome (it rendered, or it exited without
finishing) is cached per binary and engine for the life of the process; a hang, an unstartable
binary or an unknown binary is reported but not cached, so the next render probes again."""
if not binary or not os.path.isfile(binary):
return "the Blender binary is unknown, so rendering could not be probed"
if (binary, engine) in _GL_PROBES:
return _GL_PROBES[(binary, engine)]
command = [binary, "--background", "--factory-startup", "--python-exit-code", "1",
"--python", str(GL_PROBE_SCRIPT), "--", engine]
group = {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP} if os.name == "nt" else {"start_new_session": True}
try:
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, **group)
except OSError as exc:
return f"the one-pixel test render could not start: {exc}"
try:
stdout, _ = process.communicate(timeout=GL_PROBE_TIMEOUT_SECONDS)
except subprocess.TimeoutExpired:
_kill_tree(process)
try:
process.communicate(timeout=10)
except subprocess.TimeoutExpired:
pass
return f"a one-pixel test render did not finish in {GL_PROBE_TIMEOUT_SECONDS} s"
if process.returncode == 0 and "BROKKR_GL_PROBE_OK" in stdout:
outcome = None
else:
outcome = f"a one-pixel test render exited with status {process.returncode}"
_GL_PROBES[(binary, engine)] = outcome
return outcome
gl_render_failure.cache_clear = _GL_PROBES.clear
def _parse_time(value: Any) -> datetime | None:

View file

@ -0,0 +1,15 @@
"""Run inside a child Blender by blender_target.gl_render_failure: render one pixel with the engine named
after `--`, and print the completion marker only if the render returned."""
import sys
import bpy
bpy.ops.wm.read_factory_settings(use_empty=True)
scene = bpy.context.scene
scene.render.engine = sys.argv[-1]
scene.render.resolution_x = scene.render.resolution_y = 1
camera = bpy.data.objects.new("probe", bpy.data.cameras.new("probe"))
scene.collection.objects.link(camera)
scene.camera = camera
bpy.ops.render.render(write_still=False)
print("BROKKR_GL_PROBE_OK")

View file

@ -184,19 +184,22 @@ gets a `failed` receipt whose message names the rule):
`name`, `location`. Any other `objectType` (for example `TEXT` or `CURVE`) is refused with
the allowed set named. A `MESH` is a cube (`size`); a `meshType` other than `CUBE`
(case-insensitive, no surrounding whitespace) is refused rather than ignored.
`meshType` is checked only when `objectType` is `MESH`; an explicit `objectType: null` is refused.
`meshType` on any other `objectType` is refused too; an explicit `objectType: null` is refused.
- `importGltf`: `filepath`, `.gltf` or `.glb`, relative to the add-on preference
`Import Directory` (absolute paths, `..` and symlinks that resolve outside it are
refused). Empty `Import Directory` disables the action. Needs Blender's glTF add-on.
- `exportGltf`: `filepath`, `.glb` (binary) or `.gltf` (separate `.bin`), relative to the
add-on preference `Render Output Directory` (the renderStill rules: no `..`, no links, and an
existing name, or an existing `.bin` beside a `.gltf`, is refused; there is no overwrite).
existing name is refused; there is no overwrite).
Optional `extras` (custom properties become node `extras`), `yUp`, `applyModifiers`
(each true by default, must be a boolean) and `selection` (a non-empty list of object
names; any name not found, or not in the active view layer, refuses the export; the
selection is touched only when one is given, and restored afterwards). Not checked: texture
files a `.gltf` export writes beside it (only the `.bin` is), and a link or swap made between the
check and the write (the same residual as renderStill).
selection is touched only when one is given, and restored afterwards). The exporter writes into a
staging folder beside the target and Brokkr then moves each file into place (the `.glb`, or the `.gltf`
with its `.bin` and texture files), refusing the whole export, naming the file, if any of those names is
taken: nothing existing is overwritten. A refused or failed export leaves no file and no new folder, so
the same name can be retried. Each export holds an OS lock on its staging folder; the next export removes any `.brokkr-export-*` folder under the output directory whose lock is free (its Blender died), and a rollback that itself fails is refused naming the files left, which that same sweep removes. Not checked: a link or swap made between the check and the move (the
same residual as renderStill).
The receipt message carries the written path and byte size. Needs Blender's glTF add-on.
- `setCamera`: `targetObjectName` (a camera object); optional `lens` (mm),
`cameraType` (`PERSP`, `ORTHO`, `PANO`), `panoramaType` (for example
@ -223,10 +226,12 @@ gets a `failed` receipt whose message names the rule):
camera, file path and format are restored after the render. The render blocks
Blender's UI until it finishes. In a background (`-b`) Blender on Linux, the GL
engines `BLENDER_WORKBENCH`, `BLENDER_EEVEE` and `BLENDER_EEVEE_NEXT` are refused
with a `failed` receipt when `libEGL.so.1` cannot be loaded (probed once and cached for the life of the process), because
rendering would abort the whole process with no receipt; `CYCLES` renders on the
CPU. The check applies to the scene's engine when `engine` is omitted. No such
check runs on Windows or macOS.
with a `failed` receipt when a one-pixel test render of that engine does not finish in a child
process of the same Blender binary (it aborts, hangs past 120 s, or the binary is unknown). The
probe runs once per engine and is cached for the life of the process, so the first GL render
after startup waits for it. Rendering would otherwise abort the whole process with no receipt;
`CYCLES` renders on the CPU. The check applies to the scene's engine when `engine` is omitted.
A foreground Blender is not probed.
- `look`: no fields. Captures the 3D view she is looking at (the largest 3D view across the windows, its
main region) to `<Render Output Directory>/look/<commandId>.png` and puts the absolute path in the receipt's
@ -254,7 +259,9 @@ gets a `failed` receipt whose message names the rule):
The scene actions were run against Blender 5.2.3 LTS headless with
`surfaces/blender/tests/live/headless_smoke.py` (usage in its docstring). One real
failure it found: Blender's `engine` enum is dynamic, so `bl_rna` lists only
`BLENDER_EEVEE`; `renderStill` now asks Blender by assignment instead.
`BLENDER_EEVEE`; `renderStill` now asks Blender by assignment instead. `tests/live/export_gltf.py` and
`tests/live/refusals.py` (Blender 5.3.0 headless, usage in their docstrings) run `exportGltf` against the
real exporter and the render probe and `meshType` refusal against real bpy.
### Path rules and the residual race

View file

@ -0,0 +1,102 @@
"""Live proof of exportGltf on real bpy: the option names exist on the real exporter, extras reach the
file, selection filters, .gltf writes its .bin and textures without overwriting, a refused or failed
export leaves nothing behind.
BROKKR_ADDON=<path to surfaces/blender/brokkr_bridge> \
blender -b --factory-startup --python export_gltf.py -- result.json
Exit status is non-zero if any check fails.
"""
import bpy, sys, os, json, types, tempfile
from pathlib import Path
ADDON = Path(os.environ["BROKKR_ADDON"]).resolve()
pkg = types.ModuleType("brokkr_bridge"); pkg.__path__ = [str(ADDON)]
sys.modules["brokkr_bridge"] = pkg
from brokkr_bridge import blender_target as bt
out = sys.argv[sys.argv.index("--") + 1] if "--" in sys.argv else "export_gltf_result.json"
R = {"blender": bpy.app.version_string, "checks": []}
def check(name, ok, detail=None):
R["checks"].append({"name": name, "ok": bool(ok), "detail": detail})
print("CHECK", "ok " if ok else "FAIL", name, detail if not ok else "", flush=True)
# Every exporter keyword the add-on passes must be a property of the real operator.
props = {p.identifier for p in bpy.ops.export_scene.gltf.get_rna_type().properties}
passed = {"filepath", "export_format", "use_selection", "export_extras", "export_yup", "export_apply"}
check("exporter has every option the add-on passes", passed <= props, sorted(passed - props))
work = Path(tempfile.mkdtemp(prefix="brokkr-export-live-"))
bpy.ops.wm.read_factory_settings(use_empty=True)
t = bt.BrokkrBlenderTarget(bpy)
t.configure_action_dirs("", str(work))
bpy.ops.mesh.primitive_cube_add(); cube = bpy.context.active_object; cube.name = "Cube"; cube["brokkr_tag"] = "hello"
bpy.ops.mesh.primitive_uv_sphere_add(location=(3, 0, 0)); sphere = bpy.context.active_object; sphere.name = "Sphere"
image = bpy.data.images.new("brokkr_tex", 4, 4)
scratch = Path(tempfile.mkdtemp(prefix="brokkr-export-src-"))
image.filepath_raw = str(scratch / "brokkr_tex_src.png"); image.file_format = "PNG"; image.save()
mat = bpy.data.materials.new("Textured"); mat.use_nodes = True
node = mat.node_tree.nodes.new("ShaderNodeTexImage"); node.image = image
mat.node_tree.links.new(node.outputs["Color"], mat.node_tree.nodes["Principled BSDF"].inputs["Base Color"])
cube.data.materials.append(mat)
N = [0]
def act(**cmd):
N[0] += 1; cmd.setdefault("commandId", "c%d" % N[0]); cmd["action"] = "exportGltf"
return t.run_intent(bpy.context, dict(cmd, requestedBy="test/driver"))
def listing():
return sorted(str(p.relative_to(work)).replace("\\", "/") for p in work.rglob("*"))
r = act(filepath="all.glb")
check("glb accepted", r["status"] == "accepted", r["message"])
check("glb written, no staging folder", listing() == ["all.glb"], listing())
glb = (work / "all.glb").read_bytes()
check("glb carries extras", b"brokkr_tag" in glb and b"hello" in glb)
r = act(filepath="noextras.glb", extras=False)
check("extras=false leaves them out", b"brokkr_tag" not in (work / "noextras.glb").read_bytes(), r["message"])
cube.select_set(True); sphere.select_set(False)
r = act(filepath="only.glb", selection=["Sphere"])
data = (work / "only.glb").read_bytes()
check("selection exports only the sphere", b"Sphere" in data and b"Cube" not in data, r["message"])
check("selection restored", cube.select_get() and not sphere.select_get(), (cube.select_get(), sphere.select_get()))
r = act(filepath="sep/s.gltf")
check("gltf accepted", r["status"] == "accepted", r["message"])
files = listing()
check("gltf writes its bin and the texture beside it", "sep/s.gltf" in files and "sep/s.bin" in files and any(f.startswith("sep/brokkr_tex") for f in files), files)
before = {f: (work / f).read_bytes() for f in listing() if (work / f).is_file()}
texture = next(f for f in files if f.startswith("sep/brokkr_tex"))
(work / texture).write_bytes(b"precious")
r = act(filepath="sep/s2.gltf")
check("a taken texture name refuses", r["status"] == "failed" and Path(texture).name in r["message"], r["message"])
check("the taken texture is untouched", (work / texture).read_bytes() == b"precious")
check("the refused export leaves nothing", not any(f.startswith("sep/s2") for f in listing()) and not any(".brokkr-export" in f for f in listing()), listing())
r = act(filepath="fresh/deep/x.glb", selection=["Nope"])
check("refused selection makes no folder", r["status"] == "failed" and not (work / "fresh").exists(), r["message"])
orig = bpy.ops.export_scene.gltf
bt_target = t
class Boom:
def __call__(self, *a, **k):
Path(k["filepath"]).write_bytes(b"partial"); raise RuntimeError("died midway")
def get_rna_type(self): return orig.get_rna_type()
import types as _t
t.bpy = _t.SimpleNamespace(**{k: getattr(bpy, k) for k in ("data", "app", "path", "context")})
t.bpy.ops = _t.SimpleNamespace(export_scene=_t.SimpleNamespace(gltf=Boom()), import_scene=bpy.ops.import_scene, render=bpy.ops.render)
r = act(filepath="fresh/deep/x.glb")
check("a failing exporter is a failed receipt", r["status"] == "failed", r["message"])
check("and leaves no partial file or new folder", not (work / "fresh").exists(), listing())
t.bpy = bpy
r = act(filepath="fresh/deep/x.glb")
check("the same name then exports", r["status"] == "accepted" and (work / "fresh" / "deep" / "x.glb").is_file(), r["message"])
import shutil
shutil.rmtree(work, ignore_errors=True); shutil.rmtree(scratch, ignore_errors=True)
json.dump(R, open(out, "w"), indent=1)
sys.exit(0 if all(c["ok"] for c in R["checks"]) else 1)

View file

@ -0,0 +1,114 @@
{
"blender": "5.3.0",
"checks": [
{
"name": "exporter has every option the add-on passes",
"ok": true,
"detail": []
},
{
"name": "glb accepted",
"ok": true,
"detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-aa0ee157\\all.glb (72752 bytes)."
},
{
"name": "glb written, no staging folder",
"ok": true,
"detail": [
"all.glb"
]
},
{
"name": "glb carries extras",
"ok": true,
"detail": null
},
{
"name": "extras=false leaves them out",
"ok": true,
"detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-aa0ee157\\noextras.glb (72720 bytes)."
},
{
"name": "selection exports only the sphere",
"ok": true,
"detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-aa0ee157\\only.glb (70240 bytes)."
},
{
"name": "selection restored",
"ok": true,
"detail": [
true,
false
]
},
{
"name": "gltf accepted",
"ok": true,
"detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-aa0ee157\\sep\\s.gltf (2840 bytes)."
},
{
"name": "gltf writes its bin and the texture beside it",
"ok": true,
"detail": [
"all.glb",
"noextras.glb",
"only.glb",
"sep",
"sep/brokkr_tex_src.png",
"sep/s.bin",
"sep/s.gltf"
]
},
{
"name": "a taken texture name refuses",
"ok": true,
"detail": "output path already exists; output actions never overwrite: brokkr_tex_src.png"
},
{
"name": "the taken texture is untouched",
"ok": true,
"detail": null
},
{
"name": "the refused export leaves nothing",
"ok": true,
"detail": [
"all.glb",
"noextras.glb",
"only.glb",
"sep",
"sep/brokkr_tex_src.png",
"sep/s.bin",
"sep/s.gltf"
]
},
{
"name": "refused selection makes no folder",
"ok": true,
"detail": "Selection object was not found: Nope"
},
{
"name": "a failing exporter is a failed receipt",
"ok": true,
"detail": "died midway"
},
{
"name": "and leaves no partial file or new folder",
"ok": true,
"detail": [
"all.glb",
"noextras.glb",
"only.glb",
"sep",
"sep/brokkr_tex_src.png",
"sep/s.bin",
"sep/s.gltf"
]
},
{
"name": "the same name then exports",
"ok": true,
"detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-aa0ee157\\fresh\\deep\\x.glb (72752 bytes)."
}
]
}

View file

@ -0,0 +1,74 @@
"""Live proof of the renderStill GL refusal and the createObject meshType refusal on real bpy.
BROKKR_ADDON=<path to surfaces/blender/brokkr_bridge> \
blender -b --factory-startup --python refusals.py -- result.json
The pass outcome runs a real child Blender (a one-pixel Workbench and EEVEE render) and then a real
renderStill. The abort outcome needs a host whose headless GL fails (a container with libEGL and no
GPU), which this script cannot make: it runs the real probe against a stand-in binary that aborts, and
on such a host the first two checks fail instead of passing. Exit status is non-zero if any check fails.
"""
import bpy, sys, os, json, types, tempfile, stat, shutil
from pathlib import Path
ADDON = Path(os.environ["BROKKR_ADDON"]).resolve()
pkg = types.ModuleType("brokkr_bridge"); pkg.__path__ = [str(ADDON)]
sys.modules["brokkr_bridge"] = pkg
from brokkr_bridge import blender_target as bt
out = sys.argv[sys.argv.index("--") + 1] if "--" in sys.argv else "refusals_result.json"
R = {"blender": bpy.app.version_string, "background": bpy.app.background, "platform": sys.platform, "checks": []}
def check(name, ok, detail=None):
R["checks"].append({"name": name, "ok": bool(ok), "detail": detail})
print("CHECK", "ok " if ok else "FAIL", name, detail if not ok else "", flush=True)
work = Path(tempfile.mkdtemp(prefix="brokkr-refusals-live-"))
bpy.ops.wm.read_factory_settings(use_empty=True)
t = bt.BrokkrBlenderTarget(bpy)
t.configure_action_dirs("", str(work))
N = [0]
def act(action, **cmd):
N[0] += 1; cmd.setdefault("commandId", "c%d" % N[0]); cmd["action"] = action
return t.run_intent(bpy.context, dict(cmd, requestedBy="test/driver"))
for engine in ("BLENDER_WORKBENCH", "BLENDER_EEVEE_NEXT", "BLENDER_EEVEE"):
try: # the engine enum is dynamic: ask by assignment
bpy.context.scene.render.engine = engine
except TypeError:
continue
if True:
failure = bt.gl_render_failure(bpy.app.binary_path, engine)
check("real one-pixel %s render survives in a child Blender" % engine, failure is None, failure)
bpy.ops.object.camera_add(); bpy.context.scene.camera = bpy.context.active_object
r = act("renderStill", outputPath="shot.png", engine="BLENDER_WORKBENCH", resolutionX=8, resolutionY=8)
check("renderStill Workbench headless renders after the probe", r["status"] == "accepted" and (work / "shot.png").is_file(), r["message"])
stand_in = work / ("abort.cmd" if os.name == "nt" else "abort.sh")
stand_in.write_text("@echo off\r\nexit /b 3\r\n" if os.name == "nt" else "#!/bin/sh\nkill -ABRT $$\n")
stand_in.chmod(stand_in.stat().st_mode | stat.S_IEXEC)
failure = bt.gl_render_failure(str(stand_in), "BLENDER_WORKBENCH")
check("a child that aborts is a refusal reason", failure is not None and "exited with status" in failure, failure)
t.bpy = types.SimpleNamespace(data=bpy.data, path=bpy.path, context=bpy.context, ops=bpy.ops,
app=types.SimpleNamespace(background=True, binary_path=str(stand_in)))
bpy.context.scene.render.engine = "BLENDER_WORKBENCH"
r = act("renderStill", outputPath="no.png", engine="BLENDER_WORKBENCH")
check("renderStill refuses and renders nothing", r["status"] == "failed" and "cannot render" in r["message"] and not (work / "no.png").exists(), r["message"])
t.bpy = bpy
for kind in ("LIGHT", "EMPTY", "CAMERA"):
r = act("createObject", objectType=kind, meshType="CYLINDER")
check("meshType on %s is refused" % kind, r["status"] == "failed" and "MESH" in r["message"], r["message"])
check("and nothing was created for them", len([o for o in bpy.data.objects if o.type in ("LIGHT", "EMPTY")]) == 0)
r = act("createObject", objectType="MESH", meshType="cube")
check("meshType CUBE on a MESH still works", r["status"] == "accepted", r["message"])
shutil.rmtree(work, ignore_errors=True)
json.dump(R, open(out, "w"), indent=1)
sys.exit(0 if all(c["ok"] for c in R["checks"]) else 1)

View file

@ -0,0 +1,57 @@
{
"blender": "5.3.0",
"background": true,
"platform": "win32",
"checks": [
{
"name": "real one-pixel BLENDER_WORKBENCH render survives in a child Blender",
"ok": true,
"detail": null
},
{
"name": "real one-pixel BLENDER_EEVEE render survives in a child Blender",
"ok": true,
"detail": null
},
{
"name": "renderStill Workbench headless renders after the probe",
"ok": true,
"detail": "Rendered still to shot.png."
},
{
"name": "a child that aborts is a refusal reason",
"ok": true,
"detail": "a one-pixel test render exited with status 3"
},
{
"name": "renderStill refuses and renders nothing",
"ok": true,
"detail": "engine BLENDER_WORKBENCH cannot render in this headless Blender (a one-pixel test render exited with status 3); rendering would abort the process; use engine CYCLES."
},
{
"name": "meshType on LIGHT is refused",
"ok": true,
"detail": "meshType applies only to objectType MESH, not LIGHT."
},
{
"name": "meshType on EMPTY is refused",
"ok": true,
"detail": "meshType applies only to objectType MESH, not EMPTY."
},
{
"name": "meshType on CAMERA is refused",
"ok": true,
"detail": "meshType applies only to objectType MESH, not CAMERA."
},
{
"name": "and nothing was created for them",
"ok": true,
"detail": null
},
{
"name": "meshType CUBE on a MESH still works",
"ok": true,
"detail": "Blender object created."
}
]
}

View file

@ -108,6 +108,8 @@ class FakeBpy:
self.exported = []
self.export_result = {"FINISHED"}
self.export_writes = True
self.export_siblings = [] # extra files the exporter writes beside the target (textures)
self.export_raises_after_writing = None
for o in self.data.objects.values():
o.selected = o is self.mesh
o.select_get = (lambda o=o: o.selected)
@ -143,8 +145,15 @@ class FakeBpy:
assert (mode, undo) == ("EXEC_DEFAULT", False)
kwargs["selected_at_call"] = sorted(o.name for o in self.data.objects.values() if o.selected)
self.exported.append(kwargs)
target = Path(kwargs["filepath"])
if self.export_writes:
Path(kwargs["filepath"]).write_bytes(b"x" * 10)
target.write_bytes(b"x" * 10)
if target.suffix == ".gltf":
target.with_suffix(".bin").write_bytes(b"b" * 4)
for name in self.export_siblings:
(target.parent / name).write_bytes(b"t" * 3)
if self.export_raises_after_writing:
raise RuntimeError(self.export_raises_after_writing)
return self.export_result
def render_still(self, mode, undo, write_still):
@ -267,8 +276,11 @@ class ActionTests(unittest.TestCase):
self.assertIn(path, receipt["message"])
self.assertIn("10 bytes", receipt["message"])
call = self.bpy.exported[0]
self.assertEqual({k: v for k, v in call.items() if k != "selected_at_call"},
{"filepath": path, "export_format": "GLB", "export_extras": True,
staged = Path(call["filepath"]) # the exporter writes into a staging folder, then Brokkr moves the file
self.assertEqual((staged.name, staged.parent.parent, staged.parent.name.startswith(".brokkr-export-")),
("a.glb", self.root / "out" / "ship", True))
self.assertEqual({k: v for k, v in call.items() if k not in ("selected_at_call", "filepath")},
{"export_format": "GLB", "export_extras": True,
"export_yup": True, "export_apply": True, "use_selection": False})
def test_export_gltf_suffix_is_separate_and_options_pass_through(self):
@ -343,13 +355,155 @@ class ActionTests(unittest.TestCase):
self.assertEqual(sorted(p.name for p in (self.root / "out").iterdir()), ["taken.glb"])
self.assertIn("already exists", self.run_action(action="exportGltf", filepath="taken.glb")["message"])
def test_export_gltf_refuses_an_existing_bin_sibling(self):
def test_export_gltf_writes_its_bin_and_textures_beside_it_and_nothing_else(self):
self.bpy.export_siblings = ["tex.png"]
receipt = self.run_action(action="exportGltf", filepath="sub/a.gltf")
self.assertEqual(receipt["status"], "accepted", receipt)
self.assertEqual(sorted(p.name for p in (self.root / "out" / "sub").iterdir()), ["a.bin", "a.gltf", "tex.png"])
self.assertEqual(sorted(p.name for p in (self.root / "out").iterdir()), ["sub"]) # no staging folder left
def test_export_gltf_refuses_an_existing_bin_sibling_and_keeps_it(self):
(self.root / "out" / "a.bin").write_bytes(b"old")
self.assertEqual(self.run_action(action="exportGltf", filepath="a.gltf")["status"], "failed")
self.assertEqual(self.bpy.exported, [])
receipt = self.run_action(action="exportGltf", filepath="a.gltf")
self.assertEqual(receipt["status"], "failed")
self.assertIn("a.bin", receipt["message"])
self.assertEqual((self.root / "out" / "a.bin").read_bytes(), b"old")
self.assertEqual(sorted(p.name for p in (self.root / "out").iterdir()), ["a.bin"])
def test_export_gltf_never_overwrites_a_texture_the_exporter_writes(self):
(self.root / "out" / "tex.png").write_bytes(b"old")
self.bpy.export_siblings = ["tex.png"]
receipt = self.run_action(action="exportGltf", filepath="a.gltf")
self.assertEqual(receipt["status"], "failed")
self.assertIn("tex.png", receipt["message"])
self.assertEqual((self.root / "out" / "tex.png").read_bytes(), b"old")
self.assertEqual(sorted(p.name for p in (self.root / "out").iterdir()), ["tex.png"]) # no a.gltf, no a.bin
def test_a_failed_export_leaves_no_file_no_folder_and_the_name_can_be_retried(self):
self.bpy.export_raises_after_writing = "exporter died midway"
receipt = self.run_action(action="exportGltf", filepath="new/deep/a.glb")
self.assertEqual(receipt["status"], "failed")
self.assertEqual(list((self.root / "out").iterdir()), [])
self.bpy.export_raises_after_writing = None
retry = self.run_action(action="exportGltf", filepath="new/deep/a.glb")
self.assertEqual(retry["status"], "accepted", retry)
self.assertTrue((self.root / "out" / "new" / "deep" / "a.glb").is_file())
def test_a_move_that_fails_partway_rolls_back_so_the_target_is_untouched_and_retry_works(self):
self.bpy.export_siblings = ["tex1.png", "tex2.png"]
real_rename = os.rename
calls = []
def fail_on_third(src, dst):
calls.append(dst)
if len(calls) == 3:
raise OSError("disk full")
return real_rename(src, dst)
with mock.patch.object(bt.os, "rename", fail_on_third):
receipt = self.run_action(action="exportGltf", filepath="sub/a.gltf")
self.assertEqual(receipt["status"], "failed")
self.assertGreaterEqual(len(calls), 3)
self.assertEqual(list((self.root / "out").iterdir()), []) # nothing moved stays; no staging, no new folder
retry = self.run_action(action="exportGltf", filepath="sub/a.gltf")
self.assertEqual(retry["status"], "accepted", retry)
self.assertEqual(sorted(p.name for p in (self.root / "out" / "sub").iterdir()),
["a.bin", "a.gltf", "tex1.png", "tex2.png"])
HOLD_STAGE = (
"import sys\n"
"sys.path.insert(0, sys.argv[1])\n"
"import types\n"
"pkg = types.ModuleType('brokkr_bridge'); pkg.__path__ = [sys.argv[1] + '/brokkr_bridge']\n"
"sys.modules['brokkr_bridge'] = pkg\n"
"from brokkr_bridge import blender_target as bt\n"
"from pathlib import Path\n"
"stage, fd = bt._open_stage(Path(sys.argv[2]))\n"
"print(stage, flush=True)\n"
"sys.stdin.read()\n")
def start_export_holding_a_stage(self):
import subprocess
child = subprocess.Popen([sys.executable, "-c", self.HOLD_STAGE, str(ADDON.parent), str(self.root / "out")],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
self.addCleanup(child.kill)
self.addCleanup(child.wait)
self.addCleanup(child.stdout.close)
self.addCleanup(child.stdin.close)
return child, Path(child.stdout.readline().strip())
def test_a_sweep_spares_another_processs_live_stage_and_removes_a_killed_ones(self):
child, stage = self.start_export_holding_a_stage()
(stage / "a.glb").write_bytes(b"in flight")
os.utime(stage, (0, 0)) # old by any clock: only the lock decides
bt._sweep_stale_stages(self.root / "out")
self.assertTrue((stage / "a.glb").exists())
self.assertEqual(self.run_action(action="exportGltf", filepath="b.glb")["status"], "accepted")
self.assertTrue((stage / "a.glb").exists()) # an export in this process swept too
child.kill()
child.wait()
bt._sweep_stale_stages(self.root / "out")
self.assertFalse(stage.exists())
def test_a_sweep_leaves_a_folder_whose_lock_is_not_made_yet(self):
early = self.root / "out" / ".brokkr-export-early"
early.mkdir()
bt._sweep_stale_stages(self.root / "out")
self.assertTrue(early.exists())
def test_a_failed_rollback_is_refused_loudly_naming_the_files_and_the_next_export_recovers(self):
self.bpy.export_siblings = ["tex1.png"]
real_rename = os.rename
calls = []
def fail_forever_from_third(src, dst):
calls.append(dst)
if len(calls) >= 3:
raise OSError("disk gone")
return real_rename(src, dst)
with mock.patch.object(bt.os, "rename", fail_forever_from_third):
receipt = self.run_action(action="exportGltf", filepath="sub/a.gltf")
self.assertEqual(receipt["status"], "failed")
self.assertIn("could not be rolled back", receipt["message"])
self.assertIn("sub/a.bin", receipt["message"])
self.assertIn("sub/a.gltf", receipt["message"])
self.assertTrue((self.root / "out" / "sub" / "a.bin").exists())
retry = self.run_action(action="exportGltf", filepath="sub/a.gltf")
self.assertEqual(retry["status"], "accepted", retry)
self.assertEqual(sorted(p.name for p in (self.root / "out").rglob("*") if p.is_file()),
["a.bin", "a.gltf", "tex1.png"])
self.assertEqual([p.name for p in (self.root / "out").iterdir()], ["sub"]) # no stage left
def test_a_failed_texture_subfolder_move_leaves_no_empty_folder(self):
self.bpy.export_siblings = []
real_rename = os.rename
def fail_the_texture(src, dst):
if "textures" in str(dst):
raise OSError("no")
return real_rename(src, dst)
orig = self.bpy.export_gltf
def with_subfolder(mode, undo, **kw):
result = orig(mode, undo, **kw)
target = Path(kw["filepath"])
(target.parent / "textures").mkdir()
(target.parent / "textures" / "t.png").write_bytes(b"t")
return result
self.bpy.ops.export_scene.gltf = with_subfolder
with mock.patch.object(bt.os, "rename", fail_the_texture):
receipt = self.run_action(action="exportGltf", filepath="a.gltf")
self.assertEqual(receipt["status"], "failed")
self.assertEqual(list((self.root / "out").iterdir()), [])
def test_export_refuses_a_symlinked_folder(self):
os.symlink(self.root, self.root / "out" / "link")
try:
os.symlink(self.root, self.root / "out" / "link")
except OSError:
self.skipTest("the OS denies symlink creation to this user")
self.assertEqual(self.run_action(action="exportGltf", filepath="link/a.glb")["status"], "failed")
self.assertEqual(self.bpy.exported, [])
@ -427,29 +581,36 @@ class ActionTests(unittest.TestCase):
self.assertIn("CUBE", receipt["message"])
self.assertEqual(self.bpy.created, [])
# renderStill: GPU engines without a GL runtime
def test_render_still_refuses_gpu_engines_headless_when_the_gl_library_is_missing(self):
def test_mesh_type_on_a_non_mesh_object_is_refused_not_ignored(self):
for object_type in ("LIGHT", "EMPTY", "CAMERA"):
receipt = self.run_action(action="createObject", objectType=object_type, meshType="CYLINDER")
self.assertEqual(receipt["status"], "failed", object_type)
self.assertIn("MESH", receipt["message"])
self.assertEqual(self.bpy.created, [])
# renderStill: GPU engines that would abort a headless Blender
def test_render_still_refuses_gpu_engines_headless_when_a_test_render_fails(self):
self.bpy.app.background = True
for engine in ("BLENDER_WORKBENCH", "BLENDER_EEVEE", "BLENDER_EEVEE_NEXT", "blender_workbench"):
self.bpy.scene.render.ENGINES = FakeRender.ENGINES + ("BLENDER_EEVEE_NEXT",)
with mock.patch.object(bt, "missing_gl_library", return_value="libEGL.so.1"):
with mock.patch.object(bt, "gl_render_failure", return_value="a one-pixel test render exited with status 134"):
receipt = self.run_action(action="renderStill", outputPath="a.png", engine=engine)
self.assertEqual(receipt["status"], "failed", engine)
self.assertIn("libEGL.so.1", receipt["message"])
self.assertIn("one-pixel test render", receipt["message"])
self.assertIn("CYCLES", receipt["message"])
self.assertEqual(self.bpy.rendered, [])
self.assertEqual(self.bpy.scene.render.engine, "BLENDER_EEVEE")
def test_render_still_refuses_the_scene_engine_too_and_leaves_no_folder(self):
self.bpy.app.background = True # scene engine is BLENDER_EEVEE
with mock.patch.object(bt, "missing_gl_library", return_value="libEGL.so.1"):
with mock.patch.object(bt, "gl_render_failure", return_value="a one-pixel test render exited with status 134"):
receipt = self.run_action(action="renderStill", outputPath="shots/a.png")
self.assertEqual(receipt["status"], "failed")
self.assertFalse((self.root / "out" / "shots").exists())
def test_render_still_gl_check_spares_cycles_foreground_and_a_present_library(self):
probe = mock.Mock(return_value="libEGL.so.1")
with mock.patch.object(bt, "missing_gl_library", probe):
def test_render_still_gl_check_spares_cycles_foreground_and_a_working_test_render(self):
probe = mock.Mock(return_value="a one-pixel test render exited with status 134")
with mock.patch.object(bt, "gl_render_failure", probe):
self.bpy.app.background = True
self.assertEqual(self.run_action(action="renderStill", outputPath="a.png", engine="CYCLES")["status"], "accepted")
probe.assert_not_called()
@ -460,20 +621,94 @@ class ActionTests(unittest.TestCase):
probe.return_value = None
self.assertEqual(self.run_action(action="renderStill", outputPath="c.png", engine="BLENDER_WORKBENCH")["status"], "accepted")
def test_missing_gl_library_probes_only_on_linux_and_only_once(self):
bt.missing_gl_library.cache_clear()
with mock.patch.object(bt.sys, "platform", "win32"), mock.patch.object(bt.ctypes, "CDLL", side_effect=OSError) as cdll:
self.assertIsNone(bt.missing_gl_library())
cdll.assert_not_called()
bt.missing_gl_library.cache_clear()
with mock.patch.object(bt.sys, "platform", "linux"), mock.patch.object(bt.ctypes, "CDLL", side_effect=OSError) as cdll:
self.assertEqual(bt.missing_gl_library(), "libEGL.so.1")
self.assertEqual(bt.missing_gl_library(), "libEGL.so.1")
cdll.assert_called_once_with("libEGL.so.1")
bt.missing_gl_library.cache_clear()
with mock.patch.object(bt.sys, "platform", "linux"), mock.patch.object(bt.ctypes, "CDLL"):
self.assertIsNone(bt.missing_gl_library())
bt.missing_gl_library.cache_clear()
def fake_blender(self, status, marker=True):
"""A stand-in Blender binary: a script that ignores its arguments, prints the probe's completion
marker (or not) and exits with status."""
if os.name == "nt":
path = self.root / "fake_blender.cmd"
path.write_text("@echo off\r\n" + ("echo BROKKR_GL_PROBE_OK\r\n" if marker else "") + f"exit /b {status}\r\n")
else:
path = self.root / "fake_blender.sh"
path.write_text("#!/bin/sh\n" + ("echo BROKKR_GL_PROBE_OK\n" if marker else "") + f"exit {status}\n")
path.chmod(0o755)
return str(path)
def test_gl_probe_passes_when_the_test_render_finishes_and_says_so(self):
bt.gl_render_failure.cache_clear()
self.addCleanup(bt.gl_render_failure.cache_clear)
self.assertIsNone(bt.gl_render_failure(self.fake_blender(0), "BLENDER_EEVEE"))
def test_gl_probe_fails_on_an_abort_a_missing_marker_a_hang_and_an_unknown_binary(self):
bt.gl_render_failure.cache_clear()
self.addCleanup(bt.gl_render_failure.cache_clear)
self.assertIn("status 3", bt.gl_render_failure(self.fake_blender(3), "BLENDER_EEVEE"))
self.assertIn("status 0", bt.gl_render_failure(self.fake_blender(0, marker=False), "BLENDER_WORKBENCH"))
with mock.patch.object(bt, "GL_PROBE_TIMEOUT_SECONDS", 0.001):
self.assertIn("did not finish", bt.gl_render_failure(self.fake_blender(0), "BLENDER_EEVEE_NEXT"))
self.assertIn("unknown", bt.gl_render_failure("", "BLENDER_EEVEE"))
self.assertIn("unknown", bt.gl_render_failure(str(self.root / "missing"), "BLENDER_EEVEE"))
def slow_blender(self):
"""A stand-in that starts a child which holds the output pipe for 30 s."""
if os.name == "nt":
path = self.root / "slow_blender.cmd"
path.write_text("@echo off\r\nping -n 30 127.0.0.1 >nul\r\n")
else:
path = self.root / "slow_blender.sh"
path.write_text("#!/bin/sh\nsleep 30\necho BROKKR_GL_PROBE_OK\n")
path.chmod(0o755)
return path
def test_gl_probe_timeout_returns_on_time_killing_the_childs_children_and_is_not_cached(self):
import time
bt.gl_render_failure.cache_clear()
self.addCleanup(bt.gl_render_failure.cache_clear)
slow = self.slow_blender()
with mock.patch.object(bt, "GL_PROBE_TIMEOUT_SECONDS", 1):
started = time.monotonic()
failure = bt.gl_render_failure(str(slow), "BLENDER_EEVEE")
took = time.monotonic() - started
self.assertIn("did not finish", failure)
self.assertLess(took, 10)
# the same binary and engine, now fast: a timeout was not remembered
slow.unlink()
fast = self.fake_blender(0)
os.replace(fast, str(slow.with_suffix(Path(fast).suffix)))
self.assertIsNone(bt.gl_render_failure(str(slow.with_suffix(Path(fast).suffix)), "BLENDER_EEVEE"))
def test_gl_probe_caches_a_definite_abort_and_forgets_an_unstartable_binary(self):
bt.gl_render_failure.cache_clear()
self.addCleanup(bt.gl_render_failure.cache_clear)
binary = self.fake_blender(3)
self.assertIn("status 3", bt.gl_render_failure(binary, "BLENDER_EEVEE"))
self.fake_blender(0) # same path, now a working binary: the abort is still the answer
self.assertIn("status 3", bt.gl_render_failure(binary, "BLENDER_EEVEE"))
with mock.patch.object(bt.subprocess, "Popen", side_effect=OSError("denied")):
self.assertIn("could not start", bt.gl_render_failure(binary, "BLENDER_WORKBENCH"))
self.assertIsNone(bt.gl_render_failure(binary, "BLENDER_WORKBENCH"))
def test_gl_probe_runs_once_per_binary_and_engine(self):
bt.gl_render_failure.cache_clear()
self.addCleanup(bt.gl_render_failure.cache_clear)
binary = self.fake_blender(0)
with mock.patch.object(bt.subprocess, "Popen", wraps=bt.subprocess.Popen) as run:
bt.gl_render_failure(binary, "BLENDER_EEVEE")
bt.gl_render_failure(binary, "BLENDER_EEVEE")
bt.gl_render_failure(binary, "BLENDER_WORKBENCH")
self.assertEqual(run.call_count, 2)
def test_render_still_end_to_end_with_a_binary_that_aborts_and_one_that_renders(self):
bt.gl_render_failure.cache_clear()
self.addCleanup(bt.gl_render_failure.cache_clear)
self.bpy.app.background = True
self.bpy.app.binary_path = self.fake_blender(134)
refused = self.run_action(action="renderStill", outputPath="a.png")
self.assertEqual(refused["status"], "failed")
self.assertIn("status 134", refused["message"])
self.assertEqual(self.bpy.rendered, [])
bt.gl_render_failure.cache_clear()
self.bpy.app.binary_path = self.fake_blender(0)
self.assertEqual(self.run_action(action="renderStill", outputPath="a.png")["status"], "accepted")
# importGltf: names
def test_import_refuses_drive_unc_extended_stream_and_device_names(self):