forked from ChelseaKR/queer-the-stacks
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_render_view.py
More file actions
506 lines (426 loc) · 17.7 KB
/
Copy pathtest_render_view.py
File metadata and controls
506 lines (426 loc) · 17.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
"""Renderer + view assembly: content, escaping, and the wired demo view."""
from __future__ import annotations
from pathlib import Path
from app.a11y_check import check_html
from app.render import render_dashboard
from app.view import build_view, demo_view, render_view
from ingest.models import (
Author,
Book,
DailyActivity,
ReadingState,
ReadingStatus,
Source,
SourceKind,
ThemeTag,
)
from ingest.store import CatalogPoolStatus, CatalogSourceStatus
def test_demo_view_has_expected_shape(tmp_path: Path) -> None:
view = demo_view(tmp_path)
assert view.user == "demo"
assert view.currently_reading
assert view.finished
assert view.recommendations
assert view.stats.books_finished >= 7
assert view.wrapped.year == 2024
def test_render_contains_all_sections(tmp_path: Path) -> None:
view = demo_view(tmp_path)
html = render_dashboard(
view.currently_reading,
view.finished,
view.stats,
view.wrapped,
view.recommendations,
user=view.user,
)
for heading in (
"Currently reading",
"Time to finish",
"Reading stats",
"Reading Wrapped",
"Recommended for you",
"Recently finished",
):
assert heading in html
# Every rec card shows a source link and a why.
assert "Why recommended" in html
assert "Sources" in html
# Cards are the single accessible recommendation presentation.
assert "Recommendation fit scores" not in html
assert 'aria-label="Dashboard sections"' in html
assert 'action="/browse" method="get"' in html
assert 'aria-label="Reading progress for Stone Butch Blues"' in html
# Themes are rendered as text chips, not colour-only.
assert 'class="tag"' in html
def test_render_escapes_user_content() -> None:
src = Source(SourceKind.CALIBRE_TAG, "calibre:local", "2026-06-05", "x")
book = Book(
book_id="b",
title="<script>alert(1)</script>",
authors=(Author("A & B"),),
theme_tags=(ThemeTag("queer", src),),
)
state = ReadingState(
title=book.title, authors=("A & B",), status=ReadingStatus.READING, book=book
)
from app.stats import compute_stats
from app.wrapped import compute_wrapped
stats = compute_stats([state], [], 0)
wrapped = compute_wrapped([state], [], 2024)
html = render_dashboard([state], [], stats, wrapped, [], user="me")
assert "<script>alert(1)</script>" not in html
assert "<script>" in html
assert "A & B" in html
def test_build_view_empty_inputs() -> None:
view = build_view([], [], (), lists=())
assert view.recommendations == ()
assert view.stats.books_finished == 0
assert view.currently_reading == ()
def test_render_handles_empty_view() -> None:
view = build_view([], [DailyActivity(0, 0, 0)], ())
html = render_dashboard(
view.currently_reading,
view.finished,
view.stats,
view.wrapped,
view.recommendations,
)
assert "Nothing in progress" in html
assert "No recommendation candidates are stored yet" in html
def test_render_preserves_browse_query_and_exposes_live_count() -> None:
view = build_view([], [DailyActivity(0, 0, 0)], ())
html = render_dashboard(
view.currently_reading,
view.finished,
view.stats,
view.wrapped,
view.recommendations,
browse_query='queer "history"',
browse_theme='trans "history"',
browse_status="unread",
)
assert 'value="queer "history""' in html
assert 'type="hidden" name="theme" value="trans "history""' in html
assert 'type="hidden" name="status" value="unread"' in html
assert 'id="lib-filter-status"' in html
assert 'aria-live="polite"' in html
def test_render_caps_large_library_preview_but_reports_full_count() -> None:
view = build_view([], [DailyActivity(0, 0, 0)], ())
library = [
ReadingState(
title=f"Book {index:03}",
authors=("Reader",),
status=ReadingStatus.UNREAD,
)
for index in range(101)
]
html = render_dashboard(
view.currently_reading,
view.finished,
view.stats,
view.wrapped,
view.recommendations,
library=library,
)
assert "Showing the first 100 of 101 books" in html
assert 'data-complete="false"' in html
assert "Book 099" in html
assert "Book 100" not in html
def test_render_catalog_degradation_exposes_last_good_fallback() -> None:
view = build_view([], [DailyActivity(0, 0, 0)], ())
status = CatalogPoolStatus(
outbound_mode="public-metadata",
state="degraded",
attempted_at=1_700_000_010,
candidate_count=2,
sources=(
CatalogSourceStatus(
source_id="openlibrary:subject/lgbt",
status="error",
attempted_at=1_700_000_010,
fetched_at=1_700_000_000,
candidate_count=2,
error="TimeoutError",
),
),
)
html = render_dashboard(
view.currently_reading,
view.finished,
view.stats,
view.wrapped,
view.recommendations,
catalog_status=status,
)
assert '<details class="source-status" open>' in html
assert "Public metadata — explicitly enabled" in html
assert "A source failed; last-good candidates are retained" in html
assert "Last attempt failed; using last-good candidates." in html
assert "2023-11-14T22:13:20Z" in html
assert "TimeoutError" in html
assert check_html(html) == []
def test_render_data_status_never_refreshed() -> None:
view = build_view([], [DailyActivity(0, 0, 0)], ())
html = render_dashboard(
view.currently_reading,
view.finished,
view.stats,
view.wrapped,
view.recommendations,
)
assert "Data status" in html
assert "never refreshed" in html
assert "stacks refresh" in html
assert 'class="status-note" role="status"' not in html
def test_render_data_status_shows_stamp_and_no_banner_when_fresh() -> None:
view = build_view([], [DailyActivity(0, 0, 0)], ())
html = render_dashboard(
view.currently_reading,
view.finished,
view.stats,
view.wrapped,
view.recommendations,
refreshed_at=1_700_000_000,
stale=False,
)
assert "Data status" in html
assert "2023-11-14T22:13:20Z" in html # ISO-8601 UTC of the epoch stamp
assert 'class="status-note" role="status"' not in html
def test_render_data_status_stale_banner_is_visible_text() -> None:
view = build_view([], [DailyActivity(0, 0, 0)], ())
html = render_dashboard(
view.currently_reading,
view.finished,
view.stats,
view.wrapped,
view.recommendations,
refreshed_at=1_700_000_000,
stale=True,
)
assert 'role="status"' in html
assert "Stale" in html # staleness named in text, not colour-only
# --- R4: descriptor provenance surfaced in the diversity section --------------
def _diversity_section(html: str) -> str:
start = html.index("Reading diversity")
return html[start : html.index("</details>", start)]
def test_diversity_provenance_shows_source_and_date(tmp_path: Path) -> None:
html = render_view(demo_view(tmp_path))
section = _diversity_section(html)
# Every diverse-shelf tag shows the source that asserted it and when (R4).
assert "Per-descriptor provenance" in section
assert "calibre-tag" in section
assert "2026-06-05" in section
# Sensitive descriptors are flagged in text (never colour-only).
assert "(sensitive)" in section
def test_hide_sensitive_redacts_diversity_section(states: list, candidates: tuple) -> None:
view = build_view(states, [], candidates, hide_sensitive_descriptors=True)
html = render_view(view)
section = _diversity_section(html)
# Identity-adjacent labels are aggregated out of the diverse-shelf view.
assert "trans" not in section and "queer" not in section
assert "aggregated for privacy" in section
assert "Privacy:" in section
# The redacted page is still fully accessible (the a11y contract holds).
assert check_html(html) == []
def test_forecasts_render_a_ranged_estimate() -> None:
from ingest.models import ReadingStat
stat = ReadingStat(
key="k",
title="Pace Book",
authors=("Author One",),
pages_read=100,
total_pages=300,
read_time_seconds=3600,
last_read_ts=1_700_000_000,
sessions=6,
)
state = ReadingState(
title="Pace Book",
authors=("Author One",),
status=ReadingStatus.READING,
stat=stat,
)
# Six recent days with pages read give a solid per-page pace sample
# (>= MIN_DAYS_FOR_ESTIMATE), so the forecast is estimable.
daily = [DailyActivity(day_ordinal=d, seconds=600, pages=10) for d in range(1, 7)]
view = build_view([state], daily, ())
assert len(view.forecasts) == 1
forecast = view.forecasts[0].forecast
assert forecast.estimable
assert forecast.low_hours > 0
assert forecast.high_hours >= forecast.low_hours
html = render_view(view)
assert "Time to finish" in html
assert "hours" in html
assert "from your last" in html # the window basis is disclosed, never hidden
assert check_html(html) == [] # the new section is accessible
def test_forecast_without_page_stat_is_honestly_unestimated() -> None:
# A currently-reading book with no reading stat can't be forecast; it must
# say so rather than guess (unknown stays first-class).
state = ReadingState(
title="No Stats Yet",
authors=("Author Two",),
status=ReadingStatus.READING,
)
view = build_view([state], [DailyActivity(1, 600, 10)], ())
assert len(view.forecasts) == 1
assert not view.forecasts[0].forecast.estimable
html = render_view(view)
assert "not enough recent reading to estimate" in html
# --- The privacy toggle covers the whole page, not one panel ----------------
#
# The diversity panel was the only section the toggle ever reached. Three other
# sections restated the same descriptors: the per-book theme chips, the library
# table's "Themes (sourced)" column, and the stats theme mix. The first two are
# strictly *more* revealing than the aggregated breakdown, because they name the
# descriptor next to a specific title.
_SENSITIVE_LENSES = (
("Identity", frozenset({"genderfluid", "transmasc"})),
("Sea stories", frozenset({"nautical"})),
)
_SENSITIVE_NAMES = frozenset({"Identity"})
def _shelf_with_sensitive_tags() -> list[ReadingState]:
def tag(label: str) -> ThemeTag:
return ThemeTag(label, Source(SourceKind.CALIBRE_TAG, "calibre:local", "2026-06-05", label))
def state(title: str, status: ReadingStatus, labels: tuple[str, ...]) -> ReadingState:
book = Book(
book_id=title,
title=title,
authors=(Author("An Author"),),
theme_tags=tuple(tag(label) for label in labels),
)
return ReadingState(title=title, authors=("An Author",), status=status, book=book)
return [
state("In Progress", ReadingStatus.READING, ("genderfluid", "nautical")),
state("Done", ReadingStatus.FINISHED, ("transmasc",)),
state("On The Pile", ReadingStatus.UNREAD, ("genderfluid",)),
]
def _page(hide: bool) -> str:
return render_view(
build_view(
_shelf_with_sensitive_tags(),
[],
(),
lens_dimensions=_SENSITIVE_LENSES,
lens_sensitive_names=_SENSITIVE_NAMES,
hide_sensitive_descriptors=hide,
)
)
def test_hide_sensitive_removes_the_descriptor_from_every_section() -> None:
"""No sensitive descriptor survives anywhere in the rendered page.
Deliberately whole-document, not section-scoped: a section-scoped assertion
is exactly what let three other sections keep publishing these strings while
the diversity panel's own test stayed green.
"""
shown = _page(hide=False)
for label in ("genderfluid", "transmasc"):
assert label in shown, f"the fixture never rendered {label}; this test would be vacuous"
hidden = _page(hide=True)
for label in ("genderfluid", "transmasc"):
assert label not in hidden, f"the rendered page still carries {label!r}"
# Redaction, not deletion: the non-sensitive lens keeps its detail, and the
# withholding is stated in text rather than left as a silent gap.
assert "nautical" in hidden
assert "hidden for privacy" in hidden
def test_hide_sensitive_leaves_the_per_book_chips_and_library_table_clean() -> None:
"""Named explicitly, because these two tie a descriptor to a title."""
hidden = _page(hide=True)
assert '<span class="tag">genderfluid</span>' not in hidden
assert '<span class="tag">transmasc</span>' not in hidden
assert "<td>genderfluid</td>" not in hidden
assert "<td>genderfluid, nautical</td>" not in hidden
# The library row still names the book and says something was held back.
assert "In Progress" in hidden
assert "hidden for privacy" in hidden
def test_the_redacted_page_is_still_accessible() -> None:
"""Redaction must not break the a11y contract it shares the page with."""
assert check_html(_page(hide=True)) == []
def test_the_privacy_note_does_not_claim_a_redaction_that_did_not_happen() -> None:
"""The toggle on a shelf with nothing sensitive must say so, not assure.
``hide_sensitive`` records only that the toggle was requested. The page used
to key its assurance off that flag alone, so on a fully personalized lens
file it stated that identity-adjacent descriptors were hidden while listing
every one of them.
"""
states = _shelf_with_sensitive_tags()[:1]
safe_lenses = (("Sea stories", frozenset({"nautical"})),)
html = render_view(
build_view(
states,
[],
(),
lens_dimensions=safe_lenses,
lens_sensitive_names=frozenset(),
hide_sensitive_descriptors=True,
)
)
assert "nothing on this shelf matched your sensitive list" in html
assert "are aggregated into a single row" not in html
def test_no_rendered_href_contains_whitespace(tmp_path: Path) -> None:
"""Every link on the demo dashboard is a URL a browser can resolve.
The shipped `docs/audits/dashboard.html` carried
`href="https://openlibrary.org/subjects/science fiction"`, built by
interpolating a raw subject label into the citation.
"""
import re
html = render_view(demo_view(tmp_path))
hrefs = re.findall(r'href="([^"]*)"', html)
assert hrefs, "the dashboard should link somewhere"
bad = [h for h in hrefs if any(ch.isspace() for ch in h)]
assert bad == [], f"hrefs with whitespace: {bad}"
assert "https://openlibrary.org/subjects/science_fiction" in hrefs
def test_outbound_off_names_who_is_not_making_requests(tmp_path: Path) -> None:
"""The privacy claim and the citation links must not read as contradictory.
The status row said "no public catalog requests are permitted" on a page
that also offered live openlibrary.org links. Both are true — the row is
about this instance — so the row says whose requests it means, and the
recommendation section says what following a citation actually does.
"""
html = render_view(demo_view(tmp_path))
assert "Off — this instance makes no public catalog requests" in html
assert "a request your browser makes to that catalog" in html
assert "never one this instance makes on your behalf" in html
def test_wrapped_standout_hours_name_their_scope_on_the_page(tmp_path: Path) -> None:
"""The year panel must not present an all-time figure under a year-scoped label.
In the shipped demo the top five standouts total 78.0 hours inside a
37.6-hour year. That is not a wrong number, it is a different one — and a
bare "Hours" column under "Reading Wrapped 2024" makes it read as the wrong
one. The page has to name the scope and reconcile the gap in place.
"""
view = demo_view(tmp_path)
html = render_view(view)
wrapped = view.wrapped
assert wrapped.standouts_exceed_the_year, "demo world should exercise the gap"
standouts_table = html.split("Standout reads of", 1)[1].split("</table>", 1)[0]
# The column names its scope, and the old ambiguous heading is gone from
# this table (the monthly table's "Hours" really is within the year).
assert '<th scope="col">Hours (all time)</th>' in standouts_table
assert '<th scope="col">Hours</th>' not in standouts_table
# The caption reconciles the two figures rather than leaving them to collide.
assert "all-time read time" in standouts_table
assert f"more than the {wrapped.read_time_hours} hours above" in standouts_table
# And the year total says which year it belongs to.
assert f"hours read in {wrapped.year}" in html
assert check_html(html) == []
def test_wrapped_caption_omits_the_reconciliation_when_there_is_nothing_to_reconcile() -> None:
from ingest.models import ReadingStat
stat = ReadingStat(
key="k",
title="Quick Read",
authors=("Author",),
pages_read=100,
total_pages=100,
read_time_seconds=3600,
last_read_ts=1_717_000_000,
sessions=2,
)
state = ReadingState(
title="Quick Read", authors=("Author",), status=ReadingStatus.FINISHED, stat=stat
)
# Two hours of day-level activity in the same year as the finish.
day = 1_717_000_000 // 86400
view = build_view([state], [DailyActivity(day, 7200, 120)], ())
html = render_view(view)
assert "all-time read time" in html
assert "more than the" not in html
assert check_html(html) == []