forked from retoor/devplacepy
Keep composers usable, group actions and notifications, and drop the tool-count cap
Comment and post layouts stay full width on small screens. Secondary actions live in the More menu. Notifications can be grouped and throttled, and Enter can submit when that profile setting is on. Emulated-tool models accept large catalogs, with reserved names aliased on the wire and the catalog cached per owner. A dropped service-worker navigation is retried once. The test server waits 120s to finish importing before it is stopped.
This commit is contained in:
@@ -0,0 +1,100 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import requests
|
||||
|
||||
from tests.conftest import BASE_URL
|
||||
from devplacepy.database import get_table, refresh_snapshot
|
||||
from devplacepy.utils import generate_uid
|
||||
|
||||
_counter = [0]
|
||||
JSON = {"Accept": "application/json"}
|
||||
|
||||
|
||||
def _signup():
|
||||
_counter[0] += 1
|
||||
name = f"ngrp{int(time.time() * 1000)}{_counter[0]}"
|
||||
session = requests.Session()
|
||||
session.post(
|
||||
f"{BASE_URL}/auth/signup",
|
||||
data={
|
||||
"username": name,
|
||||
"email": f"{name}@t.dev",
|
||||
"password": "secret123",
|
||||
"confirm_password": "secret123",
|
||||
"birth_date": "1990-01-01",
|
||||
"accept_terms": "1",
|
||||
},
|
||||
allow_redirects=True,
|
||||
)
|
||||
return session, name
|
||||
|
||||
|
||||
def _seed(session, name, count=5):
|
||||
refresh_snapshot()
|
||||
user = get_table("users").find_one(username=name)
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
table = get_table("notifications")
|
||||
for i in range(count):
|
||||
table.insert(
|
||||
{
|
||||
"uid": generate_uid(),
|
||||
"user_uid": user["uid"],
|
||||
"type": "vote",
|
||||
"message": f"actor-{i} ++'d your post",
|
||||
"related_uid": user["uid"],
|
||||
"target_url": "/posts/seeded",
|
||||
"read": False,
|
||||
"created_at": now,
|
||||
}
|
||||
)
|
||||
refresh_snapshot()
|
||||
return user
|
||||
|
||||
|
||||
def _wait_counts(session, expected):
|
||||
deadline = time.time() + 20
|
||||
counts = {}
|
||||
while time.time() < deadline:
|
||||
counts = session.get(f"{BASE_URL}/notifications/counts").json()
|
||||
if counts.get("notifications") == expected:
|
||||
return counts
|
||||
time.sleep(0.5)
|
||||
return counts
|
||||
|
||||
|
||||
def test_grouped_page_and_counts(app_server):
|
||||
session, name = _signup()
|
||||
_seed(session, name)
|
||||
counts = _wait_counts(session, 1)
|
||||
assert counts["notifications"] == 1, counts
|
||||
page = session.get(f"{BASE_URL}/notifications", headers=JSON)
|
||||
data = page.json()
|
||||
assert data["grouping"] is True
|
||||
events = [
|
||||
entry
|
||||
for group in data["notification_groups"]
|
||||
for entry in group["event_entries"]
|
||||
]
|
||||
assert len(events) == 1
|
||||
assert events[0]["count"] == 5
|
||||
html = session.get(f"{BASE_URL}/notifications")
|
||||
assert "×5" in html.text or "×5" in html.text
|
||||
|
||||
|
||||
def test_grouping_off_restores_row_counts(app_server):
|
||||
session, name = _signup()
|
||||
_seed(session, name)
|
||||
resp = session.post(
|
||||
f"{BASE_URL}/profile/{name}/notifications/grouping",
|
||||
data={"value": "false"},
|
||||
headers=JSON,
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
counts = _wait_counts(session, 5)
|
||||
assert counts["notifications"] == 5, counts
|
||||
page = session.get(f"{BASE_URL}/notifications", headers=JSON)
|
||||
data = page.json()
|
||||
assert data["grouping"] is False
|
||||
@@ -0,0 +1,109 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
import time
|
||||
|
||||
import requests
|
||||
|
||||
from tests.conftest import BASE_URL
|
||||
|
||||
_counter = [0]
|
||||
JSON = {"Accept": "application/json"}
|
||||
|
||||
|
||||
def _signup():
|
||||
_counter[0] += 1
|
||||
name = f"nset{int(time.time() * 1000)}{_counter[0]}"
|
||||
session = requests.Session()
|
||||
session.post(
|
||||
f"{BASE_URL}/auth/signup",
|
||||
data={
|
||||
"username": name,
|
||||
"email": f"{name}@t.dev",
|
||||
"password": "secret123",
|
||||
"confirm_password": "secret123",
|
||||
"birth_date": "1990-01-01",
|
||||
"accept_terms": "1",
|
||||
},
|
||||
allow_redirects=True,
|
||||
)
|
||||
return session, name
|
||||
|
||||
|
||||
def _toggle(session, name, kind, value):
|
||||
return session.post(
|
||||
f"{BASE_URL}/profile/{name}/notifications/{kind}",
|
||||
data={"value": "true" if value else "false"},
|
||||
headers=JSON,
|
||||
)
|
||||
|
||||
|
||||
def test_owner_toggles_grouping_and_throttling(app_server):
|
||||
session, name = _signup()
|
||||
for kind, field in (("grouping", "notif_grouping_enabled"), ("throttling", "notif_throttle_enabled")):
|
||||
resp = _toggle(session, name, kind, False)
|
||||
assert resp.status_code == 200, resp.text[:200]
|
||||
assert resp.json()["data"][field] is False
|
||||
resp = _toggle(session, name, kind, True)
|
||||
assert resp.status_code == 200, resp.text[:200]
|
||||
assert resp.json()["data"][field] is True
|
||||
|
||||
|
||||
def test_other_user_cannot_toggle(app_server):
|
||||
_, target = _signup()
|
||||
attacker, _ = _signup()
|
||||
for kind in ("grouping", "throttling"):
|
||||
resp = attacker.post(
|
||||
f"{BASE_URL}/profile/{target}/notifications/{kind}",
|
||||
data={"value": "false"},
|
||||
headers=JSON,
|
||||
allow_redirects=False,
|
||||
)
|
||||
assert resp.status_code == 403
|
||||
|
||||
|
||||
def test_admin_can_toggle(app_server, seeded_db):
|
||||
_, target = _signup()
|
||||
admin = requests.Session()
|
||||
admin.post(
|
||||
f"{BASE_URL}/auth/login",
|
||||
data={"email": seeded_db["alice"]["email"], "password": seeded_db["alice"]["password"]},
|
||||
allow_redirects=True,
|
||||
)
|
||||
resp = admin.post(
|
||||
f"{BASE_URL}/profile/{target}/notifications/grouping",
|
||||
data={"value": "false"},
|
||||
headers=JSON,
|
||||
)
|
||||
assert resp.status_code == 200, resp.text[:200]
|
||||
assert resp.json()["data"]["notif_grouping_enabled"] is False
|
||||
|
||||
|
||||
def test_owner_toggles_enter_to_submit(app_server):
|
||||
session, name = _signup()
|
||||
resp = session.post(
|
||||
f"{BASE_URL}/profile/{name}/enter-to-submit",
|
||||
data={"value": "false"},
|
||||
headers=JSON,
|
||||
)
|
||||
assert resp.status_code == 200, resp.text[:200]
|
||||
assert resp.json()["data"]["enter_to_submit"] is False
|
||||
page = session.get(f"{BASE_URL}/profile/{name}", headers=JSON)
|
||||
assert page.json()["enter_to_submit"] is False
|
||||
resp = session.post(
|
||||
f"{BASE_URL}/profile/{name}/enter-to-submit",
|
||||
data={"value": "true"},
|
||||
headers=JSON,
|
||||
)
|
||||
assert resp.json()["data"]["enter_to_submit"] is True
|
||||
|
||||
|
||||
def test_other_user_cannot_toggle_enter_to_submit(app_server):
|
||||
_, target = _signup()
|
||||
attacker, _ = _signup()
|
||||
resp = attacker.post(
|
||||
f"{BASE_URL}/profile/{target}/enter-to-submit",
|
||||
data={"value": "false"},
|
||||
headers=JSON,
|
||||
allow_redirects=False,
|
||||
)
|
||||
assert resp.status_code == 403
|
||||
+62
-20
@@ -191,7 +191,7 @@ def app_server(test_db_path):
|
||||
except OSError:
|
||||
return ""
|
||||
|
||||
deadline = time.time() + 30
|
||||
deadline = time.time() + 120
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
import urllib.request
|
||||
@@ -208,8 +208,12 @@ def app_server(test_db_path):
|
||||
time.sleep(0.5)
|
||||
else:
|
||||
proc.terminate()
|
||||
proc.wait(timeout=5)
|
||||
raise RuntimeError(f"Server did not start after 30s. Log:\n{server_log()}")
|
||||
try:
|
||||
proc.wait(timeout=15)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
proc.wait(timeout=5)
|
||||
raise RuntimeError(f"Server did not start after 120s. Log:\n{server_log()}")
|
||||
|
||||
from devplacepy.database import set_setting as _set_setting
|
||||
|
||||
@@ -301,26 +305,39 @@ def page(browser_context):
|
||||
p.close()
|
||||
|
||||
|
||||
def signup_user(page, user):
|
||||
def _reach_feed(page, url, fill, submit_text):
|
||||
page.bring_to_front()
|
||||
page.goto(f"{BASE_URL}/auth/signup", wait_until="domcontentloaded")
|
||||
page.fill("#username", user["username"])
|
||||
page.fill("#email", user["email"])
|
||||
page.fill("#password", user["password"])
|
||||
page.fill("#confirm_password", user["password"])
|
||||
page.fill("#birth_date", "1990-01-01")
|
||||
page.check("#accept_terms")
|
||||
page.click("button:has-text('Create account')")
|
||||
page.wait_for_url("**/feed", timeout=10000, wait_until="domcontentloaded")
|
||||
for attempt in (1, 2):
|
||||
page.goto(url, wait_until="domcontentloaded")
|
||||
fill()
|
||||
try:
|
||||
page.click(f"button:has-text('{submit_text}')")
|
||||
page.wait_for_url("**/feed", timeout=10000, wait_until="domcontentloaded")
|
||||
return
|
||||
except Exception as error:
|
||||
dropped = "chrome-error://chromewebdata/" in str(error) or page.url.startswith("chrome-error:")
|
||||
if attempt == 2 or not dropped:
|
||||
raise
|
||||
|
||||
|
||||
def signup_user(page, user):
|
||||
def fill():
|
||||
page.fill("#username", user["username"])
|
||||
page.fill("#email", user["email"])
|
||||
page.fill("#password", user["password"])
|
||||
page.fill("#confirm_password", user["password"])
|
||||
page.fill("#birth_date", "1990-01-01")
|
||||
page.check("#accept_terms")
|
||||
|
||||
_reach_feed(page, f"{BASE_URL}/auth/signup", fill, "Create account")
|
||||
|
||||
|
||||
def login_user(page, user):
|
||||
page.bring_to_front()
|
||||
page.goto(f"{BASE_URL}/auth/login", wait_until="domcontentloaded")
|
||||
page.fill("#email", user["email"])
|
||||
page.fill("#password", user["password"])
|
||||
page.click("button:has-text('Sign in')")
|
||||
page.wait_for_url("**/feed", timeout=10000, wait_until="domcontentloaded")
|
||||
def fill():
|
||||
page.fill("#email", user["email"])
|
||||
page.fill("#password", user["password"])
|
||||
|
||||
_reach_feed(page, f"{BASE_URL}/auth/login", fill, "Sign in")
|
||||
|
||||
|
||||
def paste_image(page, selector, name="pasted.png"):
|
||||
@@ -365,10 +382,35 @@ def create_post_with_files(page, content, files, expected_count=1):
|
||||
page.wait_for_url(f"{BASE_URL}/posts/*", wait_until="domcontentloaded")
|
||||
|
||||
|
||||
def open_action_menu(locator):
|
||||
target = locator.first
|
||||
target.evaluate(
|
||||
"""el => {
|
||||
const menu = el.closest("dp-action-menu");
|
||||
if (!menu) return;
|
||||
const panel = menu.querySelector("[data-action-menu-panel]");
|
||||
if (panel && panel.matches(":popover-open")) return;
|
||||
if (typeof menu.open === "function") {
|
||||
menu.open();
|
||||
return;
|
||||
}
|
||||
const trigger = menu.querySelector("[data-action-menu-trigger]");
|
||||
if (trigger) trigger.click();
|
||||
}"""
|
||||
)
|
||||
return target
|
||||
|
||||
|
||||
def click_menu_action(locator):
|
||||
target = open_action_menu(locator)
|
||||
target.click()
|
||||
return target
|
||||
|
||||
|
||||
def assert_share_copies(page, expected_fragment):
|
||||
from playwright.sync_api import expect
|
||||
|
||||
share = page.locator("button[data-share]").first
|
||||
share = open_action_menu(page.locator("button[data-share]"))
|
||||
share.scroll_into_view_if_needed()
|
||||
assert expected_fragment in (share.get_attribute("data-share") or ""), (
|
||||
f"data-share={share.get_attribute('data-share')!r}"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
from playwright.sync_api import expect
|
||||
from tests.conftest import BASE_URL
|
||||
from tests.conftest import BASE_URL, assert_no_horizontal_overflow
|
||||
from tests.e2e.post import create_post
|
||||
|
||||
|
||||
@@ -43,6 +43,92 @@ def test_cancel_inline_edit(alice):
|
||||
expect(page.locator(".comment-text:has-text('Keep this body')")).to_be_visible()
|
||||
|
||||
|
||||
def _composer_metrics(textarea):
|
||||
return textarea.evaluate(
|
||||
"""el => {
|
||||
const form = el.closest("form");
|
||||
const actions = form.querySelector(".comment-form-actions");
|
||||
const field = el.getBoundingClientRect();
|
||||
const formBox = form.getBoundingClientRect();
|
||||
const actionBox = actions.getBoundingClientRect();
|
||||
const column = document.querySelector(".post-page, .feed-main");
|
||||
const columnBox = column ? column.getBoundingClientRect() : formBox;
|
||||
return {
|
||||
field: field.width,
|
||||
fieldHeight: field.height,
|
||||
form: formBox.width,
|
||||
column: columnBox.width,
|
||||
actionsTop: actionBox.top,
|
||||
actionsWidth: actionBox.width,
|
||||
fieldBottom: field.bottom,
|
||||
overflow: document.documentElement.scrollWidth - document.documentElement.clientWidth,
|
||||
};
|
||||
}"""
|
||||
)
|
||||
|
||||
|
||||
def _assert_composer_has_room(metrics, minimum_field, full_width=False):
|
||||
slack = 8 if full_width else 64
|
||||
assert metrics["field"] >= metrics["form"] - slack, metrics
|
||||
assert metrics["field"] >= minimum_field, metrics
|
||||
assert metrics["fieldHeight"] < 90, metrics
|
||||
assert metrics["actionsTop"] >= metrics["fieldBottom"] - 2, metrics
|
||||
assert metrics["actionsWidth"] <= metrics["form"] + 1, metrics
|
||||
assert metrics["overflow"] <= 1, metrics
|
||||
|
||||
|
||||
def _check_composer(page, textarea, minimum_field, full_width, min_column):
|
||||
textarea.fill("helps a lot.")
|
||||
metrics = _composer_metrics(textarea)
|
||||
_assert_composer_has_room(metrics, minimum_field, full_width)
|
||||
assert metrics["column"] >= min_column, metrics
|
||||
|
||||
|
||||
def test_comment_composer_field_keeps_its_width(alice):
|
||||
page, _ = alice
|
||||
page.set_viewport_size({"width": 1280, "height": 800})
|
||||
create_post(page, "devlog", "Post for the comment composer width")
|
||||
_post_comment(page, "Parent for the reply box")
|
||||
|
||||
composer = page.locator(".comment-form:not(.comment-reply-form) textarea[name='content']").last
|
||||
_check_composer(page, composer, 320, False, 480)
|
||||
|
||||
page.locator("[data-action='reply']").last.click()
|
||||
reply = page.locator(".comment-reply-form textarea[name='content']")
|
||||
expect(reply).to_be_visible()
|
||||
_check_composer(page, reply, 320, False, 480)
|
||||
|
||||
page.set_viewport_size({"width": 768, "height": 1024})
|
||||
_check_composer(page, reply, 280, False, 480)
|
||||
|
||||
page.set_viewport_size({"width": 390, "height": 844})
|
||||
_check_composer(page, reply, 200, True, 300)
|
||||
_check_composer(page, composer, 200, True, 300)
|
||||
|
||||
page.set_viewport_size({"width": 360, "height": 740})
|
||||
_check_composer(page, reply, 180, True, 280)
|
||||
assert_no_horizontal_overflow(page, ".post-page-layout")
|
||||
|
||||
page.set_viewport_size({"width": 1280, "height": 800})
|
||||
page.goto(f"{BASE_URL}/feed", wait_until="domcontentloaded")
|
||||
card = page.locator(".post-card").filter(has_text="Parent for the reply box").first
|
||||
expect(card).to_be_visible()
|
||||
card.locator("[data-action='reply']").first.click()
|
||||
feed_reply = card.locator(".comment-reply-form textarea[name='content']")
|
||||
expect(feed_reply).to_be_visible()
|
||||
_check_composer(page, feed_reply, 200, False, 480)
|
||||
|
||||
page.set_viewport_size({"width": 768, "height": 1024})
|
||||
_check_composer(page, feed_reply, 200, False, 400)
|
||||
|
||||
page.set_viewport_size({"width": 390, "height": 844})
|
||||
_check_composer(page, feed_reply, 160, True, 300)
|
||||
|
||||
page.set_viewport_size({"width": 360, "height": 740})
|
||||
_check_composer(page, feed_reply, 140, True, 280)
|
||||
assert_no_horizontal_overflow(page, ".feed-layout")
|
||||
|
||||
|
||||
def test_non_owner_sees_no_edit_button(alice, bob):
|
||||
page, _ = alice
|
||||
create_post(page, "random", "Post owned by alice")
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
from tests.conftest import BASE_URL, CACHE_VERSION_PROPAGATION_SECONDS, create_post_with_files, paste_image
|
||||
from tests.conftest import BASE_URL, CACHE_VERSION_PROPAGATION_SECONDS, click_menu_action, create_post_with_files, paste_image
|
||||
import time
|
||||
import requests
|
||||
from playwright.sync_api import expect
|
||||
@@ -849,7 +849,7 @@ def test_delete_own_post(alice):
|
||||
page, _ = alice
|
||||
create_post(page, "random", "Post to be deleted permanently here")
|
||||
post_url = page.url
|
||||
page.locator(".post-action-btn:has-text('Delete')").click()
|
||||
click_menu_action(page.locator("#post-actions-panel button:has-text('Delete')"))
|
||||
page.locator(".dialog-overlay.visible .dialog-confirm").click()
|
||||
page.wait_for_url(f"{BASE_URL}/feed", wait_until="domcontentloaded")
|
||||
set_setting("happy_404_enabled", "0")
|
||||
|
||||
@@ -35,6 +35,31 @@ def _warp_stealable(username):
|
||||
)
|
||||
|
||||
|
||||
def _clear_golden(username, crop="python"):
|
||||
from devplacepy.database import get_table
|
||||
from devplacepy.services.game import economy, store
|
||||
|
||||
user = get_table("users").find_one(username=username)
|
||||
farm = store.get_farm(user["uid"])
|
||||
for plot in store.get_plots(farm["uid"]):
|
||||
if plot.get("crop_key") != crop:
|
||||
continue
|
||||
raw = plot.get("planted_at") or ""
|
||||
try:
|
||||
start = datetime.fromisoformat(raw)
|
||||
except ValueError:
|
||||
start = datetime.now(timezone.utc)
|
||||
for step in range(2000):
|
||||
candidate = (start + timedelta(seconds=step)).isoformat()
|
||||
if economy.is_golden(plot["uid"], candidate):
|
||||
continue
|
||||
if candidate != raw:
|
||||
get_table("game_plots").update(
|
||||
{"uid": plot["uid"], "planted_at": candidate}, ["uid"]
|
||||
)
|
||||
break
|
||||
|
||||
|
||||
def _farm_coins(username):
|
||||
from devplacepy.database import get_table
|
||||
from devplacepy.services.game import store
|
||||
@@ -128,6 +153,7 @@ def test_steal_takes_build_and_pays_thief(bob):
|
||||
reset_farm("bob_test", coins=0)
|
||||
_plant_growing("alice_test", crop="python")
|
||||
_warp_stealable("alice_test")
|
||||
_clear_golden("alice_test")
|
||||
alice_coins_before = _farm_coins("alice_test")
|
||||
page.goto(f"{BASE_URL}/game/farm/alice_test", wait_until="domcontentloaded")
|
||||
page.locator("[data-game-grid]").first.wait_for(state="visible")
|
||||
|
||||
+6
-7
@@ -10,6 +10,7 @@ from tests.conftest import (
|
||||
BASE_URL,
|
||||
assert_no_horizontal_overflow,
|
||||
assert_share_copies,
|
||||
click_menu_action,
|
||||
)
|
||||
from devplacepy.database import get_table
|
||||
from devplacepy.utils import make_combined_slug
|
||||
@@ -201,8 +202,7 @@ def test_edit_gist(alice, app_server):
|
||||
page, _ = alice
|
||||
title = f"Edit Test Original {int(time.time())}"
|
||||
_create_gist(page, title=title, source_code="x = 1")
|
||||
page.locator("button:has-text('Edit')").wait_for(state="visible", timeout=5000)
|
||||
page.click("button:has-text('Edit')")
|
||||
click_menu_action(page.locator("#gist-actions-panel [data-modal='edit-gist-modal']"))
|
||||
page.wait_for_timeout(800)
|
||||
new_title = f"Edit Test Updated {int(time.time())}"
|
||||
page.fill("#edit-gist-title", new_title)
|
||||
@@ -230,8 +230,7 @@ def test_delete_gist(alice, app_server):
|
||||
page, _ = alice
|
||||
title = f"Delete Test {int(time.time())}"
|
||||
_create_gist(page, title=title, source_code="delete_me = True")
|
||||
page.locator("button[data-confirm='Delete this gist?']").wait_for(state="visible", timeout=5000)
|
||||
page.click("button[data-confirm='Delete this gist?']")
|
||||
click_menu_action(page.locator("#gist-actions-panel button[data-confirm='Delete this gist?']"))
|
||||
page.locator(".dialog-overlay.visible .dialog-confirm").click()
|
||||
page.wait_for_url(f"{BASE_URL}/gists", timeout=10000, wait_until="domcontentloaded")
|
||||
|
||||
@@ -595,7 +594,7 @@ def test_gist_created_hidden_leaves_the_listing(alice):
|
||||
|
||||
def _edit_gist_visibility(page, url, value):
|
||||
page.goto(url, wait_until="domcontentloaded")
|
||||
page.locator("[data-modal='edit-gist-modal']").click()
|
||||
click_menu_action(page.locator("#gist-actions-panel [data-modal='edit-gist-modal']"))
|
||||
page.select_option("#edit-gist-visibility", value)
|
||||
page.locator("#edit-gist-modal button.btn-primary").click()
|
||||
page.wait_for_url(url, wait_until="domcontentloaded")
|
||||
@@ -621,7 +620,7 @@ def test_gist_edit_modal_changes_visibility(alice):
|
||||
page, _ = alice
|
||||
title = f"VisGistEdit{int(time.time() * 1000)}"
|
||||
url = _create_gist_with_visibility(page, title, None)
|
||||
page.locator("[data-modal='edit-gist-modal']").click()
|
||||
click_menu_action(page.locator("#gist-actions-panel [data-modal='edit-gist-modal']"))
|
||||
expect(page.locator("#edit-gist-visibility")).to_have_value("published")
|
||||
page.select_option("#edit-gist-visibility", "hidden")
|
||||
page.locator("#edit-gist-modal button.btn-primary").click()
|
||||
@@ -633,6 +632,6 @@ def test_gist_visibility_field_fits_a_phone(mobile_page):
|
||||
page, _ = mobile_page
|
||||
title = f"VisGistPhone{int(time.time() * 1000)}"
|
||||
_create_gist_with_visibility(page, title, "hidden")
|
||||
page.locator("[data-modal='edit-gist-modal']").click()
|
||||
click_menu_action(page.locator("#gist-actions-panel [data-modal='edit-gist-modal']"))
|
||||
expect(page.locator("#edit-gist-visibility")).to_be_visible()
|
||||
assert_no_horizontal_overflow(page, ".gist-detail-page")
|
||||
|
||||
+244
-4
@@ -5,7 +5,6 @@ import time
|
||||
from playwright.sync_api import expect
|
||||
from tests.conftest import BASE_URL, paste_image
|
||||
from devplacepy.database import get_table
|
||||
import requests
|
||||
def _seed_news_seo():
|
||||
from datetime import datetime, timezone
|
||||
from devplacepy.database import get_table
|
||||
@@ -557,13 +556,15 @@ def _uid(username):
|
||||
|
||||
|
||||
def _send_as(page, receiver_uid, content):
|
||||
page.evaluate(
|
||||
ok = page.evaluate(
|
||||
"async ([uid, text]) => {"
|
||||
" const body = new URLSearchParams({receiver_uid: uid, content: text});"
|
||||
" await fetch('/messages/send', {method: 'POST', body, headers: {Accept: 'application/json'}});"
|
||||
" const resp = await fetch('/messages/send', {method: 'POST', body, headers: {Accept: 'application/json'}});"
|
||||
" return resp.ok;"
|
||||
"}",
|
||||
[receiver_uid, content],
|
||||
)
|
||||
assert ok, "seed message send must succeed"
|
||||
|
||||
|
||||
def test_dock_icon_opens_chats_panel_then_a_docked_window(alice, bob):
|
||||
@@ -666,7 +667,7 @@ def test_dock_is_absent_on_messages_page(alice):
|
||||
def test_mobile_messages_icon_opens_the_messages_page(mobile_page):
|
||||
page, _ = mobile_page
|
||||
page.goto(f"{BASE_URL}/feed", wait_until="domcontentloaded")
|
||||
page.locator("[data-chat-panel-toggle]").first.click(force=True)
|
||||
page.locator("[data-chat-panel-toggle]").first.click()
|
||||
page.wait_for_url(f"{BASE_URL}/messages", wait_until="domcontentloaded")
|
||||
|
||||
|
||||
@@ -686,3 +687,242 @@ def test_composer_plus_button_reveals_attach_tools(alice):
|
||||
area.locator("textarea[name='content']").fill("typing tucks the tools away")
|
||||
expect(upload).to_be_hidden()
|
||||
expect(more).to_have_attribute("aria-expanded", "false")
|
||||
|
||||
|
||||
def test_dock_window_plus_button_reveals_attach_tools(alice, bob):
|
||||
page_a, _ = alice
|
||||
_, user_b = bob
|
||||
uid_b = _uid(user_b["username"])
|
||||
page_a.goto(f"{BASE_URL}/profile/{user_b['username']}", wait_until="domcontentloaded")
|
||||
page_a.locator(f"[data-chat-open='{uid_b}']").click()
|
||||
window = page_a.locator(f".chat-window[data-chat-uid='{uid_b}']")
|
||||
area = window.locator(".messages-input-area")
|
||||
upload = area.locator("dp-upload .dp-upload-btn")
|
||||
more = area.locator(".composer-more-btn")
|
||||
expect(upload).to_be_hidden()
|
||||
more.click()
|
||||
expect(upload).to_be_visible()
|
||||
expect(more).to_have_attribute("aria-expanded", "true")
|
||||
area.locator("textarea[name='content']").fill("typing in the window")
|
||||
expect(upload).to_be_hidden()
|
||||
|
||||
|
||||
def test_dock_open_window_survives_navigation(alice, bob):
|
||||
page_a, user_a = alice
|
||||
page_b, user_b = bob
|
||||
uid_b = _uid(user_b["username"])
|
||||
msg = f"Restore me {int(time.time() * 1000)}"
|
||||
_send_as(page_b, _uid(user_a["username"]), msg)
|
||||
page_a.goto(f"{BASE_URL}/profile/{user_b['username']}", wait_until="domcontentloaded")
|
||||
page_a.locator(f"[data-chat-open='{uid_b}']").click()
|
||||
window = page_a.locator(f".chat-window[data-chat-uid='{uid_b}']")
|
||||
window.locator(f".message-bubble:has-text('{msg}')").wait_for(state="visible")
|
||||
page_a.goto(f"{BASE_URL}/projects", wait_until="domcontentloaded")
|
||||
window = page_a.locator(f".chat-window[data-chat-uid='{uid_b}']")
|
||||
window.locator(f".message-bubble:has-text('{msg}')").wait_for(state="visible")
|
||||
expect(window.locator("textarea[name='content']")).to_be_visible()
|
||||
|
||||
|
||||
def test_dock_panel_search_and_see_all(alice, bob):
|
||||
page_a, _ = alice
|
||||
_, user_b = bob
|
||||
uid_b = _uid(user_b["username"])
|
||||
page_a.goto(f"{BASE_URL}/feed", wait_until="domcontentloaded")
|
||||
page_a.locator("[data-chat-panel-toggle]").first.click()
|
||||
panel = page_a.locator(".chat-panel")
|
||||
expect(panel).to_be_visible()
|
||||
expect(panel.locator(".chat-panel-footer")).to_have_attribute("href", "/messages")
|
||||
panel.locator(".chat-panel-search-input").fill(user_b["username"])
|
||||
item = panel.locator(f".conversation-item[data-conv-uid='{uid_b}']")
|
||||
item.wait_for(state="visible")
|
||||
item.click()
|
||||
expect(panel).to_be_hidden()
|
||||
expect(page_a.locator(f".chat-window[data-chat-uid='{uid_b}']")).to_have_count(1)
|
||||
|
||||
|
||||
def test_dock_panel_and_window_close_controls(alice, bob):
|
||||
page_a, _ = alice
|
||||
_, user_b = bob
|
||||
uid_b = _uid(user_b["username"])
|
||||
page_a.goto(f"{BASE_URL}/feed", wait_until="domcontentloaded")
|
||||
toggle = page_a.locator("[data-chat-panel-toggle]").first
|
||||
panel = page_a.locator(".chat-panel")
|
||||
toggle.click()
|
||||
expect(panel).to_be_visible()
|
||||
page_a.keyboard.press("Escape")
|
||||
expect(panel).to_be_hidden()
|
||||
toggle.click()
|
||||
expect(panel).to_be_visible()
|
||||
page_a.locator("body").click(position={"x": 700, "y": 500})
|
||||
expect(panel).to_be_hidden()
|
||||
|
||||
page_a.goto(f"{BASE_URL}/profile/{user_b['username']}", wait_until="domcontentloaded")
|
||||
page_a.locator(f"[data-chat-open='{uid_b}']").click()
|
||||
window = page_a.locator(f".chat-window[data-chat-uid='{uid_b}']")
|
||||
window.locator(".chat-window-close").click()
|
||||
expect(window).to_have_count(0)
|
||||
|
||||
page_a.locator(f"[data-chat-open='{uid_b}']").click()
|
||||
window.locator(".chat-window-minimize").click()
|
||||
head = page_a.locator(f".chat-head[data-chat-uid='{uid_b}']")
|
||||
head.wait_for(state="visible")
|
||||
head.locator(".chat-head-close").click()
|
||||
expect(head).to_have_count(0)
|
||||
|
||||
|
||||
def test_dock_caps_expanded_windows_at_three(alice, bob):
|
||||
page_a, _ = alice
|
||||
_, user_b = bob
|
||||
from devplacepy.utils import generate_uid
|
||||
|
||||
partners = [_uid(user_b["username"])]
|
||||
for name in ("dockcap1", "dockcap2", "dockcap3"):
|
||||
row = get_table("users").find_one(username=name)
|
||||
if not row:
|
||||
get_table("users").insert(
|
||||
{
|
||||
"deleted_at": None,
|
||||
"deleted_by": None,
|
||||
"uid": generate_uid(),
|
||||
"username": name,
|
||||
"email": f"{name}@test.devplace",
|
||||
"password_hash": "x",
|
||||
"role": "Member",
|
||||
"is_active": True,
|
||||
"created_at": "2026-01-01T00:00:00+00:00",
|
||||
}
|
||||
)
|
||||
row = get_table("users").find_one(username=name)
|
||||
partners.append(row["uid"])
|
||||
page_a.goto(f"{BASE_URL}/feed", wait_until="domcontentloaded")
|
||||
for uid in partners:
|
||||
page_a.evaluate("(uid) => window.app.chatDock.open({ uid, username: 'x' }, { focus: false })", uid)
|
||||
expect(page_a.locator(".chat-window:not(.chat-window-compose)")).to_have_count(3)
|
||||
expect(page_a.locator(".chat-head")).to_have_count(1)
|
||||
|
||||
|
||||
def test_dock_toast_click_opens_window(alice, bob):
|
||||
page_a, user_a = alice
|
||||
page_b, _ = bob
|
||||
uid_a = _uid(user_a["username"])
|
||||
uid_b = _uid("bob_test")
|
||||
page_a.goto(f"{BASE_URL}/feed", wait_until="domcontentloaded")
|
||||
page_a.wait_for_function("() => !!window.app && !!window.app.chatDock")
|
||||
msg = f"Toast hello {int(time.time() * 1000)}"
|
||||
_send_as(page_b, uid_a, msg)
|
||||
page_a.evaluate(
|
||||
"(sender) => window.app.liveNotifications.onNotification("
|
||||
" { uid: 'toast-test', type: 'message', message: 'bob_test sent you a message',"
|
||||
" target_url: `/messages?with_uid=${sender}` })",
|
||||
uid_b,
|
||||
)
|
||||
toast = page_a.locator(".dp-toast-link")
|
||||
toast.first.wait_for(state="visible", timeout=10000)
|
||||
toast.first.click()
|
||||
window = page_a.locator(f".chat-window[data-chat-uid='{uid_b}']")
|
||||
window.locator(f".message-bubble:has-text('{msg}')").wait_for(state="visible", timeout=10000)
|
||||
assert page_a.url.endswith("/feed")
|
||||
|
||||
|
||||
def test_dock_window_live_message_shows_report_button(alice, bob):
|
||||
page_a, user_a = alice
|
||||
page_b, user_b = bob
|
||||
uid_a = _uid(user_a["username"])
|
||||
uid_b = _uid(user_b["username"])
|
||||
page_a.goto(f"{BASE_URL}/profile/{user_b['username']}", wait_until="domcontentloaded")
|
||||
page_a.locator(f"[data-chat-open='{uid_b}']").click()
|
||||
window = page_a.locator(f".chat-window[data-chat-uid='{uid_b}']")
|
||||
window.locator("textarea[name='content']").wait_for(state="visible")
|
||||
msg = f"Flag in window {int(time.time() * 1000)}"
|
||||
_send_as(page_b, uid_a, msg)
|
||||
bubble = window.locator(f".message-bubble.theirs:has-text('{msg}')")
|
||||
bubble.wait_for(state="visible", timeout=10000)
|
||||
expect(bubble.locator(".message-report-btn")).to_be_visible()
|
||||
|
||||
|
||||
def test_dock_reading_on_messages_page_clears_head_badge(alice, bob):
|
||||
page_a, user_a = alice
|
||||
page_b, user_b = bob
|
||||
uid_a = _uid(user_a["username"])
|
||||
uid_b = _uid(user_b["username"])
|
||||
page_a.goto(f"{BASE_URL}/profile/{user_b['username']}", wait_until="domcontentloaded")
|
||||
page_a.locator(f"[data-chat-open='{uid_b}']").click()
|
||||
window = page_a.locator(f".chat-window[data-chat-uid='{uid_b}']")
|
||||
window.locator(".chat-window-minimize").click()
|
||||
head = page_a.locator(f".chat-head[data-chat-uid='{uid_b}']")
|
||||
head.wait_for(state="visible")
|
||||
_send_as(page_b, uid_a, f"Badge check {int(time.time() * 1000)}")
|
||||
expect(head.locator(".chat-head-badge")).to_have_text("1", timeout=10000)
|
||||
|
||||
page_a.goto(f"{BASE_URL}/messages?with_uid={uid_b}", wait_until="domcontentloaded")
|
||||
page_a.locator(".messages-thread .message-bubble").first.wait_for(state="visible")
|
||||
page_a.goto(f"{BASE_URL}/feed", wait_until="domcontentloaded")
|
||||
head = page_a.locator(f".chat-head[data-chat-uid='{uid_b}']")
|
||||
head.wait_for(state="visible")
|
||||
expect(head.locator(".chat-head-badge")).to_be_hidden(timeout=10000)
|
||||
|
||||
|
||||
def test_dock_hidden_tab_does_not_mark_read_until_visible(alice, bob):
|
||||
page_a, user_a = alice
|
||||
page_b, user_b = bob
|
||||
uid_a = _uid(user_a["username"])
|
||||
uid_b = _uid(user_b["username"])
|
||||
page_a.goto(f"{BASE_URL}/profile/{user_b['username']}", wait_until="domcontentloaded")
|
||||
page_a.locator(f"[data-chat-open='{uid_b}']").click()
|
||||
window = page_a.locator(f".chat-window[data-chat-uid='{uid_b}']")
|
||||
window.locator("textarea[name='content']").wait_for(state="visible")
|
||||
page_a.wait_for_function("() => document.querySelector('dp-chat-dock').hub.isOpen()")
|
||||
|
||||
page_a.evaluate(
|
||||
"() => { Object.defineProperty(document, 'visibilityState', { value: 'hidden', configurable: true });"
|
||||
" document.dispatchEvent(new Event('visibilitychange')); }"
|
||||
)
|
||||
msg = f"Hidden tab {int(time.time() * 1000)}"
|
||||
_send_as(page_b, uid_a, msg)
|
||||
window.locator(f".message-bubble:has-text('{msg}')").wait_for(state="visible", timeout=10000)
|
||||
page_a.wait_for_timeout(500)
|
||||
unread = page_a.evaluate(
|
||||
"async (uid) => { const r = await fetch('/messages/conversations', {headers: {Accept: 'application/json'}});"
|
||||
" const d = await r.json(); const c = (d.conversations || []).find((x) => x.other_user.uid === uid);"
|
||||
" return c ? c.unread : null; }",
|
||||
uid_b,
|
||||
)
|
||||
assert unread is True, "a message to a window in a hidden tab must stay unread"
|
||||
|
||||
page_a.evaluate(
|
||||
"() => { Object.defineProperty(document, 'visibilityState', { value: 'visible', configurable: true });"
|
||||
" document.dispatchEvent(new Event('visibilitychange')); }"
|
||||
)
|
||||
page_a.wait_for_function(
|
||||
"async (uid) => { const r = await fetch('/messages/conversations', {headers: {Accept: 'application/json'}});"
|
||||
" const d = await r.json(); const c = (d.conversations || []).find((x) => x.other_user.uid === uid);"
|
||||
" return !!c && c.unread === false; }",
|
||||
arg=uid_b,
|
||||
timeout=10000,
|
||||
)
|
||||
|
||||
|
||||
def test_dock_socket_does_not_resurrect_after_last_window_closes(alice, bob):
|
||||
page_a, _ = alice
|
||||
_, user_b = bob
|
||||
uid_b = _uid(user_b["username"])
|
||||
page_a.goto(f"{BASE_URL}/profile/{user_b['username']}", wait_until="domcontentloaded")
|
||||
page_a.locator(f"[data-chat-open='{uid_b}']").click()
|
||||
page_a.locator(f".chat-window[data-chat-uid='{uid_b}'] textarea[name='content']").wait_for(state="visible")
|
||||
page_a.wait_for_function("() => document.querySelector('dp-chat-dock').hub.isOpen()")
|
||||
result = page_a.evaluate(
|
||||
"async (uid) => {"
|
||||
" const dock = document.querySelector('dp-chat-dock');"
|
||||
" const cs = dock.hub.socket;"
|
||||
" let opens = 0; const orig = cs._open.bind(cs);"
|
||||
" cs._open = () => { opens += 1; return orig(); };"
|
||||
" cs.socket.close();"
|
||||
" await new Promise((r) => setTimeout(r, 100));"
|
||||
" dock.close(uid);"
|
||||
" await new Promise((r) => setTimeout(r, 900));"
|
||||
" return { opens, hubSocket: dock.hub.socket === null, state: cs.socket ? cs.socket.readyState : null };"
|
||||
"}",
|
||||
uid_b,
|
||||
)
|
||||
assert result["hubSocket"], "the hub must not hold a socket after the last window closes"
|
||||
assert result["opens"] == 0, f"a closed socket must not reconnect with zero subscribers: {result}"
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from playwright.sync_api import expect
|
||||
|
||||
from tests.conftest import BASE_URL
|
||||
from devplacepy.database import get_table, refresh_snapshot
|
||||
from devplacepy.utils import generate_uid
|
||||
|
||||
JSON = {"Accept": "application/json"}
|
||||
|
||||
|
||||
def _seed_votes(user_uid, count=4):
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
table = get_table("notifications")
|
||||
for i in range(count):
|
||||
table.insert(
|
||||
{
|
||||
"uid": generate_uid(),
|
||||
"user_uid": user_uid,
|
||||
"type": "vote",
|
||||
"message": f"voter-{i} ++'d your post",
|
||||
"related_uid": user_uid,
|
||||
"target_url": "/posts/grouped-seed",
|
||||
"read": False,
|
||||
"created_at": now,
|
||||
}
|
||||
)
|
||||
refresh_snapshot()
|
||||
|
||||
|
||||
def test_grouped_notifications_card(alice, seeded_db):
|
||||
page, user = alice
|
||||
uid = get_table("users").find_one(username=user["username"])["uid"]
|
||||
_seed_votes(uid)
|
||||
try:
|
||||
page.goto(f"{BASE_URL}/notifications", wait_until="domcontentloaded")
|
||||
card = page.locator("[data-notification-group]").first
|
||||
expect(card).to_be_visible(timeout=10000)
|
||||
expect(card.locator(".notif-group-count")).to_have_text("×4")
|
||||
finally:
|
||||
get_table("notifications").delete(user_uid=uid, target_url="/posts/grouped-seed")
|
||||
refresh_snapshot()
|
||||
|
||||
|
||||
def test_grouping_toggle_on_profile_notifications_tab(alice):
|
||||
page, user = alice
|
||||
username = user["username"]
|
||||
page.goto(f"{BASE_URL}/profile/{username}?tab=notifications", wait_until="domcontentloaded")
|
||||
panel = page.locator("[data-notif-prefs]")
|
||||
expect(panel.locator("form[action$='/notifications/grouping']")).to_be_attached()
|
||||
expect(panel.locator("form[action$='/notifications/throttling']")).to_be_attached()
|
||||
expect(page.locator("[data-enter-to-submit-card]")).to_be_attached()
|
||||
@@ -4,7 +4,6 @@ from datetime import datetime, timedelta, timezone
|
||||
from tests.conftest import BASE_URL
|
||||
from devplacepy.database import get_table
|
||||
from devplacepy.utils import generate_uid
|
||||
import requests
|
||||
def _seed_news_seo():
|
||||
from datetime import datetime, timezone
|
||||
from devplacepy.database import get_table
|
||||
@@ -764,8 +763,6 @@ def test_message_notification_click_opens_conversation(app_server, browser, seed
|
||||
card = pa.locator(".notification-card").filter(has_text="sent you a message").first
|
||||
card.wait_for(state="visible", timeout=10000)
|
||||
card.locator("a.card-link").click()
|
||||
from devplacepy.database import get_table
|
||||
|
||||
bob_uid = get_table("users").find_one(username=seeded_db["bob"]["username"])["uid"]
|
||||
window = pa.locator(f".chat-window[data-chat-uid='{bob_uid}']")
|
||||
window.locator(".message-bubble:has-text('Click-through message from bob')").first.wait_for(
|
||||
|
||||
@@ -14,7 +14,7 @@ def _create_plain_post_engagement_ui(page, content):
|
||||
page.wait_for_url(f"{BASE_URL}/posts/*", wait_until="domcontentloaded")
|
||||
from uuid import uuid4
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from tests.conftest import BASE_URL, assert_share_copies
|
||||
from tests.conftest import BASE_URL, assert_share_copies, click_menu_action, open_action_menu
|
||||
from devplacepy.database import get_table
|
||||
from devplacepy.utils import make_combined_slug
|
||||
def _seed_posts(count):
|
||||
@@ -378,7 +378,7 @@ def test_add_poll_to_existing_post_via_edit(alice):
|
||||
_create_plain_post_engagement_ui(page, "Post that gains a poll through the edit modal.")
|
||||
expect(page.locator(".poll")).to_have_count(0)
|
||||
|
||||
page.locator("[data-modal='edit-post-modal']").click()
|
||||
click_menu_action(page.locator("#post-actions-panel [data-modal='edit-post-modal']"))
|
||||
modal = page.locator("#edit-post-modal")
|
||||
expect(modal).to_be_visible()
|
||||
modal.locator("[data-poll-toggle]").click()
|
||||
@@ -485,7 +485,7 @@ def test_post_edit_button(alice):
|
||||
page.fill("#post-title", "Editable Post")
|
||||
page.locator("#create-post-modal button.btn-primary:has-text('Post')").click()
|
||||
page.wait_for_url(f"{BASE_URL}/posts/*", wait_until="domcontentloaded")
|
||||
edit_btn = page.locator("button:has-text('Edit')")
|
||||
edit_btn = open_action_menu(page.locator("#post-actions-panel [data-modal='edit-post-modal']"))
|
||||
assert edit_btn.is_visible()
|
||||
|
||||
|
||||
@@ -497,7 +497,7 @@ def test_post_edit_modal(alice):
|
||||
page.fill("#post-title", "Edit Modal Test")
|
||||
page.locator("#create-post-modal button.btn-primary:has-text('Post')").click()
|
||||
page.wait_for_url(f"{BASE_URL}/posts/*", wait_until="domcontentloaded")
|
||||
page.click("button:has-text('Edit')")
|
||||
click_menu_action(page.locator("#post-actions-panel [data-modal='edit-post-modal']"))
|
||||
assert page.is_visible("h3:has-text('Edit Post')")
|
||||
|
||||
|
||||
@@ -509,7 +509,7 @@ def test_post_edit_submit(alice):
|
||||
page.fill("#post-title", "Original Title")
|
||||
page.locator("#create-post-modal button.btn-primary:has-text('Post')").click()
|
||||
page.wait_for_url(f"{BASE_URL}/posts/*", wait_until="domcontentloaded")
|
||||
page.click("button:has-text('Edit')")
|
||||
click_menu_action(page.locator("#post-actions-panel [data-modal='edit-post-modal']"))
|
||||
page.fill("#edit-title", "Edited Title")
|
||||
page.fill("#edit-content", "Edited content for the post")
|
||||
page.click("button:has-text('Save Changes')")
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
import time
|
||||
|
||||
from playwright.sync_api import expect
|
||||
|
||||
from tests.conftest import BASE_URL
|
||||
|
||||
JSON = {"Accept": "application/json"}
|
||||
|
||||
|
||||
def _create_post(page, content):
|
||||
page.goto(f"{BASE_URL}/feed", wait_until="domcontentloaded")
|
||||
page.locator(".feed-fab").first.wait_for(state="visible", timeout=10000)
|
||||
page.locator(".feed-fab").first.click()
|
||||
page.fill("#post-title", f"Requested {int(time.time() * 1000)}")
|
||||
page.fill("#post-content", content)
|
||||
page.locator("#create-post-modal button.btn-primary:has-text('Post')").click()
|
||||
page.wait_for_url(f"{BASE_URL}/posts/*", wait_until="domcontentloaded")
|
||||
|
||||
|
||||
def test_title_is_first_and_focused(alice):
|
||||
page, _user = alice
|
||||
page.goto(f"{BASE_URL}/feed", wait_until="domcontentloaded")
|
||||
page.locator(".feed-fab").first.wait_for(state="visible", timeout=10000)
|
||||
page.locator(".feed-fab").first.click()
|
||||
title = page.locator("#post-title")
|
||||
expect(title).to_be_focused()
|
||||
order = page.evaluate(
|
||||
"""() => {
|
||||
const title = document.querySelector('#post-title');
|
||||
const content = document.querySelector('#post-content');
|
||||
return (title.compareDocumentPosition(content) & Node.DOCUMENT_POSITION_FOLLOWING) !== 0;
|
||||
}"""
|
||||
)
|
||||
assert order is True
|
||||
|
||||
|
||||
def test_post_detail_groups_secondary_actions_in_more_menu(alice):
|
||||
page, _user = alice
|
||||
_create_post(page, "Menu grouping post content.")
|
||||
expect(page.locator(".post-votes")).to_be_visible()
|
||||
expect(page.locator("[data-action-menu-trigger]")).to_be_visible()
|
||||
panel = page.locator("#post-actions-panel")
|
||||
expect(panel).to_be_hidden()
|
||||
page.locator("[data-action-menu-trigger]").click()
|
||||
expect(panel).to_be_visible()
|
||||
expect(panel.locator("[data-share]")).to_be_visible()
|
||||
expect(panel.locator(".bookmark-btn")).to_be_visible()
|
||||
page.keyboard.press("Escape")
|
||||
expect(panel).to_be_hidden()
|
||||
|
||||
|
||||
def test_comment_enter_posts_and_shift_enter_newlines(alice):
|
||||
page, user = alice
|
||||
username = user["username"]
|
||||
try:
|
||||
_create_post(page, "Enter key comment post content.")
|
||||
box = page.locator(".comment-form textarea[name='content']").first
|
||||
box.click()
|
||||
box.fill("First line")
|
||||
box.press("Shift+Enter")
|
||||
box.type("second line")
|
||||
assert "\n" in box.input_value()
|
||||
box.fill("Posted by Enter key")
|
||||
box.press("Enter")
|
||||
expect(page.locator(".comment-text", has_text="Posted by Enter key").first).to_be_visible(timeout=10000)
|
||||
finally:
|
||||
page.request.post(
|
||||
f"{BASE_URL}/profile/{username}/enter-to-submit",
|
||||
form={"value": "true"},
|
||||
headers=JSON,
|
||||
)
|
||||
|
||||
|
||||
def test_comment_enter_newlines_when_setting_off(alice):
|
||||
page, user = alice
|
||||
username = user["username"]
|
||||
resp = page.request.post(
|
||||
f"{BASE_URL}/profile/{username}/enter-to-submit",
|
||||
form={"value": "false"},
|
||||
headers=JSON,
|
||||
)
|
||||
assert resp.status == 200
|
||||
try:
|
||||
_create_post(page, "Enter off comment post content.")
|
||||
box = page.locator(".comment-form textarea[name='content']").first
|
||||
box.click()
|
||||
box.fill("Not posted yet")
|
||||
box.press("Enter")
|
||||
box.type("still editing")
|
||||
assert "still editing" in box.input_value()
|
||||
expect(page.locator(".comment-text", has_text="Not posted yet")).to_have_count(0)
|
||||
finally:
|
||||
page.request.post(
|
||||
f"{BASE_URL}/profile/{username}/enter-to-submit",
|
||||
form={"value": "true"},
|
||||
headers=JSON,
|
||||
)
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import time
|
||||
from playwright.sync_api import expect
|
||||
from tests.conftest import BASE_URL, assert_no_horizontal_overflow
|
||||
from tests.conftest import BASE_URL, assert_no_horizontal_overflow, click_menu_action
|
||||
|
||||
|
||||
def _unique():
|
||||
@@ -23,7 +23,7 @@ def _compose(page, token, visibility=None):
|
||||
|
||||
def _edit_visibility(page, url, value):
|
||||
page.goto(url, wait_until="domcontentloaded")
|
||||
page.locator("[data-modal='edit-post-modal']").click()
|
||||
click_menu_action(page.locator("#post-actions-panel [data-modal='edit-post-modal']"))
|
||||
page.select_option("#edit-post-visibility", value)
|
||||
page.locator("#edit-post-form button.btn-primary").click()
|
||||
page.wait_for_url(url, wait_until="domcontentloaded")
|
||||
@@ -38,7 +38,7 @@ def test_new_post_defaults_to_published(alice):
|
||||
page, _ = alice
|
||||
token = _unique()
|
||||
url = _compose(page, token)
|
||||
page.locator("[data-modal='edit-post-modal']").click()
|
||||
click_menu_action(page.locator("#post-actions-panel [data-modal='edit-post-modal']"))
|
||||
expect(page.locator("#edit-post-visibility")).to_have_value("published")
|
||||
assert _feed_has(page, token)
|
||||
page.goto(url, wait_until="domcontentloaded")
|
||||
@@ -57,7 +57,7 @@ def test_create_hidden_post_leaves_the_feed(alice):
|
||||
page, _ = alice
|
||||
token = _unique()
|
||||
url = _compose(page, token, "hidden")
|
||||
page.locator("[data-modal='edit-post-modal']").click()
|
||||
click_menu_action(page.locator("#post-actions-panel [data-modal='edit-post-modal']"))
|
||||
expect(page.locator("#edit-post-visibility")).to_have_value("hidden")
|
||||
assert not _feed_has(page, token)
|
||||
page.goto(url, wait_until="domcontentloaded")
|
||||
@@ -92,7 +92,7 @@ def test_offline_post_is_not_shown_to_other_members(alice, bob):
|
||||
def test_edit_form_lists_the_three_choices(alice):
|
||||
page, _ = alice
|
||||
_compose(page, _unique())
|
||||
page.locator("[data-modal='edit-post-modal']").click()
|
||||
click_menu_action(page.locator("#post-actions-panel [data-modal='edit-post-modal']"))
|
||||
options = page.locator("#edit-post-visibility option")
|
||||
assert options.all_text_contents() == ["Published", "Hidden", "Offline"]
|
||||
|
||||
@@ -100,6 +100,6 @@ def test_edit_form_lists_the_three_choices(alice):
|
||||
def test_visibility_field_fits_a_phone(mobile_page):
|
||||
page, _ = mobile_page
|
||||
_compose(page, _unique(), "hidden")
|
||||
page.locator("[data-modal='edit-post-modal']").click()
|
||||
click_menu_action(page.locator("#post-actions-panel [data-modal='edit-post-modal']"))
|
||||
expect(page.locator("#edit-post-visibility")).to_be_visible()
|
||||
assert_no_horizontal_overflow(page, ".post-page")
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
from uuid import uuid4
|
||||
from datetime import datetime, timezone
|
||||
from playwright.sync_api import expect
|
||||
from tests.conftest import BASE_URL
|
||||
from tests.conftest import BASE_URL, open_action_menu
|
||||
from devplacepy.database import get_table
|
||||
from devplacepy.utils import make_combined_slug
|
||||
|
||||
@@ -15,33 +15,15 @@ def _confirm(page):
|
||||
page.locator(".dialog-overlay.visible .dialog-confirm").click()
|
||||
|
||||
|
||||
TRIGGER = "[data-action-menu-trigger]"
|
||||
|
||||
|
||||
def _open_menu(page):
|
||||
# aria-expanded can lag behind the popover (a dialog closing, a light
|
||||
# dismiss), so the open state that counts is whether the panel shows.
|
||||
page.wait_for_function(
|
||||
"() => document.querySelector('[data-action-menu-panel]') !== null"
|
||||
" || document.querySelector('[data-action-menu-trigger]') === null"
|
||||
)
|
||||
panel = page.locator("[data-action-menu-panel]")
|
||||
if panel.count() and panel.evaluate("(el) => el.matches(':popover-open')"):
|
||||
return
|
||||
page.click(TRIGGER)
|
||||
page.wait_for_function(
|
||||
"() => document.querySelector('[data-action-menu-panel]').matches(':popover-open')"
|
||||
)
|
||||
|
||||
|
||||
def _has(page, selector):
|
||||
_open_menu(page)
|
||||
return page.is_visible(selector)
|
||||
loc = page.locator(selector)
|
||||
if loc.count() == 0:
|
||||
return False
|
||||
return open_action_menu(loc).is_visible()
|
||||
|
||||
|
||||
def _pick(page, selector):
|
||||
_open_menu(page)
|
||||
page.click(selector)
|
||||
open_action_menu(page.locator(selector)).click()
|
||||
|
||||
|
||||
def _reset_block(page):
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
from playwright.sync_api import expect
|
||||
from tests.conftest import BASE_URL
|
||||
from tests.conftest import BASE_URL, open_action_menu
|
||||
|
||||
MUTE = "form[action='/mute/bob_test'] button"
|
||||
UNMUTE = "form[action='/mute/unmute/bob_test'] button"
|
||||
@@ -11,33 +11,15 @@ def _confirm(page):
|
||||
page.locator(".dialog-overlay.visible .dialog-confirm").click()
|
||||
|
||||
|
||||
TRIGGER = "[data-action-menu-trigger]"
|
||||
|
||||
|
||||
def _open_menu(page):
|
||||
# aria-expanded can lag behind the popover (a dialog closing, a light
|
||||
# dismiss), so the open state that counts is whether the panel shows.
|
||||
page.wait_for_function(
|
||||
"() => document.querySelector('[data-action-menu-panel]') !== null"
|
||||
" || document.querySelector('[data-action-menu-trigger]') === null"
|
||||
)
|
||||
panel = page.locator("[data-action-menu-panel]")
|
||||
if panel.count() and panel.evaluate("(el) => el.matches(':popover-open')"):
|
||||
return
|
||||
page.click(TRIGGER)
|
||||
page.wait_for_function(
|
||||
"() => document.querySelector('[data-action-menu-panel]').matches(':popover-open')"
|
||||
)
|
||||
|
||||
|
||||
def _has(page, selector):
|
||||
_open_menu(page)
|
||||
return page.is_visible(selector)
|
||||
loc = page.locator(selector)
|
||||
if loc.count() == 0:
|
||||
return False
|
||||
return open_action_menu(loc).is_visible()
|
||||
|
||||
|
||||
def _pick(page, selector):
|
||||
_open_menu(page)
|
||||
page.click(selector)
|
||||
open_action_menu(page.locator(selector)).click()
|
||||
|
||||
|
||||
def _reset_mute(page):
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
from uuid import uuid4
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from playwright.sync_api import expect
|
||||
from tests.conftest import BASE_URL
|
||||
from tests.conftest import BASE_URL, open_action_menu
|
||||
from devplacepy.database import get_table
|
||||
from devplacepy.utils import make_combined_slug
|
||||
|
||||
@@ -133,7 +133,9 @@ def test_devlog_shows_vote_and_comment_buttons(alice):
|
||||
expect(post_card.locator(".post-action-btn.vote-up")).to_be_visible()
|
||||
expect(post_card.locator(".post-action-btn.vote-down")).to_be_visible()
|
||||
expect(post_card.locator(".post-vote-count")).to_be_visible()
|
||||
expect(post_card.locator("form[action*='/posts/delete/']")).to_be_visible()
|
||||
delete_form = post_card.locator("form[action*='/posts/delete/']")
|
||||
open_action_menu(delete_form)
|
||||
expect(delete_form).to_be_visible()
|
||||
|
||||
|
||||
def test_devlog_load_more_appears_with_many_posts(alice):
|
||||
|
||||
+10
-10
@@ -5,7 +5,7 @@ import time
|
||||
from playwright.sync_api import expect
|
||||
|
||||
from devplacepy.database import get_table, refresh_snapshot, set_setting
|
||||
from tests.conftest import BASE_URL, CACHE_VERSION_PROPAGATION_SECONDS
|
||||
from tests.conftest import BASE_URL, CACHE_VERSION_PROPAGATION_SECONDS, click_menu_action, open_action_menu
|
||||
|
||||
|
||||
def _create_post(page, content):
|
||||
@@ -24,8 +24,9 @@ def test_the_report_control_is_present_on_the_feed_and_a_post(alice, bob):
|
||||
_create_post(alice_page, "A post that another member can report from the feed.")
|
||||
|
||||
bob_page.goto(f"{BASE_URL}/feed", wait_until="domcontentloaded")
|
||||
expect(bob_page.locator(".report-btn").first).to_be_visible()
|
||||
expect(bob_page.locator(".block-btn").first).to_be_attached()
|
||||
report = open_action_menu(bob_page.locator(".post-card .report-btn").first)
|
||||
expect(report).to_be_visible()
|
||||
expect(bob_page.locator(".post-card .block-btn").first).to_be_attached()
|
||||
|
||||
|
||||
def test_the_report_control_is_absent_on_your_own_content(alice):
|
||||
@@ -41,7 +42,7 @@ def test_reporting_a_post_end_to_end_through_the_dialog(alice, bob):
|
||||
slug = _create_post(alice_page, "A post reported end to end through the dialog.")
|
||||
|
||||
bob_page.goto(f"{BASE_URL}/posts/{slug}", wait_until="domcontentloaded")
|
||||
bob_page.locator(".report-btn").first.click()
|
||||
click_menu_action(bob_page.locator("#post-actions-panel .report-btn"))
|
||||
|
||||
dialog = bob_page.locator("#report-dialog")
|
||||
dialog.wait_for(state="visible")
|
||||
@@ -61,7 +62,7 @@ def test_the_admin_queue_shows_the_report_and_its_sla_badge(alice, bob):
|
||||
slug = _create_post(alice_page, "A post that must appear in the moderation queue.")
|
||||
|
||||
bob_page.goto(f"{BASE_URL}/posts/{slug}", wait_until="domcontentloaded")
|
||||
bob_page.locator(".report-btn").first.click()
|
||||
click_menu_action(bob_page.locator("#post-actions-panel .report-btn"))
|
||||
bob_page.locator("#report-dialog").wait_for(state="visible")
|
||||
bob_page.select_option("#report-reason", "spam")
|
||||
bob_page.locator("#report-form button[type='submit']").click()
|
||||
@@ -88,9 +89,10 @@ def test_blocking_from_a_content_action_bar_hides_the_author(alice, bob):
|
||||
_create_post(alice_page, marker)
|
||||
|
||||
bob_page.goto(f"{BASE_URL}/feed", wait_until="domcontentloaded")
|
||||
expect(bob_page.locator(".post-card").first).to_be_visible()
|
||||
card = bob_page.locator(".post-card").filter(has_text=marker).first
|
||||
expect(card).to_be_visible()
|
||||
|
||||
bob_page.locator(".block-btn").first.click()
|
||||
click_menu_action(card.locator(".block-btn"))
|
||||
bob_page.locator(".dialog-overlay.visible .dialog-confirm").click()
|
||||
bob_page.wait_for_load_state("domcontentloaded")
|
||||
|
||||
@@ -100,9 +102,7 @@ def test_blocking_from_a_content_action_bar_hides_the_author(alice, bob):
|
||||
bob_page.goto(
|
||||
f"{BASE_URL}/profile/{alice_user['username']}", wait_until="domcontentloaded"
|
||||
)
|
||||
bob_page.locator("[data-action-menu-trigger]").first.click()
|
||||
bob_page.locator("[data-action-menu-panel]").wait_for(state="visible")
|
||||
bob_page.locator("button:has-text('Unblock')").first.click()
|
||||
click_menu_action(bob_page.locator("#profile-actions-panel button:has-text('Unblock')"))
|
||||
bob_page.locator(".dialog-overlay.visible .dialog-confirm").click()
|
||||
bob_page.wait_for_load_state("domcontentloaded")
|
||||
|
||||
|
||||
+10
-15
@@ -1,7 +1,7 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
from playwright.sync_api import expect
|
||||
from tests.conftest import BASE_URL
|
||||
from tests.conftest import BASE_URL, open_action_menu
|
||||
from tests.e2e.project.files import _make_project_ui
|
||||
def _open_project_with_delete(page, title):
|
||||
proj_url = _make_project_ui(page, title)
|
||||
@@ -12,19 +12,13 @@ PANEL = "[data-action-menu-panel]"
|
||||
|
||||
|
||||
def _open_menu(page):
|
||||
# aria-expanded can lag behind the popover, so the open state that counts
|
||||
# is whether the panel shows.
|
||||
page.wait_for_function(
|
||||
"() => document.querySelector('[data-action-menu-panel]') !== null"
|
||||
" || document.querySelector('[data-action-menu-trigger]') === null"
|
||||
)
|
||||
panel = page.locator(PANEL)
|
||||
if panel.count() and panel.evaluate("(el) => el.matches(':popover-open')"):
|
||||
panel = page.locator("#project-actions-panel")
|
||||
if panel.count():
|
||||
open_action_menu(panel)
|
||||
return
|
||||
page.click(TRIGGER)
|
||||
page.wait_for_function(
|
||||
"() => document.querySelector('[data-action-menu-panel]').matches(':popover-open')"
|
||||
)
|
||||
trigger = page.locator(TRIGGER).first
|
||||
if trigger.count():
|
||||
trigger.click()
|
||||
|
||||
|
||||
def _menu_item(page, label):
|
||||
@@ -35,8 +29,9 @@ def _menu_item(page, label):
|
||||
|
||||
|
||||
def _pick(page, label):
|
||||
_open_menu(page)
|
||||
_menu_item(page, label).first.click()
|
||||
item = _menu_item(page, label).first
|
||||
open_action_menu(item)
|
||||
item.click()
|
||||
|
||||
|
||||
def _click_delete(page):
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from devplacepy.database import (
|
||||
NOTIFICATION_GROUP_KEYS,
|
||||
count_unread_groups,
|
||||
get_notification_grouping_enabled,
|
||||
get_notification_throttle_enabled,
|
||||
notification_group_key,
|
||||
set_notification_grouping_enabled,
|
||||
set_notification_throttle_enabled,
|
||||
)
|
||||
from devplacepy.utils import generate_uid
|
||||
|
||||
|
||||
def _row(ntype, related="actor-1", target="/posts/x", uid=None):
|
||||
return {
|
||||
"type": ntype,
|
||||
"related_uid": related,
|
||||
"target_url": target,
|
||||
"uid": uid or generate_uid(),
|
||||
}
|
||||
|
||||
|
||||
def test_group_key_actor_target_single():
|
||||
assert notification_group_key(_row("message")) == ("message", "actor-1", "/posts/x")
|
||||
assert notification_group_key(_row("vote", related="a")) == notification_group_key(
|
||||
_row("vote", related="b")
|
||||
)
|
||||
assert notification_group_key(_row("follow", related="a", target="/profile/a")) == ("follow",)
|
||||
assert notification_group_key(_row("follow", related="b", target="/profile/b")) == ("follow",)
|
||||
single = _row("badge")
|
||||
assert notification_group_key(single) == ("badge", single["uid"])
|
||||
|
||||
|
||||
def test_group_key_unlisted_type_is_single():
|
||||
row = _row("some_future_type")
|
||||
assert NOTIFICATION_GROUP_KEYS.get("some_future_type", "single") == "single"
|
||||
assert notification_group_key(row) == ("some_future_type", row["uid"])
|
||||
|
||||
|
||||
def test_all_registered_types_have_a_group_shape():
|
||||
from devplacepy.database import NOTIFICATION_TYPES
|
||||
|
||||
for entry in NOTIFICATION_TYPES:
|
||||
assert NOTIFICATION_GROUP_KEYS[entry["key"]] in ("actor", "target", "single")
|
||||
|
||||
|
||||
def _seed_user(local_db, suffix):
|
||||
uid = f"notif-{suffix}-{generate_uid()[-8:]}"
|
||||
local_db["users"].insert(
|
||||
{
|
||||
"uid": uid,
|
||||
"username": uid,
|
||||
"terms_version": "1",
|
||||
"role": "Member",
|
||||
"created_at": "1990-01-01T00:00:00",
|
||||
"deleted_at": None,
|
||||
}
|
||||
)
|
||||
return uid
|
||||
|
||||
|
||||
def _seed_notifications(local_db, user_uid, count, ntype="vote"):
|
||||
table = local_db["notifications"]
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
for i in range(count):
|
||||
table.insert(
|
||||
{
|
||||
"uid": generate_uid(),
|
||||
"user_uid": user_uid,
|
||||
"type": ntype,
|
||||
"message": f"seeded {i}",
|
||||
"related_uid": f"actor-{i}",
|
||||
"target_url": "/posts/seeded",
|
||||
"read": False,
|
||||
"created_at": now,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def test_count_unread_groups_respects_setting(local_db):
|
||||
uid = _seed_user(local_db, "groups")
|
||||
try:
|
||||
_seed_notifications(local_db, uid, 5)
|
||||
assert get_notification_grouping_enabled(uid) is True
|
||||
assert count_unread_groups(uid) == 1
|
||||
set_notification_grouping_enabled(uid, False)
|
||||
assert get_notification_grouping_enabled(uid) is False
|
||||
assert count_unread_groups(uid) == 5
|
||||
set_notification_grouping_enabled(uid, True)
|
||||
assert count_unread_groups(uid) == 1
|
||||
finally:
|
||||
local_db["notifications"].delete(user_uid=uid)
|
||||
local_db["users"].delete(uid=uid)
|
||||
|
||||
|
||||
def test_throttle_setting_defaults_on_and_toggles(local_db):
|
||||
uid = _seed_user(local_db, "throttle")
|
||||
try:
|
||||
assert get_notification_throttle_enabled(uid) is True
|
||||
set_notification_throttle_enabled(uid, False)
|
||||
assert get_notification_throttle_enabled(uid) is False
|
||||
set_notification_throttle_enabled(uid, True)
|
||||
assert get_notification_throttle_enabled(uid) is True
|
||||
finally:
|
||||
local_db["users"].delete(uid=uid)
|
||||
|
||||
|
||||
def test_missing_user_defaults_on():
|
||||
assert get_notification_grouping_enabled("no-such-user") is True
|
||||
assert get_notification_throttle_enabled("no-such-user") is True
|
||||
@@ -2757,6 +2757,225 @@ def test_meta_tool_names_restored_on_stream_chunks(local_db, monkeypatch):
|
||||
_teardown_responses_route_openai_gateway()
|
||||
|
||||
|
||||
def _setup_chat_meta_route_openai_gateway():
|
||||
from devplacepy.services.openai_gateway import routing
|
||||
|
||||
routing.provider_store.set(
|
||||
routing.ProviderIn(
|
||||
name="gwmetacc",
|
||||
base_url="https://api.meta.ai/v1/chat/completions",
|
||||
api_key="sk-test",
|
||||
)
|
||||
)
|
||||
routing.model_store.set(
|
||||
routing.ModelRouteIn(
|
||||
source_model="meta-chat-cc",
|
||||
provider="gwmetacc",
|
||||
target_model="muse-spark",
|
||||
kind="chat",
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _teardown_chat_meta_route_openai_gateway():
|
||||
from devplacepy.services.openai_gateway import routing
|
||||
|
||||
routing.model_store.remove("meta-chat-cc")
|
||||
routing.provider_store.remove("gwmetacc")
|
||||
|
||||
|
||||
def _tai_tool_body_openai_gateway(**over):
|
||||
# Mirrors a real tai/detz turn: core tools are always sent, so "shell"
|
||||
# (a Pi-verified gate trigger missing from the denylist until
|
||||
# 2026-11-10) rides every request alongside the lazy "read_file".
|
||||
body = _chat_body_openai_gateway(**over)
|
||||
body["model"] = "meta-chat-cc"
|
||||
body["tools"] = [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "shell",
|
||||
"description": "run a shell command",
|
||||
"parameters": {"type": "object", "properties": {}},
|
||||
},
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "read_file",
|
||||
"description": "read a file",
|
||||
"parameters": {"type": "object", "properties": {}},
|
||||
},
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "web_fetch",
|
||||
"description": "fetch a URL",
|
||||
"parameters": {"type": "object", "properties": {}},
|
||||
},
|
||||
},
|
||||
]
|
||||
return body
|
||||
|
||||
|
||||
class FakeChatMetaStreamResp_openai_gateway(FakeResp_openai_gateway):
|
||||
def __init__(self, payload):
|
||||
super().__init__(status=200, payload=payload)
|
||||
self._payload = payload
|
||||
|
||||
async def aiter_lines(self):
|
||||
calls = self._payload["choices"][0]["message"]["tool_calls"]
|
||||
yield (
|
||||
'data: {"id":"chatcmpl-x","object":"chat.completion.chunk",'
|
||||
'"model":"m","choices":[{"index":0,"delta":{"role":"assistant"}}]}'
|
||||
)
|
||||
for pos, call in enumerate(calls):
|
||||
name = call["function"]["name"]
|
||||
yield (
|
||||
'data: {"id":"chatcmpl-x","object":"chat.completion.chunk",'
|
||||
'"model":"m","choices":[{"index":0,"delta":{"tool_calls":'
|
||||
'[{"index":%d,"id":"call_%d","function":{"name":"%s",'
|
||||
'"arguments":"{}"}}]}}]}' % (pos, pos, name)
|
||||
)
|
||||
yield (
|
||||
'data: {"id":"chatcmpl-x","object":"chat.completion.chunk",'
|
||||
'"model":"m","choices":[{"index":0,"delta":{},'
|
||||
'"finish_reason":"tool_calls"}]}'
|
||||
)
|
||||
yield "data: [DONE]"
|
||||
|
||||
|
||||
class FakeChatMetaClient_openai_gateway:
|
||||
def __init__(self, *a, **k):
|
||||
self.calls = []
|
||||
|
||||
def build_request(self, method, url, headers=None, json=None, content=None):
|
||||
return FakeRequest(method, url, json, headers)
|
||||
|
||||
async def send(self, request, stream=False):
|
||||
self.calls.append((request.url, request.json_body))
|
||||
body = request.json_body or {}
|
||||
wire_names = [
|
||||
(tool.get("function") or {}).get("name")
|
||||
for tool in body.get("tools") or []
|
||||
]
|
||||
payload = {
|
||||
"id": "chatcmpl-x",
|
||||
"object": "chat.completion",
|
||||
"model": body.get("model"),
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"message": {
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{
|
||||
"id": "call_7",
|
||||
"type": "function",
|
||||
"function": {"name": name, "arguments": "{}"},
|
||||
}
|
||||
for name in wire_names
|
||||
],
|
||||
},
|
||||
"finish_reason": "tool_calls",
|
||||
}
|
||||
],
|
||||
"usage": {"prompt_tokens": 5, "completion_tokens": 2, "total_tokens": 7},
|
||||
}
|
||||
if stream:
|
||||
return FakeChatMetaStreamResp_openai_gateway(payload)
|
||||
return FakeResp_openai_gateway(
|
||||
payload=payload, content=json.dumps(payload).encode()
|
||||
)
|
||||
|
||||
async def post(self, url, headers=None, json=None, timeout=None):
|
||||
return await self.send(FakeRequest("POST", url, json), stream=False)
|
||||
|
||||
async def aclose(self):
|
||||
pass
|
||||
|
||||
|
||||
def test_meta_tool_names_aliased_on_chat_completions_wire(local_db, monkeypatch):
|
||||
monkeypatch.setattr(gwmod.httpx, "AsyncClient", FakeChatMetaClient_openai_gateway)
|
||||
_setup_chat_meta_route_openai_gateway()
|
||||
try:
|
||||
svc = GatewayService()
|
||||
cfg = svc.effective_config()
|
||||
cfg["gateway_vision_enabled"] = False
|
||||
rt = svc.runtime()
|
||||
logged = []
|
||||
resp = run_async(
|
||||
rt.handle_chat(
|
||||
_tai_tool_body_openai_gateway(),
|
||||
cfg,
|
||||
("guest", "test"),
|
||||
"test",
|
||||
"default",
|
||||
log=logged.append,
|
||||
)
|
||||
)
|
||||
_, sent = rt._client.calls[-1]
|
||||
wire = [tool["function"]["name"] for tool in sent["tools"]]
|
||||
assert wire == ["ext_shell", "ext_read_file", "ext_web_fetch"]
|
||||
assert any("shell->ext_shell" in line for line in logged)
|
||||
assert any("read_file->ext_read_file" in line for line in logged)
|
||||
assert any("web_fetch->ext_web_fetch" in line for line in logged)
|
||||
assert resp.status_code == 200
|
||||
payload = json.loads(bytes(resp.body).decode())
|
||||
calls = payload["choices"][0]["message"]["tool_calls"]
|
||||
assert [call["function"]["name"] for call in calls] == [
|
||||
"shell",
|
||||
"read_file",
|
||||
"web_fetch",
|
||||
]
|
||||
assert payload["choices"][0]["finish_reason"] == "tool_calls"
|
||||
finally:
|
||||
_teardown_chat_meta_route_openai_gateway()
|
||||
|
||||
|
||||
def test_meta_tool_names_restored_on_chat_completions_stream(
|
||||
local_db, monkeypatch
|
||||
):
|
||||
monkeypatch.setattr(gwmod.httpx, "AsyncClient", FakeChatMetaClient_openai_gateway)
|
||||
_setup_chat_meta_route_openai_gateway()
|
||||
try:
|
||||
svc = GatewayService()
|
||||
cfg = svc.effective_config()
|
||||
cfg["gateway_vision_enabled"] = False
|
||||
rt = svc.runtime()
|
||||
resp = run_async(
|
||||
rt.handle_chat(
|
||||
_tai_tool_body_openai_gateway(stream=True),
|
||||
cfg,
|
||||
("guest", "test"),
|
||||
"test",
|
||||
"default",
|
||||
)
|
||||
)
|
||||
|
||||
async def drain():
|
||||
out = []
|
||||
async for chunk in resp.body_iterator:
|
||||
out.append(chunk if isinstance(chunk, str) else chunk.decode())
|
||||
return "".join(out)
|
||||
|
||||
body = run_async(drain())
|
||||
_, sent = rt._client.calls[-1]
|
||||
wire = [tool["function"]["name"] for tool in sent["tools"]]
|
||||
assert wire == ["ext_shell", "ext_read_file", "ext_web_fetch"]
|
||||
assert '"name": "shell"' in body
|
||||
assert '"name": "read_file"' in body
|
||||
assert '"name": "web_fetch"' in body
|
||||
assert "ext_shell" not in body
|
||||
assert "ext_read_file" not in body
|
||||
assert "ext_web_fetch" not in body
|
||||
assert "[DONE]" in body
|
||||
finally:
|
||||
_teardown_chat_meta_route_openai_gateway()
|
||||
|
||||
|
||||
def test_responses_protocol_stream_relays_chat_chunks(local_db, monkeypatch):
|
||||
monkeypatch.setattr(gwmod.httpx, "AsyncClient", FakeResponsesClient_openai_gateway)
|
||||
FakeResponsesClient_openai_gateway.behavior = "ok"
|
||||
@@ -3173,16 +3392,28 @@ def test_emulated_tools_convert_history_for_the_meta_transpiler(local_db, monkey
|
||||
_teardown_responses_route_openai_gateway()
|
||||
|
||||
|
||||
def test_emulated_tools_over_the_cap_is_a_400_with_no_upstream_call(local_db, monkeypatch):
|
||||
from devplacepy.services.openai_gateway import tool_emulation
|
||||
|
||||
body = _chat_body_openai_gateway(
|
||||
tools=[BASH_TOOL_openai_gateway] * (tool_emulation.MAX_TOOLS + 1)
|
||||
)
|
||||
def test_emulated_tools_serve_large_catalogs_with_no_cap(local_db, monkeypatch):
|
||||
tools = [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": f"tool_{index}",
|
||||
"description": f"tool number {index}",
|
||||
"parameters": {"type": "object", "properties": {}, "required": []},
|
||||
},
|
||||
}
|
||||
for index in range(200)
|
||||
]
|
||||
body = _chat_body_openai_gateway(tools=tools, tool_choice="auto")
|
||||
try:
|
||||
rt, resp = _emulated_chat_openai_gateway(monkeypatch, body)
|
||||
assert resp.status_code == 400
|
||||
assert rt._client.calls == []
|
||||
assert resp.status_code == 200
|
||||
assert len(rt._client.calls) == 1
|
||||
_, sent = rt._client.calls[-1]
|
||||
assert "tools" not in sent and "tool_choice" not in sent
|
||||
assert '"name": "tool_0"' in sent["instructions"]
|
||||
assert '"name": "tool_199"' in sent["instructions"]
|
||||
assert len(rt._catalog_cache._entries) == 1
|
||||
finally:
|
||||
_teardown_responses_route_openai_gateway()
|
||||
|
||||
|
||||
@@ -43,6 +43,8 @@ def test_reserved_tool_names_cover_the_measured_denylist():
|
||||
"update_goal",
|
||||
"report_progress",
|
||||
"read_skill",
|
||||
"shell",
|
||||
"web_fetch",
|
||||
"write_todos",
|
||||
}
|
||||
)
|
||||
|
||||
@@ -110,15 +110,81 @@ def test_history_roundtrips_into_the_same_format_the_model_emits():
|
||||
assert '"name": "bash"' in results and "a.txt" in results
|
||||
|
||||
|
||||
def test_caps_reject_loudly():
|
||||
with pytest.raises(te.ToolEmulationError):
|
||||
te.emulate_request(_payload(tools=[BASH] * (te.MAX_TOOLS + 1)))
|
||||
huge = json.loads(json.dumps(BASH))
|
||||
huge["function"]["description"] = "x" * (te.MAX_CATALOG_CHARS + 1)
|
||||
with pytest.raises(te.ToolEmulationError):
|
||||
te.emulate_request(_payload(tools=[huge]))
|
||||
def _many_tools(count):
|
||||
return [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": f"tool_{index}",
|
||||
"description": f"tool number {index}",
|
||||
"parameters": {"type": "object", "properties": {}, "required": []},
|
||||
},
|
||||
}
|
||||
for index in range(count)
|
||||
]
|
||||
|
||||
|
||||
def test_large_catalogs_are_served_with_no_cap():
|
||||
out = te.emulate_request(_payload(tools=_many_tools(424)))
|
||||
system = out["messages"][0]["content"]
|
||||
assert '"name": "tool_0"' in system
|
||||
assert '"name": "tool_423"' in system
|
||||
assert "tools" not in out and "tool_choice" not in out
|
||||
|
||||
|
||||
def test_malformed_tools_still_reject_loudly():
|
||||
with pytest.raises(te.ToolEmulationError):
|
||||
te.emulate_request(_payload(tools=[{"type": "retrieval"}]))
|
||||
with pytest.raises(te.ToolEmulationError):
|
||||
te.emulate_request(_payload(tools=[{"type": "function", "function": {}}]))
|
||||
with pytest.raises(te.ToolEmulationError):
|
||||
te.emulate_request(_payload(tools="bash"))
|
||||
with pytest.raises(te.ToolEmulationError):
|
||||
te.cached_emulated_tools(_payload(tools="bash"))
|
||||
|
||||
|
||||
def test_catalog_cache_reuses_the_built_instruction_per_owner():
|
||||
cache = te.CatalogCache()
|
||||
owner = ("user", "uid-1")
|
||||
first = te.emulate_request(_payload(tools=_many_tools(424)), cache, owner)
|
||||
assert len(cache._entries) == 1
|
||||
second = te.emulate_request(_payload(tools=_many_tools(424)), cache, owner)
|
||||
assert len(cache._entries) == 1
|
||||
assert second["messages"][0]["content"] == first["messages"][0]["content"]
|
||||
emulated = te.cached_emulated_tools(_payload(tools=_many_tools(424)), cache, owner)
|
||||
assert emulated is not None and len(emulated[0]) == 424
|
||||
|
||||
|
||||
def test_catalog_cache_is_namespaced_per_owner_and_toolset():
|
||||
cache = te.CatalogCache()
|
||||
payload = _payload(tools=_many_tools(10))
|
||||
te.emulate_request(payload, cache, ("user", "uid-1"))
|
||||
te.emulate_request(payload, cache, ("user", "uid-2"))
|
||||
assert len(cache._entries) == 2
|
||||
assert cache.lookup(payload, ("user", "uid-3")) is None
|
||||
changed = _payload(tools=_many_tools(11))
|
||||
assert cache.lookup(changed, ("user", "uid-1")) is None
|
||||
renamed_choice = _payload(tools=_many_tools(10), tool_choice="required")
|
||||
assert cache.lookup(renamed_choice, ("user", "uid-1")) is None
|
||||
|
||||
|
||||
def test_catalog_cache_evicts_oldest_first_within_bounds():
|
||||
cache = te.CatalogCache()
|
||||
cache.MAX_ENTRIES = 3
|
||||
for index in range(5):
|
||||
te.emulate_request(
|
||||
_payload(tools=_many_tools(index + 1)), cache, ("user", "uid-1")
|
||||
)
|
||||
assert len(cache._entries) == 3
|
||||
assert cache.lookup(_payload(tools=_many_tools(1)), ("user", "uid-1")) is None
|
||||
assert cache.lookup(_payload(tools=_many_tools(5)), ("user", "uid-1")) is not None
|
||||
|
||||
|
||||
def test_catalog_cache_never_caches_a_shape_error():
|
||||
cache = te.CatalogCache()
|
||||
with pytest.raises(te.ToolEmulationError):
|
||||
te.emulate_request(_payload(tools=[{"type": "retrieval"}]), cache, ("user", "uid-1"))
|
||||
assert len(cache._entries) == 0
|
||||
|
||||
|
||||
def test_existing_stop_sequences_are_kept_and_capped():
|
||||
|
||||
Reference in New Issue
Block a user