vienalatina/apps/board/tests/conftest.py
Pablo Volenski 7e70004e7b
Marca: the admin owns the look, logo included
The brand colours were two identical `:root` blocks — one in the theme, one in
the members area's stylesheet — with a comment in the second reading *"If the
brand colours change, change them in both."* There was no logo anywhere, no
favicon in either `<head>`, and `params.defaultImage` was the empty string with
a comment saying it was waiting for one. Every one of those was a change only
somebody with the repository could make.

`brand.FACTORY` is the single source of truth for the palette now, and
`test_brand.py` parses both stylesheets and fails the build if either drifts
from it. That is what retires the comment: not by merging the two files — they
are served by different things and each has to stand alone — but by making a
divergence fail a test instead of going unnoticed for a month.

**Gestión → Marca**, admins only, saves to two places in one submit, because
the two halves of the site cannot read the same store: SQLite for the members
area, which must render when the git server is down, and `data/brand.yaml` plus
`static/brand/` in the content repository for the public site, which is files
on disk. SQLite is written first and the commits follow — if Gitea is
unreachable the change still takes effect here, `published_at` stays NULL, and
the screen offers to try the publish again. The other order would let a git
outage block a change that does not need git.

The easy half is six colour pickers, each with the name of what it changes, and
a live preview of the real chrome. The three brand shades are worked out from
the brand colour in HLS, so one picked colour gives a coherent set rather than
one red button on an orange background; scaling RGB towards white would have
washed the hue out. A WCAG contrast warning names any pair that will be hard to
read, with its ratio, and saves it anyway: an admin may have a reason, and what
this prevents is shipping an unreadable site without once being told.

The advanced half, behind a fold, is every token as a text field and a free CSS
box appended last so it wins. **The Marca screen deliberately does not load the
generated stylesheet** — every other page does — which is what keeps *Restaurar
lo de fábrica* reachable after somebody writes `* { display: none }` into that
box, and the reason the colours an admin picks do not show on the page where
they pick them. The preview block is where they do.

Only differences from the factory are stored, so a token added later arrives
with its default already in place for every existing install. Both halves serve
a generated stylesheet rather than an inline `<style>`, because the CSP has no
'unsafe-inline' and an inline block would simply not apply.

The logo also fills the gap phase I left: it is the share-card fallback and the
`Organization` logo, ahead of `defaultImage`, and the home page carries
`og:image` for the first time — the front page of the site was the last place
that should share as a bare link.

No SVG and no ICO: the logo takes PNG, JPG or WebP and the favicon PNG, both
identified from their bytes by the sniffer the wall already uses. An SVG is XML
that can carry script and would be served from our own origin.

A new table, so `CREATE TABLE IF NOT EXISTS` is enough and no migration is
involved. `FakeRepo` moved from test_content.py into conftest.py, since two
features commit to the content repository now. Verified by building with Hugo
0.135.0 and the pipeline's flags both ways: with a brand.yaml the second
stylesheet, the favicon and the logo appear, and without one the output is
byte-for-byte identical to the build before any of this existed.

545 tests pass.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NizVpJ2dwzCbjCrTLCjeHn
2026-10-03 20:25:52 +00:00

153 lines
4.9 KiB
Python

"""Shared fixtures.
Tests drive the app through Flask's test client rather than poking functions
directly, because most of what is worth checking here is a decision about who
may do what — and that decision is only real once it has survived routing,
the session and the CSRF hook.
Sign-in is faked by writing the session cookie: the OAuth round trip belongs to
Gitea, and the tests that care about it stub the two network calls instead.
"""
from __future__ import annotations
import hashlib
import sys
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
from apps.board import gitea # noqa: E402
from apps.board.app import create_app # noqa: E402
from apps.board.db import connect # noqa: E402
@pytest.fixture
def app(tmp_path):
application = create_app({
"SECRET_KEY": "test-secret",
"DB_PATH": str(tmp_path / "board.db"),
"OWNER_LOGIN": "owner",
"SESSION_COOKIE_SECURE": False,
"COOLDOWN_SECONDS": 0,
"BASE_URL": "http://localhost",
"ADMIN_TOKEN": "admintoken",
"UPLOAD_DIR": str(tmp_path / "uploads"),
"TESTING": True,
})
yield application
@pytest.fixture
def db(app):
conn = connect(app.config["DB_PATH"])
yield conn
conn.close()
@pytest.fixture
def client(app):
return app.test_client()
@pytest.fixture
def make_member(db):
"""Insert a member and return its id. The owner already exists, seeded."""
def _make(login, role="user", active=1):
cursor = db.execute(
"""INSERT INTO members (gitea_login, display_name, email, role, active)
VALUES (?, ?, ?, ?, ?)""",
(login, login.title(), f"{login}@example.com", role, active),
)
return cursor.lastrowid
return _make
@pytest.fixture
def owner_id(db):
return db.execute("SELECT id FROM members WHERE role = 'owner'").fetchone()["id"]
@pytest.fixture
def sign_in(client):
def _sign_in(member_id):
with client.session_transaction() as session:
session["member_id"] = member_id
session["csrf"] = "token-for-tests"
return _sign_in
@pytest.fixture
def post(client):
"""POST with a valid CSRF token, so tests exercise authorisation rather
than repeatedly rediscovering that the CSRF hook works."""
def _post(url, data=None, **kwargs):
# A real anonymous visitor gets a CSRF token when the form renders, so
# signed-out pages (invitations, password recovery) need one here too —
# otherwise every such test fails on the hook rather than on its subject.
with client.session_transaction() as session:
session.setdefault("csrf", "token-for-tests")
payload = dict(data or {})
payload.setdefault("csrf_token", "token-for-tests")
return client.post(url, data=payload, **kwargs)
return _post
# --- the git server, as a dictionary --------------------------------------
#
# Shared because two features commit to the content repository now: the editor
# (test_content.py) and the brand (test_brand.py). What matters in both is the
# payload — which files, with which bytes, under whose name — and `requests` can
# be trusted to do HTTP.
class FakeRepo:
"""A repository in a dict, with shas that change when content does."""
def __init__(self):
self.files: dict[str, bytes] = {}
self.commits: list[str] = []
self.authors: list[dict] = []
self.reads = 0
@staticmethod
def _sha(data: bytes) -> str:
return hashlib.sha1(data).hexdigest()
def list_directory(self, path, token=None):
out = []
for name, data in self.files.items():
if name.startswith(path + "/") and "/" not in name[len(path) + 1:]:
out.append({"name": name.rsplit("/", 1)[1], "path": name,
"type": "file", "sha": self._sha(data)})
return out
def read_file(self, path, token=None):
self.reads += 1
if path not in self.files:
raise gitea.GiteaError("Ese archivo ya no existe.")
return self.files[path].decode("utf-8"), self._sha(self.files[path])
def write_file(self, path, data, message, token=None, sha=None, member=None):
if sha and self.files.get(path) is not None and self._sha(self.files[path]) != sha:
raise gitea.StaleFile("Alguien más guardó este archivo mientras lo editabas.")
self.files[path] = data
self.commits.append(message)
self.authors.append(gitea._identity(member))
return self._sha(data)
def delete_file(self, path, sha, message, token=None, member=None):
self.files.pop(path, None)
self.commits.append(message)
@pytest.fixture
def repo(monkeypatch):
fake = FakeRepo()
for name in ("list_directory", "read_file", "write_file", "delete_file"):
monkeypatch.setattr(gitea, name, getattr(fake, name))
return fake