From 97221856e5a91f89e46dc2632d1f32ee398f92d8 Mon Sep 17 00:00:00 2001 From: Silas Santini <70163606+pancakereport@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:44:22 -0800 Subject: [PATCH 1/2] Fix bugs in the course pages that the frontend upgrade's reviews found - A group page for a group that doesn't exist: load_group raised (a 500), and the page asked again on every render, nonstop. The server answers nothing, the page asks once, from an effect, and shows Not found. - Next Ticket, or any move from one ticket or group page to another, kept the previous page's state: its assignment and question (#24), a half-typed description, and a ticket that was never loaded. Each ticket and group now gets a new page. bootstrap-select chose its placeholder when it set up the new page's assignment menu, so SelectPicker chooses the value again. - A settings Save button stayed disabled after a failed save, since a failed request never calls its callback. makeRequest returns a promise that settles either way, and the form waits on that. - A ticket or group with no question showed "QNaN". - Party groups were sorted with a one-argument comparator, which leaves the order undefined; they're sorted by ID. - MagicWordDisplay set state while rendering. It fetches a timed magic word from an effect, right away rather than after the first ten seconds. Closes #24 Co-Authored-By: Claude Opus 5.5 --- oh_queue/views.py | 2 +- src/components/app.jsx | 31 +++++-- src/components/config_linked_form.jsx | 10 +-- src/components/magic_word_display.jsx | 112 +++++++++----------------- src/components/party_group_layout.jsx | 14 +++- src/components/select_picker.jsx | 10 ++- src/socket.js | 30 ++++--- src/state.ts | 25 +++++- tests/e2e/conftest.py | 32 ++++++++ tests/e2e/test_pages.py | 90 ++++++++++++++++++++- tests/test_app.py | 8 ++ 11 files changed, 254 insertions(+), 110 deletions(-) diff --git a/oh_queue/views.py b/oh_queue/views.py index 8b575aa..6edc682 100755 --- a/oh_queue/views.py +++ b/oh_queue/views.py @@ -1352,7 +1352,7 @@ def create_group(form): def load_group(group_id): if not group_id: return socket_error("Invalid group ID") - group = Group.query.filter_by(id=group_id, course=get_course()).one() + group = Group.query.filter_by(id=group_id, course=get_course()).one_or_none() if group: return group_json(group) diff --git a/src/components/app.jsx b/src/components/app.jsx index bdbbc60..8757b69 100755 --- a/src/components/app.jsx +++ b/src/components/app.jsx @@ -1,5 +1,11 @@ import React from "react"; -import { BrowserRouter, Route, Routes, useNavigate } from "react-router-dom"; +import { + BrowserRouter, + Route, + Routes, + useNavigate, + useParams, +} from "react-router-dom"; import { setApp } from "../app_instance"; import { isPartyRoot } from "../common"; import { ActivityLogLayout } from "./activity_log_layout"; @@ -19,6 +25,7 @@ import { initialState, isStaff, loadTicket, + receiveGroup, receiveTicket, setGroup, setTicket, @@ -120,7 +127,7 @@ export class App extends React.Component { this.state.currentUser = data.current_user; } if (Object.hasOwn(data, "groups")) { - this.state.groups = Array.from(data.groups).sort((x) => x.id); + this.state.groups = Array.from(data.groups).sort((a, b) => a.id - b.id); } if (Object.hasOwn(data, "presence")) { this.state.presence = data.presence; @@ -155,7 +162,7 @@ export class App extends React.Component { loadGroup(id) { if (isStaff(this.state)) { this.socket.emit("load_group", id, (group) => { - setGroup(this.state, group); + receiveGroup(this.state, id, group); this.refresh(); }); } @@ -213,10 +220,11 @@ export class App extends React.Component { } if (callback) callback(response); }; + // A promise of whether the request succeeded (see Socket.emit). if (request !== undefined) { - this.socket.emit(eventType, request, cb); + return this.socket.emit(eventType, request, cb); } else { - this.socket.emit(eventType, cb); + return this.socket.emit(eventType, cb); } } @@ -250,7 +258,8 @@ export class App extends React.Component { ; +} + // Gives App the router's navigate function, for following the server's redirects. function RememberNavigate({ onNavigate }) { const navigate = useNavigate(); diff --git a/src/components/config_linked_form.jsx b/src/components/config_linked_form.jsx index f6d80fd..65bfbde 100755 --- a/src/components/config_linked_form.jsx +++ b/src/components/config_linked_form.jsx @@ -44,11 +44,11 @@ export function ConfigLinked({ configKey, configKeys = [], config, render }) { ? { key: configKey, value: e.target ? value : e } : { keys: configKeys, values }; - app.makeRequest(`update_config`, requestBody, (isSuccess) => { - if (isSuccess) { - minimumTime.then(() => setSaving(false)); - } - }); + // Whether or not it worked: a failed save shows the offline banner, and can be tried again. + app + .makeRequest(`update_config`, requestBody) + .then(() => minimumTime) + .then(() => setSaving(false)); return false; }; diff --git a/src/components/magic_word_display.jsx b/src/components/magic_word_display.jsx index eb4fca3..f0e4bcd 100755 --- a/src/components/magic_word_display.jsx +++ b/src/components/magic_word_display.jsx @@ -2,86 +2,46 @@ import React from "react"; import { app } from "../app_instance"; import { isStaff } from "../state"; -export class MagicWordDisplay extends React.Component { - constructor(...args) { - super(...args); - - this.state = { - loaded: false, - oldMagicWord: undefined, - magicWord: undefined, - refreshInterval: null, - }; - - this.loadState = this.loadState.bind(this); - - this.loadState(); - } - - loadState() { - if (this.state.loaded) return; - var config = this.props.state.config; - if (!this.props.state.loaded || !config) { - setTimeout(this.loadState, 100); +// How often a timed magic word is fetched again, since it changes. +const REFRESH_MS = 10000; + +// For staff, the current magic word when it's a timed one, which they can't +// otherwise know. (Staff set a text magic word themselves.) +export function MagicWordDisplay({ state }) { + const [magicWord, setMagicWord] = React.useState(undefined); + const timed = + state.loaded && + isStaff(state) && + state.config.queue_magic_word_mode === "timed_numeric"; + + React.useEffect(() => { + if (!timed) { return; } - if (isStaff(this.props.state) && config.queue_magic_word_mode !== "none") { - if (this.state.refreshInterval) { - clearInterval(this.state.refreshInterval); - this.state.refreshInterval = null; - } - this.setState({ - refreshInterval: setInterval(() => { - let mode = this.props.state.config.queue_magic_word_mode; - if ( - mode !== "timed_numeric" && - (mode !== "none" || this.state.magicWord !== undefined) - ) - return; - app.makeRequest("refresh_magic_word", (res) => { - let magicWord = res.magic_word || null; - this.setState({ - oldMagicWord: this.state.magicWord, - magicWord: magicWord, - }); - }); - }, 10000), + let stopped = false; + const refresh = () => + app.makeRequest("refresh_magic_word", (res) => { + if (!stopped && res) { + setMagicWord(res.magic_word || null); + } }); - } - this.setState({ - loaded: true, - }); - } + refresh(); + const interval = setInterval(refresh, REFRESH_MS); + return () => { + stopped = true; + clearInterval(interval); + }; + }, [timed]); - componentWillUnmount() { - if (this.state.refreshInterval) { - clearInterval(this.state.refreshInterval); - this.state.refreshInterval = null; - } + if (!timed || magicWord === undefined) { + return false; } - render() { - if (!this.state.loaded) { - this.loadState(); - return false; - } - if ( - this.props.state.config.queue_magic_word_mode === "none" || - this.state.magicWord === undefined - ) { - return false; - } - - let magicWordElem = Loading...; - if (this.state.magicWord) { - let magicWord = this.state.magicWord; - magicWordElem = {magicWord}; - } - - return ( -
-

Magic word: {magicWordElem}

-
- ); - } + return ( +
+

+ Magic word: {magicWord ? {magicWord} : Loading...} +

+
+ ); } diff --git a/src/components/party_group_layout.jsx b/src/components/party_group_layout.jsx index bb3c51f..77a97e5 100755 --- a/src/components/party_group_layout.jsx +++ b/src/components/party_group_layout.jsx @@ -14,6 +14,7 @@ import { getGroup, getTicket, groupIsMine, + isGroupMissing, isStaff, ticketQuestion, ticketStatus, @@ -34,6 +35,16 @@ export function PartyGroupLayout({ state, loadGroup, socket }) { setDescription(savedDescription); } + // Staff can open any group's page, so load it if it isn't one of the active + // groups the page already has. Once: a group that doesn't exist stays missing. + const staff = isStaff(state); + const hasGroup = group != null; + React.useEffect(() => { + if (staff && !hasGroup) { + loadGroup(groupID); + } + }, [staff, hasGroup, groupID, loadGroup]); + // Signed-out visitors get no groups; the home page asks them to sign in. if (state.loaded && !state.currentUser) { return ; @@ -42,10 +53,9 @@ export function PartyGroupLayout({ state, loadGroup, socket }) { if (!group) { // Only staff can load a group that isn't active; students get its page // only for an active group, or their own. - if (state.loaded && !isStaff(state)) { + if (state.loaded && (!staff || isGroupMissing(state, groupID))) { return ; } - loadGroup(groupID); return "loading..."; } const ticket = getTicket(state, group.ticket_id); diff --git a/src/components/select_picker.jsx b/src/components/select_picker.jsx index 2df259d..9076688 100755 --- a/src/components/select_picker.jsx +++ b/src/components/select_picker.jsx @@ -11,7 +11,15 @@ export class SelectPicker extends React.Component { this.refreshSelect(); } refreshSelect() { - $(this.selectRef.current).selectpicker("refresh"); + const select = this.selectRef.current; + $(select).selectpicker("refresh"); + // bootstrap-select chooses its title placeholder when it first sets up a + // select whose option React chose, so a controlled select's value is + // chosen again. + const { value } = this.props; + if (value != null) { + $(select).selectpicker("val", String(value)); + } } componentDidUpdate() { this.refreshSelect(); diff --git a/src/socket.js b/src/socket.js index 95a06c2..5d42215 100755 --- a/src/socket.js +++ b/src/socket.js @@ -83,19 +83,25 @@ export class Socket { this.handlers.delete(eventType); } + // Sends requests one at a time, in order. Returns a promise of whether this + // one succeeded, settled once it's done (after its callback, if it has one), + // since a failed request doesn't call its callback. emit(...args) { - const processQueue = () => { - if (this.jobs.length > 0) { - const args = this.jobs[0]; - this.actuallyEmit(...args) - .finally(this.jobs.shift.bind(this.jobs)) - .then(processQueue); + return new Promise((resolve) => { + const processQueue = () => { + if (this.jobs.length > 0) { + const [args, done] = this.jobs[0]; + this.actuallyEmit(...args) + .then(done) + .finally(this.jobs.shift.bind(this.jobs)) + .then(processQueue); + } + }; + this.jobs.push([args, resolve]); + if (this.jobs.length === 1) { + processQueue(); } - }; - this.jobs.push(args); - if (this.jobs.length === 1) { - processQueue(); - } + }); } actuallyEmit(event, params = {}, callback = null) { @@ -112,10 +118,12 @@ export class Socket { if (callback != null) { callback(action); } + return true; }) .catch((e) => { console.error(e); this.trigger("disconnect"); + return false; }); } } diff --git a/src/state.ts b/src/state.ts index e8d192e..f7c6ed8 100755 --- a/src/state.ts +++ b/src/state.ts @@ -106,6 +106,8 @@ export type State = { ticketCounts: Record | null; /* Ticket IDs for any tickets we are currently loading. */ loadingTickets: Set; + /* Group IDs the server has no group for. */ + missingGroups: Set; /* Current ticket filter. */ filter: Filter; /* Selected queue tab. */ @@ -126,6 +128,7 @@ export const initialState: State = { tickets: new Map(), ticketCounts: null, loadingTickets: new Set(), + missingGroups: new Set(), filter: { location_id: null, assignment_id: null, @@ -174,9 +177,10 @@ export function ticketLocation(state: State, ticket: Ticket): TicketLocation { } export function ticketQuestion(state: State, ticket: Ticket | Group): string { - let question = ticket.question ?? ""; - if (!isNaN(Number(question))) { - question = "Q" + parseInt(question); + // A question number, such as "3", is shown as "Q3"; anything else as it is. + const question = (ticket.question ?? "").trim(); + if (question !== "" && !isNaN(Number(question))) { + return "Q" + parseInt(question); } return question; } @@ -404,7 +408,20 @@ export function setGroup(state: State, group: Group): void { state.groups.splice(state.groups.indexOf(oldGroup), 1); } state.groups.push(group); - state.groups.sort((group) => group.id); + state.groups.sort((a, b) => a.id - b.id); +} + +/* A group loaded by ID, or null if there's no such group. */ +export function receiveGroup(state: State, id: number, group: Group | null) { + if (group != null) { + setGroup(state, group); + } else { + state.missingGroups.add(id); + } +} + +export function isGroupMissing(state: State, id: number): boolean { + return state.missingGroups.has(id); } export function groupIsActive(group: Group): boolean { diff --git a/tests/e2e/conftest.py b/tests/e2e/conftest.py index 4f66ec0..beab58e 100644 --- a/tests/e2e/conftest.py +++ b/tests/e2e/conftest.py @@ -2,6 +2,7 @@ tests. They need Chrome and the frontend build (`yarn build`), so `pytest` leaves them out (pytest.ini); run them with `pytest tests/e2e`.""" +import json import threading import time from pathlib import Path @@ -26,6 +27,8 @@ class Site: def __init__(self, driver, base_url): self.driver = driver self.base_url = base_url + # scripts that run on every page, added by watch_requests + self.scripts = [] def log_in(self, email, name, is_staff): """Sign in through the development login, as a TA or a student in every offering.""" @@ -57,6 +60,32 @@ def button(self, text): return self.wait(lambda: next((e for e in self.driver.find_elements(By.XPATH, xpath) if e.is_displayed()), None)) + def watch_requests(self, fail=()): + """From the next page opened: count the page's API requests by endpoint, in + window.requests, and make those to the endpoints in fail fail, as if the + server were unreachable.""" + # in a function, so its names don't become globals the page's scripts see + script = """(() => { + window.requests = {}; + const fail = %s; + const fetch = window.fetch; + window.fetch = (url, ...rest) => { + const endpoint = String(url).split("/api/")[1]; + if (endpoint) { + window.requests[endpoint] = (window.requests[endpoint] || 0) + 1; + if (fail.includes(endpoint)) { + return Promise.reject(new TypeError("Failed to fetch")); + } + } + return fetch(url, ...rest); + }; + })();""" % json.dumps(list(fail)) + added = self.driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {"source": script}) + self.scripts.append(added["identifier"]) + + def requests(self, endpoint): + return self.driver.execute_script("return window.requests[arguments[0]] || 0", endpoint) + def text(self): return self.driver.find_element(By.TAG_NAME, "body").text @@ -104,6 +133,9 @@ def site(app, live): live.driver.delete_all_cookies() live.console_errors() yield live + for script in live.scripts: + live.driver.execute_cdp_cmd("Page.removeScriptToEvaluateOnNewDocument", {"identifier": script}) + live.scripts.clear() @pytest.hookimpl(hookwrapper=True) diff --git a/tests/e2e/test_pages.py b/tests/e2e/test_pages.py index c48c086..861b5bc 100644 --- a/tests/e2e/test_pages.py +++ b/tests/e2e/test_pages.py @@ -1,10 +1,12 @@ """Every page of a course opens without errors, settings and descriptions are saved, and a ticket goes from request to resolved.""" +import time + import pytest from selenium.webdriver.common.by import By -from oh_queue.models import (ConfigEntry, Group, GroupAttendance, GroupAttendanceStatus, GroupStatus, Ticket, +from oh_queue.models import (Assignment, ConfigEntry, Group, GroupAttendance, GroupAttendanceStatus, GroupStatus, Ticket, TicketStatus, User, db) from tests.conftest import COURSE @@ -12,11 +14,11 @@ STUDENT = ("student@example.edu", "Student Person", False) -def add_group(app): +def add_group(app, question="3"): """An active group of one student, and its id.""" with app.app_context(): student = User(email="grouped@example.edu", name="Grouped Student", course="cs61a") - group = Group(question="3", description="", assignment_id=1, location_id=1, course="cs61a", + group = Group(question=question, description="", assignment_id=1, location_id=1, course="cs61a", group_status=GroupStatus.active) db.session.add_all([student, group]) db.session.flush() @@ -208,3 +210,85 @@ def test_welcome_message_references_without_semicolons(site, app): link = site.driver.find_element(By.LINK_TEXT, "Zoom") assert link.get_attribute("href") == "https://berkeley.zoom.us/j/1?pwd=x®ion=us" assert site.console_errors() == [] + + +def test_group_that_does_not_exist(site): + """Staff see that it isn't found, after asking for it once.""" + site.watch_requests() + site.log_in(*STAFF) + site.visit(f"{COURSE}/groups/12345") + site.wait(lambda: "Not found" in site.text()) + time.sleep(2) + assert site.requests("load_group") == 1 + assert site.console_errors() == [] + + +def test_group_without_a_question(site, app): + add_group(app, question="") + site.log_in(*STAFF) + site.visit(COURSE + "/party") + site.wait(lambda: "Return to group" in site.text() or "Join" in site.text()) + assert "QNaN" not in site.text() + + +def test_failed_setting_save_can_be_tried_again(site): + site.watch_requests(fail=["update_config"]) + site.log_in(*STAFF) + site.visit(COURSE + "/admin") + delay = site.driver.find_element(By.CSS_SELECTOR, "input[type=number]") + delay.clear() + delay.send_keys("12") + save = site.driver.find_elements(By.CSS_SELECTOR, "button[name=btn-submit]")[0] + save.click() + site.wait(lambda: site.requests("update_config") == 1) + site.wait(lambda: save.is_enabled() and "is-loading" not in save.get_attribute("class")) + + +def test_next_ticket_shows_the_next_tickets_assignment(site, app): + """Not the previous ticket's, left over from its page.""" + with app.app_context(): + maps = Assignment(name="Maps", course="cs61a", visible=True) + db.session.add(maps) + tickets = [] + for email, assignment_id, question in (("first@example.edu", 1, "3"), ("second@example.edu", 2, "7")): + student = User(email=email, name=email, course="cs61a") + db.session.add(student) + db.session.flush() + ticket = Ticket(user=student, status=TicketStatus.pending, assignment_id=assignment_id, location_id=1, + question=question, description="", course="cs61a") + db.session.add(ticket) + db.session.flush() + tickets.append(ticket.id) + db.session.commit() + maps_id = maps.id + first, second = tickets + + site.log_in(*STAFF) + site.visit(f"{COURSE}/tickets/{first}") + site.button("Help").click() + site.wait(lambda: "Being helped by you" in site.text()) + site.button("Resolve").click() + site.wait(lambda: "Resolved by" in site.text()) + site.button("Next Ticket").click() + site.wait(lambda: site.driver.current_url.rstrip("/").endswith(f"/tickets/{second}")) + site.wait(lambda: site.driver.find_element(By.ID, "question").get_attribute("value") == "7") + # the menu bootstrap-select shows, not just the select it hides + assert site.driver.execute_script('return $("#assignment_id").val()') == str(maps_id) + assert "Maps" in site.driver.find_element(By.CSS_SELECTOR, "button[data-id=assignment_id]").text + + assert "Update Assignment" not in site.text() + assert site.console_errors() == [] + + +def test_staff_see_a_timed_magic_word(site, app): + site.visit(COURSE + "/") # sets up the course's settings + with app.app_context(): + settings = {"queue_magic_word_mode": "timed_numeric", "queue_magic_word_data": "0123456789abcdef:60:1000:9999"} + for key, value in settings.items(): + ConfigEntry.query.filter_by(course="cs61a", key=key).one().value = value + db.session.commit() + site.log_in(*STAFF) + site.visit(COURSE + "/") + # right away, not after the first ten-second refresh + site.wait(lambda: "Magic word:" in site.text(), timeout=5) + assert site.console_errors() == [] diff --git a/tests/test_app.py b/tests/test_app.py index 2751e74..53e2239 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -191,3 +191,11 @@ def test_asking_twice_points_to_the_ticket_already_on_the_queue(client): second = client.post(COURSE + "/api/create", json=form).get_json()["action"] assert second["messages"][0]["text"] == "You are already on the queue" assert second["redirect"] == first + + +def test_loading_a_group_that_does_not_exist(client): + """Answers nothing, rather than failing, so the group's page can say it isn't found.""" + log_in(client) + response = client.post(COURSE + "/api/load_group", json=12345) + assert response.status_code == 200 + assert response.get_json()["action"] is None From b4d4712232a488897fef5348d6470c2986f7a480 Mon Sep 17 00:00:00 2001 From: Silas Santini <70163606+pancakereport@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:53:25 -0800 Subject: [PATCH 2/2] Fix issues from the code review - A group page whose request failed (the network down for a moment) stayed on "loading..." for good: it asks again whenever the connection comes back. - An ID that isn't a group's, such as /groups/abc, got an error back that was stored as a group, so the page never said it isn't found. Only a group with that ID counts as one. - Only a question of digits is shown as a number ("Q3"), so "1e3" or "Infinity" are shown as they are. - A timed magic word is forgotten when the mode changes, so an old one isn't shown if timed mode comes back. - The empty question test waits for the group's card, and watch_requests can fail only the first few requests to an endpoint. Co-Authored-By: Claude Opus 5.5 --- src/components/magic_word_display.jsx | 2 ++ src/components/party_group_layout.jsx | 12 ++++++++---- src/state.ts | 9 +++++---- tests/e2e/conftest.py | 11 ++++++----- tests/e2e/test_pages.py | 25 ++++++++++++++++++++++--- 5 files changed, 43 insertions(+), 16 deletions(-) diff --git a/src/components/magic_word_display.jsx b/src/components/magic_word_display.jsx index f0e4bcd..3db9764 100755 --- a/src/components/magic_word_display.jsx +++ b/src/components/magic_word_display.jsx @@ -30,6 +30,8 @@ export function MagicWordDisplay({ state }) { return () => { stopped = true; clearInterval(interval); + // so an old word isn't shown if the timed mode comes back + setMagicWord(undefined); }; }, [timed]); diff --git a/src/components/party_group_layout.jsx b/src/components/party_group_layout.jsx index 77a97e5..ba88ef3 100755 --- a/src/components/party_group_layout.jsx +++ b/src/components/party_group_layout.jsx @@ -36,14 +36,18 @@ export function PartyGroupLayout({ state, loadGroup, socket }) { } // Staff can open any group's page, so load it if it isn't one of the active - // groups the page already has. Once: a group that doesn't exist stays missing. + // groups the page already has: once, and again whenever the connection comes + // back, since a failed request leaves the page offline. A group that doesn't + // exist stays missing. const staff = isStaff(state); const hasGroup = group != null; + const missing = isGroupMissing(state, groupID); + const online = !state.offline; React.useEffect(() => { - if (staff && !hasGroup) { + if (staff && online && !hasGroup && !missing) { loadGroup(groupID); } - }, [staff, hasGroup, groupID, loadGroup]); + }, [staff, online, hasGroup, missing, groupID, loadGroup]); // Signed-out visitors get no groups; the home page asks them to sign in. if (state.loaded && !state.currentUser) { @@ -53,7 +57,7 @@ export function PartyGroupLayout({ state, loadGroup, socket }) { if (!group) { // Only staff can load a group that isn't active; students get its page // only for an active group, or their own. - if (state.loaded && (!staff || isGroupMissing(state, groupID))) { + if (state.loaded && (!staff || missing)) { return ; } return "loading..."; diff --git a/src/state.ts b/src/state.ts index f7c6ed8..e7f2288 100755 --- a/src/state.ts +++ b/src/state.ts @@ -179,8 +179,8 @@ export function ticketLocation(state: State, ticket: Ticket): TicketLocation { export function ticketQuestion(state: State, ticket: Ticket | Group): string { // A question number, such as "3", is shown as "Q3"; anything else as it is. const question = (ticket.question ?? "").trim(); - if (question !== "" && !isNaN(Number(question))) { - return "Q" + parseInt(question); + if (/^\d+$/.test(question)) { + return "Q" + parseInt(question, 10); } return question; } @@ -411,9 +411,10 @@ export function setGroup(state: State, group: Group): void { state.groups.sort((a, b) => a.id - b.id); } -/* A group loaded by ID, or null if there's no such group. */ +/* The server's answer to loading a group by ID: the group, or else nothing or + * an error (for an ID that isn't one), so there's no such group. */ export function receiveGroup(state: State, id: number, group: Group | null) { - if (group != null) { + if (group != null && group.id === id) { setGroup(state, group); } else { state.missingGroups.add(id); diff --git a/tests/e2e/conftest.py b/tests/e2e/conftest.py index beab58e..8bbf415 100644 --- a/tests/e2e/conftest.py +++ b/tests/e2e/conftest.py @@ -60,10 +60,11 @@ def button(self, text): return self.wait(lambda: next((e for e in self.driver.find_elements(By.XPATH, xpath) if e.is_displayed()), None)) - def watch_requests(self, fail=()): + def watch_requests(self, fail=None): """From the next page opened: count the page's API requests by endpoint, in - window.requests, and make those to the endpoints in fail fail, as if the - server were unreachable.""" + window.requests, and make requests to the endpoints in fail, a dict of + endpoint to how many of its first requests fail, fail as if the server were + unreachable.""" # in a function, so its names don't become globals the page's scripts see script = """(() => { window.requests = {}; @@ -73,13 +74,13 @@ def watch_requests(self, fail=()): const endpoint = String(url).split("/api/")[1]; if (endpoint) { window.requests[endpoint] = (window.requests[endpoint] || 0) + 1; - if (fail.includes(endpoint)) { + if (window.requests[endpoint] <= (fail[endpoint] || 0)) { return Promise.reject(new TypeError("Failed to fetch")); } } return fetch(url, ...rest); }; - })();""" % json.dumps(list(fail)) + })();""" % json.dumps(fail or {}) added = self.driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {"source": script}) self.scripts.append(added["identifier"]) diff --git a/tests/e2e/test_pages.py b/tests/e2e/test_pages.py index 861b5bc..8da8eac 100644 --- a/tests/e2e/test_pages.py +++ b/tests/e2e/test_pages.py @@ -223,16 +223,35 @@ def test_group_that_does_not_exist(site): assert site.console_errors() == [] +def test_group_page_with_an_id_that_is_not_a_number(site): + site.log_in(*STAFF) + site.visit(f"{COURSE}/groups/abc") + site.wait(lambda: "Not found" in site.text()) + + +def test_group_page_asks_again_after_a_failed_request(site): + """A group that doesn't exist: the first request fails, as if the network were down, + and the page asks again once it's back online.""" + site.watch_requests(fail={"load_group": 1}) + site.log_in(*STAFF) + site.visit(f"{COURSE}/groups/12345") + # the page polls every ten seconds, which brings it back online + site.wait(lambda: "Not found" in site.text(), timeout=25) + assert site.requests("load_group") == 2 + + def test_group_without_a_question(site, app): add_group(app, question="") site.log_in(*STAFF) site.visit(COURSE + "/party") - site.wait(lambda: "Return to group" in site.text() or "Join" in site.text()) - assert "QNaN" not in site.text() + # the group's card, which shows its assignment, question and location + card = site.wait(lambda: next(iter(site.driver.find_elements(By.CSS_SELECTOR, ".card-holder .panel")), None)) + site.wait(lambda: "Hog" in card.text and "Cory 247" in card.text) + assert "QNaN" not in card.text def test_failed_setting_save_can_be_tried_again(site): - site.watch_requests(fail=["update_config"]) + site.watch_requests(fail={"update_config": 1}) site.log_in(*STAFF) site.visit(COURSE + "/admin") delay = site.driver.find_element(By.CSS_SELECTOR, "input[type=number]")