Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Keep both copies behind each crawler's least agreeing comparisons

Claudebf4f12a847bd
diff --git a/mwmbl/admin_views.py b/mwmbl/admin_views.py
index cbea20c..034c9c5 100644
--- a/mwmbl/admin_views.py
+++ b/mwmbl/admin_views.py
@@ -35,6 +35,7 @@ from django.shortcuts import render
from redis import RedisError
from mwmbl import count_urls, pricing, quota, search_callers, search_setup, traffic
+from mwmbl.crawler import worst_agreements
from mwmbl.crawler.stats import BLACKLISTED_REMOVED_COUNT_KEY
from mwmbl.curated_domains import get_curated_domains
from mwmbl.indexer import blacklist_snapshot, purge_queue
@@ -547,3 +548,58 @@ def paying_users_view(request):
"price_per_1000_queries_cents": pricing.PRICE_PER_1000_QUERIES_CENTS,
}
return render(request, "admin/paying_users.html", context)
+
+
+WORST_AGREEMENT_GAP_LABELS = {
+ "hour": "Crawled within an hour of each other",
+ "day": "Crawled within a day of each other",
+ "week": "Crawled within a week of each other",
+ "older": "Crawled more than a week apart",
+ worst_agreements.UNKNOWN_GAP: "Crawl gap unknown",
+}
+
+
+@staff_member_required
+def worst_agreements_view(request):
+ username = request.GET.get("username", "").strip()
+ weeks_ago = int(request.GET.get("weeks_ago", 0))
+ window = search_callers.window_start(utc_today()) - timedelta(weeks=weeks_ago)
+ context = {
+ "title": "Worst agreements",
+ "username": username,
+ "window": window,
+ "weeks_ago": weeks_ago,
+ "week_choices": range(worst_agreements.KEPT_WINDOWS),
+ "per_bucket": worst_agreements.WORST_PER_BUCKET,
+ }
+ if not username:
+ return render(request, "admin/worst_agreements.html", context)
+
+ crawler = MwmblUser.objects.filter(username=username).first()
+ if crawler is None:
+ context["not_found"] = True
+ return render(request, "admin/worst_agreements.html", context)
+
+ try:
+ by_bucket = worst_agreements.read_worst_agreements(worst_agreements.get_redis(), crawler.id, window)
+ except RedisError as e:
+ logger.exception("Could not read the worst agreements from Redis")
+ context["redis_error"] = str(e)
+ return render(request, "admin/worst_agreements.html", context)
+
+ other_ids = {entry["other_user_id"] for entries in by_bucket.values() for entry in entries}
+ # The index keeps the ids of deleted users, so some have no name left.
+ usernames = dict(MwmblUser.objects.filter(id__in=other_ids).values_list("id", "username"))
+ context["buckets"] = [
+ {
+ "label": WORST_AGREEMENT_GAP_LABELS[bucket],
+ "entries": [
+ entry
+ | {"other_username": usernames.get(entry["other_user_id"], f"deleted user {entry['other_user_id']}")}
+ for entry in entries
+ ],
+ }
+ for bucket, entries in by_bucket.items()
+ if entries
+ ]
+ return render(request, "admin/worst_agreements.html", context)
diff --git a/mwmbl/crawler/app.py b/mwmbl/crawler/app.py
index 907222f..8471f8c 100644
--- a/mwmbl/crawler/app.py
+++ b/mwmbl/crawler/app.py
@@ -14,6 +14,7 @@ from ninja import NinjaAPI, Router, Schema
from ninja.errors import HttpError
from redis import Redis
+from mwmbl.crawler import worst_agreements
from mwmbl.crawler.agreement import record_agreements
from mwmbl.crawler.batch import (
CrawlerErrorReport,
@@ -41,6 +42,7 @@ from mwmbl.settings import (
VERSION,
)
from mwmbl.tinysearchengine.indexer import Document
+from mwmbl.utils import utc_today
stats_manager = StatsManager(
Redis.from_url(os.environ.get("REDIS_URL", "redis://127.0.0.1:6379"), decode_responses=True)
@@ -276,6 +278,9 @@ def _register_routes(r: Router | NinjaAPI):
# Last, since they are only analytics: a failure to store them still answers with an
# error, but after the batch is indexed, uploaded and counted.
record_agreements(indexed.agreements, api_key.user, results.crawler_version)
+ worst_agreements.record_worst_agreements(
+ worst_agreements.get_redis(), indexed.agreements, api_key.user.id, utc_today()
+ )
return {
"status": "ok",
diff --git a/mwmbl/crawler/worst_agreements.py b/mwmbl/crawler/worst_agreements.py
new file mode 100644
index 0000000..f770f0b
--- /dev/null
+++ b/mwmbl/crawler/worst_agreements.py
@@ -0,0 +1,111 @@
+"""
+Both copies behind each crawler's least agreeing comparisons, kept so an admin can read them.
+
+CrawlerAgreement keeps only the scores, and finding the text in the submitted batches means
+knowing where to look. Here the copies are kept while they are at hand, for a fixed number of
+the lowest-scoring comparisons per crawler and week: memory stays bounded, and there is no
+similarity below which a comparison is judged bad.
+
+They are ranked within buckets of the gap between the two crawls. Pages change, so ranked
+together, stale copies of busy pages would crowd out copies crawled minutes apart that differ
+by one inserted sentence - the ones most worth reading.
+
+Each comparison is kept under both crawlers, since a low similarity says the copies differ,
+not which one is wrong: the honest crawler revisiting a spammed URL holds the spam as the
+other copy.
+"""
+
+import json
+from datetime import date, datetime, time, timedelta, timezone
+from typing import Optional
+
+import redis
+from django.conf import settings
+
+from mwmbl.indexer.agreement import Agreement
+from mwmbl.search_callers import window_start
+
+WORST_KEY = "crawler:worst-agreements:{user_id}:{window}:{bucket}"
+
+WORST_PER_BUCKET = 50
+
+WINDOW_DAYS = 7
+
+# This week and the three before it. A few hundred kilobytes per crawler at most.
+KEPT_WINDOWS = 4
+
+# Upper bounds of the gap between the two crawls, in seconds, either way round.
+GAP_BUCKETS = {
+ "hour": 60 * 60,
+ "day": 60 * 60 * 24,
+ "week": 60 * 60 * 24 * 7,
+ "older": None,
+}
+UNKNOWN_GAP = "unknown"
+BUCKETS = list(GAP_BUCKETS) + [UNKNOWN_GAP]
+
+_redis: Optional[redis.Redis] = None
+
+
+def get_redis() -> redis.Redis:
+ global _redis
+ if _redis is None:
+ _redis = redis.from_url(settings.REDIS_URL, decode_responses=True)
+ return _redis
+
+
+def gap_bucket(last_crawled_delta: Optional[int]) -> str:
+ if last_crawled_delta is None:
+ return UNKNOWN_GAP
+ gap = abs(last_crawled_delta)
+ return next(name for name, limit in GAP_BUCKETS.items() if limit is None or gap < limit)
+
+
+def record_worst_agreements(client: redis.Redis, agreements: list[Agreement], user_id: int, today: date):
+ window = window_start(today)
+ expire_at = datetime.combine(window + timedelta(days=WINDOW_DAYS * KEPT_WINDOWS), time(), tzinfo=timezone.utc)
+ pipeline = client.pipeline()
+ for agreement in agreements:
+ # An empty extract scores zero against anything, so these would fill every bucket.
+ # CrawlerAgreement counts them.
+ if agreement.extract_empty or agreement.existing_extract_empty:
+ continue
+ bucket = gap_bucket(agreement.last_crawled_delta)
+ for owner_id, entry in _entries(agreement, user_id):
+ key = WORST_KEY.format(user_id=owner_id, window=window.isoformat(), bucket=bucket)
+ pipeline.zadd(key, {json.dumps(entry, sort_keys=True): agreement.extract_similarity})
+ # Lowest first, so everything from this rank on is the best of the rest.
+ pipeline.zremrangebyrank(key, WORST_PER_BUCKET, -1)
+ pipeline.expireat(key, expire_at)
+ pipeline.execute()
+
+
+def _entries(agreement: Agreement, user_id: int) -> list[tuple[int, dict]]:
+ scores = {
+ "url": agreement.url,
+ "title_similarity": agreement.title_similarity,
+ "extract_similarity": agreement.extract_similarity,
+ "last_crawled_delta": agreement.last_crawled_delta,
+ }
+ submitted = {"title": agreement.title, "extract": agreement.extract}
+ stored = {"title": agreement.existing_title, "extract": agreement.existing_extract}
+ return [
+ (
+ user_id,
+ scores
+ | {"role": "submitter", "other_user_id": agreement.existing_user_id, "own": submitted, "other": stored},
+ ),
+ (
+ agreement.existing_user_id,
+ scores | {"role": "stored", "other_user_id": user_id, "own": stored, "other": submitted},
+ ),
+ ]
+
+
+def read_worst_agreements(client: redis.Redis, user_id: int, window: date) -> dict[str, list[dict]]:
+ """The kept comparisons of each gap bucket, least agreeing first."""
+ pipeline = client.pipeline()
+ for bucket in BUCKETS:
+ pipeline.zrange(WORST_KEY.format(user_id=user_id, window=window.isoformat(), bucket=bucket), 0, -1)
+ members_by_bucket = pipeline.execute()
+ return {bucket: [json.loads(member) for member in members] for bucket, members in zip(BUCKETS, members_by_bucket)}
diff --git a/mwmbl/indexer/agreement.py b/mwmbl/indexer/agreement.py
index 66ec8a0..436a8bd 100644
--- a/mwmbl/indexer/agreement.py
+++ b/mwmbl/indexer/agreement.py
@@ -39,6 +39,10 @@ class Agreement(NamedTuple):
"""Seconds from the stored copy's crawl to the incoming one's: pages change, so a large
gap explains a low similarity that a small one does not. The stored crawl time is the
latest of the copies merged into it, not necessarily that of its text."""
+ title: str
+ extract: str
+ existing_title: str
+ existing_extract: str
def find_stored_copies(
@@ -75,6 +79,10 @@ def compare(document: Document, stored_copy: StoredCopy, stored_last_crawled: Op
extract_empty=_is_empty(document.extract),
existing_extract_empty=_is_empty(stored_copy.extract),
last_crawled_delta=document.last_crawled - stored_last_crawled if both_crawled else None,
+ title=document.title,
+ extract=document.extract,
+ existing_title=stored_copy.title,
+ existing_extract=stored_copy.extract,
)
diff --git a/mwmbl/templates/admin/mwmbl_index.html b/mwmbl/templates/admin/mwmbl_index.html
index c8f9811..2eb1a44 100644
--- a/mwmbl/templates/admin/mwmbl_index.html
+++ b/mwmbl/templates/admin/mwmbl_index.html
@@ -26,6 +26,10 @@
<th scope="row"><a href="{% url 'paying_users' %}">Paying users</a></th>
<td>API users and members, their quotas, usage and what they pay, and Seed Search usage.</td>
</tr>
+ <tr>
+ <th scope="row"><a href="{% url 'worst_agreements' %}">Worst agreements</a></th>
+ <td>A crawler's copies that least match other crawlers' copies of the same URLs, side by side.</td>
+ </tr>
</table>
</div>
{% endblock %}
diff --git a/mwmbl/templates/admin/worst_agreements.html b/mwmbl/templates/admin/worst_agreements.html
new file mode 100644
index 0000000..ae72756
--- /dev/null
+++ b/mwmbl/templates/admin/worst_agreements.html
@@ -0,0 +1,91 @@
+{% extends "admin/base_site.html" %}
+
+{% block title %}Worst agreements | {{ site_title|default:"Django site admin" }}{% endblock %}
+
+{% block breadcrumbs %}
+ <div class="breadcrumbs">
+ <a href="{% url 'admin:index' %}">Home</a>
+ &rsaquo; Worst agreements
+ </div>
+{% endblock %}
+
+{% block content %}
+ <style>
+ .worst .note { color: #666; font-size: 0.9em; }
+ .worst .bad { color: #ba2121; font-weight: bold; }
+ .worst .result { padding: 12px 10px; border-top: 1px solid var(--hairline-color, #eee); display: flex; flex-wrap: wrap; gap: 8px 24px; }
+ .worst .copies { flex: 999 1 480px; min-width: 0; }
+ .worst .scores { flex: 1 1 180px; font-size: 0.9em; }
+ .worst .url { color: #3c6e47; font-size: 0.9em; overflow-wrap: anywhere; }
+ .worst .title { font-size: 1.2em; margin: 2px 0; }
+ .worst .extract { margin: 0; line-height: 1.5; }
+ .worst .other { margin-top: 10px; padding-left: 12px; border-left: 3px solid var(--hairline-color, #ddd); color: #555; }
+ .worst .other .title { font-size: 1em; }
+ </style>
+
+ <div id="content-main" class="worst">
+
+ <div class="module">
+ <h2>Crawler</h2>
+ <form method="get" style="padding: 10px">
+ <label for="username">Username</label>
+ <input type="text" id="username" name="username" value="{{ username }}">
+ <label for="weeks_ago">Week</label>
+ <select id="weeks_ago" name="weeks_ago">
+ {% for choice in week_choices %}
+ <option value="{{ choice }}" {% if choice == weeks_ago %}selected{% endif %}>
+ {% if choice == 0 %}this week{% else %}{{ choice }} week{{ choice|pluralize }} ago{% endif %}
+ </option>
+ {% endfor %}
+ </select>
+ <input type="submit" value="Show">
+ </form>
+ <p class="note" style="padding: 0 10px">
+ The {{ per_bucket }} comparisons with the lowest extract similarity this crawler was part
+ of in the week from {{ window }}, in either role, for each gap between the two crawls.
+ A low similarity says the copies differ, not which is wrong: read both. Comparisons
+ with an empty extract on either side are left out.
+ </p>
+ </div>
+
+ {% if not_found %}
+ <div class="module"><p class="bad" style="padding: 10px">No user named {{ username }}.</p></div>
+ {% elif redis_error %}
+ <div class="module">
+ <h2>Redis unreachable</h2>
+ <p class="bad">{{ redis_error }}</p>
+ </div>
+ {% elif username and not buckets %}
+ <div class="module"><p style="padding: 10px">Nothing kept for {{ username }} that week.</p></div>
+ {% endif %}
+
+ {% for bucket in buckets %}
+ <div class="module">
+ <h2>{{ bucket.label }}</h2>
+ {% for entry in bucket.entries %}
+ <div class="result">
+ <div class="copies">
+ <div class="url">{{ entry.url }}</div>
+ <div class="title">{{ entry.own.title }}</div>
+ <p class="extract">{{ entry.own.extract }}</p>
+ <div class="other">
+ <div class="note">{{ entry.other_username }}'s copy</div>
+ <div class="title">{{ entry.other.title }}</div>
+ <p class="extract">{{ entry.other.extract }}</p>
+ </div>
+ </div>
+ <div class="scores">
+ <div>Extract similarity <strong>{{ entry.extract_similarity|floatformat:2 }}</strong></div>
+ <div>Title similarity <strong>{{ entry.title_similarity|floatformat:2 }}</strong></div>
+ <div class="note">
+ {% if entry.role == "submitter" %}{{ username }} submitted over {{ entry.other_username }}'s copy
+ {% else %}{{ entry.other_username }} submitted over {{ username }}'s copy{% endif %}
+ </div>
+ </div>
+ </div>
+ {% endfor %}
+ </div>
+ {% endfor %}
+
+ </div>
+{% endblock %}
diff --git a/mwmbl/urls.py b/mwmbl/urls.py
index b2bbd81..7bf98db 100644
--- a/mwmbl/urls.py
+++ b/mwmbl/urls.py
@@ -26,6 +26,7 @@ from mwmbl.admin_views import (
index_count_view,
paying_users_view,
search_traffic_view,
+ worst_agreements_view,
)
from mwmbl.api import api as v1_api
from mwmbl.api import register_routers, v2_api
@@ -64,6 +65,7 @@ urlpatterns = [
path("admin/search-traffic/", search_traffic_view, name="search_traffic"),
path("admin/paying-users/", paying_users_view, name="paying_users"),
path("admin/index-count/", index_count_view, name="index_count"),
+ path("admin/worst-agreements/", worst_agreements_view, name="worst_agreements"),
path("admin/", admin.site.urls),
path("accounts/", include("allauth.urls")),
path("", index, name="index"),
diff --git a/test/test_crawler_agreement.py b/test/test_crawler_agreement.py
index b327d95..c865bde 100644
--- a/test/test_crawler_agreement.py
+++ b/test/test_crawler_agreement.py
@@ -9,12 +9,15 @@ from django.test import Client
from django.utils import timezone
from mwmbl.crawler.agreement import AGREEMENT_RETENTION, prune_agreements, record_agreements
+from mwmbl.crawler.worst_agreements import UNKNOWN_GAP, read_worst_agreements
from mwmbl.indexer.agreement import Agreement, StoredCopy, compare, find_stored_copies, trigram_similarity
from mwmbl.indexer.blacklist_providers import StaticBlacklistProvider
from mwmbl.indexer.blacklist_snapshot import SnapshotBlacklist
from mwmbl.indexer.index_batches import _most_held_copies, index_documents
from mwmbl.models import ApiKey, CrawlerAgreement, generate_api_key
+from mwmbl.search_callers import window_start
from mwmbl.tinysearchengine.indexer import PAGE_SIZE, Document, DocumentSource, DocumentState, TinyIndex
+from mwmbl.utils import utc_today
URL = "https://example.com/page"
@@ -108,6 +111,10 @@ def test_compare():
extract_empty=False,
existing_extract_empty=False,
last_crawled_delta=600,
+ title="Title",
+ extract="Buy cheap pills",
+ existing_title="Title",
+ existing_extract="An extract",
)
@@ -168,6 +175,10 @@ def test_index_documents_reports_one_agreement_per_url(index_path, no_blacklist)
extract_empty=False,
existing_extract_empty=False,
last_crawled_delta=None,
+ title="Python tutorial",
+ extract="Learn python today",
+ existing_title="Python tutorial",
+ existing_extract="Learn python today",
)
]
@@ -255,6 +266,10 @@ def _agreement(url=URL):
extract_empty=False,
existing_extract_empty=True,
last_crawled_delta=60,
+ title="Title",
+ extract="Extract",
+ existing_title="Title",
+ existing_extract="",
)
@@ -308,12 +323,14 @@ def test_post_results_records_agreements(user, index_path, no_blacklist):
index_documents([Document("Python tutorial", URL, "Learn python today", user_ids=[other_user.id])], index_path)
raw_key, key_hash = generate_api_key()
ApiKey.objects.create(user=user, key=key_hash, name="Crawl key", scopes=[ApiKey.Scope.CRAWL])
+ worst_redis = fakeredis.FakeRedis(decode_responses=True)
with (
patch("mwmbl.crawler.app.settings.DATA_PATH", str(index_path).rsplit("/", 1)[0]),
patch("mwmbl.crawler.app.settings.INDEX_NAME", "test.tinysearch"),
patch("mwmbl.crawler.app.upload_object", return_value="fake/path.json.gz"),
patch("mwmbl.crawler.app.stats_manager"),
+ patch("mwmbl.crawler.worst_agreements.get_redis", return_value=worst_redis),
):
response = Client().post(
"/api/v1/crawler/results",
@@ -332,3 +349,5 @@ def test_post_results_records_agreements(user, index_path, no_blacklist):
assert stored.title_similarity == 1.0
assert stored.extract_similarity < 1.0
assert stored.crawler_version == "1.2.0"
+ kept = read_worst_agreements(worst_redis, user.id, window_start(utc_today()))
+ assert [entry["own"]["extract"] for entry in kept[UNKNOWN_GAP]] == ["Learn rust today"]
diff --git a/test/test_worst_agreements.py b/test/test_worst_agreements.py
new file mode 100644
index 0000000..4a6242b
--- /dev/null
+++ b/test/test_worst_agreements.py
@@ -0,0 +1,141 @@
+from datetime import date, timedelta
+
+import fakeredis
+import pytest
+from django.contrib.auth import get_user_model
+from django.test import Client
+
+from mwmbl.crawler.worst_agreements import (
+ UNKNOWN_GAP,
+ WORST_PER_BUCKET,
+ gap_bucket,
+ read_worst_agreements,
+ record_worst_agreements,
+)
+from mwmbl.indexer.agreement import Agreement
+from mwmbl.search_callers import window_start
+from mwmbl.utils import utc_today
+
+TODAY = date(2026, 10, 21)
+WINDOW = window_start(TODAY)
+SUBMITTER_ID = 1
+STORED_ID = 2
+
+
+def client():
+ return fakeredis.FakeRedis(decode_responses=True)
+
+
+def _agreement(url="https://example.com/", extract_similarity=0.5, delta=60, extract="Spam", existing_extract="Real"):
+ return Agreement(
+ url=url,
+ existing_user_id=STORED_ID,
+ title_similarity=1.0,
+ extract_similarity=extract_similarity,
+ extract_empty=not extract.strip(),
+ existing_extract_empty=not existing_extract.strip(),
+ last_crawled_delta=delta,
+ title="Title",
+ extract=extract,
+ existing_title="Title",
+ existing_extract=existing_extract,
+ )
+
+
+ "delta, bucket",
+ [(None, UNKNOWN_GAP), (0, "hour"), (-3599, "hour"), (3600, "day"), (-86400 * 3, "week"), (86400 * 30, "older")],
+)
+def test_gap_bucket(delta, bucket):
+ assert gap_bucket(delta) == bucket
+
+
+def test_keeps_the_comparison_under_both_crawlers(client):
+ record_worst_agreements(client, [_agreement()], SUBMITTER_ID, TODAY)
+
+ (submitted,) = read_worst_agreements(client, SUBMITTER_ID, WINDOW)["hour"]
+ (stored,) = read_worst_agreements(client, STORED_ID, WINDOW)["hour"]
+
+ assert submitted["role"] == "submitter"
+ assert submitted["other_user_id"] == STORED_ID
+ assert (submitted["own"]["extract"], submitted["other"]["extract"]) == ("Spam", "Real")
+ assert stored["role"] == "stored"
+ assert stored["other_user_id"] == SUBMITTER_ID
+ assert (stored["own"]["extract"], stored["other"]["extract"]) == ("Real", "Spam")
+
+
+def test_keeps_only_the_least_agreeing(client):
+ agreements = [
+ _agreement(url=f"https://example.com/{i}", extract_similarity=i / 100) for i in range(WORST_PER_BUCKET + 10)
+ ]
+
+ record_worst_agreements(client, agreements, SUBMITTER_ID, TODAY)
+
+ kept = read_worst_agreements(client, SUBMITTER_ID, WINDOW)["hour"]
+ assert [entry["extract_similarity"] for entry in kept] == [i / 100 for i in range(WORST_PER_BUCKET)]
+
+
+def test_ranks_each_crawl_gap_separately(client):
+ """A stale copy scoring lower does not push out a fresh one."""
+ stale = [_agreement(url=f"https://example.com/{i}", extract_similarity=0.1, delta=86400 * 30) for i in range(60)]
+ fresh = _agreement(url="https://example.com/fresh", extract_similarity=0.6, delta=60)
+
+ record_worst_agreements(client, stale + [fresh], SUBMITTER_ID, TODAY)
+
+ kept = read_worst_agreements(client, SUBMITTER_ID, WINDOW)
+ assert [entry["url"] for entry in kept["hour"]] == ["https://example.com/fresh"]
+ assert len(kept["older"]) == WORST_PER_BUCKET
+
+
+def test_skips_empty_extracts(client):
+ record_worst_agreements(client, [_agreement(extract=""), _agreement(existing_extract=" ")], SUBMITTER_ID, TODAY)
+
+ assert not any(read_worst_agreements(client, SUBMITTER_ID, WINDOW).values())
+
+
+def test_keeps_each_week_apart(client):
+ record_worst_agreements(client, [_agreement()], SUBMITTER_ID, TODAY)
+
+ assert not any(read_worst_agreements(client, SUBMITTER_ID, WINDOW - timedelta(weeks=1)).values())
+
+
+def test_keys_expire(client):
+ record_worst_agreements(client, [_agreement()], SUBMITTER_ID, TODAY)
+
+ assert all(client.ttl(key) > 0 for key in client.keys("crawler:worst-agreements:*"))
+
+
+def test_admin_page_shows_both_copies(client):
+ User = get_user_model()
+ admin = User.objects.create_superuser(username="admin", email="[email protected]", password="pw")
+ submitter = User.objects.create_user(username="sneaky", email="[email protected]", password="pw")
+ other = User.objects.create_user(username="honest", email="[email protected]", password="pw")
+ agreement = _agreement(extract="Buy cheap pills", existing_extract="Learn python")._replace(
+ existing_user_id=other.id
+ )
+ record_worst_agreements(client, [agreement], submitter.id, utc_today())
+ browser = Client()
+ browser.force_login(admin)
+
+ with pytest.MonkeyPatch.context() as monkeypatch:
+ monkeypatch.setattr("mwmbl.crawler.worst_agreements.get_redis", lambda: client)
+ response = browser.get("/admin/worst-agreements/", {"username": "sneaky"})
+
+ content = response.content.decode()
+ assert response.status_code == 200
+ assert "Buy cheap pills" in content
+ assert "Learn python" in content
+ assert "honest's copy" in content
+
+
+def test_admin_page_with_an_unknown_user(client):
+ admin = get_user_model().objects.create_superuser(username="admin", email="[email protected]", password="pw")
+ browser = Client()
+ browser.force_login(admin)
+
+ response = browser.get("/admin/worst-agreements/", {"username": "nobody"})
+
+ assert "No user named nobody" in response.content.decode()