Merge pull request 'feat/wave-12-bulk-users' (#4) from feat/wave-12-bulk-users into main
Reviewed-on: #4
This commit is contained in:
@@ -207,9 +207,12 @@ def run(page, base, tok):
|
||||
chk("auth resolved to the admin account", page.eval("(window.WP_USER||{}).role") == "admin")
|
||||
chk("the directory is visible",
|
||||
page.eval("getComputedStyle(document.getElementById('users-main')).display") != "none")
|
||||
chk("manager table renders 9 columns",
|
||||
page.eval("document.querySelectorAll('#users-table thead th').length") == 9,
|
||||
# 10 since CR-020 (T12.2): the 9 data columns plus the row-selection column.
|
||||
chk("manager table renders 10 columns (9 + row selection)",
|
||||
page.eval("document.querySelectorAll('#users-table thead th').length") == 10,
|
||||
page.eval("document.querySelectorAll('#users-table thead th').length"))
|
||||
chk("...the first is the selection column",
|
||||
page.eval("!!document.querySelector('#users-table thead th.selcell #sel-all')"))
|
||||
chk("an admin sees every account in the fixture (7)",
|
||||
page.eval("document.querySelectorAll('#users-table tbody tr').length") == 7,
|
||||
page.eval("document.querySelectorAll('#users-table tbody tr').length"))
|
||||
@@ -237,15 +240,22 @@ def run(page, base, tok):
|
||||
|
||||
# Your own row: permissions locked so you cannot demote yourself, job function
|
||||
# still editable. Asserted on the two cells, not "no select in the row".
|
||||
# The cells are found by their HEADER, not by position: CR-020's selection
|
||||
# column moved every column one to the right and these asserted r.cells[3]
|
||||
# and [4], which then read the username and the email (T12.6).
|
||||
ROW = ("const r=[...document.querySelectorAll('#users-table tbody tr')]"
|
||||
".find(r=>r.querySelector('.me-tag'));")
|
||||
".find(r=>r.querySelector('.me-tag'));"
|
||||
"const col=n=>[...document.querySelectorAll('#users-table thead th')]"
|
||||
".findIndex(h=>h.textContent.trim().toLowerCase()===n);")
|
||||
def own(q):
|
||||
return "(()=>{" + ROW + "if(!r)return false;const c=r.cells[3];return " + q + "})()"
|
||||
return "(()=>{" + ROW + "if(!r)return false;const c=r.cells[col('permissions')];return " + q + "})()"
|
||||
chk("your own permissions cell is locked, not a dropdown",
|
||||
page.eval(own("!c.querySelector('select') && !!c.querySelector('.tag')")))
|
||||
chk("...and wears the Administrator pill", page.eval(own("!!c.querySelector('.tag.admin')")))
|
||||
chk("...while your job function stays editable",
|
||||
page.eval("(()=>{" + ROW + "return !!r && !!r.cells[4].querySelector('select')})()"))
|
||||
page.eval("(()=>{" + ROW + "return !!r && !!r.cells[col('project role')].querySelector('select')})()"))
|
||||
chk("...and your own row cannot be ticked for a bulk action",
|
||||
page.eval("(()=>{" + ROW + "return !!r && !r.querySelector('input.selbox')})()"))
|
||||
|
||||
page.eval("[...document.querySelectorAll('#users-table tbody button')]"
|
||||
".find(b=>/project/i.test(b.textContent)).click()")
|
||||
|
||||
326
tests/bulk_users_check.py
Normal file
326
tests/bulk_users_check.py
Normal file
@@ -0,0 +1,326 @@
|
||||
#!/usr/bin/env python3
|
||||
"""CR-020 (wave 12): bulk user administration, server side.
|
||||
|
||||
python tests/bulk_users_check.py
|
||||
|
||||
Self-contained and needs NO browser: a throwaway SQLite database in a temp
|
||||
folder, the API driven in-process with FastAPI's TestClient, everything deleted
|
||||
afterward. Your real wpsuite.db is never touched.
|
||||
|
||||
What it proves is the wave's own exit criteria, measured on the server, where
|
||||
they are enforced:
|
||||
- every bulk action works on a list, row by row, with the single-user rules;
|
||||
- the caller's own account is refused on its own row, never the whole batch;
|
||||
- a super user's batch cannot reach an account or project outside their scope;
|
||||
- one AuditLog row per changed account, the same shape the single route writes;
|
||||
- a partial failure is reported row by row, never as a clean success;
|
||||
- project add/remove never touches the user's other projects or their roles;
|
||||
- the single-user routes, now built on the same functions, behave as before.
|
||||
|
||||
Exit codes: 0 all passed, 1 a check failed, 2 the run could not start.
|
||||
"""
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import warnings
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
TMP = tempfile.mkdtemp(prefix="wp-bulk-users-check-")
|
||||
os.environ["DATABASE_URL"] = "sqlite:///" + os.path.join(TMP, "bulk.db").replace("\\", "/")
|
||||
os.environ["AUTH_SECRET_KEY"] = "bulk-users-check-key-bulk-users-check-0000"
|
||||
os.environ.pop("WP_OKTA_FAKE_DIRECTORY", None)
|
||||
sys.path.insert(0, ROOT)
|
||||
|
||||
try:
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import select
|
||||
from server import app as A, auth, models
|
||||
from server.db import SessionLocal
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print("could not start:", exc)
|
||||
sys.exit(2)
|
||||
|
||||
RESULTS = []
|
||||
|
||||
|
||||
def check(name, ok, detail=""):
|
||||
RESULTS.append(bool(ok))
|
||||
print(f" {'PASS' if ok else 'FAIL'} {name}" + (f" ({detail})" if detail and not ok else ""))
|
||||
|
||||
|
||||
db = SessionLocal()
|
||||
|
||||
|
||||
def account(uid, role="project_user"):
|
||||
u = models.User(id=uid, username=uid[5:], role=role, email=uid[5:] + "@example.test")
|
||||
db.add(u)
|
||||
db.commit()
|
||||
return u
|
||||
|
||||
|
||||
def member(uid, pid, role=""):
|
||||
db.add(models.ProjectMember(id=f"pm_{uid}_{pid}", user_id=uid, project_id=pid, role=role))
|
||||
db.commit()
|
||||
|
||||
|
||||
def client(user):
|
||||
c = TestClient(A.app, base_url="http://127.0.0.1", raise_server_exceptions=False)
|
||||
c.cookies.set(auth.COOKIE_NAME, auth.create_token(user))
|
||||
return c
|
||||
|
||||
|
||||
def fresh():
|
||||
s = SessionLocal()
|
||||
s.expire_all()
|
||||
return s
|
||||
|
||||
|
||||
def audit(action, entity_id=None):
|
||||
s = fresh()
|
||||
q = select(models.AuditLog).where(models.AuditLog.action == action)
|
||||
if entity_id:
|
||||
q = q.where(models.AuditLog.entity_id == entity_id)
|
||||
return s.scalars(q.order_by(models.AuditLog.at)).all()
|
||||
|
||||
|
||||
def roles_of(uid):
|
||||
s = fresh()
|
||||
return {m.project_id: (m.role or "") for m in
|
||||
s.scalars(select(models.ProjectMember).where(models.ProjectMember.user_id == uid))}
|
||||
|
||||
|
||||
def by_user(resp):
|
||||
return {r["user_id"]: r for r in resp.json().get("results", [])}
|
||||
|
||||
|
||||
# ── fixture ──────────────────────────────────────────────────────────────────
|
||||
admin = account("user_admin", "admin")
|
||||
admin2 = account("user_admin2", "admin")
|
||||
superu = account("user_super") # super user on proj1 and proj4 by membership
|
||||
pu = account("user_pu") # plain project user: manages nobody
|
||||
for n in range(1, 10):
|
||||
account(f"user_u{n}")
|
||||
for pid in ("proj1", "proj2", "proj3", "proj4"):
|
||||
db.add(models.Project(id=pid, name=pid))
|
||||
db.commit()
|
||||
member("user_super", "proj1", "project_super_user")
|
||||
member("user_super", "proj4", "project_super_user")
|
||||
member("user_pu", "proj1")
|
||||
for n in (1, 2, 3, 4, 5):
|
||||
member(f"user_u{n}", "proj1")
|
||||
member("user_u6", "proj1"); member("user_u6", "proj2", "project_admin") # partly outside super's scope
|
||||
member("user_u7", "proj2") # wholly outside it
|
||||
member("user_u8", "proj1"); member("user_u8", "proj4", "project_super_user") # a role super may not grant
|
||||
ca, cs, cp = client(admin), client(superu), client(pu)
|
||||
|
||||
|
||||
def single_routes():
|
||||
print("\n0. the single-user routes still behave as before (now on the shared functions)")
|
||||
r = ca.post("/api/auth/users/user_admin/role", json={"role": "project_user"})
|
||||
check("changing your own role: 400, same words", r.status_code == 400 and "own role" in r.json()["detail"])
|
||||
r = ca.post("/api/auth/users/user_admin/active", json={"is_active": False})
|
||||
check("disabling yourself: 400, same words", r.status_code == 400 and "disable your own" in r.json()["detail"])
|
||||
r = ca.delete("/api/auth/users/user_admin")
|
||||
check("deleting yourself: 400, same words", r.status_code == 400 and "delete your own" in r.json()["detail"])
|
||||
r = cs.post("/api/auth/users/user_u6/role", json={"role": "project_admin"})
|
||||
check("a super user changing an account outside their scope: 403", r.status_code == 403)
|
||||
r = cs.put("/api/auth/users/user_u3/projects", json={"project_ids": ["proj1", "proj2"]})
|
||||
check("a super user assigning a project they don't run: 403", r.status_code == 403)
|
||||
r = ca.post("/api/auth/users/user_u9/role", json={"role": "project_admin"})
|
||||
check("a single role change still works and returns the directory row",
|
||||
r.status_code == 200 and r.json().get("role") == "project_admin")
|
||||
one = audit("role_changed", "user_u9")
|
||||
check("...and writes one role_changed row", len(one) == 1 and one[0].detail == {"from": "project_user", "to": "project_admin"},
|
||||
str([e.detail for e in one]))
|
||||
ca.post("/api/auth/users/user_u9/role", json={"role": "project_user"})
|
||||
|
||||
|
||||
def bulk_role():
|
||||
print("\n1. bulk permissions role")
|
||||
r = ca.post("/api/auth/bulk-users/role", json={
|
||||
"user_ids": ["user_u1", "user_u2", "user_admin", "user_nobody", "user_u1", "bad id!"],
|
||||
"role": "project_admin"})
|
||||
res = by_user(r)
|
||||
check("200 even though some rows fail (a partial failure is a result, not an error)", r.status_code == 200)
|
||||
check("u1 and u2 changed", res["user_u1"]["status"] == "ok" and res["user_u2"]["status"] == "ok")
|
||||
check("your own row is refused with its reason; the rest still ran",
|
||||
res["user_admin"]["status"] == "failed" and "own role" in res["user_admin"]["reason"])
|
||||
check("an unknown account is refused as 'User not found'",
|
||||
res["user_nobody"]["status"] == "failed" and res["user_nobody"]["reason"] == "User not found")
|
||||
check("a malformed id is refused, not crashed on", res["bad id!"]["status"] == "failed")
|
||||
check("a duplicated id is applied once", r.json()["requested"] == 5)
|
||||
check("counts match the rows", (r.json()["ok"], r.json()["failed"]) == (2, 3), str(r.json()))
|
||||
rows = audit("role_changed", "user_u1")
|
||||
check("one role_changed audit row per changed account, same shape as the single route",
|
||||
len(rows) == 1 and rows[0].detail == {"from": "project_user", "to": "project_admin"}
|
||||
and rows[0].actor == "admin" and rows[0].entity_type == "user", str([e.detail for e in rows]))
|
||||
r = ca.post("/api/auth/bulk-users/role", json={"user_ids": ["user_u1"], "role": "project_admin"})
|
||||
check("a row already in that role is 'unchanged' and writes no audit row",
|
||||
by_user(r)["user_u1"]["status"] == "unchanged" and len(audit("role_changed", "user_u1")) == 1)
|
||||
r = cs.post("/api/auth/bulk-users/role", json={"user_ids": ["user_u3"], "role": "admin"})
|
||||
check("a super user cannot grant admin in bulk either (grantable_roles, whole request 400)",
|
||||
r.status_code == 400)
|
||||
r = cs.post("/api/auth/bulk-users/role", json={"user_ids": ["user_u3", "user_u6", "user_u7"],
|
||||
"role": "project_admin"})
|
||||
res = by_user(r)
|
||||
check("super user: an account wholly inside their projects changes", res["user_u3"]["status"] == "ok")
|
||||
check("super user: an account also on a project they don't run is refused, with the reason",
|
||||
res["user_u6"]["status"] == "failed" and "don't administer" in res["user_u6"]["reason"],
|
||||
res["user_u6"]["reason"])
|
||||
check("super user: an account they cannot see is 'User not found' (no existence leak)",
|
||||
res["user_u7"]["status"] == "failed" and res["user_u7"]["reason"] == "User not found")
|
||||
r = ca.post("/api/auth/bulk-users/role", json={"user_ids": ["user_admin2"], "role": "project_user"})
|
||||
check("demoting another admin works while one active admin remains (the caller)",
|
||||
by_user(r)["user_admin2"]["status"] == "ok")
|
||||
|
||||
|
||||
def bulk_active():
|
||||
print("\n2. bulk activate / disable")
|
||||
r = ca.post("/api/auth/bulk-users/active", json={"user_ids": ["user_u4", "user_admin", "user_u5"],
|
||||
"is_active": False})
|
||||
res = by_user(r)
|
||||
check("u4 and u5 disabled", res["user_u4"]["status"] == "ok" and res["user_u5"]["status"] == "ok"
|
||||
and not fresh().get(models.User, "user_u4").is_active)
|
||||
check("your own account is refused on its own row",
|
||||
res["user_admin"]["status"] == "failed" and "disable your own" in res["user_admin"]["reason"])
|
||||
check("one user_disabled audit row each, same shape as the single route",
|
||||
[e.detail for e in audit("user_disabled", "user_u4")] == [{"is_active": False}])
|
||||
r = ca.post("/api/auth/bulk-users/active", json={"user_ids": ["user_u4", "user_u2"], "is_active": True})
|
||||
res = by_user(r)
|
||||
check("re-enable: u4 ok, u2 (already active) unchanged",
|
||||
res["user_u4"]["status"] == "ok" and res["user_u2"]["status"] == "unchanged")
|
||||
|
||||
|
||||
def bulk_projects():
|
||||
print("\n3. bulk project add / remove")
|
||||
r = cs.post("/api/auth/bulk-users/projects", json={"user_ids": ["user_u1", "user_u2", "user_u8"],
|
||||
"project_id": "proj1", "op": "add", "role": "project_admin"})
|
||||
res = by_user(r)
|
||||
check("add with a per-project role: every row ok", all(res[u]["status"] == "ok" for u in ("user_u1", "user_u2", "user_u8")),
|
||||
str(res))
|
||||
check("the role landed on that project", roles_of("user_u1").get("proj1") == "project_admin")
|
||||
check("the user's OTHER project and its role are untouched - even a role the caller could not grant",
|
||||
roles_of("user_u8").get("proj4") == "project_super_user", str(roles_of("user_u8")))
|
||||
rows = audit("project_access_changed", "user_u1")
|
||||
check("one project_access_changed row per account, in the single route's shape",
|
||||
len(rows) == 1 and set(rows[0].detail) == {"projects", "scope", "overrides"}
|
||||
and rows[0].detail["scope"] == "managed", str([e.detail for e in rows]))
|
||||
r = cs.post("/api/auth/bulk-users/projects", json={"user_ids": ["user_u1"], "project_id": "proj2", "op": "add"})
|
||||
check("a super user cannot add anyone to a project they don't run (403)", r.status_code == 403)
|
||||
r = cs.post("/api/auth/bulk-users/projects", json={"user_ids": ["user_u1"], "project_id": "proj1",
|
||||
"op": "add", "role": "project_super_user"})
|
||||
check("a super user cannot hand out super user on a project (400)", r.status_code == 400)
|
||||
r = ca.post("/api/auth/bulk-users/projects", json={"user_ids": ["user_u6"], "project_id": "proj3", "op": "add"})
|
||||
check("admin adds u6 to proj3; proj1 and proj2 memberships and roles stay",
|
||||
by_user(r)["user_u6"]["status"] == "ok"
|
||||
and roles_of("user_u6") == {"proj1": "", "proj2": "project_admin", "proj3": ""}, str(roles_of("user_u6")))
|
||||
r = cs.post("/api/auth/bulk-users/projects", json={"user_ids": ["user_u2", "user_u9"], "project_id": "proj1", "op": "remove"})
|
||||
res = by_user(r)
|
||||
check("remove: u2 taken off proj1", res["user_u2"]["status"] == "ok" and "proj1" not in roles_of("user_u2"))
|
||||
check("remove: someone not on it is 'User not found' to a super user who cannot see them",
|
||||
res["user_u9"]["status"] == "failed")
|
||||
r = ca.post("/api/auth/bulk-users/projects", json={"user_ids": ["user_u9"], "project_id": "proj1", "op": "remove"})
|
||||
check("remove: an admin removing someone not on the project gets 'unchanged'",
|
||||
by_user(r)["user_u9"]["status"] == "unchanged")
|
||||
r = ca.post("/api/auth/bulk-users/projects", json={"user_ids": ["user_u1"], "project_id": "proj1", "op": "replace"})
|
||||
check("only add and remove exist: no replace-the-whole-list (400)", r.status_code == 400)
|
||||
|
||||
|
||||
def bulk_delete():
|
||||
print("\n4. bulk delete")
|
||||
r = ca.post("/api/auth/bulk-users/delete", json={"user_ids": ["user_u5", "user_admin", "user_gone"]})
|
||||
res = by_user(r)
|
||||
check("u5 deleted", res["user_u5"]["status"] == "ok" and fresh().get(models.User, "user_u5") is None)
|
||||
check("your own account is refused on its own row, the others still ran",
|
||||
res["user_admin"]["status"] == "failed" and "delete your own" in res["user_admin"]["reason"])
|
||||
check("an account that no longer exists is reported, not hidden",
|
||||
res["user_gone"]["status"] == "failed" and res["user_gone"]["reason"] == "User not found")
|
||||
check("one user_deleted audit row, same shape as the single route",
|
||||
[e.detail for e in audit("user_deleted", "user_u5")] == [{"role": "project_user"}])
|
||||
check("the deleted account's memberships went with it", roles_of("user_u5") == {})
|
||||
|
||||
|
||||
def csv_resolve():
|
||||
print("\n6. CSV upload: usernames in, a line-by-line report out (T12.4)")
|
||||
text = ("username\n" # header, skipped
|
||||
"u3\n"
|
||||
"U3\n" # same person, different case: a duplicate
|
||||
"nobody\n"
|
||||
"\n" # blank lines are not rows
|
||||
"u6\n" # visible to the super user, but also on a project they don't run
|
||||
"u7\n" # not visible to the super user at all
|
||||
"super\n" # the caller themself
|
||||
"u8@example.test,extra column\n" # an email address, matched to exactly one account
|
||||
",\n") # an empty first column
|
||||
r = cs.post("/api/auth/bulk-users/resolve", json={"text": text})
|
||||
j = r.json()
|
||||
rows = {x["line"]: x for x in j["rows"]}
|
||||
check("200 with a row for every non-blank line after the header",
|
||||
r.status_code == 200 and sorted(rows) == [2, 3, 4, 6, 7, 8, 9, 10], sorted(rows))
|
||||
check("a valid username is accepted", rows[2]["status"] == "ok" and rows[2]["user_id"] == "user_u3")
|
||||
check("a repeated username is rejected as a duplicate of its first line, not applied twice",
|
||||
rows[3]["status"] == "rejected" and rows[3]["reason"] == "duplicate of line 2")
|
||||
check("an unknown username: 'User not found', with its line number", rows[4]["reason"] == "User not found")
|
||||
check("an account the caller may not change: rejected with the single route's own reason",
|
||||
rows[6]["status"] == "rejected" and "don't administer" in rows[6]["reason"], rows[6]["reason"])
|
||||
check("an account the caller cannot see: 'User not found' (a CSV leaks no more than the table)",
|
||||
rows[7]["reason"] == "User not found")
|
||||
check("the caller's own account is rejected with a clear reason", "your own account" in rows[8]["reason"])
|
||||
check("an email address resolves when exactly one account has it",
|
||||
rows[9]["status"] == "ok" and rows[9]["user_id"] == "user_u8")
|
||||
check("an empty first column is rejected, not skipped", rows[10]["reason"] == "no username in the first column")
|
||||
check("the ids handed back are exactly the accepted rows",
|
||||
j["user_ids"] == ["user_u3", "user_u8"] and (j["accepted"], j["rejected"]) == (2, 6), str(j["user_ids"]))
|
||||
r = cs.post("/api/auth/bulk-users/active", json={"user_ids": j["user_ids"] + ["user_u7"], "is_active": False})
|
||||
res = by_user(r)
|
||||
check("the CSV's ids go through the same bulk route and the same guards: an id slipped in by hand "
|
||||
"is still refused", res["user_u7"]["status"] == "failed" and res["user_u3"]["status"] == "ok")
|
||||
ca.post("/api/auth/bulk-users/active", json={"user_ids": ["user_u3", "user_u8"], "is_active": True})
|
||||
r = cp.post("/api/auth/bulk-users/resolve", json={"text": "u3"})
|
||||
check("a plain project user cannot resolve a list (403)", r.status_code == 403)
|
||||
r = cs.post("/api/auth/bulk-users/resolve", json={"text": "x" * 200_001})
|
||||
check("an oversized upload is refused (422)", r.status_code == 422)
|
||||
s = fresh()
|
||||
s.add(models.User(id="user_twin1", username="twin1", email="shared@example.test"))
|
||||
s.add(models.User(id="user_twin2", username="twin2", email="shared@example.test"))
|
||||
s.commit()
|
||||
r = ca.post("/api/auth/bulk-users/resolve", json={"text": "shared@example.test"})
|
||||
check("an email shared by two accounts matches neither", r.json()["rows"][0]["reason"] == "User not found")
|
||||
|
||||
|
||||
def gates():
|
||||
print("\n7. who may call, and how much")
|
||||
for path, body in (("role", {"role": "project_user"}), ("active", {"is_active": False}),
|
||||
("projects", {"project_id": "proj1", "op": "add"}), ("delete", {})):
|
||||
r = cp.post(f"/api/auth/bulk-users/{path}", json={"user_ids": ["user_u3"], **body})
|
||||
check(f"a plain project user is refused /bulk-users/{path} (403)", r.status_code == 403, str(r.status_code))
|
||||
anon = TestClient(A.app, base_url="http://127.0.0.1", raise_server_exceptions=False)
|
||||
check("no session: 401", anon.post("/api/auth/bulk-users/delete", json={"user_ids": ["user_u3"]}).status_code == 401)
|
||||
r = ca.post("/api/auth/bulk-users/active", json={"user_ids": [f"user_x{i}" for i in range(501)], "is_active": False})
|
||||
check("more than 500 ids in one request is refused (422)", r.status_code == 422, str(r.status_code))
|
||||
|
||||
|
||||
SECTIONS = [single_routes, bulk_role, bulk_active, bulk_projects, bulk_delete, csv_resolve, gates]
|
||||
|
||||
|
||||
def main() -> int:
|
||||
print("Wave 12 bulk user administration - server checks")
|
||||
try:
|
||||
for section in SECTIONS:
|
||||
try:
|
||||
section()
|
||||
except Exception as exc: # noqa: BLE001 - a missing route must read as FAIL, not a traceback
|
||||
check(f"section {section.__name__} ran to the end", False, f"{type(exc).__name__}: {exc}")
|
||||
finally:
|
||||
db.close()
|
||||
A.engine.dispose()
|
||||
shutil.rmtree(TMP, ignore_errors=True)
|
||||
passed = sum(RESULTS)
|
||||
print(f"\n{passed}/{len(RESULTS)} checks passed.")
|
||||
return 0 if passed == len(RESULTS) else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
197
tests/bulk_users_ui_check.py
Normal file
197
tests/bulk_users_ui_check.py
Normal file
@@ -0,0 +1,197 @@
|
||||
#!/usr/bin/env python3
|
||||
"""CR-020 (wave 12): bulk user administration in the browser, at 1440px and 390px.
|
||||
|
||||
python tests/bulk_users_ui_check.py
|
||||
|
||||
Self-contained like the other probes: a throwaway SQLite database seeded by
|
||||
browser_check.seed(), its own uvicorn, headless Edge or Chrome over CDP. Your
|
||||
real wpsuite.db is never touched. Run it alone, not back to back with another
|
||||
probe (file-map.md: chained runs exhaust the browser's ports).
|
||||
|
||||
The server rules are proven in tests/bulk_users_check.py without a browser.
|
||||
This file proves the page: selection, the toolbar, the CSV path and the typed
|
||||
delete, end to end against the real server, operable by keyboard, and holding
|
||||
together at 390px. It writes the after-screenshots CLAUDE.md asks for to
|
||||
docs/reference/baseline/wave-12/; the before-shots are the existing
|
||||
users-1440.png and after-wave9/users-390.png.
|
||||
|
||||
Exit 0 all passed, 1 a failure, 2 could not run.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
import cdp # noqa: E402
|
||||
from browser_check import seed, start_server, chk, _PASS, _FAIL # noqa: E402
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
SHOTS = os.path.join(ROOT, "docs", "reference", "baseline", "wave-12")
|
||||
READY = "!!document.querySelector('#users-table table')"
|
||||
|
||||
|
||||
def api(base, path, token):
|
||||
req = urllib.request.Request(base + path, headers={"Cookie": "wp_session=" + token})
|
||||
with urllib.request.urlopen(req, timeout=10) as r:
|
||||
return json.loads(r.read().decode())
|
||||
|
||||
|
||||
def user(base, token, username):
|
||||
return next((u for u in api(base, "/api/auth/users", token) if u["username"] == username), None)
|
||||
|
||||
|
||||
def press(page, key, code, vk):
|
||||
"""A REAL key event (Input.dispatchKeyEvent), not a synthetic KeyboardEvent:
|
||||
only a real one triggers a checkbox's native Space toggle - the lesson
|
||||
launcher_check.py records."""
|
||||
for t in ("keyDown", "keyUp"):
|
||||
page.ws.call("Input.dispatchKeyEvent", {"type": t, "key": key, "code": code,
|
||||
"windowsVirtualKeyCode": vk, "text": " " if t == "keyDown" else ""})
|
||||
time.sleep(0.3)
|
||||
|
||||
|
||||
def answer(page, ok=True, typed=None):
|
||||
time.sleep(0.4)
|
||||
if typed is not None:
|
||||
page.eval("document.getElementById('wp-dlg-input').value=%s" % json.dumps(typed))
|
||||
page.eval("document.getElementById('%s').click()" % ("wp-dlg-ok" if ok else "wp-dlg-cancel"))
|
||||
time.sleep(1.2)
|
||||
|
||||
|
||||
def tick(page, username):
|
||||
page.eval("(() => { const b=[...document.querySelectorAll('input.selbox')]"
|
||||
".find(x => x.dataset.id==='user_%s'); if(b) b.click(); })()" % username)
|
||||
time.sleep(0.2)
|
||||
|
||||
|
||||
BAR_390 = """(function(){
|
||||
var bar=document.getElementById('bulk-bar'); var out={sw:document.documentElement.scrollWidth,under:[],clipped:[],n:0};
|
||||
bar.querySelectorAll('button, select').forEach(function(el){
|
||||
var r=el.getBoundingClientRect(); if(!r.width||!r.height) return; out.n++;
|
||||
var id=el.tagName+' '+(el.textContent||el.id).trim().slice(0,20)+' '+Math.round(r.width)+'x'+Math.round(r.height);
|
||||
if(Math.min(r.width,r.height)<24) out.under.push(id);
|
||||
if(r.left<-2||r.right>392) out.clipped.push(id);
|
||||
});
|
||||
return JSON.stringify(out);
|
||||
})()"""
|
||||
|
||||
|
||||
def main():
|
||||
exe = cdp.find_browser()
|
||||
if not exe:
|
||||
print("no headless-capable browser found; set WP_BROWSER.")
|
||||
return 2
|
||||
tmpdir = tempfile.mkdtemp(prefix="wpsuite-bulkui-")
|
||||
db_path = os.path.join(tmpdir, "check.db")
|
||||
server = browser = None
|
||||
try:
|
||||
tok = seed(db_path)
|
||||
port = cdp.free_port()
|
||||
base = "http://127.0.0.1:%d" % port
|
||||
server = start_server(port, db_path)
|
||||
if server is None:
|
||||
print("server would not start")
|
||||
return 2
|
||||
browser = cdp.Browser(exe)
|
||||
page = browser.page()
|
||||
|
||||
def visit(who, width, mobile=False):
|
||||
page.clear_cookies()
|
||||
page.set_cookie("wp_session", tok[who])
|
||||
page.viewport(width, 900 if width > 500 else 844, mobile=mobile)
|
||||
page.goto(base + "/users.html", wait_for=READY)
|
||||
time.sleep(0.6)
|
||||
|
||||
print("\n1. the admin at 1440px")
|
||||
visit("root", 1440)
|
||||
page.screenshot(os.path.join(SHOTS, "users-1440.png"))
|
||||
chk("a selection column with select-all", page.eval("!!document.getElementById('sel-all')"))
|
||||
chk("no bulk bar until a row is selected", page.eval("document.getElementById('bulk-bar').hidden"))
|
||||
page.eval("document.querySelector('input.selbox[data-id=\"user_pat\"]').focus()")
|
||||
press(page, " ", "Space", 32)
|
||||
chk("Space on a focused row checkbox selects it (keyboard operable)",
|
||||
page.eval("document.querySelector('input.selbox[data-id=\"user_pat\"]').checked"))
|
||||
chk("the bar appears, reachable by keyboard",
|
||||
page.eval("!document.getElementById('bulk-bar').hidden && document.querySelector('#bulk-bar button').tabIndex >= 0"))
|
||||
tick(page, "legacy")
|
||||
chk("the bar counts the selection", page.eval("document.getElementById('bulk-count').textContent") == "2 selected")
|
||||
page.screenshot(os.path.join(SHOTS, "users-1440-selected.png"))
|
||||
page.eval("document.getElementById('bulk-role').value='project_admin';"
|
||||
"document.querySelector('[onclick=\"bulkRole()\"]').click()")
|
||||
time.sleep(0.4)
|
||||
chk("the confirm names the count", "for 2 users" in (page.eval("document.getElementById('wp-dlg-msg').textContent") or ""))
|
||||
answer(page)
|
||||
chk("both accounts changed on the server",
|
||||
user(base, tok["root"], "pat")["role"] == "project_admin" and user(base, tok["root"], "legacy")["role"] == "project_admin")
|
||||
chk("the result is announced", "2 changed" in page.eval("document.getElementById('bulk-banner').textContent")
|
||||
and page.eval("document.getElementById('bulk-banner').getAttribute('role')") in ("status", "alert"))
|
||||
tick(page, "pat")
|
||||
page.eval("const f=document.getElementById('user-filter'); f.value='active'; f.dispatchEvent(new Event('change'))")
|
||||
time.sleep(0.3)
|
||||
chk("changing the filter clears the selection, and says so",
|
||||
page.eval("document.getElementById('bulk-bar').hidden") and
|
||||
"filter changed" in page.eval("document.getElementById('sel-banner').textContent"))
|
||||
|
||||
print("\n2. the super user, a CSV with good and bad lines")
|
||||
visit("sue", 1440)
|
||||
page.eval("loadCsv(new File(['username\\npat\\nmix\\nbob\\nsue\\npat\\n'], 'list.csv', {type:'text/csv'}))")
|
||||
time.sleep(1.5)
|
||||
rep = page.eval("document.getElementById('csv-banner').textContent") or ""
|
||||
chk("only the account she may change is selected", page.eval("document.getElementById('bulk-count').textContent") == "1 selected", rep)
|
||||
chk("every bad line is reported by number and reason: another job, not found, herself, a duplicate",
|
||||
all(s in rep for s in ("Line 3 (mix)", "Line 4 (bob): User not found", "Line 5 (sue)", "Line 6 (pat): duplicate of line 2")), rep)
|
||||
page.eval("document.getElementById('bulk-project-role').value='project_admin';"
|
||||
"document.querySelector('[onclick=\"bulkProject(\\'add\\')\"]').click()")
|
||||
answer(page)
|
||||
roles = api(base, "/api/auth/users/user_pat/projects", tok["root"])["roles"]
|
||||
chk("add to project with a role landed on the server", roles.get("projA") == "project_admin", roles)
|
||||
|
||||
print("\n3. bulk delete needs the typed word")
|
||||
visit("root", 1440)
|
||||
tick(page, "bob")
|
||||
page.eval("document.querySelector('[onclick=\"bulkDelete()\"]').click()")
|
||||
time.sleep(0.4)
|
||||
chk("the dialog lists the username", "bob" in page.eval("document.getElementById('wp-dlg-msg').textContent"))
|
||||
page.eval("document.getElementById('wp-dlg-input').value='delete'; document.getElementById('wp-dlg-ok').click()")
|
||||
time.sleep(0.4)
|
||||
chk("a wrong word sends nothing", user(base, tok["root"], "bob") is not None
|
||||
and page.eval("document.getElementById('wp-dlg-overlay').classList.contains('open')"))
|
||||
answer(page, typed="DELETE")
|
||||
chk("DELETE deletes, and the report says so", user(base, tok["root"], "bob") is None
|
||||
and "1 changed" in page.eval("document.getElementById('bulk-banner').textContent"))
|
||||
|
||||
print("\n4. the gloved-hands width: 390px")
|
||||
visit("root", 390, mobile=True)
|
||||
page.screenshot(os.path.join(SHOTS, "users-390.png"))
|
||||
tick(page, "pat")
|
||||
m = json.loads(page.eval(BAR_390))
|
||||
page.screenshot(os.path.join(SHOTS, "users-390-selected.png"))
|
||||
chk("390px with the bar open: no sideways scrolling", m["sw"] <= 392, m["sw"])
|
||||
chk("390px: no bar control clipped past the screen", not m["clipped"], m["clipped"])
|
||||
chk("390px: every bar control meets the 24px floor", m["n"] > 0 and not m["under"], m["under"])
|
||||
|
||||
errs = [e for e in page.js_errors() if "beforeunload" not in e]
|
||||
chk("no JavaScript errors in the whole run", not errs, errs[:3])
|
||||
finally:
|
||||
if browser is not None:
|
||||
try:
|
||||
browser.close()
|
||||
except Exception:
|
||||
pass
|
||||
if server is not None:
|
||||
server.terminate()
|
||||
|
||||
print("\n" + "-" * 54)
|
||||
print("%d/%d checks passed." % (len(_PASS), len(_PASS) + len(_FAIL)))
|
||||
for f in _FAIL:
|
||||
print(" - " + f)
|
||||
return 1 if _FAIL else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -112,6 +112,33 @@ def main():
|
||||
chk("cancel means no: bob is still an account",
|
||||
st == 200 and any(u.get("username") == "bob" for u in (users or [])),
|
||||
ascii_([u.get("username") for u in (users or [])]))
|
||||
# CR-020 / T12.5: the bulk delete is a PROMPT-style dialog (typed DELETE),
|
||||
# the kind this file's docstring says belongs back here.
|
||||
print("\n4. bulk delete needs the typed word")
|
||||
page.eval("(() => { const b=[...document.querySelectorAll('input.selbox')]"
|
||||
".find(x => x.dataset.id==='user_bob'); b.click(); })()")
|
||||
time.sleep(0.3)
|
||||
chk("ticking a row shows the bulk bar",
|
||||
page.eval("!document.getElementById('bulk-bar').hidden"))
|
||||
page.eval("document.querySelector('[onclick=\"bulkDelete()\"]').click()")
|
||||
time.sleep(0.4)
|
||||
chk("the bulk delete asks through the kit's prompt, listing the username",
|
||||
page.eval("(() => { const o=document.getElementById('wp-dlg-overlay');"
|
||||
" return o.classList.contains('open')"
|
||||
" && document.getElementById('wp-dlg-input-wrap').style.display !== 'none'"
|
||||
" && /bob/.test(document.getElementById('wp-dlg-msg').textContent); })()"))
|
||||
page.eval("document.getElementById('wp-dlg-input').value='delete';"
|
||||
"document.getElementById('wp-dlg-ok').click()")
|
||||
time.sleep(0.3)
|
||||
chk("the wrong word keeps it open and names what to type",
|
||||
page.eval("document.getElementById('wp-dlg-overlay').classList.contains('open')"
|
||||
" && /DELETE/.test(document.getElementById('wp-dlg-err').textContent)"))
|
||||
page.eval("document.getElementById('wp-dlg-cancel').click()")
|
||||
time.sleep(0.6)
|
||||
st, users = api(base, "/api/auth/users", tok["root"])
|
||||
chk("cancel means no: bob is still an account after the bulk prompt",
|
||||
st == 200 and any(u.get("username") == "bob" for u in (users or [])))
|
||||
|
||||
errs = [e for e in page.js_errors() if "beforeunload" not in e]
|
||||
chk("no JavaScript errors, and no path reached a native dialog (they throw here)",
|
||||
not errs, ascii_(errs[:3]))
|
||||
|
||||
Reference in New Issue
Block a user