Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Read the search traffic counters on an admin page

Daoud Clarke6fc06547e22b
diff --git a/mwmbl/admin_views.py b/mwmbl/admin_views.py
index bb92f17..67aaa7a 100644
--- a/mwmbl/admin_views.py
+++ b/mwmbl/admin_views.py
@@ -1,6 +1,6 @@
-"""Admin-only visibility on the blacklist filtering state that lives in Redis.
+"""Admin-only visibility on state that lives in Redis, which nothing else can show.
-Retrieval filtering, the snapshot refresh and the index purge are three processes talking
+Blacklist status: retrieval filtering, the snapshot refresh and the index purge are three processes talking
to each other through Redis keys, and none of that state is reachable from the Django
admin: a snapshot that never publishes and a purge queue that never drains look exactly
like everything working, because retrieval quietly falls back to the built-in rules either
@@ -10,18 +10,27 @@ the queue waiting to be purged, and the background tasks that maintain both - on
The page is read-only, and deliberately cheap: the snapshot's size comes from STRLEN so a
page load never pulls the ~11 MB blob out of Redis, and the queue is sampled with
SRANDMEMBER so looking at it cannot consume it.
+
+Search traffic: #425 counts every search request into Redis, and being read is the whole of
+what those counters are for - #411 asks how many searches a day, how much of that is one
+client at volume, and how much of it is our own server-side render. The page describes rather
+than judges, for the same reason the classification stayed out of the keys: any rule about
+what a bot looks like belongs to whoever is reading, and can be a different rule next week.
"""
import os
-from datetime import timedelta
+from collections import Counter, defaultdict
+from datetime import date, timedelta
from logging import getLogger
from background_task.models import CompletedTask, Task
from django.conf import settings
from django.contrib.admin.views.decorators import staff_member_required
+from django.http import HttpRequest
from django.shortcuts import render
from redis import RedisError
+from mwmbl import traffic
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
@@ -32,6 +41,15 @@ from mwmbl.indexer.blacklist_snapshot import (
get_snapshot_blacklist,
)
from mwmbl.indexer.purge_queue import MAX_QUEUE_SIZE, PURGE_QUEUE_KEY, peek_purge_queue
+from mwmbl.traffic import (
+ HEADER_LABELS,
+ STATUS_LABELS,
+ TRACKED_USER_AGENTS,
+ TRAFFIC_EXPIRE_SECONDS,
+ USER_AGENT_EXPIRE_SECONDS,
+ read_request_counts,
+ read_user_agent_counts,
+)
from mwmbl.utils import utc_today
logger = getLogger(__name__)
@@ -171,3 +189,120 @@ def blacklist_status_view(request):
context["tasks"] = _task_status()
return render(request, "admin/blacklist_status.html", context)
+
+
+SECONDS_PER_DAY = 60 * 60 * 24
+
+# Both windows come from the expiries rather than from taste: a window wider than what Redis
+# keeps shows zeros for days that were never retained, which reads as no traffic rather than
+# as no data, and the two keys are not kept for the same length of time.
+TRAFFIC_MAX_DAYS = TRAFFIC_EXPIRE_SECONDS // SECONDS_PER_DAY
+TRAFFIC_DEFAULT_DAYS = 7
+TRAFFIC_WINDOW_CHOICES = [1, 7, TRAFFIC_MAX_DAYS]
+USER_AGENT_MAX_DAYS = USER_AGENT_EXPIRE_SECONDS // SECONDS_PER_DAY
+
+# Enough to see the shape of the tail without putting two thousand caller-supplied strings
+# through the template.
+TOP_USER_AGENTS = 100
+
+# Positions in the read_request_counts coordinate, which is (day, endpoint, headers, status).
+DAY, ENDPOINT, HEADERS, STATUS = 0, 1, 2, 3
+
+
+def _traffic_days(request: HttpRequest) -> list[date]:
+ """The days to report on, most recent first, matching _removed_counts above."""
+ try:
+ requested = int(request.GET.get("days", TRAFFIC_DEFAULT_DAYS))
+ except ValueError:
+ requested = TRAFFIC_DEFAULT_DAYS
+ days = min(max(requested, 1), TRAFFIC_MAX_DAYS)
+ today = utc_today()
+ return [today - timedelta(days=offset) for offset in range(days)]
+
+
+def _requests_by_label(counts: dict, dimension: int, labels: list) -> dict:
+ """Requests as endpoints against one dimension of the counter key.
+
+ The three tables on this page - per day, per header combination, per status class - are
+ the same table with a different column, so they are one function called three times.
+ Endpoints with no traffic are left out rather than padding each table with a dozen zero
+ rows, and the busiest comes first.
+ """
+ per_endpoint: dict[str, Counter] = defaultdict(Counter)
+ for coordinate, count in counts.items():
+ per_endpoint[coordinate[ENDPOINT]][coordinate[dimension]] += count
+
+ rows = [
+ {
+ "endpoint": endpoint,
+ "counts": [by_label[label] for label in labels],
+ "total": sum(by_label.values()),
+ }
+ for endpoint, by_label in per_endpoint.items()
+ ]
+ rows.sort(key=lambda row: (-row["total"], row["endpoint"]))
+
+ totals = [sum(by_label[label] for by_label in per_endpoint.values()) for label in labels]
+ return {"labels": labels, "rows": rows, "totals": totals, "total": sum(totals)}
+
+
+def _user_agents(redis_client, days: list[date], counts: dict) -> dict:
+ """The most-seen user agent strings, and how much traffic they do not account for.
+
+ The gap between the requests counted over these days and the sum of the tracked agents is
+ the tail the trim dropped, and the only place a client that randomises its user agent
+ shows up at all.
+ """
+ agent_days = days[:USER_AGENT_MAX_DAYS]
+ tracked = read_user_agent_counts(redis_client, agent_days, TRACKED_USER_AGENTS)
+ tracked_total = sum(count for _, count in tracked)
+ request_total = sum(count for coordinate, count in counts.items() if coordinate[DAY] in set(agent_days))
+
+ top = [
+ {
+ "user_agent": user_agent,
+ "count": count,
+ "share": 100 * count / tracked_total if tracked_total else 0,
+ }
+ for user_agent, count in tracked[:TOP_USER_AGENTS]
+ ]
+ return {
+ "days": agent_days,
+ "top": top,
+ "tracked": len(tracked),
+ "tracked_limit": TRACKED_USER_AGENTS,
+ "tracked_total": tracked_total,
+ "request_total": request_total,
+ "gap": request_total - tracked_total,
+ }
+
+
+@staff_member_required
+def search_traffic_view(request):
+ days = _traffic_days(request)
+ context = {
+ "title": "Search traffic",
+ "days": days,
+ "window_choices": TRAFFIC_WINDOW_CHOICES,
+ "max_days": TRAFFIC_MAX_DAYS,
+ "user_agent_max_days": USER_AGENT_MAX_DAYS,
+ "top_user_agents": TOP_USER_AGENTS,
+ # Off means the page is telling the truth about Redis and nothing about the traffic,
+ # which is not something a reader should have to infer from empty rows.
+ "counting_enabled": settings.SEARCH_TRAFFIC_COUNTING,
+ }
+
+ # As on the blacklist page: everything below this line comes from Redis, and a page about
+ # what Redis holds has to render when Redis is down.
+ try:
+ redis_client = traffic.get_redis()
+ counts = read_request_counts(redis_client, days)
+ context["by_day"] = _requests_by_label(counts, DAY, days)
+ context["by_headers"] = _requests_by_label(counts, HEADERS, HEADER_LABELS)
+ context["by_status"] = _requests_by_label(counts, STATUS, STATUS_LABELS)
+ context["user_agents"] = _user_agents(redis_client, days, counts)
+ except RedisError as e:
+ logger.exception("Could not read search traffic from Redis")
+ context["redis_error"] = str(e)
+
+ return render(request, "admin/search_traffic.html", context)
diff --git a/mwmbl/templates/admin/_traffic_table.html b/mwmbl/templates/admin/_traffic_table.html
new file mode 100644
index 0000000..3576b07
--- /dev/null
+++ b/mwmbl/templates/admin/_traffic_table.html
@@ -0,0 +1,33 @@
+{% load humanize %}
+{% comment %} One of the three request tables. They differ only in their columns, so one view
+ function builds all three and this renders all three: `table`, `column_header`, and
+ `label_date` when the columns are dates. {% endcomment %}
+{% if table.rows %}
+ <table>
+ <thead>
+ <tr>
+ <th>{{ column_header }}</th>
+ {% for label in table.labels %}
+ <th class="num">{% if label_date %}{{ label|date:"j M" }}{% else %}{{ label }}{% endif %}</th>
+ {% endfor %}
+ <th class="num">Total</th>
+ </tr>
+ </thead>
+ <tbody>
+ {% for row in table.rows %}
+ <tr>
+ <td><code>{{ row.endpoint }}</code></td>
+ {% for count in row.counts %}<td class="num">{{ count|intcomma }}</td>{% endfor %}
+ <td class="num strong">{{ row.total|intcomma }}</td>
+ </tr>
+ {% endfor %}
+ <tr class="strong">
+ <td>All endpoints</td>
+ {% for count in table.totals %}<td class="num">{{ count|intcomma }}</td>{% endfor %}
+ <td class="num">{{ table.total|intcomma }}</td>
+ </tr>
+ </tbody>
+ </table>
+{% else %}
+ <p class="note">No requests counted in this window.</p>
+{% endif %}
diff --git a/mwmbl/templates/admin/mwmbl_index.html b/mwmbl/templates/admin/mwmbl_index.html
index be54f21..f7dc871 100644
--- a/mwmbl/templates/admin/mwmbl_index.html
+++ b/mwmbl/templates/admin/mwmbl_index.html
@@ -14,6 +14,10 @@
<th scope="row"><a href="{% url 'blacklist_status' %}">Blacklist status</a></th>
<td>The published snapshot, the purge queue and the tasks that maintain them.</td>
</tr>
+ <tr>
+ <th scope="row"><a href="{% url 'search_traffic' %}">Search traffic</a></th>
+ <td>Requests per endpoint and per day, and the user agents that sent them.</td>
+ </tr>
</table>
</div>
{% endblock %}
diff --git a/mwmbl/templates/admin/search_traffic.html b/mwmbl/templates/admin/search_traffic.html
new file mode 100644
index 0000000..c71026a
--- /dev/null
+++ b/mwmbl/templates/admin/search_traffic.html
@@ -0,0 +1,131 @@
+{% extends "admin/base_site.html" %}
+{% load humanize %}
+
+{% block title %}Search traffic | {{ site_title|default:"Django site admin" }}{% endblock %}
+
+{% block breadcrumbs %}
+ <div class="breadcrumbs">
+ <a href="{% url 'admin:index' %}">Home</a>
+ &rsaquo; Search traffic
+ </div>
+{% endblock %}
+
+{% block content %}
+ <style>
+ .search-traffic table { width: 100%; margin-bottom: 10px; }
+ .search-traffic td.num, .search-traffic th.num { text-align: right; white-space: nowrap; }
+ .search-traffic .strong, .search-traffic .bad { font-weight: bold; }
+ .search-traffic .bad { color: #ba2121; }
+ .search-traffic .agent { word-break: break-all; font-family: monospace; }
+ .search-traffic .note { color: #666; font-size: 0.9em; }
+ </style>
+
+ <div id="content-main" class="search-traffic">
+
+ <div class="module">
+ <h2>{{ days|length }} day{{ days|length|pluralize }} to {{ days.0 }} (UTC)</h2>
+ <p class="note">
+ Today is included and still filling. Show
+ {% for choice in window_choices %}
+ <a href="?days={{ choice }}">{{ choice }} day{{ choice|pluralize }}</a>{% if not forloop.last %} &middot;{% endif %}
+ {% endfor %}
+ &mdash; counts expire after {{ max_days }} days and the user agent strings after
+ {{ user_agent_max_days }}, so there is no longer window to ask for. Nothing here
+ records a query or joins a user agent to an address.
+ {% if not counting_enabled %}
+ <span class="bad">SEARCH_TRAFFIC_COUNTING is off on this instance, so nothing is
+ being written; anything below was left in the same Redis by one that counts.</span>
+ {% endif %}
+ </p>
+ </div>
+
+ {% if redis_error %}
+ <div class="module">
+ <h2>Redis unreachable</h2>
+ <p class="bad">{{ redis_error }}</p>
+ <p class="note">
+ Everything here is read from Redis, and counting fails the same way and is dropped
+ rather than retried, so an outage is also a hole in the numbers.
+ </p>
+ </div>
+ {% else %}
+
+ <div class="module">
+ <h2>Requests per day</h2>
+ {% include "admin/_traffic_table.html" with table=by_day column_header="Endpoint" label_date=1 %}
+ <p class="note">
+ Endpoints with no traffic are left out. <code>ui_search</code> and
+ <code>ui_keystroke</code> are the Django UI, split because only the debounced request
+ carries <code>external=1</code> and without that the UI reads about tenfold busier.
+ </p>
+ </div>
+
+ <div class="module">
+ <h2>Requests by header combination</h2>
+ {% include "admin/_traffic_table.html" with table=by_headers column_header="Endpoint" %}
+ <p class="note">
+ Which of <code>User-Agent</code> and <code>Accept-Language</code> arrived, and nothing
+ inferred from it. <code>neither</code> is what our own server-side render sends, so on
+ <code>v1_search</code> it is mostly mwmbl.org rather than anything exotic; a missing
+ <code>Accept-Language</code> is a hint that a client is not a browser, and only a hint.
+ </p>
+ </div>
+
+ <div class="module">
+ <h2>Requests by status class</h2>
+ {% include "admin/_traffic_table.html" with table=by_status column_header="Endpoint" %}
+ <p class="note">
+ What it cost us, roughly: a 4xx bought a URL match and nothing else, a 2xx bought a
+ ranker run. A client sending queries it never gets an answer to lives in the 4xx column.
+ </p>
+ </div>
+
+ <div class="module">
+ <h2>User agents</h2>
+ <p>
+ Over the last {{ user_agents.days|length }} day{{ user_agents.days|length|pluralize }},
+ {{ user_agents.request_total|intcomma }} requests counted and
+ {{ user_agents.tracked_total|intcomma }} attributed to one of
+ {{ user_agents.tracked|intcomma }} tracked user agents
+ ({{ user_agents.tracked_limit|intcomma }} kept per day), leaving a gap of
+ <span class="{% if user_agents.gap %}bad{% endif %}">{{ user_agents.gap|intcomma }}</span>.
+ </p>
+ <p class="note">
+ The gap is the tail the trim dropped, and the one number here that reports on
+ something otherwise invisible: a client randomising its user agent shows up as a
+ growing gap and in no other way.
+ </p>
+
+ <h3>Top {{ top_user_agents }} by requests</h3>
+ {% if user_agents.top %}
+ <table>
+ <thead>
+ <tr><th>#</th><th class="num">Requests</th><th class="num">Share</th><th>User agent</th></tr>
+ </thead>
+ <tbody>
+ {% for agent in user_agents.top %}
+ <tr>
+ <td class="num">{{ forloop.counter }}</td>
+ <td class="num">{{ agent.count|intcomma }}</td>
+ <td class="num">{{ agent.share|floatformat:1 }}%</td>
+ {% comment %} Caller-supplied strings. Autoescaping is what keeps them inert,
+ so no |safe here, ever. {% endcomment %}
+ <td class="agent">{{ agent.user_agent }}</td>
+ </tr>
+ {% endfor %}
+ </tbody>
+ </table>
+ <p class="note">
+ Summed across the window, so a client that comes back every day outranks one that
+ came once. <code>(none)</code> sent no <code>User-Agent</code> at all, which is
+ what our own front end does. Strings are truncated at 512 characters on the way in.
+ </p>
+ {% else %}
+ <p class="note">No user agents recorded in this window.</p>
+ {% endif %}
+ </div>
+
+ {% endif %}
+
+ </div>
+{% endblock %}
diff --git a/mwmbl/urls.py b/mwmbl/urls.py
index 6aa043d..ecca798 100644
--- a/mwmbl/urls.py
+++ b/mwmbl/urls.py
@@ -21,7 +21,7 @@ from django.urls import include, path
from django.views.generic import RedirectView
import mwmbl.crawler.app as crawler
-from mwmbl.admin_views import blacklist_status_view
+from mwmbl.admin_views import blacklist_status_view, search_traffic_view
from mwmbl.api import api as v1_api
from mwmbl.api import register_routers, v2_api
from mwmbl.search_setup import batch_cache, queued_batches, ranker
@@ -57,6 +57,7 @@ urlpatterns = [
# Before admin.site.urls so the admin catch-all does not shadow it. Access is gated by
# staff_member_required on the view, matching the rest of the admin.
path("admin/blacklist-status/", blacklist_status_view, name="blacklist_status"),
+ path("admin/search-traffic/", search_traffic_view, name="search_traffic"),
path("admin/", admin.site.urls),
path("accounts/", include("allauth.urls")),
path("", index, name="index"),
diff --git a/test/test_admin_search_traffic.py b/test/test_admin_search_traffic.py
new file mode 100644
index 0000000..5a28b46
--- /dev/null
+++ b/test/test_admin_search_traffic.py
@@ -0,0 +1,215 @@
+"""Tests for the search traffic admin page (mwmbl.admin_views.search_traffic_view).
+
+Counting is off in mwmbl.settings_test, so the one test that seeds through the middleware's
+own code path turns it back on, as test_traffic.py does. Everything else writes the keys
+directly: record_request can only ever write today's.
+"""
+
+from datetime import timedelta
+
+import fakeredis
+import pytest
+from django.contrib.auth import get_user_model
+from django.test import RequestFactory
+from redis import ConnectionError as RedisConnectionError
+
+from mwmbl import admin_views, traffic
+from mwmbl.utils import utc_today
+
+User = get_user_model()
+
+TRAFFIC_URL = "/admin/search-traffic/"
+
+
+def redis_client(monkeypatch):
+ client = fakeredis.FakeStrictRedis(decode_responses=True)
+ monkeypatch.setattr(traffic, "_redis", client)
+ return client
+
+
+def staff_client(client, db):
+ user = User.objects.create_user(username="staff_member_1", password="correctpassword", is_staff=True)
+ client.force_login(user)
+ return client
+
+
+def record(redis_client, endpoint, day=None, headers="user_agent+language", status="2xx", count=1, user_agent=None):
+ """Seed the counters the way record_request writes them, on any day."""
+ day = day or utc_today()
+ redis_client.incrby(
+ traffic.REQUEST_COUNT_KEY.format(date=day, endpoint=endpoint, headers=headers, status=status), count
+ )
+ if user_agent is not None:
+ redis_client.zincrby(traffic.USER_AGENT_COUNT_KEY.format(date=day), count, user_agent)
+
+
+def window(days):
+ """The days most recent first, and the counts over them, as the view reads them."""
+ dates = [utc_today() - timedelta(days=offset) for offset in range(days)]
+ return dates, traffic.read_request_counts(traffic.get_redis(), dates)
+
+
+ "requested,expected", [("0", 1), ("-5", 1), ("1", 1), ("30", 30), ("999", 30), ("nonsense", 7), ("", 7)]
+)
+def test_days_is_clamped_to_what_is_retained(requested, expected):
+ """A window wider than the expiry would show zeros for days that were never kept, which
+ reads as no traffic rather than as no data."""
+ request = RequestFactory().get(TRAFFIC_URL, {"days": requested})
+
+ assert len(admin_views._traffic_days(request)) == expected
+
+
+def test_requests_are_counted_per_endpoint_per_day(redis_client):
+ yesterday = utc_today() - timedelta(days=1)
+ record(redis_client, "v1_search", count=10)
+ record(redis_client, "v1_search", day=yesterday, count=4)
+ record(redis_client, "ui_search", count=3)
+
+ days, counts = window(2)
+ table = admin_views._requests_by_label(counts, admin_views.DAY, days)
+
+ # Busiest first, the ten endpoints with no traffic absent rather than zero rows, and the
+ # columns running from today backwards as _traffic_days orders them.
+ assert [row["endpoint"] for row in table["rows"]] == ["v1_search", "ui_search"]
+ assert len(traffic.ALL_ENDPOINT_LABELS) > 2
+ assert table["rows"][0]["counts"] == [10, 4]
+ assert table["rows"][0]["total"] == 14
+ assert table["totals"] == [13, 4]
+ assert table["total"] == 17
+
+
+def test_the_splits_slice_the_same_requests(redis_client):
+ """The header split and the status split are one set of requests counted two ways. If
+ they disagree, one of them is dropping a dimension of the key."""
+ record(redis_client, "v1_search", headers="neither", status="2xx", count=7)
+ record(redis_client, "v1_search", headers="user_agent", status="4xx", count=2)
+ record(redis_client, "ui_keystroke", headers="user_agent+language", status="2xx", count=5)
+
+ days, counts = window(1)
+ by_day = admin_views._requests_by_label(counts, admin_views.DAY, days)
+ by_headers = admin_views._requests_by_label(counts, admin_views.HEADERS, traffic.HEADER_LABELS)
+ by_status = admin_views._requests_by_label(counts, admin_views.STATUS, traffic.STATUS_LABELS)
+
+ assert by_day["total"] == by_headers["total"] == by_status["total"] == 14
+ assert dict(zip(traffic.HEADER_LABELS, by_headers["totals"]))["neither"] == 7
+ assert dict(zip(traffic.STATUS_LABELS, by_status["totals"]))["4xx"] == 2
+
+
+def test_the_page_reads_what_the_middleware_writes(redis_client, settings, rf):
+ """The two sides label an endpoint in different places, so a request the middleware
+ counts under a label the page does not read shows up here rather than as a silent zero."""
+ settings.SEARCH_TRAFFIC_COUNTING = True
+ request = rf.get("/app/home/", {"q": "test", "external": "1"}, HTTP_USER_AGENT="Firefox")
+ request.resolver_match = type("Match", (), {"view_name": "home"})()
+
+ traffic.record_request(request, type("Response", (), {"status_code": 200})())
+
+ days, counts = window(1)
+ table = admin_views._requests_by_label(counts, admin_views.DAY, days)
+ assert [(row["endpoint"], row["total"]) for row in table["rows"]] == [("ui_search", 1)]
+
+
+def test_user_agents_are_summed_across_days_and_ranked(redis_client):
+ yesterday = utc_today() - timedelta(days=1)
+ record(redis_client, "v1_search", count=3, user_agent="EveryDayBot/1.0")
+ record(redis_client, "v1_search", day=yesterday, count=3, user_agent="EveryDayBot/1.0")
+ record(redis_client, "v1_search", count=5, user_agent="OneOff/1.0")
+
+ agents = admin_views._user_agents(traffic.get_redis(), *window(2))
+
+ assert [agent["user_agent"] for agent in agents["top"]] == ["EveryDayBot/1.0", "OneOff/1.0"]
+ assert agents["top"][0]["count"] == 6
+ assert agents["top"][0]["share"] == pytest.approx(100 * 6 / 11)
+ assert agents["tracked_total"] == 11
+
+
+def test_the_agent_window_stops_at_the_agent_expiry(redis_client):
+ """The two keys have different expiries, so a thirty day request window must not compare
+ a week of user agents against a month of requests."""
+ old_day = utc_today() - timedelta(days=admin_views.USER_AGENT_MAX_DAYS + 1)
+ record(redis_client, "v1_search", count=10, user_agent="Known/1.0")
+ record(redis_client, "v1_search", day=old_day, count=100)
+
+ agents = admin_views._user_agents(traffic.get_redis(), *window(30))
+
+ assert len(agents["days"]) == admin_views.USER_AGENT_MAX_DAYS
+ assert agents["request_total"] == 10
+ assert agents["gap"] == 0
+
+
+def test_the_gap_is_the_traffic_no_tracked_agent_accounts_for(redis_client):
+ record(redis_client, "v1_search", count=10, user_agent="Known/1.0")
+ # A request counted on the same day whose agent the trim has since dropped.
+ record(redis_client, "v1_search", headers="neither", count=4)
+
+ agents = admin_views._user_agents(traffic.get_redis(), *window(1))
+
+ assert (agents["request_total"], agents["tracked_total"], agents["gap"]) == (14, 10, 4)
+
+
+def test_view_requires_staff(client, db):
+ user = User.objects.create_user(username="ordinary_user_2", password="correctpassword")
+ client.force_login(user)
+
+ response = client.get(TRAFFIC_URL)
+
+ assert response.status_code == 302
+ assert "/admin/login/" in response.url
+
+
+def test_view_renders_the_tables(staff_client, redis_client):
+ record(redis_client, "v1_search", count=1234, user_agent="SomeBot/2.0")
+
+ response = staff_client.get(TRAFFIC_URL)
+ content = response.content.decode()
+
+ assert response.status_code == 200
+ assert "SomeBot/2.0" in content
+ assert "1,234" in content
+ assert response.context["by_day"]["total"] == 1234
+ assert response.context["by_headers"]["total"] == 1234
+ assert response.context["by_status"]["total"] == 1234
+
+
+def test_view_renders_an_empty_window(staff_client, redis_client):
+ response = staff_client.get(TRAFFIC_URL)
+
+ assert response.status_code == 200
+ assert "No requests counted in this window" in response.content.decode()
+
+
+def test_view_escapes_user_agent_strings(staff_client, redis_client):
+ """The one string on this page that a caller chooses."""
+ record(redis_client, "v1_search", user_agent="<script>alert(1)</script>")
+
+ content = staff_client.get(TRAFFIC_URL).content.decode()
+
+ assert "<script>alert(1)</script>" not in content
+ assert "&lt;script&gt;alert(1)&lt;/script&gt;" in content
+
+
+def test_view_says_so_when_counting_is_disabled(staff_client, redis_client, settings):
+ settings.SEARCH_TRAFFIC_COUNTING = False
+
+ assert "SEARCH_TRAFFIC_COUNTING is off" in staff_client.get(TRAFFIC_URL).content.decode()
+
+
+def test_view_renders_when_redis_is_down(staff_client, monkeypatch):
+ def explode():
+ raise RedisConnectionError("connection refused")
+
+ monkeypatch.setattr(admin_views.traffic, "get_redis", explode)
+
+ response = staff_client.get(TRAFFIC_URL)
+
+ # The page you load when Redis is down has to report that rather than 500.
+ assert response.status_code == 200
+ assert "connection refused" in response.content.decode()
+ assert "by_day" not in response.context
+
+
+def test_admin_index_links_to_the_traffic_page(staff_client):
+ assert TRAFFIC_URL in staff_client.get("/admin/").content.decode()