Skip to main content
Version: v2.1.x (v2.1.1)

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 .py and .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 unless allow_no_backup is set.
  • Four threads that call migrate() on one new database apply each migration once. That is what lets every process call migrate() 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_current raises 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_DIR overrides it.
  • A backup taken while another connection holds an uncommitted write passes PRAGMA integrity_check and contains none of the uncommitted row. backup_db uses 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 videos column.
  • Two databases written by hand in an older layout, fixtures/db/pre_agents.sql and fixtures/db/pre_publishing.sql, converge to the current schema and keep their rows, renamed columns and user-set settings included.
  • notified_status is backfilled to status@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 at high after 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 VOICING stage before the migration is relabelled VOICING_WITH_SCENES. A VOICING row 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_at and scheduled_timezone set 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 WARNING by 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 under test_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_model outside the OpenAI catalog moves to gpt-image-2.5-flare, both OpenAI models are kept, and the image_provider row 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 means auto has 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 code in 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_key makes a write idempotent. video_costs splits a shared agent session evenly across its videos. The spend summary's until bound is exclusive, so two adjacent ranges count no event twice.
  • last_voice_model returns 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 $0 rate 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_conflict decides 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_error is the matching check when a script is written.
  • resolve_voice uses the video's voice, then the install default.
  • eleven_v4 sits in every model set eleven_v3 is in and in no other.
  • DEFAULT_VOICES keep their order, DEFAULT_VOICE_ID is 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, the m. host) come back as https://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_component is 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_file and image_file derive 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_symlinks keeps a link inside images/ out of a copytree.
  • A name that gets a suffix leaves room for it. output_file and scene_file refuse 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_fingerprint changes 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_errors validates 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_band derives a line count from maxWords and fontSize, 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_sql agrees with pickable, and cartoon_mascot_clash_sql names a Cartoon 3D style or resolved renderer with a non-empty mascot.
  • resolve_default turns an archived or unapproved default into no mascot. mascot_gpu_error asks for a GPU test when the status is unknown. code_for reads a built-in's code from its versioned file.
  • Copies are compared with their originals: EMOTIONS with the engine's sheet.js, the safe zone with mcp/text_audit.py, FPS with Root.tsx and mcp/server.py, the box and walk constants with the engine's frame.html and driver.js, and the caption defaults with Subtitles.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 loads driver.js in a Node vm context, 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.js and the three model sheets as JPEGs, the form the API serves a built-in's sheets in. On a migrated database, code_for returns that mascot.js.
  • The code registers window.MASCOT, and every view's face record carries bx.

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_status returns the four values the GPU gates read, and gpu_unavailable_reason names 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 tubematic container 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 None and never becomes 0.
  • tree_bytes counts 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_secrets never 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_pin is 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 after Authorization: Basic, a Cookie: or Set-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_logging returns None on 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 the VERSION file beside the package directory, the relationship the Dockerfile's COPY VERSION /app/lib/VERSION keeps inside a container. A blank TUBEMATIC_VERSION is ignored.
  • The version rule is SemVer with an optional prerelease and no +build metadata. The development marker develop passes is_valid() and fails is_release().
  • GITHUB_REPO is a bare lowercase owner/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.