tubematic_core/tests
Covers tubematic_core/, the Python package every Tubematic process shares: the migration runner
and each migration, backups, service tokens, logging, the version string, and the rule modules the
API, the MCP server and the worker all import.
Duplication is intentional says why the package
exists. The suite needs pytest and cryptography, and one file runs node when it is on PATH.
python -m pytest tubematic_core/tests
Run each suite in its own pytest invocation. README.md lists the suites that fail to
collect together.
The tests import tubematic_core from the repository root. Most files insert that directory on
sys.path themselves, and python -m pytest run from the root adds it for the rest. Inside a
container the package arrives through PYTHONPATH=/app/lib.
The migration runner and backups
test_db.py
Covers db.py: migration discovery, the schema_migrations table, connect() and migrate()
(Migrations).
- Discovery sorts by numeric prefix, accepts
.pyand.sql, allows gaps and treats a duplicate number as a hard error. migrate()applies what is pending and stamps it, does nothing on a second run, and takes a backup only when something is pending on an existing database. A failed backup stops the migration unlessallow_no_backupis set.- Four threads that call
migrate()on one new database apply each migration once. That is what lets every process callmigrate()at start with no coordination. - Four threads that call
connect()on a new file all succeed (_ensure_wal). The test repeats the race on 30 fresh files, because a single race catches a broken WAL switch in about one run out of six. assert_schema_currentraises on a database that is behind.
Trap: A migration is stamped inside the transaction it runs in, and the whole run is one
transaction, because a commit per migration would release the write lock between them. A stamp
written outside the transaction would leave a database that claims a version it never reached, and
no later migrate() would try again.
test_backup.py
Covers db.py::backup_db (Backups).
- The backup directory is the sibling of the database's parent, and
TUBEMATIC_BACKUPS_DIRoverrides it. - A backup taken while another connection holds an uncommitted write passes
PRAGMA integrity_checkand contains none of the uncommitted row.backup_dbuses SQLite's online backup API for this: a plain file copy taken during a write is torn, and it looks fine until someone restores it. - Two backups in the same one-second stamp land on different files, and the retry loop gives up after too many collisions.
- A failed backup raises
MigrationError, removes its partial file and leaves an earlier good backup alone.
Trap: A backup name is reserved with os.O_CREAT | os.O_EXCL. Two containers that start together
back up in the same second, and a check followed by a separate open lets both see the name as
free. When one of them then fails, its cleanup deletes the other's finished backup. The two
concurrency tests force that interleaving with a two-party barrier, because a bare thread race
passes most of the time against the broken code.
Migrations
One file per migration, in migration order. 0005 is covered by
test_usage_accounting.py. The
migration reference lists what each migration changes.
Each file migrates a database up to the migration before its own, inserts rows, and then migrates
the rest, so the rows exist before the migration under test runs.
test_baseline.py
Covers 0001_baseline.py.
- A new database gets every table and every
videoscolumn. - Two databases written by hand in an older layout,
fixtures/db/pre_agents.sqlandfixtures/db/pre_publishing.sql, converge to the current schema and keep their rows, renamed columns and user-set settings included. notified_statusis backfilled tostatus@updated_at. Left blank, the first notification sweep after an upgrade would announce every waiting video at once.
Trap: The two fixtures are typed out by hand. A fixture generated by today's code would converge against today's migrations by construction and prove nothing about a real upgrade.
test_visual_style.py
Covers 0002, the three visual-style columns.
- A new video defaults to
auto. - Every video that existed before the migration is set to
motion_graphics.
Trap: ADD COLUMN ... DEFAULT 'auto' applies the default to existing rows too. Without the trailing
UPDATE, every video in flight becomes auto and the next agent session restyles it. A migration
without that line still adds the right columns and passes a schema-only check.
test_agent_effort.py
Covers 0003, the two agent-effort columns.
- An agent row that existed before the column ends at
high, so an install that never changes the setting runs athighafter an upgrade too. - Existing videos are not backfilled.
Trap: This migration has no backfill for videos. A video that existed before it has no per-video
choice to keep, so anything other than '' would pin it to a level nobody chose. An UPDATE added
to mirror 0002 is what these tests catch.
test_pause_seeds_only.py
Covers 0004, which sets every paused domain that is not a curriculum seed to active.
- A paused non-seed domain becomes active.
- A paused seed stays paused.
Trap: Only curriculum seeds have a pause control (Domain pause), so
a paused non-seed domain would stay paused with nothing able to change it. An UPDATE without the
seed condition would resume a domain a person paused.
test_voice_models_migration.py
Covers 0006, which moves the ElevenLabs model from one install-wide setting onto every voice in
the roster and adds projects.default_voice_id.
- Every voice gets the model the install was using, and a voice that already has a valid model keeps it.
- A blank, missing or retired stored model falls back to
eleven_multilingual_v2.
Trap: A corrupt roster is left as it was. Readers treat a malformed roster as empty, so a bad rewrite would drop every voice.
test_agent_progress_migration.py
Covers 0007, the per-video progress record.
- Every existing video starts with a clean record.
- Usage recorded under the
VOICINGstage before the migration is relabelledVOICING_WITH_SCENES. AVOICINGrow written after the migration keeps its stage.
Trap: Sessions recorded as VOICING before this migration also wrote the scenes. Without the
relabel the dashboard would show that spend as voicing alone.
test_scheduled_publishing_migration.py
Covers 0008, the two scheduling columns.
- Every existing video ends with
scheduled_atandscheduled_timezoneset to''.
Trap: The worker's due-time pass selects on scheduled_at, so any other value there reads as a
schedule.
test_auto_pilot_migration.py
Covers 0009, the Auto Pilot hold and block columns.
- Every existing video ends neither held nor blocked.
Trap: Auto Pilot refuses to post a held video, so a non-zero default would exempt the whole existing library.
test_default_script_profile_migration.py
Covers 0010, which adds projects.default_script_profile_id.
- Every existing domain ends with no default.
Trap: A non-blank default would write a domain's curriculum videos in a style nobody picked.
test_image_model_migration.py
Covers 0011, which moves a stored image_model of gpt-image-2 to gpt-image-2.5-flare.
- Another model, and another settings key that holds the same text, are left alone.
Trap: Without the rewrite, the settings reader falls back to the Gemini default while the provider
stays openai, and every later settings save is refused. These tests stop at 0011, because 0016
rewrites every model outside the OpenAI catalog and would hide what 0011 does.
test_auto_pilot_in_flight_migration.py
Covers 0012, which renames the setting auto_pilot_max_scheduled to auto_pilot_max_in_flight.
- The stored number carries over unchanged, 0 included.
- An install that never stored the setting gets no row.
Trap: The value is copied as it is because the new count includes everything the old count did. The same number can only stop Auto Pilot sooner and can never spend more.
test_topic_cap_migration.py
Covers 0013, which adds projects.topic_cap (default 100) and the idx_videos_project_id index.
- A domain that already holds 100 or more videos gets its count plus 100, capped at 750.
- Every video counts, archived and rejected ones included.
Trap: A domain at its cap takes no research topics (Topic cap). The migration must give headroom to a domain that was filing topics before the upgrade, or the upgrade closes it.
test_mining_sources_migration.py
Covers 0014, which brings a stored mining_youtube_urls list to the form its writers accept.
- A YouTube video URL is rewritten to
https://www.youtube.com/watch?v=<id>, and two spellings of one video are kept once. - An entry that is not a YouTube video URL is dropped and logged at
WARNINGby name. So is everything past 50 videos, and a value that is not a JSON list is cleared.
Trap: The dashboard sends the whole list on every change, and the writer refuses a list with a bad entry. One leftover entry would make every later save fail, which is why bad entries are dropped.
test_gemini_3_pro_image_migration.py
Covers 0015, which moves a stored image_model of gemini-3-pro-image-preview to
gemini-3-pro-image.
- Another model and another settings key are left alone. These tests stop at
0015, for the reason given undertest_image_model_migration.py.
Trap: Without the rewrite, the settings reader falls back to the default model, a cheaper model the user did not choose.
test_openai_only_images_migration.py
Covers 0016, which leaves OpenAI as the one image provider.
- A stored
image_modeloutside the OpenAI catalog moves togpt-image-2.5-flare, both OpenAI models are kept, and theimage_providerrow is deleted. - A database that never stored either key gets nothing written.
Trap: The migration matches with NOT IN the OpenAI catalog and names no Gemini model. The MCP
server reads image_model raw, so any value outside the catalog, a hand-edited one included, would
make every generate_image call refuse.
test_resolved_renderer_migration.py
Covers 0017, which adds videos.resolved_renderer, the renderer auto settled on for a video.
- Every video that existed before the migration is set to
dom. - A video created after the migration starts at
'', which meansautohas not settled yet.
Trap: ADD COLUMN gives every existing row ''. Without the backfill, a video in flight reads as
unresolved, and a revision could decide that a video whose scenes are already written is Cartoon 3D
and discard them.
test_mascots_migration.py
Covers 0018: the mascots and mascot_versions tables, the three mascot columns and the seeded
Tubi row (mascots and mascot_versions).
- Existing domains and videos end with no mascot.
- The one new mascot is Tubi: ready, approved at version 1, with an empty
codein its version row.
Trap: Tubi's drawing code lives in a versioned file in the repository and never in the database or
in a migration. test_builtin_tubi.py covers that file.
test_renderers_migration.py
Covers 0019: the render lease columns and the renderers, renderer_enrollments and
render_timings tables.
- Existing videos end unleased, with
''in all five lease columns. - The built-in renderer's row is seeded enabled and unprobed.
Trap: An empty lease is what lets the worker's lease sweep queue again a render that was in progress
during the upgrade. An unprobed built-in row makes the GPU gates read unknown until the
renderer's first probe.
Shared rules
test_usage_accounting.py
Covers the 0005 usage ledger and the pricing in usage.py and prices.py
(How a call is priced).
- The rate order (manual, then synced, then the built-in snapshot, one source per model) and the rules for a missing rate.
- Editing a price does not change recorded events. Adding a price fills in the events that were unpriced, which is why their units are kept.
- ElevenLabs rows are credits and are never priced. Costs an agent CLI reports are stored as given.
- An
event_keymakes a write idempotent.video_costssplits a shared agent session evenly across its videos. The spend summary'suntilbound is exclusive, so two adjacent ranges count no event twice. last_voice_modelreturns the model of a video's latest voicing call. A voice preview, another video's call and another provider's call do not count.
Trap: An unknown model is unpriced (NULL) and never $0, and so is a billed call whose usage could
not be read. A zero reads as a free call and understates spend with nothing left to repair it from.
record_usage returns None and logs when it cannot write. It never raises, because bookkeeping
must not fail a video.
test_prices_sync.py
Covers the price sync in prices.py.
- The source is chosen per model: OpenRouter's rates when it lists the model, LiteLLM's for a model OpenRouter lacks. Mixing fields from both for one model would make a wrong figure untraceable.
- Zero rates are dropped, because a stored
$0rate prices a paid call as free. - A manual row is never overwritten, and a move of more than five times is rejected.
- A sync that newly prices a model fills in that model's unpriced events.
Trap: A failed sync keeps every existing price, including a failure part-way through, because the sync runs inside a savepoint. Without it, half the models could end on new rates.
test_voice_models.py
Covers voice_models.py, where the MCP server and the API learn what each ElevenLabs model can
speak (The model follows the voice).
markup_conflictdecides whether a scripted video may move to a voice on another model. A script with no markup fits every model, and a legacy flat script counts only<ipa>.phoneme_model_erroris the matching check when a script is written.resolve_voiceuses the video's voice, then the install default.eleven_v4sits in every model seteleven_v3is in and in no other.DEFAULT_VOICESkeep their order,DEFAULT_VOICE_IDis the first, and every entry is on an offered model. One bad entry makes every roster reader drop the whole list, which leaves a new install with no voices.
Trap: A <phoneme> tag conflicts with any model that cannot honour it, with no exemption for the
video's current model. When a voice's model is edited in Settings, the edited model is both the
current one and the target, and an exemption would pass the edit through to a paid voicing. A video
voice that has left the roster resolves to nothing, because a fallback would spend on a voice nobody
chose.
test_youtube.py
Covers youtube.py, the rule for what a mining URL may be.
- Accepted forms (
watch?v=,youtu.be,shorts,live, them.host) come back ashttps://www.youtube.com/watch?v=<id>. - Each refusal sits beside an accepted form:
file://, loopback addresses, a look-alike host, userinfo, a port, an id of the wrong length, control characters and an/embed/or channel URL. - The list check refuses the whole list and names every bad entry, and caps the list at 50 distinct videos.
Trap: Every accepted URL becomes Gemini's file_uri on a paid call, so a check that accepts too
much sends an arbitrary address to the provider. The accepted forms are tested too, so a rule that
refuses everything also fails.
test_ids_and_jobfiles.py
Covers ids.py and jobfiles.py, which every process uses to turn an id into a path
(Ids that become paths).
- The strict id check accepts the real id shapes and refuses anything that could leave its directory. Each refusal sits beside a working control.
is_componentis the looser check for use on disk. It accepts a legacy id with a dot or a space, and still refuses.,.., a separator and a name over 255 bytes in UTF-8.job_file,images_dir,output_file,scene_fileandimage_filederive the fixed layout and refuse a symlink in any component below the root. A symlinked root is allowed, and a path that does not exist yet still derives.ignore_symlinkskeeps a link insideimages/out of acopytree.- A name that gets a suffix leaves room for it.
output_fileandscene_filerefuse a 252-byte stem and create nothing, and a 251-byte stem's file is written for real, since the bound is the filesystem's (ENAMETOOLONG). source_fingerprintchanges on any edit or move in a tree and refuses a symlink in it.
Trap: The 128-character cap is a rule for new ids only. Applied in is_component, it would move
every longer legacy video to FAILED. The symlink check walks each component, because containment
alone passes a job directory linked to another video's directory inside the root, which hands one
video another's files. The id check is a fullmatch, because re.match with $ accepts a trailing
newline.
test_mascots.py
Covers mascots.py, the mascot rules every process shares
(Mascots).
cue_errorsvalidates a cue track against the engine's real box, the safe zone and the caption band. A walk is checked along its path, so two clear positions on opposite sides of the band are refused. The second in view must be one unbroken stretch. One bad walk is reported once per kind of violation.caption_bandderives a line count frommaxWordsandfontSize, so large captions that wrap to three or four lines still keep the mascot off them. A hidden caption band frees the space.holds_pickable_sqlagrees withpickable, andcartoon_mascot_clash_sqlnames a Cartoon 3D style or resolved renderer with a non-empty mascot.resolve_defaultturns an archived or unapproved default into no mascot.mascot_gpu_errorasks for a GPU test when the status isunknown.code_forreads a built-in's code from its versioned file.- Copies are compared with their originals:
EMOTIONSwith the engine'ssheet.js, the safe zone withmcp/text_audit.py,FPSwithRoot.tsxandmcp/server.py, the box and walk constants with the engine'sframe.htmlanddriver.js, and the caption defaults withSubtitles.tsx.
Trap: cue_errors is the one check between an agent's cue track and a mascot that stands on the
captions in a finished video. It is a Python port of the engine's walk model, so the constants above
must stay equal to the engine's.
test_mascot_driver_agreement.py
Covers the walk model in mascots.py against the engine's driver.js.
- The test runs
renderer/remotion/mascot-tools/driver-agreement.mjs, which loadsdriver.jsin a Nodevmcontext, on five fixed tracks. - At each sampled frame it compares where the feet stand with
boxes_at_frames, within one pixel.
Trap: The constant checks in test_mascots.py compare text. A change to the logic on either side
passes them, and this file is the one that runs both.
Needs: node on PATH. Without it the test skips and says why.
test_builtin_tubi.py
Covers the files of the built-in mascot in renderer/remotion/mascot-builtin/tubi/v1/.
- The directory holds
mascot.jsand the three model sheets as JPEGs, the form the API serves a built-in's sheets in. On a migrated database,code_forreturns thatmascot.js. - The code registers
window.MASCOT, and every view's face record carriesbx.
Trap: The engine's blush() reads bx, and a face without it turns every blush into NaN with no
error. Version 1 is immutable: a changed drawing ships as a new version directory with a migration.
test_renderers.py
Covers renderers.py, the rules the render gateway, the worker, the API and the MCP server share
about the machines that render.
- The scheduler (Which renderer gets which video) is a pure function, tested case by case: who may claim, the tolerance for a slower caller, the starvation limit, and that offline, disabled, removed and outdated renderers never hold a video back.
- A GPU-only video is skipped by a renderer without a verified GPU even past starvation, and that renderer takes the next video.
- The estimate is the median of the last five timings for a kind of video, so one stalled render does not make a machine look slow for long.
gpu_statusreturns the four values the GPU gates read, andgpu_unavailable_reasonnames every renderer and its state.- Enrollment secrets are stored hashed, work once and expire, and a removed renderer is never revived (Enrollment). The built-in token never expires, and rotation keeps the old credential working until the new one is first used (Credentials).
Trap: In gpu_status, unknown outranks not_usable. A renderer that has not been probed may have
a working GPU, so the message asks for a test. A rotation the renderer never received is issued
again without dropping the credential the renderer still holds, since dropping it would leave that
renderer with no credential that authenticates.
test_disk_usage.py
Covers disk_usage.py: the host half of the disk-usage figure and the one rule for "old image" that
upgrade.py deletes by (Old images). Docker is faked from
recorded JSON.
- A previous release's images are old and the running ones are not. A fork's release images count as Tubematic's.
- An image that a
tubematiccontainer uses, running or stopped, is never old. Neither is an image outside Tubematic's repositories, nor an untagged image Compose did not build for this project. - Short and full image ids join, and a size Docker did not report stays
Noneand never becomes 0. tree_bytescounts a hardlinked file once and never follows a symlink.- The snapshot write is atomic, and the command the poller starts runs one measurement at a time.
Trap: With no Tubematic containers, or with Docker missing or unreadable, no image is old. old_images
decides what upgrade.py deletes, so each refusal is tested beside a control that is named old.
Infrastructure
test_auth.py
Covers auth.py: the service tokens, the admin password and the render gateway's TLS pair
(The secrets directory).
- The secrets directory is mode 0700 and its files 0644.
ensure_secretsnever replaces a secret and refills an empty one. - A missing or empty secret file raises, so every caller fails closed.
- A malformed stored password hash never verifies and never raises.
- The certificate is a self-signed P-256 CA with no host name (The TLS pair). A stdlib client built the way a renderer's is completes a real handshake against it, and a client that trusts another install's certificate refuses it.
- A pair missing either half is made again as a pair, also after a repair that was interrupted between its two renames.
gateway_pinis the sha256 of the certificate's DER and fails closed without a certificate.
Trap: Rotation rewrites a secret file in place and keeps its inode. A bind mount pins the inode it
started with, so an atomic rename would leave every running container on the old value. A complete
TLS pair is never replaced, including one that does not load, and rotate_secrets refuses both of
its names: a new certificate is a new pin, and every enrolled renderer would be cut off.
Needs: cryptography.
test_logging.py
Covers the JSONL logging module, logging.py (Logging).
- Redaction has two axes. The pattern axis catches a labelled or provider-shaped secret, including
an ElevenLabs
sk_key, the credential afterAuthorization: Basic, aCookie:orSet-Cookie:header and a Discord webhook token in a URL path. The value axis catches a stored secret that appears with no recognisable shape. A short or empty stored secret is ignored, so an unset key does not redact every line. - The formatter redacts before it writes, and a rotated key is picked up from the secret provider.
- Files past the retention cutoff are pruned at startup and at rollover, for the writing service only.
- Reads return the newest records across services, skip malformed lines, and open only files that match the naming scheme.
- Werkzeug access lines stay out of the file, and a real Werkzeug warning lands.
setup_json_loggingreturnsNoneon a directory it cannot create or write and never raises. It runs at import time in every service, so a raise there would stop the process.
Trap: The secret cache marks "never fetched" with a sentinel and does not use 0.0.
time.monotonic() counts from boot, so on a machine that has just started, a 0.0 marker makes the
cache look fresh for its first minute, and nothing is redacted while startup failures are logged.
test_secrets_are_redacted_on_a_freshly_booted_machine sets a small clock to reproduce it.
test_version.py
Covers version.py (Version numbers in the code).
version()reads theVERSIONfile beside the package directory, the relationship the Dockerfile'sCOPY VERSION /app/lib/VERSIONkeeps inside a container. A blankTUBEMATIC_VERSIONis ignored.- The version rule is SemVer with an optional prerelease and no
+buildmetadata. The development markerdeveloppassesis_valid()and failsis_release(). GITHUB_REPOis a bare lowercaseowner/name, because its owner is the default image namespace, which Docker refuses in upper case.
Trap: The real VERSION file is checked with is_valid(), so the suite passes on the development
branch and on a release line. A check with is_release() would fail on every development checkout.