diff --git a/CHANGELOG.md b/CHANGELOG.md index a85e227..9a3e570 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ All notable changes to lectern are documented here. ## [Unreleased] ### Added +- **`reg-canvas discussions`: one running report per term, sorted by week.** With no `--week`, `review` covers every "Week N" discussion and writes `classes/semesters/-discussions-grading.md`, with one section per week. A rerun refreshes it and keeps every deny already ticked. A student with a ticked post stays listed even after posting enough to drop off the list, so a denial is never lost. `--force` starts fresh. `apply` now requires `--week`, because the report includes hand-graded weeks that a blanket apply would overwrite. +- **`canvas_api`: dropped connections are retried when that is safe.** On the first live discussion run, a TLS handshake timed out partway through about 600 like requests. A GET is now retried with backoff, and so is a write the caller marks `idempotent` (grades, likes and posting in `discussions apply`). Other writes are not retried, because a timeout can arrive after Canvas has acted, and a second announcement would notify students twice. - **`reg-canvas audit` and `reg-canvas discussions`: gradebook audit and discussion grading.** The first full read of the Fa26 gradebooks found no forgotten posting, but it did find three problems. Weeks 5 and 6 were ungraded in every section. 326 §03's Exam 1 was filed under Class Participation, so it counted at 10% instead of 60%. And 378's missing-submission policy was off, so non-posters were blank and left out of the current score. `audit` reports all three kinds of problem, plus hidden grades (missing-work zeros counted apart), and exits 1 when it finds something. `discussions review` grades by post count (2 or more = 5, 1 = 3) and writes a vault note listing only the posts that need a human look: one post, a post under 25 words, or 30% phrase overlap with another student. Each of those posts has a deny box. `discussions apply` reads the ticks back and sets changed scores, likes every credited post, and with `--post` posts the grades. It is a dry run until `--apply`. Posts are read to measure them, as an instructor does in SpeedGrader, and the text is reduced to metrics in memory. It is never written, printed or kept, and a test enforces that. The metrics (length, Flesch-Kincaid grade, sentence-length spread, vocabulary ratio, reply structure, names a classmate, links, overlap) are documented as prompts to read, not an AI detector. `--exclude-sis` and `--full-credit-sis` take `SIS@326-03` to scope to one section. Live-checked read-only on the three Fa26 sections, with the same counts as the prototype scripts. New module `canvas_grading`; runbook sections in `docs/canvas-api.md`. - **`reg-lms-grades-import --exclude-sis`: course staff with a student role.** A grad assistant who needs the student view is enrolled as a student in every section's Canvas course, so the export lists them like a student and `reg-gradebook import` stops with "in Canvas but not in roster". Their SIS IDs now go to `grades.filtered.csv` with reason `staff`, alongside the Test Student and ISA filters. `reg-canvas grades-export --import` passes the same flag through. Found on the first live `reg-canvas` export, 2026-10-21. - **`docs/gradescope-workflow.md`: getting Gradescope totals back into lectern.** Gradescope has no instructor API and a Canvas token does not reach it, so the doc now describes the supported route: link the course through Gradescope's Canvas tool (LTI 1.3), post totals to Canvas, and read them with `reg-canvas grades-export`. It warns against pushing the same column from both Gradescope and `reg-canvas grades-push`, and notes that item analysis still needs the per-question export. diff --git a/SKILL.md b/SKILL.md index a134cbf..603eb6c 100644 --- a/SKILL.md +++ b/SKILL.md @@ -281,10 +281,10 @@ reg-canvas grades-push --term fa26 --vault-root --course "CECS 326" --sectio reg-canvas announce --term fa26 --vault-root --course "CECS 326" \ --file '/posted/fa26-{section}-ANNOUNCE.md' # dry run; add --apply reg-canvas audit --term fa26 --vault-root # what was never graded or posted -reg-canvas discussions review --term fa26 --vault-root --week "Week 7" \ - --workdir ~/tmp/canvas-discussions/fa26-w7 # writes the vault note to judge -reg-canvas discussions apply --workdir ~/tmp/canvas-discussions/fa26-w7 \ - --note /classes/semesters/fa26-discussions-w7-grading.md --post # dry run; add --apply +reg-canvas discussions review --term fa26 --vault-root \ + --workdir ~/tmp/canvas-discussions/fa26 # term report, a section per week; rerun keeps ticks +reg-canvas discussions apply --workdir ~/tmp/canvas-discussions/fa26 --week "Week 7" \ + --note /classes/semesters/fa26-discussions-grading.md --post # dry run; add --apply ``` ==Every write is a dry run until `--apply`.== An agent shows the dry run and diff --git a/docs/canvas-api.md b/docs/canvas-api.md index f7e4b57..934c557 100644 --- a/docs/canvas-api.md +++ b/docs/canvas-api.md @@ -279,14 +279,20 @@ flowchart LR ``` ```sh -W=~/tmp/canvas-discussions/fa26-w7 -reg-canvas discussions review --term fa26 --vault-root --week "Week 7" --workdir $W \ +W=~/tmp/canvas-discussions/fa26 +reg-canvas discussions review --term fa26 --vault-root --workdir $W \ --exclude-sis @326-03 --full-credit-sis @326-01 ``` -`review` writes the vault note -`classes/semesters/-discussions--grading.md`. The note lists only -these students, each with a SpeedGrader link: +`review` writes one running report per term, +`classes/semesters/-discussions-grading.md`, with a section for each +"Week N" discussion. Run it whenever you like: mid-week to see who has posted, +and again after the due date. ==A rerun adds new posts and keeps every box you +have ticked.== `--week "Week 7"` limits it to one week, and then it writes a +separate note for that week. `--force` starts the note fresh. + +In each week's section, the note lists only these students, each with a +SpeedGrader link: - students who made one post - students with a post under 25 words @@ -298,11 +304,15 @@ Each listed post has a **deny** box. Tick it when the post does not earn credit, and that student drops one tier. ```sh -reg-canvas discussions apply --workdir $W --note --post # dry run -reg-canvas discussions apply --workdir $W --note --post --apply # send -rm -rf $W +N=/classes/semesters/fa26-discussions-grading.md +reg-canvas discussions apply --workdir $W --note $N --week "Week 7" --post # dry run +reg-canvas discussions apply --workdir $W --note $N --week "Week 7" --post --apply # send +rm -rf $W # at the end of the term ``` +`apply` needs `--week`. The report covers every week, including any you graded +by hand, and applying a week overwrites the grades already entered for it. + `--exclude-sis` leaves course staff who hold a student enrolment out of grading. `--full-credit-sis` gives a student full credit whatever the count, for an agreed arrangement. Both take `SIS` for every section or `SIS@326-03` @@ -359,6 +369,7 @@ and tell your Canvas administrators the same day. | `expected one Canvas course, found …` | `reg-canvas courses` lists two courses with the same class number, or none. | Write the `canvas:` block into the class note by hand. | | `names assignments this course does not have` | The import file's `(id)` columns come from another section's export. | Export that section again, rebuild the overlay, and push it. | | `discussions apply` says "no plan in …" | `ls ` shows no `plan.json`. | Run `discussions review` with the same `--workdir` first. | -| `review` refuses to overwrite the note | The note already exists and may hold your ticks. | Finish that round, or pass `--force` to start again. | +| `apply` says "name the week(s) to apply" | You left out `--week`. | Add `--week "Week N"` for the week you reviewed. | +| `apply` stops with "cannot reach Canvas" | A dropped connection that outlasted the retries. | Run the same command again. Grades and likes are only set once. | | A like fails with `HTTP 403` | The topic does not allow liking. | Turn on **Allow liking** in the discussion's settings. | | An export has fewer columns than Canvas's own | `reg-canvas grades-export --stdout --course-id \| head -1` lists the assignment columns. Unpublished and hidden assignments are left out. | Publish the assignment, or ignore the column if it is not graded yet. | diff --git a/lectern/canvas.py b/lectern/canvas.py index 393eb21..669a20e 100644 --- a/lectern/canvas.py +++ b/lectern/canvas.py @@ -769,8 +769,9 @@ def writes(sp): act = sp.add_subparsers(dest="action", required=True) r = act.add_parser("review", help="write the short list to judge (reads only)") target(r) - r.add_argument("--week", action="append", required=True, - help='assignment name prefix, e.g. "Week 5" (repeatable)') + r.add_argument("--week", action="append", + help='assignment name prefix, e.g. "Week 5" (repeatable; ' + 'default: every "Week N" discussion)') r.add_argument("--workdir", required=True, help="private working dir (mode 700); " "holds student records, delete after apply") r.add_argument("--exclude-sis", nargs="+", default=[], metavar="SIS[@SEC]", @@ -778,13 +779,16 @@ def writes(sp): r.add_argument("--full-credit-sis", nargs="+", default=[], metavar="SIS[@SEC]", help="full credit whatever the count (an agreed arrangement)") r.add_argument("--note", help="vault note to write (default with --term/--vault-root: " - "classes/semesters/-discussions--grading.md)") + "classes/semesters/-discussions-grading.md, one section per week)") r.add_argument("--no-note", action="store_true", help="write no vault note") - r.add_argument("--force", action="store_true", help="overwrite an existing note") + r.add_argument("--force", action="store_true", + help="start the note fresh, dropping ticks (default: a rerun keeps them)") r.set_defaults(func=cmd_discussions) ap_ = act.add_parser("apply", help="set scores and likes from the review") ap_.add_argument("--workdir", required=True) ap_.add_argument("--note", help="read the ticked deny boxes from this note") + ap_.add_argument("--week", action="append", + help='the week to apply, e.g. "Week 7" (required; repeatable)') ap_.add_argument("--post", action="store_true", help="also post the grades (shows students every hidden grade)") writes(ap_) diff --git a/lectern/canvas_api.py b/lectern/canvas_api.py index 7da43e3..fcf839b 100644 --- a/lectern/canvas_api.py +++ b/lectern/canvas_api.py @@ -185,8 +185,14 @@ def _url(self, path: str, params: dict | list | None = None) -> str: def _scrub(self, text: str) -> str: return text.replace(self.token, "[token]") if self.token else text - def request(self, method: str, path: str, params=None, data=None): - """One call. Returns ``(parsed JSON, response headers)``.""" + def request(self, method: str, path: str, params=None, data=None, idempotent=None): + """One call. Returns ``(parsed JSON, response headers)``. + + A dropped connection is retried for a GET, or for a write the caller + marks ``idempotent`` (setting a grade or a like). Other writes are not + retried: a timeout can arrive after Canvas has acted, and a second + announcement would notify students twice. + """ url = self._url(path, params) if urllib.parse.urlsplit(url).netloc != self.host: raise CanvasError(f"refusing to send the token to {urllib.parse.urlsplit(url).netloc}") @@ -196,8 +202,15 @@ def request(self, method: str, path: str, params=None, data=None): body = json.dumps(data).encode("utf-8") headers["Content-Type"] = "application/json" + safe = method == "GET" if idempotent is None else idempotent for attempt in range(self.retries + 1): - status, rh, raw = self.transport(method, url, headers, body) + try: + status, rh, raw = self.transport(method, url, headers, body) + except CanvasError as e: + if e.status is None and safe and attempt < self.retries: + self.sleep(2 ** attempt) + continue + raise text = raw.decode("utf-8", errors="replace") # Canvas throttles with 403 + "Rate Limit Exceeded"; 429 on some hosts. throttled = status == 429 or (status == 403 and "Rate Limit Exceeded" in text) @@ -255,11 +268,11 @@ def get_all(self, path: str, params=None) -> Iterator[dict]: return page, headers = self.request("GET", nxt) - def post(self, path: str, data: dict): - return self.request("POST", path, data=data)[0] + def post(self, path: str, data: dict, idempotent: bool = False): + return self.request("POST", path, data=data, idempotent=idempotent)[0] - def put(self, path: str, data: dict): - return self.request("PUT", path, data=data)[0] + def put(self, path: str, data: dict, idempotent: bool = False): + return self.request("PUT", path, data=data, idempotent=idempotent)[0] def wait_progress(self, progress: dict, timeout: float = 120.0) -> dict: """Poll a Canvas Progress object until it completes or fails.""" diff --git a/lectern/canvas_grading.py b/lectern/canvas_grading.py index c268f55..a38aee9 100644 --- a/lectern/canvas_grading.py +++ b/lectern/canvas_grading.py @@ -304,14 +304,38 @@ def _private_write(path: Path, text: str) -> None: os.chmod(path, 0o600) -def default_note(vault: Path, term: str, weeks: list[str]) -> Path: +_WEEK = re.compile(r"^(Week \d+)\b") + + +def week_of(name: str, wanted: list[str] | None) -> str | None: + """The week an assignment belongs to: a ``--week`` prefix, or its own ``Week N``.""" + if wanted: + return next((w for w in wanted if name.startswith(w)), None) + m = _WEEK.match(name) + return m.group(1) if m else None + + +def _week_order(week: str): + m = re.search(r"\d+", week) + return (int(m.group()) if m else 0, week) + + +def default_note(vault: Path, term: str, weeks: list[str] | None = None) -> Path: + if not weeks: # the term's running report, one section per week + return vault / "classes" / "semesters" / f"{term}-discussions-grading.md" slug = "-".join(re.sub(r"[^a-z0-9]+", "", w.lower()).replace("week", "w") for w in weeks) return vault / "classes" / "semesters" / f"{term}-discussions-{slug}-grading.md" def review(client: CanvasClient, args, targets) -> int: wd = _private_dir(Path(args.workdir).expanduser()) - plan, flagged, rows = [], [], [] + plan, rows = [], [] + flagged: dict[str, list[str]] = defaultdict(list) + summary: dict[str, list[str]] = defaultdict(list) + note = note_path(args) + # A rerun refreshes the note and keeps every deny already ticked in it, so + # the review can run mid-week and again after the due date. + kept = set() if args.force or not note else denials(wd, note) - _file_denials(wd) for t in targets: studs = students(client, t.course_id, scoped(args.exclude_sis, t)) full = scoped(args.full_credit_sis, t) @@ -319,7 +343,7 @@ def review(client: CanvasClient, args, targets) -> int: firsts = {k: v for k, v in firsts.items() if v} key = section_key(t) for a in client.get_all(f"courses/{t.course_id}/assignments"): - week = next((w for w in args.week if a["name"].startswith(w)), None) + week = week_of(a["name"], args.week) topic = a.get("discussion_topic") if not week or not topic: continue @@ -344,29 +368,41 @@ def review(client: CanvasClient, args, targets) -> int: tally[score_for(len(ents), forced)] += 1 short = sum(1 for _, m in ents if m["words"] < SHORT_WORDS) copied = sum(1 for _, m in ents if m["max_overlap"] >= OVERLAP) - if forced or (len(ents) >= 2 and not short and not copied): + ticked = any(e in kept for e, _ in ents) + if forced or (len(ents) >= 2 and not short and not copied and not ticked): continue - why = [f"one post only ({PARTIAL} pt)" if len(ents) == 1 else "", + why = ["denied in an earlier review" if ticked and len(ents) >= 2 + and not short and not copied else "", + f"one post only ({PARTIAL} pt)" if len(ents) == 1 else "", f"{short} post(s) under {SHORT_WORDS} words" if short else "", f"{copied} post(s) sharing {OVERLAP:.0%}+ phrasing with another student" if copied else ""] sg = (f"{client.base}/courses/{t.course_id}/gradebook/speed_grader" f"?assignment_id={a['id']}&student_id={uid}") - flagged.append(f"- **{key} {week}**, {s['name']}: " + flagged[week].append(f"- **{key}**, {s['name']}: " f"{'; '.join(x for x in why if x)}. [SpeedGrader]({sg})") for eid, m in ents: - flagged.append(f" - [ ] deny entry `{eid}` ({describe(m)}): {client.base}" + box = "x" if eid in kept else " " + flagged[week].append(f" - [{box}] deny entry `{eid}` ({describe(m)}): {client.base}" f"/courses/{t.course_id}/discussion_topics/{topic['id']}" f"?entry_id={eid}") - print(f"{t.label} {week}: {len(per)} of {len(studs)} posted; " - f"{tally[FULL]} at {FULL}, {tally[PARTIAL]} at {PARTIAL}") - - body = [f"# Discussion grading: {', '.join(args.week)}", "", + line = (f"{len(per)} of {len(studs)} posted; " + f"{tally[FULL]} at {FULL}, {tally[PARTIAL]} at {PARTIAL}") + print(f"{t.label} {week}: {line}") + summary[week].append(f"- {key}: {line}") + + title = (f"Discussion grading: {', '.join(args.week)}" if args.week + else f"Discussion grading {args.term or ''}".strip()) + body = [f"# {title}", "", f"Rule: 2+ credited posts = {FULL}, 1 = {PARTIAL}, 0 = 0. Every credited post " "gets a like; no comments are written.", "Everyone not listed has 2+ posts of normal length.", "", "Tick **deny** on any post that does not earn credit.", ""] - body += flagged or ["Nobody needs review."] + for week in sorted(summary, key=_week_order): + body += [f"## {week}", ""] + summary[week] + [""] + body += (flagged[week] or ["Nobody needs review."]) + [""] + if not summary: + body.append("No discussion assignments matched.") text = "\n".join(body) + "\n" _private_write(wd / "plan.json", json.dumps(plan)) _private_write(wd / "REVIEW.md", text) @@ -376,16 +412,16 @@ def review(client: CanvasClient, args, targets) -> int: w.writeheader() w.writerows(rows) _private_write(wd / "METRICS.csv", buf.getvalue()) - n = sum(1 for line in flagged if line.startswith("- ")) + n = sum(1 for lines in flagged.values() for line in lines if line.startswith("- **")) print(f"\n{n} to review: {wd / 'REVIEW.md'}") - note = note_path(args) if note: - if note.exists() and not args.force: - raise GradingError(f"{note} exists and may hold your ticks; pass --force to overwrite") + lost = kept - {e for p in plan for e in p["entries"]} + if lost: + print(f"warning: ticked entries no longer in Canvas (deleted posts?): {sorted(lost)}") stamp = datetime.now().astimezone().isoformat(timespec="seconds") fm = ("---\n" - f"title: \"Discussion grading: {', '.join(args.week)}\"\n" + f"title: \"{title}\"\n" "type: report\n" f"term: {args.term or ''}\n" "tags: [teaching, discussion, grading, internal]\n" @@ -393,19 +429,19 @@ def review(client: CanvasClient, args, targets) -> int: f"created: {stamp}\n---\n") how = ("> [!info] How to use this\n" "> Tick **deny** on a post that does not earn credit, then run " - f"`reg-canvas discussions apply --workdir {args.workdir} --note '{note}'` " - "for the dry run.\n") + f"`reg-canvas discussions apply --workdir {args.workdir} --note '{note}' " + "--week \"Week N\"` for that week's dry run. Rerun `review` any time: " + "it adds new posts and keeps your ticks.\n") head, rest = text.split("\n", 1) _private_write(note, fm + head + "\n\n" + how + rest) - print(f"Vault note: {note}") + print(f"Vault note: {note}" + (f" (kept {len(kept)} tick(s))" if kept else "")) return 0 def note_path(args) -> Path | None: if getattr(args, "note", None): return Path(args.note).expanduser() - if getattr(args, "no_note", False) or not (args.vault_root and args.term - and getattr(args, "week", None)): + if getattr(args, "no_note", False) or not (args.vault_root and args.term): return None return default_note(Path(args.vault_root), args.term, args.week) @@ -413,10 +449,14 @@ def note_path(args) -> Path | None: _TICK = re.compile(r"^\s*- \[[xX]\] deny entry `(\d+)`", re.M) +def _file_denials(wd: Path) -> set[int]: + if not (wd / "deny.txt").exists(): + return set() + return {int(t) for t in (wd / "deny.txt").read_text().split()} + + def denials(wd: Path, note: Path | None) -> set[int]: - deny = set() - if (wd / "deny.txt").exists(): - deny |= {int(t) for t in (wd / "deny.txt").read_text().split()} + deny = _file_denials(wd) if note and note.exists(): deny |= {int(x) for x in _TICK.findall(note.read_text(encoding="utf-8"))} return deny @@ -432,6 +472,11 @@ def apply(client: CanvasClient, args) -> int: plan = json.loads((wd / "plan.json").read_text()) except FileNotFoundError: raise GradingError(f"no plan in {wd}; run reg-canvas discussions review first") from None + if not args.week: + weeks = sorted({p["week"] for p in plan}, key=_week_order) + raise GradingError("name the week(s) to apply with --week, e.g. --week \"Week 7\"; " + f"this review covers {', '.join(weeks) or 'nothing'}. Applying " + "an older week overwrites the grades already entered for it.") note = Path(args.note).expanduser() if args.note else None deny = denials(wd, note) if deny: @@ -439,6 +484,8 @@ def apply(client: CanvasClient, args) -> int: groups: dict[tuple, list] = defaultdict(list) for p in plan: + if args.week and not any(p["week"].startswith(w) for w in args.week): + continue credited = [e for e in p["entries"] if e not in deny] groups[(p["course"], p["label"], p["assignment"], p["topic"], p["week"])].append( (p, credited, score_for(len(credited), p["full_credit"]))) @@ -460,12 +507,14 @@ def apply(client: CanvasClient, args) -> int: if grades: client.wait_progress(client.post( f"courses/{cid}/assignments/{aid}/submissions/update_grades", - {"grade_data": grades})) + {"grade_data": grades}, idempotent=True)) for e in likes: - client.post(f"courses/{cid}/discussion_topics/{tid}/entries/{e}/rating", {"rating": 1}) + client.post(f"courses/{cid}/discussion_topics/{tid}/entries/{e}/rating", {"rating": 1}, + idempotent=True) if args.post: r, _ = client.request("POST", f"{client.base}/api/graphql", - data={"query": POST_GRADES, "variables": {"id": str(aid)}}) + data={"query": POST_GRADES, "variables": {"id": str(aid)}}, + idempotent=True) errs = (((r or {}).get("data") or {}).get("postAssignmentGrades") or {}).get("errors") if errs: raise GradingError(f"{label} {week}: posting failed: {errs}") diff --git a/tests/test_canvas.py b/tests/test_canvas.py index 6acd667..77437de 100644 --- a/tests/test_canvas.py +++ b/tests/test_canvas.py @@ -405,3 +405,22 @@ def test_syllabus_refuses_a_file_without_the_notes_serial(vault, tmp_path, capsy "--course", "CECS 326", "--section", "01", "--file", str(f), "--apply"], client=client) assert rc == 2 and "487BD388" in capsys.readouterr().err and fake.writes() == [] + + +def test_a_dropped_connection_is_retried_only_when_safe(): + calls = [] + + def flaky(method, url, headers, body): + calls.append(method) + if len(calls) == 1: + raise CanvasError("cannot reach Canvas: timed out") + return 200, {}, b"{}" + + c = CanvasClient(BASE, TOKEN, transport=flaky, sleep=lambda s: None) + assert c.get("courses") == {} and calls == ["GET", "GET"] + calls.clear() + assert c.post("x/rating", {"rating": 1}, idempotent=True) == {} and len(calls) == 2 + calls.clear() + with pytest.raises(CanvasError): + c.post("courses/1/discussion_topics", {"is_announcement": True}) + assert calls == ["POST"] diff --git a/tests/test_canvas_grading.py b/tests/test_canvas_grading.py index 061cac6..0773a02 100644 --- a/tests/test_canvas_grading.py +++ b/tests/test_canvas_grading.py @@ -58,7 +58,7 @@ def run_review(tmp_path, argv=()): def run_apply(tmp_path, argv=(), extra=None): client, fake = client_for(routes(extra)) ns = canvas.build_parser().parse_args( - ["discussions", "apply", "--workdir", str(tmp_path / "wd"), *argv]) + ["discussions", "apply", "--workdir", str(tmp_path / "wd"), "--week", "Week 5", *argv]) assert ns.func(client, ns) == 0 return fake @@ -118,13 +118,22 @@ def test_staff_are_excluded_and_full_credit_is_honoured(tmp_path): assert "Able, Bo" not in (tmp_path / "wd" / "REVIEW.md").read_text() -def test_review_will_not_overwrite_a_ticked_note(tmp_path): +def test_a_rerun_keeps_ticks_and_force_drops_them(tmp_path): note = tmp_path / "note.md" - note.write_text("- [x] deny entry `101`") - client, _ = client_for(routes()) - rc = canvas.main(["discussions", "review", "--course-id", "7", "--week", "Week 5", - "--workdir", str(tmp_path / "wd"), "--note", str(note)], client=client) - assert rc == 2 and "[x]" in note.read_text() + run_review(tmp_path, ["--note", str(note)]) + note.write_text(note.read_text().replace("- [ ] deny entry `101`", "- [x] deny entry `101`")) + run_review(tmp_path, ["--note", str(note)]) + assert "- [x] deny entry `101`" in note.read_text() + run_review(tmp_path, ["--note", str(note), "--force"]) + assert "[x]" not in note.read_text() + + +def test_a_ticked_student_stays_listed_after_more_posts(tmp_path): + note = tmp_path / "note.md" + note.write_text(" - [x] deny entry `100` (...)\n") + run_review(tmp_path, ["--note", str(note)]) # Ann has 2 normal posts, so is normally unlisted + text = note.read_text() + assert "Zed, Ann: denied in an earlier review" in text and "- [x] deny entry `100`" in text # ── apply ──────────────────────────────────────────────────────────────────── @@ -191,3 +200,31 @@ def test_audit_flags_empty_groups_policy_and_hidden_grades(): assert "1 submitted, not graded" in text and "past due, 1 ungraded" in text assert "1 student(s) see a score that differs" in text assert n >= 3 and not fake.writes() + + +def test_without_week_every_week_gets_its_own_section(tmp_path): + extra = {("GET", "courses/7/assignments"): [ + {"id": 50, "name": "Week 5 - Memory", "discussion_topic": {"id": 70}}, + {"id": 52, "name": "Week 10 - Files", "discussion_topic": {"id": 72}}, + {"id": 51, "name": "Exam 1", "discussion_topic": {"id": 71}}], + ("GET", "courses/7/discussion_topics/72/view"): {"view": []}} + client, _ = client_for(routes(extra)) + note = tmp_path / "term.md" + ns = canvas.build_parser().parse_args( + ["discussions", "review", "--course-id", "7", "--workdir", str(tmp_path / "wd"), + "--exclude-sis", "999", "--note", str(note)]) + ns.func(client, ns) + text = note.read_text() + assert text.index("## Week 5") < text.index("## Week 10") and "Exam 1" not in text + + +def test_apply_week_limits_the_writes(tmp_path): + run_review(tmp_path) + client, fake = client_for(routes()) + ns = canvas.build_parser().parse_args( + ["discussions", "apply", "--workdir", str(tmp_path / "wd"), "--week", "Week 9", "--apply"]) + ns.func(client, ns) + assert not fake.writes() + rc = canvas.main(["discussions", "apply", "--workdir", str(tmp_path / "wd"), "--apply"], + client=client) + assert rc == 2 and not fake.writes()