Files
cc-ci/tests/loomio/custom/_loomio.py
T
2026-11-26 02:50:48 +00:00

127 lines
4.8 KiB
Python

"""Shared loomio test helpers.
Loomio is a Rails app. There is no unauthenticated write API (account creation is email/login-token
based and the REST API is session-authenticated), so state is created through the app's own console
(`bundle exec rails runner`) using the same models/services the API controllers use — STYLE §1 option
2. Each test then reads its object back through the PUBLIC HTTP API, a different path, so a broken
DB/serializer/routing layer is named rather than hidden.
Every helper is idempotent: it looks the user/group/discussion up by a run-scoped identifier first.
Identifiers carry the `ccci-` prefix and use `.example.com` (§8) so state left behind on a warm
canonical is attributable.
"""
from __future__ import annotations
import json
import os
import sys
import uuid
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "..", "runner"))
from harness import lifecycle # noqa: E402
RUN_ID = uuid.uuid4().hex[:10]
ADMIN_EMAIL = f"ccci-loomio-{RUN_ID}@ccci.example.com"
ADMIN_PW = "Ccci-Loomio-Test-2026!"
GROUP_NAME = f"ccci loomio {RUN_ID}"
GROUP_HANDLE = f"ccci-loomio-{RUN_ID}"
DISCUSSION_TITLE = f"ccci discussion {RUN_ID}"
DISCUSSION_MARKER = f"ccci-marker-{RUN_ID}-roundtrip"
_EMAIL = json.dumps(ADMIN_EMAIL) # JSON string literals are valid Ruby double-quoted strings
_PW = json.dumps(ADMIN_PW)
_GROUP_NAME = json.dumps(GROUP_NAME)
_GROUP_HANDLE = json.dumps(GROUP_HANDLE)
_DISCUSSION_TITLE = json.dumps(DISCUSSION_TITLE)
_DISCUSSION_MARKER = json.dumps(DISCUSSION_MARKER)
# Creates a verified user + an OPEN, public, explore-listed group owned by that user. Prints the
# group key on its own line so the caller can read it back through the public API.
_GROUP_RUNNER = f"""
email = {_EMAIL}
user = User.find_by(email: email)
unless user
user = User.new(name: "ccci loomio", email: email, email_verified: true,
password: {_PW}, password_confirmation: {_PW})
user.save!
end
user.update!(email_verified: true) unless user.email_verified?
group = Group.find_by(handle: {_GROUP_HANDLE})
unless group
group = Group.new(name: {_GROUP_NAME}, handle: {_GROUP_HANDLE},
group_privacy: "open", listed_in_explore: true)
group.save!
group.add_admin!(user)
end
puts "GROUP_KEY=" + group.reload.key.to_s
"""
# Same, plus a public discussion in that group. Prints both keys.
_DISCUSSION_RUNNER = (
_GROUP_RUNNER
+ f"""
discussion = Discussion.find_by(group_id: group.id, title: {_DISCUSSION_TITLE})
unless discussion
discussion = Discussion.new(title: {_DISCUSSION_TITLE}, description: {_DISCUSSION_MARKER},
group: group, private: false)
DiscussionService.create(discussion: discussion, actor: user)
end
puts "DISCUSSION_KEY=" + discussion.reload.key.to_s
"""
)
# The app's entrypoint exports these from the mounted secrets and derives DATABASE_URL before
# puma starts; a bare `docker exec` does not inherit them (the image ships no config/database.yml),
# so reproduce the entrypoint env here. `$1` carries the Ruby program (passed as an argv element, so
# no quoting of the program itself is needed).
_ENTRYPOINT_ENV = """
export DEVISE_SECRET="$(cat /run/secrets/devise_secret)"
export SECRET_COOKIE_TOKEN="$(cat /run/secrets/secret_cookie_token)"
export POSTGRES_PASSWORD="$(cat /run/secrets/db_password)"
export DB_HOST=db
export DATABASE_URL="postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db/${POSTGRES_DB}"
exec bundle exec rails runner "$1"
"""
def _rails(domain: str, code: str) -> str:
"""Run Ruby through the app's Rails console (the same process the API controllers run in)."""
return lifecycle.exec_in_app(
domain,
["sh", "-c", _ENTRYPOINT_ENV, "loomio-runner", code],
service="app",
timeout=300,
)
def _key(out: str, prefix: str) -> str:
for line in out.splitlines():
if line.startswith(prefix):
return line.split("=", 1)[1].strip()
raise AssertionError(
f"rails runner did not report {prefix} (last 800 chars of output: {out[-800:]!r})"
)
def ensure_group(domain: str) -> str:
"""Create (or reuse) the run's user + public group; return the group key."""
return _key(_rails(domain, _GROUP_RUNNER), "GROUP_KEY=")
def ensure_discussion(domain: str) -> tuple[str, str]:
"""Create (or reuse) the run's user + public group + public discussion; return (group, discussion) keys."""
out = _rails(domain, _DISCUSSION_RUNNER)
return _key(out, "GROUP_KEY="), _key(out, "DISCUSSION_KEY=")
def unwrap(body: object, root: str) -> dict:
"""AMS wraps responses with a root key (`{"groups": {...}}`); accept a bare object too."""
if isinstance(body, dict) and isinstance(body.get(root), dict):
return body[root]
assert isinstance(body, dict), f"expected a JSON object, got {type(body).__name__}: {body!r}"
return body