clipwright/tests/test_postiz.py
pedro-bento d56455e555
All checks were successful
CI / backend-tests (push) Successful in 32s
CI / frontend-build (push) Successful in 31s
fix(publish): channel-by-id selection, DD/MM/YYYY scheduling, app-first boot (#1)
- Postiz publishing now selects exact channels by integration id; identifier
  mapping fixes instagram-standalone (was 'not connected') and multiple channels
  per network (was first-only); settings.__type uses the real identifier
- Publish modal lists all channels, DD/MM/YYYY + HH:MM scheduling with validation,
  surfaces backend errors and a success confirmation
- Remove AWS/S3 clip backup and ElevenLabs voice dubbing (server, UI, tests, docs)
- Boot straight into the app; remove the landing/launch screen
- CI backend-tests runs in a python:3.11-slim container (Forgejo has no 3.11 cache)

Reviewed-on: #1
Co-authored-by: pedro-bento <mail@pbento.pt>
Co-committed-by: pedro-bento <mail@pbento.pt>
2026-10-04 20:07:42 +01:00

389 lines
16 KiB
Python

"""Postiz client + publishing route hardening (Oracle backend review).
Covers the credential-exfil default removal (H1), the ``scheduled_date``
normalisation for the drip queue (H3), the disabled-channel refusal (M7) and
the error paths that used to 500 (M9). No network: the Postiz client functions
are stubbed with monkeypatch.
"""
import asyncio
import inspect
from datetime import datetime, timedelta, timezone
import httpx
import pytest
import postiz
POSTIZ_HEADERS = {"X-Postiz-Url": "https://postiz.example", "X-Postiz-Key": "k"}
def _app():
return pytest.importorskip("app")
# --- postiz.py -------------------------------------------------------------
class TestResolveBase:
def test_bare_host_gets_the_api_prefix(self):
assert postiz._resolve_base("https://p.example") == \
"https://p.example/api/public/v1"
def test_trailing_slash_is_trimmed(self):
assert postiz._resolve_base("https://p.example/") == \
"https://p.example/api/public/v1"
def test_existing_prefix_is_not_doubled(self):
assert postiz._resolve_base("https://p.example/api/public/v1") == \
"https://p.example/api/public/v1"
assert postiz._resolve_base("https://p.example/api/public/v1/") == \
"https://p.example/api/public/v1"
def test_env_fallback_used_when_no_argument(self, monkeypatch):
monkeypatch.setenv("POSTIZ_URL", "https://env.example/")
assert postiz._resolve_base(None) == "https://env.example/api/public/v1"
def test_missing_url_is_refused(self, monkeypatch):
monkeypatch.delenv("POSTIZ_URL", raising=False)
with pytest.raises(postiz.PostizError) as exc:
postiz._resolve_base(None)
assert exc.value.status_code == 400
assert "Missing Postiz URL" in exc.value.detail
def test_no_builtin_host_is_shipped(self):
# H1: the old silent default would ship a caller's key to a host we
# picked. It must not exist anywhere in the module.
assert "postiz.pbento.pt" not in inspect.getsource(postiz)
class TestHandle:
def test_success_returns_json(self):
assert postiz._handle(httpx.Response(200, json={"ok": True})) == {"ok": True}
def test_empty_body_is_none(self):
assert postiz._handle(httpx.Response(200, content=b"")) is None
def test_error_body_is_truncated(self):
with pytest.raises(postiz.PostizError) as exc:
postiz._handle(httpx.Response(500, text="x" * 5000))
assert exc.value.status_code == 500
assert "x" * 500 in exc.value.detail
assert "x" * 501 not in exc.value.detail
# --- app.py per-provider settings -----------------------------------------
class TestPostizSettings:
def test_tiktok_requires_a_posting_method(self):
s = _app()._postiz_settings("tiktok", "Title", "caption", [])
assert s["__type"] == "tiktok"
assert s["content_posting_method"] == "DIRECT_POST"
assert s["privacy_level"] == "PUBLIC_TO_EVERYONE"
def test_instagram_sets_post_type(self):
assert _app()._postiz_settings("instagram", "Title", "caption", []) == \
{"__type": "instagram", "post_type": "post"}
def test_youtube_sets_title_and_type(self):
s = _app()._postiz_settings("youtube", "My Short", "caption", ["tag"])
assert s["__type"] == "youtube"
assert s["type"] == "public"
assert s["title"] == "My Short"
assert s["tags"] == [{"value": "tag", "label": "tag"}]
def test_youtube_title_is_padded_to_the_minimum(self):
assert len(_app()._postiz_settings("youtube", "A", "caption", [])["title"]) >= 2
class TestIdentifierPlatformMap:
"""Several Postiz identifiers map to one platform; `settings.__type` must
stay the *real* identifier or Postiz routes the post to the wrong place."""
def test_map_groups_aliases_and_keeps_unknown(self):
f = _app()._identifier_platform
assert f("instagram") == "instagram"
assert f("instagram-standalone") == "instagram"
assert f("tiktok") == "tiktok"
assert f("tiktok-business") == "tiktok"
assert f("youtube") == "youtube"
# An unmapped provider keeps its identifier as the platform label.
assert f("threads") == "threads"
# Case/whitespace are normalised; a missing id is an empty label.
assert f(" INSTAGRAM-STANDALONE ") == "instagram"
assert f(None) == ""
def test_instagram_alias_keeps_identifier_as_type(self):
s = _app()._postiz_settings("instagram-standalone", "T", "caption", [])
assert s["__type"] == "instagram-standalone"
assert s["post_type"] == "post"
def test_tiktok_alias_keeps_identifier_as_type(self):
s = _app()._postiz_settings("tiktok-business", "T", "caption", [])
assert s["__type"] == "tiktok-business"
assert s["content_posting_method"] == "DIRECT_POST"
def test_youtube_identifier_is_echoed_unchanged(self):
assert _app()._postiz_settings("youtube", "T", "caption", [])["__type"] == "youtube"
class TestIsoDate:
def test_naive_date_gets_the_timezone(self):
assert _app()._postiz_iso_date("2026-12-31T12:00:00", "UTC") == \
"2026-12-31T12:00:00.000Z"
def test_unscheduled_defaults_to_now(self):
out = _app()._postiz_iso_date(None, "UTC")
assert out.endswith("Z") and "T" in out
def test_unparseable_date_is_a_400(self):
from fastapi import HTTPException
with pytest.raises(HTTPException) as exc:
_app()._postiz_iso_date("not-a-date", "UTC")
assert exc.value.status_code == 400
class TestScheduledNormalisation:
def test_scheduled_date_is_backfilled_without_dropping_raw_fields(self):
app = _app()
post = {"id": "p1", "date": "2026-12-31T12:00:00.000Z"}
out = app._normalise_postiz_post(post)
assert out["scheduled_date"] == "2026-12-31T12:00:00.000Z"
assert out["date"] == "2026-12-31T12:00:00.000Z"
assert out is not post
assert app._normalise_postiz_post(
{"id": "p2", "scheduledDate": "2026-01-02T00:00:00.000Z"}
)["scheduled_date"] == "2026-01-02T00:00:00.000Z"
assert app._normalise_postiz_post(
{"id": "p3", "scheduled_date": "kept"})["scheduled_date"] == "kept"
# --- /api/postiz/post request builder -------------------------------------
@pytest.fixture()
def publish_env(tmp_path, monkeypatch):
app = _app()
out = tmp_path / "output"
job_dir = out / "job1"
job_dir.mkdir(parents=True)
(job_dir / "clip_1.mp4").write_bytes(b"video")
monkeypatch.setattr(app, "OUTPUT_DIR", str(out))
monkeypatch.setattr(app, "jobs", {
"job1": {"result": {"clips": [{
"video_url": "/videos/job1/clip_1.mp4",
"title": "Clip title",
"video_description_for_instagram": "caption #one",
}]}}
})
return app
@pytest.fixture()
def stubbed(monkeypatch):
calls = {"order": [], "integrations": []}
def list_integrations(base, key, *a, **k):
calls["order"].append("list")
calls["base"] = base
return calls["integrations"]
def upload_media(base, key, path, *a, **k):
calls["order"].append("upload")
calls["uploaded"] = path
return {"id": "media-1", "path": "media/path"}
def create_post(base, key, payload, *a, **k):
calls["order"].append("create")
calls["payload"] = payload
return [{"postId": "p1", "integration": "x"}]
monkeypatch.setattr(postiz, "list_integrations", list_integrations)
monkeypatch.setattr(postiz, "upload_media", upload_media)
monkeypatch.setattr(postiz, "create_post", create_post)
return calls
def _call(app, method, path, **kw):
async def _do():
transport = httpx.ASGITransport(app=app.app)
async with httpx.AsyncClient(transport=transport,
base_url="http://testserver") as c:
return await getattr(c, method)(path, **kw)
return asyncio.run(_do())
def _post(app, payload, headers=POSTIZ_HEADERS):
return _call(app, "post", "/api/postiz/post", json=payload, headers=headers)
def test_builder_targets_each_integration_and_uploads_first(publish_env, stubbed):
stubbed["integrations"] = [
{"id": "i-tt", "identifier": "tiktok", "disabled": False},
{"id": "i-yt", "identifier": "youtube"},
]
r = _post(publish_env, {"job_id": "job1", "clip_index": 0,
"platforms": ["tiktok", "youtube"], "title": "My Title"})
assert r.status_code == 200, r.text
assert stubbed["order"] == ["list", "upload", "create"]
payload = stubbed["payload"]
assert [p["integration"]["id"] for p in payload["posts"]] == ["i-tt", "i-yt"]
assert [p["settings"]["__type"] for p in payload["posts"]] == ["tiktok", "youtube"]
assert payload["posts"][0]["value"][0]["image"][0]["id"] == "media-1"
assert payload["shortLink"] is False and payload["type"] == "now"
assert stubbed["uploaded"].endswith("clip_1.mp4")
def test_disabled_integration_is_refused(publish_env, stubbed):
stubbed["integrations"] = [{"id": "i-yt", "identifier": "youtube", "disabled": True}]
r = _post(publish_env, {"job_id": "job1", "clip_index": 0, "platforms": ["youtube"]})
assert r.status_code == 400
assert "Disabled" in r.json()["detail"]
assert "upload" not in stubbed["order"] and "create" not in stubbed["order"]
def test_missing_integration_is_refused(publish_env, stubbed):
stubbed["integrations"] = [{"id": "i-tt", "identifier": "tiktok"}]
r = _post(publish_env, {"job_id": "job1", "clip_index": 0, "platforms": ["instagram"]})
assert r.status_code == 400
assert "Not connected" in r.json()["detail"]
assert "upload" not in stubbed["order"]
def test_clip_without_video_url_is_400_not_500(publish_env, stubbed):
publish_env.jobs["job1"]["result"]["clips"] = [{"title": "no url"}]
r = _post(publish_env, {"job_id": "job1", "clip_index": 0, "platforms": ["tiktok"]})
assert r.status_code == 400
assert "video_url" in r.json()["detail"]
def test_missing_url_or_key_is_a_400(publish_env, stubbed, monkeypatch):
monkeypatch.delenv("POSTIZ_URL", raising=False)
monkeypatch.delenv("POSTIZ_API_KEY", raising=False)
body = {"job_id": "job1", "clip_index": 0, "platforms": ["tiktok"]}
r = _post(publish_env, body, headers={"X-Postiz-Key": "k"})
assert r.status_code == 400 and "URL" in r.json()["detail"]
r = _post(publish_env, body, headers={"X-Postiz-Url": "https://p.example"})
assert r.status_code == 400 and "key" in r.json()["detail"].lower()
def test_bad_scheduled_date_is_a_400(publish_env, stubbed):
stubbed["integrations"] = [{"id": "i-tt", "identifier": "tiktok"}]
r = _post(publish_env, {"job_id": "job1", "clip_index": 0,
"platforms": ["tiktok"], "scheduled_date": "tomorrow"})
assert r.status_code == 400
def test_scheduled_window_is_widened_and_posts_are_normalised(publish_env, monkeypatch):
captured = {}
def list_posts(base, key, start, end, *a, **k):
captured["start"], captured["end"] = start, end
return [{"id": "p1", "date": "2026-01-05T00:00:00.000Z"}]
monkeypatch.setattr(postiz, "list_posts", list_posts)
r = _call(publish_env, "get", "/api/postiz/scheduled", headers=POSTIZ_HEADERS)
assert r.status_code == 200, r.text
assert r.json()["scheduled_posts"][0]["scheduled_date"] == \
"2026-01-05T00:00:00.000Z"
start = datetime.fromisoformat(captured["start"].replace("Z", "+00:00"))
end = datetime.fromisoformat(captured["end"].replace("Z", "+00:00"))
assert (end - start) >= timedelta(days=89)
# --- /api/postiz/post channel selection ------------------------------------
def test_integration_ids_pick_exact_channels_and_report_posted(publish_env, stubbed):
stubbed["integrations"] = [
{"id": "yt-main", "identifier": "youtube", "name": "Main channel"},
{"id": "yt-second", "identifier": "youtube", "name": "Second channel"},
{"id": "ig-1", "identifier": "instagram-standalone", "name": "IG"},
]
r = _post(publish_env, {"job_id": "job1", "clip_index": 0,
"integration_ids": ["yt-second", "ig-1"],
"title": "My Title"})
assert r.status_code == 200, r.text
body = r.json()
assert body["success"] is True
assert body["posted"] == [
{"integration_id": "yt-second", "identifier": "youtube",
"platform": "youtube", "name": "Second channel"},
{"integration_id": "ig-1", "identifier": "instagram-standalone",
"platform": "instagram", "name": "IG"},
]
posts = stubbed["payload"]["posts"]
assert [p["integration"]["id"] for p in posts] == ["yt-second", "ig-1"]
assert [p["settings"]["__type"] for p in posts] == \
["youtube", "instagram-standalone"]
assert posts[1]["settings"]["post_type"] == "post"
assert stubbed["payload"]["type"] == "now"
def test_unknown_integration_id_is_a_400(publish_env, stubbed):
stubbed["integrations"] = [{"id": "i-tt", "identifier": "tiktok"}]
r = _post(publish_env, {"job_id": "job1", "clip_index": 0,
"integration_ids": ["nope"]})
assert r.status_code == 400
assert "nope" in r.json()["detail"]
assert "upload" not in stubbed["order"] and "create" not in stubbed["order"]
def test_disabled_integration_id_is_a_400(publish_env, stubbed):
stubbed["integrations"] = [
{"id": "i-ig", "identifier": "instagram-standalone", "name": "IG",
"disabled": True},
]
r = _post(publish_env, {"job_id": "job1", "clip_index": 0,
"integration_ids": ["i-ig"]})
assert r.status_code == 400
assert "Disabled" in r.json()["detail"]
assert "upload" not in stubbed["order"] and "create" not in stubbed["order"]
def test_legacy_platforms_fallback_matches_mapped_identifiers(publish_env, stubbed):
stubbed["integrations"] = [
{"id": "yt-a", "identifier": "youtube", "name": "A"},
{"id": "yt-b", "identifier": "youtube", "name": "B"},
{"id": "ig-1", "identifier": "instagram-standalone", "name": "IG"},
{"id": "tt-1", "identifier": "tiktok-business", "name": "TT"},
]
r = _post(publish_env, {"job_id": "job1", "clip_index": 0,
"platforms": ["instagram", "tiktok", "youtube"]})
assert r.status_code == 200, r.text
posts = stubbed["payload"]["posts"]
# First enabled match per platform; duplicate YouTube channels do not collapse.
assert [p["integration"]["id"] for p in posts] == ["ig-1", "tt-1", "yt-a"]
assert [p["settings"]["__type"] for p in posts] == \
["instagram-standalone", "tiktok-business", "youtube"]
assert [e["platform"] for e in r.json()["posted"]] == \
["instagram", "tiktok", "youtube"]
def test_no_channels_requested_is_a_400(publish_env, stubbed):
stubbed["integrations"] = [{"id": "i-tt", "identifier": "tiktok"}]
r = _post(publish_env, {"job_id": "job1", "clip_index": 0})
assert r.status_code == 400
def test_scheduled_date_in_the_past_is_a_400(publish_env, stubbed):
stubbed["integrations"] = [{"id": "i-tt", "identifier": "tiktok"}]
past = (datetime.now(timezone.utc) - timedelta(hours=1)).isoformat()
r = _post(publish_env, {"job_id": "job1", "clip_index": 0,
"integration_ids": ["i-tt"],
"scheduled_date": past})
assert r.status_code == 400
assert "past" in r.json()["detail"].lower()
assert "upload" not in stubbed["order"] and "create" not in stubbed["order"]
def test_future_scheduled_date_sets_schedule_type(publish_env, stubbed):
stubbed["integrations"] = [{"id": "i-tt", "identifier": "tiktok"}]
future = (datetime.now(timezone.utc) + timedelta(days=2)).isoformat()
r = _post(publish_env, {"job_id": "job1", "clip_index": 0,
"integration_ids": ["i-tt"],
"scheduled_date": future})
assert r.status_code == 200, r.text
assert stubbed["payload"]["type"] == "schedule"