Half of this already existed and nothing said so. `threads.pinned` has
been in the schema since the board shipped, with an index on it and a
toggle route, but it was @admin_required, reachable only from inside a
thread, and Inicio ignored it.
Who. Moderators and above, on both halves. Curating what the public
reads is the whole of a moderator's job, and content.py has said so
since the queue was built. Locking a thread rides the same route and is
still an admin's: it stops named people saying anything more to each
other, which is power over people rather than over content, and this
codebase keeps those apart everywhere else.
What is stored. A moment, not a flag — several posts can be pinned and
the newest pin goes first, so the value is the order. `pinned:
'2026-10-13T12:00:00'` in a post's own frontmatter, written only when
true; `threads.pinned_at` beside the flag the wall already had, cleared
on unpinning so that pinning again puts it where a new pin belongs. One
key carrying both means `{{ if .Params.pinned }}` still reads as a
yes/no and nothing has to be kept in step with anything.
translate.py needs nothing: it copies the whole frontmatter and rewrites
only TRANSLATED_KEYS, so a pinned post is pinned in German too. Asserted
against the real list rather than assumed.
Two ways to pin a public post — the switch beside Publicar, and one
press in the Contenido list, because deciding what the site leads with
means looking at the list rather than opening each post to find out what
is in it. Both commit; the file is the record.
Migration 10 adds the columns and recreates the wall's index, which now
names pinned_at. `CREATE INDEX IF NOT EXISTS` leaves an existing index
exactly as it is, so without that a running server keeps the old
definition forever while a fresh install gets the new one. Nothing
breaks either way, which is the problem.
Checked rather than assumed: built with Hugo 0.135.0 and the pipeline's
flags, two pinned posts come out above a newer unpinned one and in
pin order rather than post order, with the pill on the cards and on the
article. And the wall rendered at 390px, where the pinned thread leads
and nothing overflows.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NizVpJ2dwzCbjCrTLCjeHn
938 lines
38 KiB
Python
938 lines
38 KiB
Python
"""The editor.
|
|
|
|
Gitea is replaced by a dictionary. What matters here is not that HTTP works —
|
|
`requests` can be trusted for that — but that the files this produces are the
|
|
files `scripts/translate.py` expects, because a post the pipeline cannot parse
|
|
publishes in Spanish and is never translated, silently. Several tests therefore
|
|
import the real translate.py and run its parser over what the editor wrote.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import importlib.util
|
|
import io
|
|
import sys
|
|
from datetime import date as date_type
|
|
from datetime import datetime
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
|
|
from apps.board import content, gitea
|
|
from apps.board.tests.conftest import FakeRepo # noqa: F401 (used by the `repo` fixture)
|
|
|
|
REPO_ROOT = Path(__file__).resolve().parents[3]
|
|
|
|
|
|
def _load_translate():
|
|
"""Import scripts/translate.py directly — it is a script, not a package."""
|
|
sys.path.insert(0, str(REPO_ROOT / "scripts"))
|
|
spec = importlib.util.spec_from_file_location(
|
|
"vl_translate", REPO_ROOT / "scripts" / "translate.py")
|
|
module = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(module)
|
|
return module
|
|
|
|
|
|
translate = _load_translate()
|
|
|
|
|
|
@pytest.fixture
|
|
def editor(db, make_member, sign_in):
|
|
"""An admin. The editor commits through the server's own content token
|
|
now, so there is nothing to store per person."""
|
|
member_id = make_member("editora", role="admin")
|
|
sign_in(member_id)
|
|
return member_id
|
|
|
|
|
|
def publish(post, title="Sabores del barrio", body="Texto del artículo.", **extra):
|
|
data = {"title": title, "body": body, "date": "2026-09-25"}
|
|
data.update(extra)
|
|
return post("/comunidad/contenido/post/nuevo", data)
|
|
|
|
|
|
# --- the contract with the pipeline --------------------------------------
|
|
|
|
def test_the_filename_is_one_translate_py_can_parse(repo, editor, post):
|
|
publish(post)
|
|
path, = repo.files
|
|
assert path == "content/post/2026-09-25-sabores-del-barrio.es.md"
|
|
assert translate.split_lang(Path(path)) == ("2026-09-25-sabores-del-barrio", "es")
|
|
|
|
|
|
def test_accents_are_folded_not_dropped():
|
|
assert content.slugify("Gastronomía en Viena") == "gastronomia-en-viena"
|
|
assert content.slugify("¿Qué comer?") == "que-comer"
|
|
assert content.slugify("—") == "sin-titulo"
|
|
|
|
|
|
def test_the_frontmatter_marks_an_authored_source(repo, editor, post):
|
|
publish(post, description="Un resumen.")
|
|
path, = repo.files
|
|
fm, body = translate.split_frontmatter(repo.files[path].decode())
|
|
assert fm["lang"] == "es"
|
|
assert fm["manual_translation"] is False
|
|
assert "categories" not in fm # the taxonomy is gone, not emptied
|
|
assert "translated_from" not in fm # what makes it a source, not output
|
|
assert not translate.is_generated(fm)
|
|
assert body.strip() == "Texto del artículo."
|
|
|
|
|
|
def test_two_posts_with_one_title_land_on_different_days(repo, editor, post):
|
|
publish(post, title="Resumen del mes", date="2026-09-25")
|
|
publish(post, title="Resumen del mes", date="2026-10-25")
|
|
assert sorted(repo.files) == [
|
|
"content/post/2026-09-25-resumen-del-mes.es.md",
|
|
"content/post/2026-10-25-resumen-del-mes.es.md",
|
|
]
|
|
|
|
|
|
def test_the_freeze_toggle_round_trips(repo, editor, post, client):
|
|
publish(post, manual_translation="on")
|
|
path, = repo.files
|
|
fm, _ = translate.split_frontmatter(repo.files[path].decode())
|
|
assert translate.is_frozen(fm)
|
|
|
|
name = path.rsplit("/", 1)[1]
|
|
body = client.get(f"/comunidad/contenido/post/editar/{name}").get_data(as_text=True)
|
|
assert 'name="manual_translation" checked' in body.replace(" ", " ")
|
|
|
|
|
|
def test_pages_are_not_dated(repo, editor, post):
|
|
post("/comunidad/contenido/page/nuevo", {"title": "Acerca", "body": "Quiénes somos."})
|
|
assert list(repo.files) == ["content/page/acerca.es.md"]
|
|
|
|
|
|
def test_the_commit_message_does_not_skip_translation(repo, editor, post):
|
|
publish(post)
|
|
assert repo.commits and all("[skip-translate]" not in m for m in repo.commits)
|
|
|
|
|
|
# --- concurrency and safety ----------------------------------------------
|
|
|
|
def test_a_stale_sha_is_refused_with_something_readable(repo, editor, post, client):
|
|
publish(post)
|
|
path, = repo.files
|
|
name = path.rsplit("/", 1)[1]
|
|
repo.files[path] = "---\ntitle: Otra cosa\n---\n\nAlguien llegó antes.\n".encode()
|
|
|
|
response = post(f"/comunidad/contenido/post/editar/{name}",
|
|
{"title": "Mi versión", "body": "Texto", "date": "2026-09-25",
|
|
"sha": "unasha-vieja"})
|
|
assert response.status_code == 400
|
|
assert "Alguien más guardó" in response.get_data(as_text=True)
|
|
assert b"Alguien" in repo.files[path] # the other edit survived
|
|
|
|
|
|
@pytest.mark.parametrize("name", [
|
|
"..%2F..%2Fetc%2Fpasswd", ".woodpecker.yml", "config.yaml",
|
|
"hola.de.md", "hola.es.md.bak", "a/b.es.md",
|
|
])
|
|
def test_only_spanish_source_filenames_are_reachable(repo, editor, client, name):
|
|
assert client.get(f"/comunidad/contenido/post/editar/{name}").status_code == 404
|
|
|
|
|
|
def test_a_generated_sibling_is_hidden_and_refused(repo, editor, client):
|
|
repo.files["content/post/hola.es.md"] = (
|
|
b"---\ntitle: Hola\nlang: es\ntranslated_from: de\n---\n\nGenerado.\n")
|
|
assert "Hola" not in client.get("/comunidad/contenido").get_data(as_text=True)
|
|
|
|
response = client.get("/comunidad/contenido/post/editar/hola.es.md",
|
|
follow_redirects=True)
|
|
assert "traducción automática" in response.get_data(as_text=True)
|
|
|
|
|
|
def test_deleting_leaves_the_siblings_to_the_pipeline(repo, editor, post):
|
|
publish(post)
|
|
path, = repo.files
|
|
repo.files["content/post/2026-09-25-sabores-del-barrio.de.md"] = b"generado"
|
|
|
|
post(f"/comunidad/contenido/post/eliminar/{path.rsplit('/', 1)[1]}")
|
|
assert path not in repo.files
|
|
# Reaping the German file is translate.py's job, on the next run.
|
|
assert "content/post/2026-09-25-sabores-del-barrio.de.md" in repo.files
|
|
|
|
|
|
# --- who may publish -----------------------------------------------------
|
|
|
|
CONTENT_ROUTES = [
|
|
"/comunidad/contenido",
|
|
"/comunidad/contenido/post",
|
|
"/comunidad/contenido/post/nuevo",
|
|
]
|
|
|
|
|
|
@pytest.mark.parametrize("path", CONTENT_ROUTES)
|
|
def test_a_plain_member_cannot_publish(repo, client, make_member, sign_in, path):
|
|
"""Posting to the board is not the same permission as publishing to the
|
|
public site, so the editor is admins and the owner only."""
|
|
sign_in(make_member("vecina"))
|
|
assert client.get(path).status_code == 403
|
|
|
|
|
|
@pytest.mark.parametrize("path", CONTENT_ROUTES)
|
|
def test_anonymous_is_sent_to_login(repo, client, path):
|
|
response = client.get(path)
|
|
assert response.status_code == 302
|
|
assert "/comunidad/login" in response.headers["Location"]
|
|
|
|
|
|
def test_a_commit_is_attributed_to_whoever_wrote_it(repo, client, post, editor, db):
|
|
"""One token does the committing, so the author has to be named explicitly
|
|
or git history would credit every post to the same service account and
|
|
there would be nobody to ask about a page a year from now."""
|
|
publish(post)
|
|
|
|
assert repo.authors, "nothing was committed"
|
|
assert repo.authors[-1] == {"name": "Editora", "email": "editora@example.com"}
|
|
|
|
|
|
# --- images --------------------------------------------------------------
|
|
|
|
def _image(name="foto.jpg", size=32):
|
|
return (io.BytesIO(b"x" * size), name)
|
|
|
|
|
|
def test_an_uploaded_image_is_committed_and_referenced(repo, editor, post):
|
|
publish(post, picture=_image())
|
|
uploads = [p for p in repo.files if p.startswith("static/uploads/")]
|
|
assert len(uploads) == 1
|
|
document = repo.files["content/post/2026-09-25-sabores-del-barrio.es.md"].decode()
|
|
fm, _ = translate.split_frontmatter(document)
|
|
assert fm["image"].startswith("/uploads/")
|
|
assert fm["image"].endswith(".jpg")
|
|
|
|
|
|
def test_two_uploads_of_one_filename_do_not_collide(repo, editor, post):
|
|
publish(post, title="Uno", picture=_image())
|
|
publish(post, title="Dos", picture=_image())
|
|
uploads = [p for p in repo.files if p.startswith("static/uploads/")]
|
|
assert len(uploads) == 2
|
|
|
|
|
|
def test_a_script_disguised_as_an_image_is_refused(repo, editor, post):
|
|
response = publish(post, picture=_image("payload.svg"))
|
|
assert response.status_code == 400
|
|
assert "Formato de imagen no admitido" in response.get_data(as_text=True)
|
|
assert not repo.files
|
|
|
|
|
|
def test_an_oversized_image_says_so_instead_of_failing(app, repo, editor, post):
|
|
app.config["UPLOAD_MAX_BYTES"] = 1024
|
|
response = publish(post, picture=_image(size=4096))
|
|
assert response.status_code == 400
|
|
assert "máximo" in response.get_data(as_text=True)
|
|
|
|
|
|
# --- listing, preview, cache ---------------------------------------------
|
|
|
|
def test_the_listing_reads_each_file_once(repo, editor, client):
|
|
publish_paths = {
|
|
"content/post/2026-09-01-uno.es.md": b"---\ntitle: Uno\ndate: 2026-09-01\nlang: es\n---\n\nA\n",
|
|
"content/post/2026-09-02-dos.es.md": b"---\ntitle: Dos\ndate: 2026-09-02\nlang: es\n---\n\nB\n",
|
|
}
|
|
repo.files.update(publish_paths)
|
|
|
|
client.get("/comunidad/contenido")
|
|
after_first = repo.reads
|
|
assert after_first == 2
|
|
|
|
body = client.get("/comunidad/contenido").get_data(as_text=True)
|
|
assert repo.reads == after_first # served from content_cache
|
|
assert "Uno" in body and "Dos" in body
|
|
|
|
|
|
def test_the_listing_refreshes_when_a_file_changes(repo, editor, client):
|
|
repo.files["content/post/2026-09-01-uno.es.md"] = (
|
|
b"---\ntitle: Uno\ndate: 2026-09-01\nlang: es\n---\n\nA\n")
|
|
client.get("/comunidad/contenido")
|
|
repo.files["content/post/2026-09-01-uno.es.md"] = (
|
|
b"---\ntitle: Uno corregido\ndate: 2026-09-01\nlang: es\n---\n\nA\n")
|
|
body = client.get("/comunidad/contenido").get_data(as_text=True)
|
|
assert "Uno corregido" in body
|
|
|
|
|
|
def test_the_preview_renders_markdown_and_escapes_html(repo, editor, post):
|
|
response = post("/comunidad/contenido/post/vista-previa", {
|
|
"title": "Prueba", "date": "2026-09-25",
|
|
"body": "**fuerte** y <script>alert(1)</script>",
|
|
})
|
|
page = response.get_data(as_text=True)
|
|
assert "<strong>fuerte</strong>" in page
|
|
assert "<script>alert(1)</script>" not in page
|
|
assert not repo.files # a preview must not publish anything
|
|
|
|
|
|
# --- who may write which collection --------------------------------------
|
|
#
|
|
# One blueprint, two answers. A moderator curates what the public reads, so
|
|
# posts are theirs. The static pages are the site's own structure — "Acerca de",
|
|
# contact — and changing those is an administrator's job. The check lives in
|
|
# _collection_or_404, which every route here calls before doing anything.
|
|
|
|
def test_a_moderator_may_publish_a_post(repo, db, post, make_member, sign_in):
|
|
sign_in(make_member("luisa", role="moderator"))
|
|
|
|
response = post("/comunidad/contenido/post/nuevo",
|
|
{"title": "Aviso", "body": "Texto.", "date": "2026-09-25"})
|
|
|
|
assert response.status_code == 302
|
|
assert list(repo.files) == ["content/post/2026-09-25-aviso.es.md"]
|
|
|
|
|
|
def test_a_moderator_may_not_touch_the_static_pages(repo, client, post,
|
|
make_member, sign_in):
|
|
sign_in(make_member("luisa", role="moderator"))
|
|
|
|
assert client.get("/comunidad/contenido/page").status_code == 403
|
|
assert client.get("/comunidad/contenido/page/nuevo").status_code == 403
|
|
assert post("/comunidad/contenido/page/nuevo",
|
|
{"title": "Acerca de", "body": "Texto."}).status_code == 403
|
|
assert repo.files == {}
|
|
|
|
|
|
def test_a_member_may_not_use_the_editor_at_all(repo, client, post,
|
|
make_member, sign_in):
|
|
"""Their route to the public site is a proposal, which waits for somebody."""
|
|
sign_in(make_member("maria"))
|
|
|
|
for path in ("/comunidad/contenido", "/comunidad/contenido/post/nuevo",
|
|
"/comunidad/contenido/page/nuevo"):
|
|
assert client.get(path).status_code == 403, path
|
|
assert repo.files == {}
|
|
|
|
|
|
def test_the_tabs_only_offer_what_this_member_may_open(repo, client, make_member, sign_in):
|
|
"""A tab that always produces a 403 is worse than no tab."""
|
|
sign_in(make_member("luisa", role="moderator"))
|
|
assert "Páginas" not in client.get("/comunidad/contenido").get_data(as_text=True)
|
|
|
|
sign_in(make_member("admina", role="admin"))
|
|
assert "Páginas" in client.get("/comunidad/contenido").get_data(as_text=True)
|
|
|
|
|
|
# --- when the git server refuses the token -------------------------------
|
|
#
|
|
# This is the shape of a real outage, and it went undiagnosed for two phases.
|
|
# `_content_request` answered 401/403 with PermissionError, for a caller
|
|
# (tokens.py) that had been deleted — so the editor 500ed and approving a
|
|
# submission blamed a missing photograph. Both are asserted here, from the
|
|
# outside, because both were invisible from the inside.
|
|
|
|
class RefusingRepo:
|
|
"""Gitea with a token that has no repository scope: 403 to everything."""
|
|
|
|
class Response:
|
|
status_code = 403
|
|
|
|
@staticmethod
|
|
def json():
|
|
return {}
|
|
|
|
def request(self, *args, **kwargs):
|
|
return self.Response()
|
|
|
|
|
|
@pytest.fixture
|
|
def refused(monkeypatch):
|
|
monkeypatch.setattr(gitea, "requests", RefusingRepo())
|
|
|
|
|
|
def test_the_editor_says_what_is_wrong_instead_of_500ing(
|
|
refused, client, make_member, sign_in):
|
|
sign_in(make_member("admina", role="admin"))
|
|
|
|
for path in ("/comunidad/contenido", "/comunidad/contenido/page"):
|
|
response = client.get(path)
|
|
assert response.status_code == 200, path
|
|
body = response.get_data(as_text=True)
|
|
assert "CONTENT_TOKEN" in body and "repository" in body, path
|
|
|
|
|
|
def test_a_refused_write_does_not_escape_as_a_permission_error(
|
|
refused, client, post, make_member, sign_in):
|
|
"""PermissionError is an OSError, which is how it ended up being reported as
|
|
a missing file somewhere else entirely. It must not leave gitea.py."""
|
|
sign_in(make_member("admina", role="admin"))
|
|
|
|
response = post("/comunidad/contenido/post/nuevo",
|
|
{"title": "Aviso", "body": "Texto.", "date": "2026-09-25"})
|
|
|
|
assert response.status_code == 400 # back to the form, not a 500
|
|
assert "rechazó el token" in response.get_data(as_text=True)
|
|
|
|
|
|
def test_an_unexpected_error_renders_the_site_is_own_page(app, client, make_member,
|
|
sign_in, monkeypatch):
|
|
"""Flask's default 500 page is in English, has no way back, and says nothing.
|
|
Ours says something and is logged with the path.
|
|
|
|
PROPAGATE_EXCEPTIONS off on purpose: the fixture sets TESTING, which re-raises
|
|
instead of running the handler, and the handler is the subject here."""
|
|
app.config["PROPAGATE_EXCEPTIONS"] = False
|
|
sign_in(make_member("maria"))
|
|
|
|
def explode():
|
|
raise RuntimeError("something nobody anticipated")
|
|
monkeypatch.setattr("apps.board.board.get_db", explode)
|
|
|
|
response = client.get("/comunidad/muro")
|
|
|
|
assert response.status_code == 500
|
|
body = response.get_data(as_text=True)
|
|
assert "Algo falló de nuestro lado" in body
|
|
assert "Viena Latina" in body # the site's chrome, not Flask's
|
|
|
|
|
|
# --- the byline ----------------------------------------------------------
|
|
#
|
|
# The commit has named the author since the editor was built; the page did not,
|
|
# so a reader could not tell whose article they were reading. These check the
|
|
# three places it can go wrong: publishing, approving somebody else's proposal,
|
|
# and editing — where re-signing the post with the editor's name would be worse
|
|
# than having no byline at all.
|
|
|
|
def test_a_published_post_names_its_author(repo, db, post, make_member, sign_in):
|
|
import yaml
|
|
author = make_member("luisa", role="moderator")
|
|
db.execute("UPDATE members SET display_name = ?, profile_published = 1 WHERE id = ?",
|
|
("Luisa Fernández", author))
|
|
sign_in(author)
|
|
|
|
publish(post)
|
|
|
|
path, = repo.files
|
|
front = yaml.safe_load(repo.files[path].decode().split("---")[1])
|
|
assert front["author"] == "Luisa Fernández"
|
|
assert front["author_url"] == "/luisa"
|
|
|
|
|
|
def test_without_a_published_page_the_byline_does_not_link(
|
|
repo, db, post, make_member, sign_in):
|
|
import yaml
|
|
author = make_member("luisa", role="moderator")
|
|
db.execute("UPDATE members SET profile_published = 0 WHERE id = ?", (author,))
|
|
sign_in(author)
|
|
|
|
publish(post)
|
|
|
|
path, = repo.files
|
|
front = yaml.safe_load(repo.files[path].decode().split("---")[1])
|
|
assert front["author"] == "Luisa"
|
|
assert "author_url" not in front # a byline linking to a 404 is worse
|
|
|
|
|
|
def test_editing_a_post_keeps_the_author_it_already_had(
|
|
repo, editor, post, client):
|
|
"""The one that matters. An admin fixing a typo in somebody's article must
|
|
not end up signing it — the same rule the board has about editing other
|
|
people's words."""
|
|
import yaml
|
|
repo.files["content/post/2026-09-25-de-otro.es.md"] = (
|
|
"---\ntitle: De otro\ndate: 2026-09-25\nlang: es\n"
|
|
"manual_translation: false\nauthor: Salvador Dalí\nauthor_url: /salvador\n"
|
|
"---\n\nTexto.\n").encode("utf-8")
|
|
|
|
page = client.get("/comunidad/contenido/post/editar/2026-09-25-de-otro.es.md")
|
|
body = page.get_data(as_text=True)
|
|
assert 'name="author" value="Salvador Dalí"' in body
|
|
assert 'name="author_url" value="/salvador"' in body
|
|
|
|
post("/comunidad/contenido/post/editar/2026-09-25-de-otro.es.md",
|
|
{"title": "De otro", "body": "Texto corregido.", "date": "2026-09-25",
|
|
"sha": repo._sha(repo.files["content/post/2026-09-25-de-otro.es.md"]),
|
|
"author": "Salvador Dalí", "author_url": "/salvador"})
|
|
|
|
front = yaml.safe_load(
|
|
repo.files["content/post/2026-09-25-de-otro.es.md"].decode().split("---")[1])
|
|
assert front["author"] == "Salvador Dalí"
|
|
assert front["author_url"] == "/salvador"
|
|
|
|
|
|
def test_an_author_url_cannot_point_off_the_site(repo, editor, post):
|
|
"""It arrives as a hidden field, which is a convention and not a promise."""
|
|
import yaml
|
|
post("/comunidad/contenido/post/nuevo",
|
|
{"title": "Aviso", "body": "Texto.", "date": "2026-09-25",
|
|
"author": "Alguien", "author_url": "https://ejemplo.invalid/premio"})
|
|
|
|
path, = repo.files
|
|
front = yaml.safe_load(repo.files[path].decode().split("---")[1])
|
|
assert "author_url" not in front
|
|
|
|
|
|
def test_a_page_carries_no_byline(repo, editor, post):
|
|
"""Acerca de and Contacto are the site speaking, not a person."""
|
|
import yaml
|
|
post("/comunidad/contenido/page/nuevo", {"title": "Acerca de", "body": "Texto."})
|
|
|
|
path, = repo.files
|
|
front = yaml.safe_load(repo.files[path].decode().split("---")[1])
|
|
assert "author" not in front
|
|
|
|
|
|
# --- where a page sits in the public menu --------------------------------
|
|
#
|
|
# The menu used to be three names in config.yaml, so a page published here never
|
|
# appeared on the site and the three languages had to be kept in step by hand.
|
|
# It is built from the pages now, which makes these two fields the whole of the
|
|
# navigation: `parent` nests a page under another, `weight` orders them.
|
|
|
|
def test_a_page_records_where_it_goes_in_the_menu(repo, editor, post):
|
|
import yaml
|
|
post("/comunidad/contenido/page/nuevo",
|
|
{"title": "Estatutos", "body": "Texto.", "parent": "acerca", "weight": "10"})
|
|
|
|
path, = repo.files
|
|
front = yaml.safe_load(repo.files[path].decode().split("---")[1])
|
|
assert front["parent"] == "acerca"
|
|
assert front["weight"] == 10
|
|
|
|
|
|
def test_a_top_level_page_carries_no_parent_line(repo, editor, post):
|
|
"""Rather than `parent: ""`, which is a line somebody has to decide whether
|
|
to worry about."""
|
|
import yaml
|
|
post("/comunidad/contenido/page/nuevo", {"title": "Contacto", "body": "Texto."})
|
|
|
|
path, = repo.files
|
|
assert "parent" not in yaml.safe_load(repo.files[path].decode().split("---")[1])
|
|
|
|
|
|
def test_a_parent_that_is_not_a_basename_is_dropped(repo, editor, post):
|
|
"""It arrives from a select, so anything else is somebody crafting a
|
|
request — and a parent with a slash in it would be a path, not a page."""
|
|
import yaml
|
|
post("/comunidad/contenido/page/nuevo",
|
|
{"title": "Estatutos", "body": "Texto.", "parent": "../../etc/passwd"})
|
|
|
|
path, = repo.files
|
|
assert "parent" not in yaml.safe_load(repo.files[path].decode().split("---")[1])
|
|
|
|
|
|
def test_a_page_keeps_its_place_when_edited(repo, editor, post, client):
|
|
repo.files["content/page/acerca.es.md"] = (
|
|
"---\ntitle: Acerca\nlang: es\n---\n\nTexto.\n").encode("utf-8")
|
|
repo.files["content/page/estatutos.es.md"] = (
|
|
"---\ntitle: Estatutos\nlang: es\nparent: acerca\nweight: 10\n---\n\nTexto.\n"
|
|
).encode("utf-8")
|
|
|
|
body = client.get("/comunidad/contenido/page/editar/estatutos.es.md").get_data(as_text=True)
|
|
assert 'value="acerca" selected' in body or 'value="acerca" selected' in body
|
|
assert 'value="10"' in body
|
|
|
|
|
|
def test_the_parent_select_never_offers_the_page_itself(repo, editor, client):
|
|
repo.files["content/page/acerca.es.md"] = (
|
|
"---\ntitle: Acerca\nlang: es\n---\n\nTexto.\n").encode("utf-8")
|
|
repo.files["content/page/contacto.es.md"] = (
|
|
"---\ntitle: Contacto\nlang: es\n---\n\nTexto.\n").encode("utf-8")
|
|
|
|
body = client.get("/comunidad/contenido/page/editar/acerca.es.md").get_data(as_text=True)
|
|
|
|
assert 'value="contacto"' in body
|
|
assert 'value="acerca"' not in body
|
|
|
|
|
|
def test_a_post_has_no_menu_fields(repo, editor, client):
|
|
"""Articles are dated and listed, never in the menu."""
|
|
body = client.get("/comunidad/contenido/post/nuevo").get_data(as_text=True)
|
|
assert 'name="parent"' not in body
|
|
assert 'name="weight"' not in body
|
|
|
|
|
|
def test_a_parent_that_has_been_deleted_is_kept_and_named(repo, editor, client):
|
|
"""Otherwise the next save would quietly promote the page to the top of the
|
|
menu, and nobody would connect that to having deleted another page."""
|
|
repo.files["content/page/estatutos.es.md"] = (
|
|
"---\ntitle: Estatutos\nlang: es\nparent: borrada\n---\n\nTexto.\n"
|
|
).encode("utf-8")
|
|
|
|
body = client.get("/comunidad/contenido/page/editar/estatutos.es.md").get_data(as_text=True)
|
|
|
|
assert 'value="borrada" selected' in body
|
|
assert "no encontrada" in body
|
|
|
|
|
|
# --- events, which are posts with a date of their own ---------------------
|
|
|
|
def test_an_event_carries_its_own_date_and_an_ics(repo, editor, post):
|
|
"""The post's `date` is when it was announced; `event_date` is when it
|
|
happens, and the two are weeks apart in the normal case."""
|
|
import yaml
|
|
post("/comunidad/contenido/post/nuevo",
|
|
{"title": "Feria de otoño", "body": "Ven.", "date": "2026-10-03",
|
|
"event_date": "2026-10-24",
|
|
"event_time": "18:30", "event_location": "Plaza de Ottakring"})
|
|
|
|
path, = repo.files
|
|
front = yaml.safe_load(repo.files[path].decode().split("---")[1])
|
|
# The day the writer chose, and the clock attached to it — see `stamp`.
|
|
assert front["date"].date().isoformat() == "2026-10-03"
|
|
assert front["event_date"] == "2026-10-24"
|
|
assert front["event_time"] == "18:30"
|
|
assert front["event_location"] == "Plaza de Ottakring"
|
|
# Hugo builds an .ics only for pages that ask for one.
|
|
assert front["outputs"] == ["HTML", "ics"]
|
|
|
|
|
|
def test_a_post_with_no_event_date_is_simply_an_article(repo, editor, post):
|
|
"""There is nothing to tick any more, so there is no "said it was an event
|
|
and did not say when" to refuse. The date is the whole declaration."""
|
|
import yaml
|
|
response = post("/comunidad/contenido/post/nuevo",
|
|
{"title": "Algún día", "body": "Texto.", "date": "2026-10-03"})
|
|
|
|
assert response.status_code == 302
|
|
path, = repo.files
|
|
front = yaml.safe_load(repo.files[path].decode().split("---")[1])
|
|
assert "event_date" not in front
|
|
|
|
|
|
def test_a_nonsense_hour_is_refused(repo, editor, post):
|
|
response = post("/comunidad/contenido/post/nuevo",
|
|
{"title": "Feria", "body": "Texto.", "date": "2026-10-03",
|
|
"event_date": "2026-10-24", "event_time": "25:99"})
|
|
|
|
assert response.status_code == 400
|
|
assert repo.files == {}
|
|
|
|
|
|
def test_an_ordinary_post_carries_no_event_lines(repo, editor, post):
|
|
"""Rather than three empty keys for somebody to wonder about."""
|
|
import yaml
|
|
post("/comunidad/contenido/post/nuevo",
|
|
{"title": "Un artículo", "body": "Texto.", "date": "2026-10-03",
|
|
"event_date": ""})
|
|
|
|
path, = repo.files
|
|
front = yaml.safe_load(repo.files[path].decode().split("---")[1])
|
|
for key in ("event_date", "event_time", "event_location", "outputs"):
|
|
assert key not in front, key
|
|
|
|
|
|
def test_an_event_keeps_its_date_when_edited(repo, editor, post, client):
|
|
import yaml
|
|
repo.files["content/post/2026-10-03-feria.es.md"] = (
|
|
"---\ntitle: Feria\ndate: 2026-10-03\nlang: es\nmanual_translation: false\n"
|
|
"event_date: '2026-10-24'\nevent_time: '18:30'\n"
|
|
"event_location: La plaza\n---\n\nVen.\n").encode("utf-8")
|
|
|
|
body = client.get("/comunidad/contenido/post/editar/2026-10-03-feria.es.md").get_data(as_text=True)
|
|
assert 'value="2026-10-24"' in body
|
|
assert 'value="18:30"' in body
|
|
|
|
post("/comunidad/contenido/post/editar/2026-10-03-feria.es.md",
|
|
{"title": "Feria", "body": "Ven pronto.", "date": "2026-10-03",
|
|
"event_date": "2026-10-24",
|
|
"event_time": "18:30", "event_location": "La plaza",
|
|
"sha": repo._sha(repo.files["content/post/2026-10-03-feria.es.md"])})
|
|
|
|
front = yaml.safe_load(
|
|
repo.files["content/post/2026-10-03-feria.es.md"].decode().split("---")[1])
|
|
assert front["event_date"] == "2026-10-24"
|
|
|
|
|
|
# --- said out loud: a machine wrote this ----------------------------------
|
|
|
|
def test_a_post_marked_as_ai_says_so_in_its_own_frontmatter(repo, editor, post):
|
|
"""The file in the repository is the record of what was published, so the
|
|
disclosure travels with it rather than living in a database the public
|
|
site cannot read."""
|
|
publish(post, ai_generated="on")
|
|
path, = repo.files
|
|
fm, _ = translate.split_frontmatter(repo.files[path].decode())
|
|
assert fm["ai_generated"] is True
|
|
|
|
|
|
def test_an_ordinary_post_carries_no_such_line(repo, editor, post):
|
|
"""`ai_generated: false` on every post ever written is noise in the
|
|
repository and a question in the mind of whoever reads the file."""
|
|
publish(post)
|
|
path, = repo.files
|
|
fm, _ = translate.split_frontmatter(repo.files[path].decode())
|
|
assert "ai_generated" not in fm
|
|
|
|
|
|
def test_correcting_a_typo_does_not_quietly_remove_the_disclosure(
|
|
repo, editor, post, client):
|
|
"""The failure this is shaped around: a flag loaded into the form but not
|
|
written back out again survives exactly until somebody fixes a comma.
|
|
"""
|
|
publish(post, ai_generated="on")
|
|
path, = repo.files
|
|
name = path.rsplit("/", 1)[1]
|
|
|
|
form = client.get(f"/comunidad/contenido/post/editar/{name}").get_data(as_text=True)
|
|
assert 'name="ai_generated" checked' in form.replace(" ", " ")
|
|
|
|
post(f"/comunidad/contenido/post/editar/{name}",
|
|
{"title": "Sabores del barrio", "body": "Texto corregido.",
|
|
"date": "2026-09-25", "sha": repo._sha(repo.files[path]), "ai_generated": "on"})
|
|
fm, _ = translate.split_frontmatter(repo.files[path].decode())
|
|
assert fm["ai_generated"] is True
|
|
|
|
|
|
def test_the_disclosure_can_be_taken_off_again(repo, editor, post, client):
|
|
"""Somebody rewrites the text themselves. The switch is theirs to turn
|
|
off, and the line goes with it."""
|
|
publish(post, ai_generated="on")
|
|
path, = repo.files
|
|
name = path.rsplit("/", 1)[1]
|
|
post(f"/comunidad/contenido/post/editar/{name}",
|
|
{"title": "Sabores del barrio", "body": "Reescrito a mano.",
|
|
"date": "2026-09-25", "sha": repo._sha(repo.files[path])})
|
|
fm, _ = translate.split_frontmatter(repo.files[path].decode())
|
|
assert "ai_generated" not in fm
|
|
|
|
|
|
def test_the_disclosure_is_not_one_of_the_keys_translation_rewrites(repo, editor, post):
|
|
"""A translated post was still machine-written, so the flag has to reach
|
|
the German and Portuguese siblings untouched.
|
|
|
|
`translate_file` copies the whole frontmatter (`new_fm = dict(fm)`) and
|
|
rewrites only TRANSLATED_KEYS, so this needs no change to the pipeline —
|
|
asserted against the real list rather than assumed, because a key quietly
|
|
added to it would send the flag through a translation engine.
|
|
"""
|
|
publish(post, ai_generated="on")
|
|
path, = repo.files
|
|
fm, _ = translate.split_frontmatter(repo.files[path].decode())
|
|
assert fm["ai_generated"] is True
|
|
assert "ai_generated" not in translate.TRANSLATED_KEYS
|
|
|
|
|
|
# --- what the site leads with ---------------------------------------------
|
|
|
|
def test_a_pinned_post_carries_the_moment_it_was_pinned(repo, editor, post):
|
|
"""One key for both the flag and the order. Several posts can be pinned and
|
|
the newest pin goes first, so the value has to say when — and it is written
|
|
only when it is true, like the IA disclosure, so no post carries a line
|
|
reading `pinned: false` for somebody to wonder about."""
|
|
publish(post, pinned="on")
|
|
path, = repo.files
|
|
fm, _ = translate.split_frontmatter(repo.files[path].decode())
|
|
assert isinstance(fm["pinned"], str) and fm["pinned"].startswith("20")
|
|
|
|
publish(post, title="Sin fijar", pinned="")
|
|
other = [p for p in repo.files if p != path][0]
|
|
fm, _ = translate.split_frontmatter(repo.files[other].decode())
|
|
assert "pinned" not in fm
|
|
|
|
|
|
def test_editing_a_pinned_post_does_not_count_as_pinning_it_again(repo, editor, post):
|
|
"""Otherwise fixing a typo would carry it above everything pinned since,
|
|
which is the same shape of bug as the publication date and lands in the
|
|
same place."""
|
|
publish(post, pinned="on")
|
|
path, = repo.files
|
|
before, _ = translate.split_frontmatter(repo.files[path].decode())
|
|
|
|
post(f"/comunidad/contenido/post/editar/{path.rsplit('/', 1)[1]}",
|
|
{"title": "Sabores del barrio", "body": "Corregido.", "date": "2026-09-25",
|
|
"pinned": "on", "pinned_at": before["pinned"],
|
|
"sha": repo._sha(repo.files[path])})
|
|
|
|
after, _ = translate.split_frontmatter(repo.files[path].decode())
|
|
assert after["pinned"] == before["pinned"]
|
|
|
|
|
|
def test_the_pin_survives_an_edit_that_says_nothing_about_it(repo, editor, post, client):
|
|
"""The form loads it back the way it was left. A flag read into the form
|
|
but not written out again is a flag that one correction quietly removes."""
|
|
publish(post, pinned="on")
|
|
path, = repo.files
|
|
name = path.rsplit("/", 1)[1]
|
|
page = client.get(f"/comunidad/contenido/post/editar/{name}").get_data(as_text=True)
|
|
assert 'name="pinned" checked' in page.replace(' >', '>')
|
|
|
|
|
|
def test_pinning_from_the_list_commits_without_opening_the_post(repo, editor, post):
|
|
publish(post)
|
|
path, = repo.files
|
|
name = path.rsplit("/", 1)[1]
|
|
|
|
post(f"/comunidad/contenido/post/fijar/{name}", {"value": "1"})
|
|
fm, body = translate.split_frontmatter(repo.files[path].decode())
|
|
assert fm["pinned"] and body.strip() == "Texto del artículo."
|
|
|
|
post(f"/comunidad/contenido/post/fijar/{name}", {"value": "0"})
|
|
fm, body = translate.split_frontmatter(repo.files[path].decode())
|
|
assert "pinned" not in fm and body.strip() == "Texto del artículo."
|
|
|
|
|
|
def test_a_plain_member_cannot_pin_a_post(repo, post, make_member, sign_in):
|
|
sign_in(make_member("maria"))
|
|
assert post("/comunidad/contenido/post/fijar/cualquiera.es.md",
|
|
{"value": "1"}).status_code == 403
|
|
|
|
|
|
def test_a_moderator_can_pin_a_post(repo, post, make_member, sign_in):
|
|
"""Curating what the public reads is the whole of a moderator's job, and
|
|
`COLLECTIONS["post"]["role"]` has said so since the queue was built."""
|
|
sign_in(make_member("modera", role="moderator"))
|
|
publish(post)
|
|
path, = repo.files
|
|
response = post(f"/comunidad/contenido/post/fijar/{path.rsplit('/', 1)[1]}",
|
|
{"value": "1"})
|
|
assert response.status_code in (302, 303)
|
|
fm, _ = translate.split_frontmatter(repo.files[path].decode())
|
|
assert fm["pinned"]
|
|
|
|
|
|
def test_the_pin_is_not_one_of_the_keys_translation_rewrites(repo, editor, post):
|
|
"""A pinned post is pinned in German too. `translate_file` copies the whole
|
|
frontmatter and rewrites only TRANSLATED_KEYS, so this needs no change to
|
|
the pipeline — asserted against the real list, because a key quietly added
|
|
to it would send a timestamp through a translation engine."""
|
|
publish(post, pinned="on")
|
|
assert "pinned" not in translate.TRANSLATED_KEYS
|
|
|
|
|
|
def test_the_pinned_post_is_first_in_the_editors_list(repo, editor, post, client):
|
|
publish(post, title="Un aviso viejo", date="2026-01-05", pinned="on")
|
|
publish(post, title="Algo de ayer", date="2026-09-25")
|
|
|
|
page = client.get("/comunidad/contenido/post").get_data(as_text=True)
|
|
assert page.index("Un aviso viejo") < page.index("Algo de ayer")
|
|
|
|
|
|
# --- a post nobody titled -------------------------------------------------
|
|
|
|
def test_an_untitled_post_is_named_when_it_is_published(repo, editor, post):
|
|
publish(post, title="")
|
|
path, = repo.files
|
|
assert path == "content/post/2026-09-25-sin-titulo.es.md"
|
|
fm, _ = translate.split_frontmatter(repo.files[path].decode())
|
|
assert fm["title"] == "Sin Título"
|
|
|
|
|
|
def test_two_untitled_posts_on_one_day_do_not_collide(repo, editor, post):
|
|
"""The filename is what collides in a repository, not the title: both
|
|
would be `<fecha>-sin-titulo.es.md`, and the second would come back as
|
|
"somebody else saved this file while you were editing it" — a message
|
|
about a conflict that never happened. So the numbering is done against
|
|
the names already in the folder."""
|
|
publish(post, title="")
|
|
publish(post, title="")
|
|
assert sorted(repo.files) == [
|
|
"content/post/2026-09-25-sin-titulo-2.es.md",
|
|
"content/post/2026-09-25-sin-titulo.es.md",
|
|
]
|
|
fm, _ = translate.split_frontmatter(
|
|
repo.files["content/post/2026-09-25-sin-titulo-2.es.md"].decode())
|
|
assert fm["title"] == "Sin Título 2"
|
|
|
|
|
|
def test_the_same_name_is_free_again_on_another_day(repo, editor, post):
|
|
"""A dated collection only collides within its own day, so the number
|
|
starts over rather than counting up forever."""
|
|
publish(post, title="", date="2026-09-25")
|
|
publish(post, title="", date="2026-10-25")
|
|
assert sorted(repo.files) == [
|
|
"content/post/2026-09-25-sin-titulo.es.md",
|
|
"content/post/2026-10-25-sin-titulo.es.md",
|
|
]
|
|
|
|
|
|
def test_clearing_the_title_on_an_edit_does_not_walk_the_number_up(
|
|
repo, editor, post):
|
|
"""The post being edited must not count as the collision it has to avoid,
|
|
or every save would rename it one higher."""
|
|
publish(post, title="")
|
|
path, = repo.files
|
|
name = path.rsplit("/", 1)[1]
|
|
for _ in range(3):
|
|
post(f"/comunidad/contenido/post/editar/{name}",
|
|
{"title": "", "body": "Otra corrección.", "date": "2026-09-25",
|
|
"sha": repo._sha(repo.files[path])})
|
|
fm, _ = translate.split_frontmatter(repo.files[path].decode())
|
|
assert fm["title"] == "Sin Título"
|
|
assert list(repo.files) == [path]
|
|
|
|
|
|
def test_a_post_still_needs_a_body(repo, editor, post):
|
|
response = publish(post, title="", body="")
|
|
assert not repo.files
|
|
assert "cuerpo no puede estar vacío" in response.get_data(as_text=True)
|
|
|
|
|
|
# --- the order the site reads them in -------------------------------------
|
|
|
|
def test_two_posts_published_on_one_day_do_not_have_the_same_date(
|
|
repo, editor, post):
|
|
"""The bug behind «the posts are not in the order they were written».
|
|
|
|
`date: 2026-09-25` with no clock is byte-identical for everything published
|
|
that day, so Hugo falls through its sort keys to the title and the day
|
|
comes out alphabetised — permanently, because a rebuild changes nothing
|
|
about the files. The day is still the one the writer chose; the time is
|
|
only what breaks the tie.
|
|
"""
|
|
publish(post, title="Zutano llega tarde", date="2026-09-25")
|
|
publish(post, title="Abc va primero", date="2026-09-25")
|
|
|
|
dates = {}
|
|
for path, blob in repo.files.items():
|
|
fm, _ = translate.split_frontmatter(blob.decode())
|
|
dates[path] = fm["date"]
|
|
|
|
assert len(dates) == 2
|
|
for path, when in dates.items():
|
|
assert isinstance(when, datetime), f"{path} carries a bare date: {when!r}"
|
|
assert when.date() == date_type(2026, 9, 25)
|
|
# And the URL still carries only the day, so nothing anybody linked moves.
|
|
assert sorted(repo.files) == [
|
|
"content/post/2026-09-25-abc-va-primero.es.md",
|
|
"content/post/2026-09-25-zutano-llega-tarde.es.md",
|
|
]
|
|
|
|
|
|
def test_the_newest_post_is_first_in_the_editors_own_list(repo, editor, post, client):
|
|
"""Contenido sorted on the same date-only string, with the filename as the
|
|
tiebreak — and `reverse=True` reverses the filename too, so the day came
|
|
out in descending-alphabetical slug order."""
|
|
publish(post, title="Abc se publica primero", date="2026-09-25")
|
|
publish(post, title="Zutano se publica después", date="2026-09-25")
|
|
|
|
page = client.get("/comunidad/contenido/post").get_data(as_text=True)
|
|
assert page.index("Zutano se publica después") < page.index("Abc se publica primero")
|
|
|
|
|
|
def test_correcting_a_post_does_not_move_it_to_the_top(repo, editor, post):
|
|
"""An edit keeps the publication time the file already carried, as long as
|
|
the day has not moved. Without that, fixing a typo in a year-old post would
|
|
restamp it with today's clock and carry it up the page."""
|
|
publish(post, title="Una nota de hace tiempo", date="2026-09-25")
|
|
path, = repo.files
|
|
before, _ = translate.split_frontmatter(repo.files[path].decode())
|
|
|
|
post(f"/comunidad/contenido/post/editar/{path.rsplit('/', 1)[1]}",
|
|
{"title": "Una nota de hace tiempo", "body": "Corregida.",
|
|
"date": "2026-09-25", "date_stamped": before["date"].isoformat(),
|
|
"sha": repo._sha(repo.files[path])})
|
|
|
|
after, _ = translate.split_frontmatter(repo.files[path].decode())
|
|
assert after["date"] == before["date"]
|
|
|
|
|
|
def test_moving_a_post_to_another_day_restamps_it(repo, editor, post):
|
|
"""The other half: a date deliberately changed is a date changed, and the
|
|
clock that goes with it is the one it is being published at now."""
|
|
publish(post, title="Se adelanta", date="2026-09-25")
|
|
path, = repo.files
|
|
before, _ = translate.split_frontmatter(repo.files[path].decode())
|
|
|
|
post(f"/comunidad/contenido/post/editar/{path.rsplit('/', 1)[1]}",
|
|
{"title": "Se adelanta", "body": "Texto.", "date": "2026-10-01",
|
|
"date_stamped": before["date"].isoformat(),
|
|
"sha": repo._sha(repo.files[path])})
|
|
|
|
# An edit writes back to the file it opened — the filename keeps the day it
|
|
# was created with, and always has. The date Hugo sorts and builds the URL
|
|
# from is the one in the frontmatter, and that is the one that moves.
|
|
after, _ = translate.split_frontmatter(repo.files[path].decode())
|
|
assert after["date"].date() == date_type(2026, 10, 1)
|
|
assert after["date"] != before["date"]
|