vienalatina/apps/board/tests/test_tools.py
Pablo Volenski 81d9fae4a9
Identidad, tipografías, y tres herramientas de administración
The second half of the superadministrator's job: not just who may do things, but
what they get to do that nobody else does.

**Identidad** is everything that used to be frozen in config.yaml — the name and
the one-line tagline in all three languages, the association's accounts
elsewhere, a public email, a city and street, a share picture and the footer
line. It commits data/site.yaml the way Marca commits data/brand.yaml.

Hugo cannot have config.yaml overridden by a data file, so the name and tagline
are read through two new partials that prefer the data file and fall back to the
config; every template showing either calls one, so they cannot drift. A site
with no data/site.yaml builds byte-for-byte what it built before — asserted by
building both ways and diffing with the stylesheet fingerprint normalised.

The contact fields are not decoration: they become ContactPoint and
PostalAddress in the Organization schema, which is what puts an association in a
local result rather than only a web one, and the social links become sameAs,
which is how an engine knows an Instagram account and this site are one body.

**Marca** grows a typeface and a roundness. Four system stacks — nothing
downloaded, which is deliberate and a GDPR matter — or an uploaded .woff2,
sniffed by its wOF2 signature, capped at 400 KB, named ahead of the old stack so
a font that fails to load leaves a readable site. The fold-out warning covers
missing accented glyphs, file size, synthesised bold, and licensing: a font is
software, a desktop licence is not a webfont licence, and that liability follows
the platform to every organisation it is installed for. SIL OFL and Apache-2.0
are named, with seven places to find them.

**Three tools.** Estado del sistema exercises the content token against the
repository rather than checking it is non-empty — "present" was never the
problem, a wrong scope broke publishing for three phases while looking fine —
and reports mail, backups, disk and every documented setting the container does
not have. It changes nothing on purpose. Registro de actividad records the dozen
acts that change who can do what; the actor is cleared and not cascaded on
erasure, and log() never raises, because an administrator who could not be
appointed because the note about it could not be saved is worse than a gap in
the notes. Biblioteca de medios lists every picture with the posts that use it
and, finally, shows the orphans — a picture whose post was deleted has stayed in
the repository, deployed and unreferenced, for the life of this site with no way
to see one.

Two bugs found by looking at the rendered pages rather than at the tests:

**Gestión had disappeared from the superadministrator's own navigation.**
base.html asked `g.member.role in ('owner', 'admin')`, right until a role
appeared above both. 622 tests passed while it was broken, because every one of
them signed in as an admin or below. The templates now call the same
`is_at_least` the handlers do, and test_navigation.py covers the tier above
admin — verified by reintroducing the tuple and watching it fail.

And the status screen counted the tombstone as a suspended member.

Migration 8 is plain ADD COLUMNs; `activity` and `site` are new tables, so
CREATE TABLE IF NOT EXISTS covers them with no step at all. The erase guard
caught both the moment they existed, which is that test doing its job.

627 tests pass. Hugo builds clean with the pipeline's flags, both with and
without the two data files.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NizVpJ2dwzCbjCrTLCjeHn
2026-10-06 12:18:04 +00:00

261 lines
11 KiB
Python

"""The three screens the superadministrator gets, and the identity half.
Grouped in one file because they are one phase and share one question: who may
open this, and does it tell the truth about the running system.
"""
from __future__ import annotations
import json
import pytest
from apps.board import activity, identity
SCREENS = {
"/comunidad/gestion/identidad": "superadmin",
"/comunidad/gestion/estado": "superadmin",
"/comunidad/gestion/registro": "superadmin",
"/comunidad/gestion/medios": "admin",
}
@pytest.fixture
def boss(superadmin_id, sign_in):
sign_in(superadmin_id)
return superadmin_id
@pytest.mark.parametrize("url", sorted(SCREENS))
def test_every_screen_opens_for_the_superadmin(client, boss, url, repo):
assert client.get(url).status_code == 200
@pytest.mark.parametrize("url,needs", sorted(SCREENS.items()))
def test_each_screen_refuses_the_roles_below_it(client, make_member, sign_in,
url, needs, repo):
"""Medios is open to admins — they are the people who upload, and the worst
an admin can do there is remove a picture from a post they could already
have edited. The other three are the platform's."""
# Everything above the rank passes too, which is what `is_at_least` means.
allowed = {"superadmin": set(), "admin": {"admin", "owner"}}[needs]
for role in ("user", "moderator", "admin", "owner"):
sign_in(make_member(f"persona-{role}", role=role))
expected = 200 if role in allowed else 403
assert client.get(url).status_code == expected, (url, role)
# --- identity -------------------------------------------------------------
def test_the_identity_round_trips_all_three_languages(client, db, post, boss, repo):
post("/comunidad/gestion/identidad", {
"name-es": "Viena Latina", "tagline-es": "La comunidad en Viena.",
"name-de": "Wien Latina", "tagline-de": "Die Community in Wien.",
"tagline-pt-br": "A comunidade em Viena.",
"social-instagram": "https://instagram.com/vienalatina",
"email": "hola@vienalatina.com", "city": "Wien",
"footer_text": "Asociación Viena Latina",
})
body = client.get("/comunidad/gestion/identidad").get_data(as_text=True)
for value in ("Wien Latina", "Die Community in Wien.",
"A comunidade em Viena.", "https://instagram.com/vienalatina",
"hola@vienalatina.com", "Asociación Viena Latina"):
assert value in body, value
def test_an_untouched_language_is_not_written_at_all(client, db, post, boss, repo):
"""A file repeating config.yaml's own values back at it would make the
fallback meaningless and freeze today's defaults for good."""
post("/comunidad/gestion/identidad", {"tagline-es": "Sólo esto."})
names = json.loads(db.execute("SELECT names_json FROM site").fetchone()[0])
assert names == {"es": {"name": "", "tagline": "Sólo esto."}}
yaml = repo.files["data/site.yaml"].decode("utf-8")
assert "de:" not in yaml and "pt-br:" not in yaml
def test_a_social_link_that_is_not_https_is_refused(client, db, post, boss, repo):
"""These render in the footer of every public page. `javascript:` in an href
is a script running on vienalatina.com."""
response = post("/comunidad/gestion/identidad",
{"social-instagram": "javascript:alert(1)"},
follow_redirects=True)
assert "tiene que empezar por https" in response.get_data(as_text=True)
assert db.execute("SELECT COUNT(*) AS n FROM site").fetchone()["n"] == 0
def test_a_tagline_is_flattened_to_one_line(client, db, post, boss, repo):
"""A newline inside og:description is a share card that renders raggedly in
some readers and truncated in others."""
post("/comunidad/gestion/identidad", {"tagline-es": "Una línea.\n\nY otra."})
names = json.loads(db.execute("SELECT names_json FROM site").fetchone()[0])
assert names["es"]["tagline"] == "Una línea. Y otra."
def test_the_yaml_is_what_hugo_reads(client, post, boss, repo):
post("/comunidad/gestion/identidad", {
"name-es": "Viena Latina", "tagline-es": "La comunidad.",
"social-instagram": "https://instagram.com/vl",
"social-bluesky": "https://bsky.app/profile/vl",
"email": "hola@vienalatina.com", "city": "Wien",
})
yaml = repo.files["data/site.yaml"].decode("utf-8")
assert ' name: "Viena Latina"' in yaml
assert ' tagline: "La comunidad."' in yaml
# sameAs is a flat list of URLs: the names of the networks appear nowhere in
# the schema, only the addresses.
assert 'sameAs:\n - "https://instagram.com/vl"' in yaml
assert 'email: "hola@vienalatina.com"' in yaml
def test_a_quote_in_a_name_cannot_break_the_file(client, post, boss, repo):
post("/comunidad/gestion/identidad", {"name-es": 'Viena "La" Latina\\'})
yaml = repo.files["data/site.yaml"].decode("utf-8")
assert r'name: "Viena \"La\" Latina\\"' in yaml
# --- the activity log -----------------------------------------------------
def test_the_acts_that_change_power_are_recorded(client, db, post, boss, make_member):
maria = make_member("maria")
post(f"/comunidad/miembros/{maria}/rol", {"role": "moderator"})
post(f"/comunidad/miembros/{maria}/estado", {"active": "0"})
rows = db.execute(
"SELECT action, object, detail FROM activity ORDER BY id").fetchall()
assert [(r["action"], r["object"]) for r in rows] == [
("role.changed", "Maria"), ("member.suspended", "Maria")]
assert "Miembro → Moderador" in rows[0]["detail"]
def test_the_log_survives_the_person_who_wrote_it(client, db, post, boss, make_member):
"""The row stays and the name goes. That a role was changed is the
association's record; whose name was on it is the erased person's data."""
admin_id = make_member("admina", role="admin")
maria = make_member("maria")
sign_in_as = client.session_transaction
with sign_in_as() as session:
session["member_id"] = admin_id
session["csrf"] = "token-for-tests"
post(f"/comunidad/miembros/{maria}/rol", {"role": "moderator"})
with sign_in_as() as session:
session["member_id"] = boss
post(f"/comunidad/miembros/{admin_id}/eliminar")
rows = db.execute("SELECT actor_id, action FROM activity "
"WHERE action = 'role.changed'").fetchall()
assert len(rows) == 1
assert rows[0]["actor_id"] is None
def test_a_broken_log_does_not_break_the_thing_it_records(app, db, boss,
make_member, monkeypatch):
"""An administrator who could not be appointed because the note about it
could not be saved is a worse outcome than a gap in the notes."""
with app.test_request_context():
monkeypatch.setattr(activity, "get_db",
lambda: (_ for _ in ()).throw(RuntimeError("no")))
activity.log("role.changed", "Maria") # must not raise
def test_the_registro_reads_as_sentences(client, db, post, boss, make_member):
maria = make_member("maria")
post(f"/comunidad/miembros/{maria}/rol", {"role": "moderator"})
body = client.get("/comunidad/gestion/registro").get_data(as_text=True)
assert "cambió el rol de Maria" in body
# --- the media library ----------------------------------------------------
def test_an_orphan_is_named_as_one_and_a_used_picture_is_not(client, db, boss, repo):
repo.files["static/uploads/usada-aaaaaa.jpg"] = b"\xff\xd8\xff"
repo.files["static/uploads/huerfana-bbbbbb.jpg"] = b"\xff\xd8\xff"
db.execute("""INSERT INTO content_cache (path, sha, title, date, image)
VALUES ('content/post/x.es.md', 'a', 'Un artículo', '2026-01-01',
'/uploads/usada-aaaaaa.jpg')""")
body = client.get("/comunidad/gestion/medios").get_data(as_text=True)
assert "1 no la usa nadie" in body
assert "Un artículo" in body
# And the orphan is first, because it is the only row anybody has to act on.
assert body.index("huerfana-bbbbbb") < body.index("usada-aaaaaa")
def test_a_picture_in_use_cannot_be_deleted(client, db, post, boss, repo):
repo.files["static/uploads/usada-aaaaaa.jpg"] = b"\xff\xd8\xff"
db.execute("""INSERT INTO content_cache (path, sha, title, date, image)
VALUES ('content/post/x.es.md', 'a', 'Un artículo', '2026-01-01',
'/uploads/usada-aaaaaa.jpg')""")
response = post("/comunidad/gestion/medios/usada-aaaaaa.jpg/eliminar",
follow_redirects=True)
assert "está en uso" in response.get_data(as_text=True)
assert "static/uploads/usada-aaaaaa.jpg" in repo.files
def test_an_orphan_is_deleted_and_logged(client, db, post, boss, repo):
repo.files["static/uploads/huerfana-bbbbbb.jpg"] = b"\xff\xd8\xff"
post("/comunidad/gestion/medios/huerfana-bbbbbb.jpg/eliminar",
{"sha": repo._sha(b"\xff\xd8\xff")})
assert "static/uploads/huerfana-bbbbbb.jpg" not in repo.files
assert db.execute("SELECT action, object FROM activity").fetchone()["object"] == \
"huerfana-bbbbbb.jpg"
def test_the_editor_records_which_picture_a_post_uses(client, repo, db, post,
superadmin_id, sign_in):
"""Which is what makes "does anything use this?" a query rather than a
re-read of every post's frontmatter from the git server.
The cache is filled by the listing rather than by the write — it is keyed on
the sha the git server reports — so opening Contenido is the step that puts
the row there."""
sign_in(superadmin_id)
post("/comunidad/contenido/post/nuevo",
{"title": "Con foto", "body": "Texto.", "date": "2026-10-03",
"image": "/uploads/foto-abcdef.jpg"})
client.get("/comunidad/contenido/post")
row = db.execute("SELECT image FROM content_cache").fetchone()
assert row["image"] == "/uploads/foto-abcdef.jpg"
# --- the status screen ----------------------------------------------------
def test_the_status_screen_says_when_the_token_cannot_write(client, boss, monkeypatch):
""""Present" was never the problem. A token with the wrong scope is
non-empty, looks fine, and cannot write a single file — which is exactly the
configuration that broke publishing for three phases."""
from apps.board import gitea, status
monkeypatch.setattr(status.gitea, "list_directory",
lambda *a, **k: (_ for _ in ()).throw(
gitea.GiteaError("403: sin permiso de repositorio")))
body = client.get("/comunidad/gestion/estado").get_data(as_text=True)
assert "no puede leer el repositorio" in body
assert "sin permiso de repositorio" in body
def test_the_status_screen_counts_what_is_there(client, db, boss, make_member, repo):
make_member("maria")
make_member("luisa", role="moderator")
body = client.get("/comunidad/gestion/estado").get_data(as_text=True)
assert "3 miembros" in body # the superadministrator and the two
assert "2 con algún cargo" in body # superadministrator + moderator