Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Add tests for curation views, crawler, moderation training, retrieve and platform accounts

blueheron7861b87ac9e1634
diff --git a/test/test_background_and_main.py b/test/test_background_and_main.py
new file mode 100644
index 0000000..9ed61ff
--- /dev/null
+++ b/test/test_background_and_main.py
@@ -0,0 +1,177 @@
+"""
+The long-running loops and process entry points in mwmbl.background and mwmbl.main: what
+they restart on, what they run, and how the server app is assembled.
+"""
+
+from datetime import datetime, timezone
+from pathlib import Path
+from unittest.mock import MagicMock
+
+import pytest
+
+from mwmbl import background, main
+from mwmbl.models import OldIndex
+
+
+class LoopStopped(BaseException):
+ """Ends a while True once the test has seen what it came for; not an Exception, so loops cannot swallow it."""
+
+
+def test_copy_all_indexes_resumes_after_the_last_copied_page(monkeypatch):
+ OldIndex.objects.create(index_path="/old/fresh", last_page_copied=None)
+ OldIndex.objects.create(index_path="/old/partial", last_page_copied=9)
+ OldIndex.objects.create(index_path="/old/finished", last_page_copied=50)
+ calls = []
+
+ def fake_copy(old_path, new_path, start_page, num_pages):
+ calls.append((old_path, start_page))
+ return start_page if old_path == "/old/finished" else start_page + 5
+
+ monkeypatch.setattr(background, "copy_pages", fake_copy)
+
+ updated = background.copy_all_indexes(Path("/new"))
+
+ assert sorted(calls) == [("/old/finished", 51), ("/old/fresh", 0), ("/old/partial", 10)]
+ assert updated == 2
+ assert OldIndex.objects.get(index_path="/old/fresh").last_page_copied == 5
+ assert OldIndex.objects.get(index_path="/old/partial").last_page_copied == 15
+ assert OldIndex.objects.get(index_path="/old/finished").last_page_copied == 50
+ assert OldIndex.objects.get(index_path="/old/fresh").last_copied_time <= datetime.now(timezone.utc)
+
+
+def test_copy_loop_sleeps_when_idle_and_survives_errors(monkeypatch):
+ outcomes = iter([RuntimeError("disk gone"), 0])
+
+ def copy_all(path):
+ outcome = next(outcomes)
+ if isinstance(outcome, Exception):
+ raise outcome
+ return outcome
+
+ monkeypatch.setattr(background, "copy_all_indexes", copy_all)
+ sleeps = []
+
+ def record_sleep(seconds):
+ sleeps.append(seconds)
+ if len(sleeps) == 2:
+ raise LoopStopped
+
+ monkeypatch.setattr(background, "sleep", record_sleep)
+
+ with pytest.raises(LoopStopped):
+ background.copy_indexes_continuously()
+
+ assert sleeps == [10, 10]
+
+
+def test_retraining_task_runs_the_management_command(monkeypatch):
+ call_command = MagicMock()
+ monkeypatch.setattr(background, "call_command", call_command)
+
+ background.retrain_domain_moderation_model.now()
+
+ call_command.assert_called_once_with("train_domain_moderation_model")
+
+
+def test_token_flush_task_runs_the_management_command(monkeypatch):
+ call_command = MagicMock()
+ monkeypatch.setattr(background, "call_command", call_command)
+
+ background.flush_expired_tokens.now()
+
+ call_command.assert_called_once_with("flushexpiredtokens")
+
+
+def test_seed_crawl_worker_restarts_after_a_failure(monkeypatch):
+ runs = []
+
+ def worker():
+ runs.append(1)
+ if len(runs) == 1:
+ raise ConnectionError("redis went away")
+
+ monkeypatch.setattr(main.django, "setup", MagicMock())
+ monkeypatch.setattr("mwmbl.indexer.seed_crawl.run_seed_crawl_worker", worker)
+ sleeps = []
+
+ def record_sleep(seconds):
+ sleeps.append(seconds)
+ if len(sleeps) == 2:
+ raise LoopStopped
+
+ monkeypatch.setattr(main, "sleep", record_sleep)
+
+ with pytest.raises(LoopStopped):
+ main.run_seed_crawls()
+
+ assert len(runs) == 2
+ assert sleeps == [main.TASK_QUEUE_RESTART_SECONDS] * 2
+
+
+def run_environment(monkeypatch):
+ calls = []
+ monkeypatch.setattr(main.django, "setup", MagicMock())
+ monkeypatch.setattr(main, "call_command", lambda *args: calls.append(args))
+ return calls
+
+
+def test_the_copy_indexes_app_copies_indexes_after_migrating(monkeypatch, run_environment):
+ monkeypatch.setenv("MWMBL_APP", "copy_indexes")
+ copy = MagicMock()
+ monkeypatch.setattr(background, "copy_indexes_continuously", copy)
+
+ main.run()
+
+ copy.assert_called_once()
+ assert ("migrate",) in run_environment
+
+
+def test_the_process_tasks_app_runs_only_the_queue(monkeypatch, run_environment):
+ monkeypatch.setenv("MWMBL_APP", "process_tasks")
+ queue = MagicMock()
+ monkeypatch.setattr(main, "run_background_tasks", queue)
+
+ main.run()
+
+ queue.assert_called_once()
+
+
+def test_an_unknown_app_is_an_error(monkeypatch, run_environment):
+ monkeypatch.setenv("MWMBL_APP", "nonsense")
+
+ with pytest.raises(ValueError, match="Unknown MWMBL_APP: nonsense"):
+ main.run()
+
+
[email protected]("run_background_tasks", [True, False])
+def test_the_server_app_starts_helper_processes_only_when_asked(
+ monkeypatch, settings, run_environment, run_background_tasks
+):
+ monkeypatch.setenv("MWMBL_APP", "server")
+ settings.RUN_BACKGROUND_TASKS = run_background_tasks
+ context = MagicMock()
+ context.Process.return_value.pid = 99
+ monkeypatch.setattr(main.multiprocessing, "get_context", lambda method: context)
+ gunicorn_settings = {}
+
+ class RecordingConfig:
+ def set(self, key, value):
+ gunicorn_settings[key] = value
+
+ class FakeBaseApplication:
+ def __init__(self):
+ self.cfg = RecordingConfig()
+
+ def run(self):
+ self.load_config()
+
+ monkeypatch.setattr(main, "BaseApplication", FakeBaseApplication)
+
+ main.run()
+
+ assert gunicorn_settings["bind"] == "0.0.0.0:5000"
+ assert gunicorn_settings["worker_class"] == "uvicorn.workers.UvicornWorker"
+ expected_processes = 2 if run_background_tasks else 0
+ assert context.Process.return_value.start.call_count == expected_processes
diff --git a/test/test_crawl_supervisor.py b/test/test_crawl_supervisor.py
new file mode 100644
index 0000000..95b2874
--- /dev/null
+++ b/test/test_crawl_supervisor.py
@@ -0,0 +1,155 @@
+"""
+The crawler supervisor: it respawns dead workers, gives up on a crash-looping indexer,
+and the module-level helpers and CLI entry point delegate to it.
+"""
+
+import sys
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from mwmbl import crawl
+from mwmbl.crawl import Crawler
+
+
+class LoopStopped(BaseException):
+ """Breaks the supervisor's while True once the test has seen what it came for."""
+
+
+def _process(alive: bool, exitcode: int | None = None) -> MagicMock:
+ process = MagicMock()
+ process.is_alive.return_value = alive
+ process.exitcode = exitcode
+ process.pid = 4242
+ return process
+
+
+def supervisor_environment():
+ with (
+ patch.object(crawl, "validate_environment"),
+ patch.object(Crawler, "check_redis"),
+ patch.object(crawl, "CRAWLER_WORKERS", 2),
+ ):
+ yield
+
+
+def test_run_gives_up_when_the_indexer_keeps_crashing(supervisor_environment):
+ with (
+ patch.object(crawl, "Process", side_effect=lambda target: _process(alive=False, exitcode=1)),
+ patch.object(crawl.time, "sleep"),
+ ):
+ with pytest.raises(RuntimeError, match="crashed 6 times in the last hour"):
+ Crawler().run()
+
+
+def test_run_respawns_a_dead_batch_worker(supervisor_environment):
+ started = []
+
+ def make_process(target):
+ process = _process(alive=target.__name__ != "process_batch_continuously" or not started)
+ started.append(process)
+ return process
+
+ sleeps = []
+
+ def stop_after_first_pass(seconds):
+ sleeps.append(seconds)
+ if seconds == 10:
+ raise LoopStopped
+
+ with (
+ patch.object(crawl, "Process", side_effect=make_process),
+ patch.object(crawl.time, "sleep", side_effect=stop_after_first_pass),
+ ):
+ with pytest.raises(LoopStopped):
+ Crawler().run()
+
+ # Two workers and an indexer at startup, then the dead first worker is replaced
+ # (the indexer is alive, so it is not).
+ assert len(started) == 4
+ started[3].start.assert_called_once()
+
+
+def test_run_rejects_zero_workers():
+ with (
+ patch.object(crawl, "validate_environment"),
+ patch.object(Crawler, "check_redis"),
+ patch.object(crawl, "CRAWLER_WORKERS", 0),
+ ):
+ with pytest.raises(AssertionError, match="CRAWLER_WORKERS"):
+ Crawler().run()
+
+
+def test_run_once_checks_the_environment_then_crawls_and_indexes():
+ crawler = Crawler()
+ with (
+ patch.object(crawl, "validate_environment") as validate,
+ patch.object(Crawler, "check_redis") as check_redis,
+ patch.object(Crawler, "process_batch") as process_batch,
+ patch.object(Crawler, "run_indexing") as run_indexing,
+ ):
+ crawler.run_once()
+
+ validate.assert_called_once()
+ check_redis.assert_called_once()
+ process_batch.assert_called_once()
+ run_indexing.assert_called_once()
+
+
[email protected]("name", ["check_redis", "process_batch", "run_indexing", "run", "run_once"])
+def test_module_level_helpers_delegate_to_the_default_crawler(monkeypatch, name):
+ default_crawler = MagicMock()
+ monkeypatch.setattr(crawl, "_default_crawler", default_crawler)
+
+ result = getattr(crawl, name)()
+
+ getattr(default_crawler, name).assert_called_once_with()
+ assert result is getattr(default_crawler, name).return_value
+
+
+def test_default_crawler_is_created_once(monkeypatch):
+ monkeypatch.setattr(crawl, "_default_crawler", None)
+
+ first = crawl.get_default_crawler()
+ second = crawl.get_default_crawler()
+
+ assert first is second
+
+
[email protected]("argv, expected", [(["mwmbl-crawl"], "run"), (["mwmbl-crawl", "--once"], "run_once")])
+def test_main_chooses_between_continuous_and_single_pass(monkeypatch, argv, expected):
+ monkeypatch.setattr(sys, "argv", argv)
+ with patch.object(crawl, "run") as run, patch.object(crawl, "run_once") as run_once:
+ crawl.main()
+
+ called, not_called = (run, run_once) if expected == "run" else (run_once, run)
+ called.assert_called_once()
+ not_called.assert_not_called()
+
+
+def fresh_curated_domains_cache(monkeypatch):
+ monkeypatch.setattr(crawl, "_curated_domains_cache", {"stale.example"})
+ monkeypatch.setattr(crawl, "_curated_domains_fetched_at", 0.0)
+
+
+def test_curated_domains_are_fetched_and_then_served_from_the_cache(fresh_curated_domains_cache, monkeypatch):
+ response = MagicMock()
+ response.json.return_value = {"domains": [{"name": "a.example"}, {"name": "b.example"}]}
+ get = MagicMock(return_value=response)
+ monkeypatch.setattr(crawl.requests, "get", get)
+ monkeypatch.setattr(crawl.time, "monotonic", lambda: 1000.0)
+
+ first = crawl._fetch_curated_domains()
+ second = crawl._fetch_curated_domains()
+
+ assert first == second == {"a.example", "b.example"}
+ get.assert_called_once()
+
+
+def test_a_failed_fetch_keeps_serving_the_cached_domains(fresh_curated_domains_cache, monkeypatch):
+ monkeypatch.setattr(crawl.requests, "get", MagicMock(side_effect=crawl.requests.ConnectionError("down")))
+ monkeypatch.setattr(crawl.time, "monotonic", lambda: 1000.0)
+
+ assert crawl._fetch_curated_domains() == {"stale.example"}
diff --git a/test/test_crawler_app.py b/test/test_crawler_app.py
new file mode 100644
index 0000000..76869a4
--- /dev/null
+++ b/test/test_crawler_app.py
@@ -0,0 +1,162 @@
+"""
+The crawler API's read endpoints and dataset upload: the S3 layout they share, and
+the input checks that stop a request reaching the bucket.
+"""
+
+import gzip
+import json
+from datetime import datetime, timezone
+from unittest.mock import MagicMock
+
+import pytest
+from django.test import Client
+
+from mwmbl.crawler import app
+from mwmbl.crawler.batch import HashedBatch
+from mwmbl.settings import PUBLIC_URL_PREFIX
+
+USER_HASH = "a" * 64
+DATE = "2024-01-02"
+
+
+def client():
+ return Client()
+
+
+def s3(monkeypatch):
+ boto3 = MagicMock()
+ monkeypatch.setattr(app, "boto3", boto3)
+ return boto3
+
+
+def test_upload_object_names_the_file_after_date_type_user_and_time(s3):
+ now = datetime(2024, 1, 2, 0, 1, 5, tzinfo=timezone.utc)
+ batch = HashedBatch(user_id_hash=USER_HASH, timestamp=1.0, items=[])
+
+ filename = app.upload_object(batch, now, USER_HASH, "results")
+
+ prefix = f"1/{app.VERSION}/{DATE}/results/{USER_HASH}/00065__"
+ assert filename.startswith(prefix)
+ assert filename.endswith(".json.gz")
+ body = s3.resource.return_value.Object.return_value.put.call_args.kwargs["Body"]
+ assert json.loads(gzip.decompress(body))["user_id_hash"] == USER_HASH
+
+
+def test_batch_ids_are_the_sorted_file_stems(s3):
+ keys = [f"1/{app.VERSION}/{DATE}/1/{USER_HASH}/{name}.json.gz" for name in ("b", "a")]
+ s3.resource.return_value.Bucket.return_value.objects.filter.return_value = [MagicMock(key=k) for k in keys]
+
+ result = app.get_batch_ids_for_prefix("some/prefix/")
+
+ assert result == {"batch_ids": ["a", "b"]}
+
+
+def test_subfolders_are_the_user_hashes_under_a_date(s3):
+ prefix = f"1/{app.VERSION}/{DATE}/1/"
+ s3.client.return_value.list_objects.return_value = {"CommonPrefixes": [{"Prefix": f"{prefix}{USER_HASH}/"}]}
+
+ assert app.get_subfolders(prefix) == [USER_HASH]
+
+
+def test_listing_batches_for_a_user_and_date(client, s3):
+ key = f"1/{app.VERSION}/{DATE}/1/{USER_HASH}/batch-1.json.gz"
+ s3.resource.return_value.Bucket.return_value.objects.filter.return_value = [MagicMock(key=key)]
+
+ response = client.get(f"/crawler/batches/{DATE}/users/{USER_HASH}")
+
+ assert response.status_code == 200
+ assert response.json() == {"batch_ids": ["batch-1"]}
+
+
+def test_listing_crawlers_active_on_a_date(client, s3):
+ prefix = f"1/{app.VERSION}/{DATE}/1/"
+ s3.client.return_value.list_objects.return_value = {"CommonPrefixes": [{"Prefix": f"{prefix}{USER_HASH}/"}]}
+
+ response = client.get(f"/crawler/batches/{DATE}/users")
+
+ assert response.status_code == 200
+ assert response.json() == [USER_HASH]
+
+
+ "path",
+ [
+ f"/crawler/batches/20240102/users/{USER_HASH}",
+ f"/crawler/batches/{DATE}/users/short",
+ "/crawler/batches/yesterday/users",
+ ],
+)
+def test_malformed_dates_and_user_ids_are_rejected_before_touching_s3(client, s3, path):
+ response = client.get(path)
+
+ assert response.status_code == 400
+ s3.resource.assert_not_called()
+ s3.client.assert_not_called()
+
+
+def test_fetching_a_batch_returns_its_public_url_and_content(client, monkeypatch):
+ batch = {"user_id_hash": USER_HASH, "items": []}
+ fetched = []
+
+ def fake_get(url):
+ fetched.append(url)
+ return MagicMock(content=gzip.compress(json.dumps(batch).encode()))
+
+ monkeypatch.setattr(app.requests, "get", fake_get)
+
+ response = client.get(f"/crawler/batches/{DATE}/users/{USER_HASH}/batch/batch-1")
+
+ expected_url = f"{PUBLIC_URL_PREFIX}1/{app.VERSION}/{DATE}/1/{USER_HASH}/batch-1.json.gz"
+ assert response.status_code == 200
+ assert response.json() == {"url": expected_url, "batch": batch}
+ assert fetched == [expected_url]
+
+
+def test_latest_batch_is_gone(client):
+ assert client.get("/crawler/latest-batch").status_code == 410
+
+
+def test_crawler_status_is_ok(client):
+ assert client.get("/crawler/").json() == {"status": "ok"}
+
+
+def _dataset(user_id: str) -> dict:
+ return {
+ "user_id": user_id,
+ "date": DATE,
+ "timestamp": 1704672000000,
+ "extensionVersion": "0.6.1",
+ "queryDataset": [],
+ "searchResults": [],
+ }
+
+
+def test_dataset_with_a_wrong_length_user_id_is_rejected(client, s3):
+ response = client.post("/crawler/dataset", data=_dataset("short"), content_type="application/json")
+
+ assert response.status_code == 400
+ s3.resource.assert_not_called()
+
+
+def test_dataset_is_stored_under_the_hash_of_the_user_id(client, s3, monkeypatch):
+ stats = MagicMock()
+ monkeypatch.setattr(app, "stats_manager", stats)
+ user_id = "b" * app.USER_ID_LENGTH
+
+ response = client.post("/crawler/dataset", data=_dataset(user_id), content_type="application/json")
+
+ body = response.json()
+ assert response.status_code == 200
+ assert body["public_user_id"] == app._get_user_id_hash(MagicMock(user_id=user_id))
+ assert user_id not in body["url"]
+ stats.record_dataset.assert_called_once()
+
+
+def test_curated_domains_endpoint_lists_domains_sorted(client, monkeypatch):
+ monkeypatch.setattr("mwmbl.curated_domains.get_curated_domains", lambda: {"b.example", "a.example"})
+
+ response = client.get("/crawler/curated-domains")
+
+ assert response.json() == {"domains": [{"name": "a.example"}, {"name": "b.example"}]}
diff --git a/test/test_fsqueue.py b/test/test_fsqueue.py
new file mode 100644
index 0000000..d98793d
--- /dev/null
+++ b/test/test_fsqueue.py
@@ -0,0 +1,103 @@
+"""
+The filesystem queue moves each item between state directories with os.rename, so an item
+is only ever in one state and two consumers can never take the same one.
+"""
+
+from pathlib import Path
+
+import pytest
+
+from mwmbl.indexer.fsqueue import (
+ FSQueue,
+ FSQueueError,
+ FSState,
+ GzipJsonBlobSerializer,
+ GzipJsonRowSerializer,
+ ZstdJsonSerializer,
+)
+
+
+def queue(tmp_path):
+ return FSQueue(tmp_path, "items", GzipJsonBlobSerializer())
+
+
+def _names(queue: FSQueue, state: FSState) -> list[str]:
+ return sorted(path.name for path in Path(queue._get_dir(state)).iterdir())
+
+
+ "serializer, item",
+ [
+ (ZstdJsonSerializer(), {"a": [1, 2, 3]}),
+ (GzipJsonBlobSerializer(), {"a": [1, 2, 3]}),
+ (GzipJsonRowSerializer(), [{"a": 1}, {"b": 2}]),
+ ],
+)
+def test_serializers_round_trip(serializer, item):
+ assert serializer.deserialize(serializer.serialize(item)) == item
+
+
+def test_queue_creates_a_directory_per_state(queue):
+ for state in FSState:
+ assert _names(queue, state) == []
+
+
+def test_queue_requires_an_existing_directory(tmp_path):
+ with pytest.raises(ValueError, match="not a directory"):
+ FSQueue(tmp_path / "missing", "items", GzipJsonBlobSerializer())
+
+
+def test_queue_name_cannot_contain_a_slash(tmp_path):
+ with pytest.raises(ValueError, match="'/'"):
+ FSQueue(tmp_path, "a/b", GzipJsonBlobSerializer())
+
+
+def test_put_makes_an_item_ready_and_get_locks_it(queue):
+ queue.put({"url": "https://example.com"})
+ assert len(_names(queue, FSState.READY)) == 1
+
+ item_id, item = queue.get()
+
+ assert item == {"url": "https://example.com"}
+ assert _names(queue, FSState.READY) == []
+ assert _names(queue, FSState.LOCKED) == [item_id]
+
+
+def test_get_on_an_empty_queue_returns_nothing(queue):
+ assert queue.get() is None
+
+
+def test_done_and_error_move_a_locked_item(queue):
+ queue.put("first")
+ queue.put("second")
+ first_id, _ = queue.get()
+ second_id, _ = queue.get()
+
+ queue.done(first_id)
+ queue.error(second_id)
+
+ assert _names(queue, FSState.DONE) == [first_id]
+ assert _names(queue, FSState.ERROR) == [second_id]
+ assert _names(queue, FSState.LOCKED) == []
+
+
+def test_unlock_all_returns_locked_items_to_ready(queue):
+ queue.put("item")
+ item_id, _ = queue.get()
+
+ queue.unlock_all()
+
+ assert _names(queue, FSState.READY) == [item_id]
+ assert _names(queue, FSState.LOCKED) == []
+
+
+def test_corrupt_item_raises_with_its_id(queue):
+ queue.put("item")
+ (path,) = Path(queue._get_dir(FSState.READY)).iterdir()
+ path.write_bytes(b"not gzip")
+
+ with pytest.raises(FSQueueError) as error:
+ queue.get()
+
+ assert error.value.item_id == path.name
diff --git a/test/test_ltr_sklearn.py b/test/test_ltr_sklearn.py
new file mode 100644
index 0000000..eb6f2ca
--- /dev/null
+++ b/test/test_ltr_sklearn.py
@@ -0,0 +1,89 @@
+"""
+The scikit-learn building blocks the ranking experiments compose: feature extraction from
+result records and a regressor that learns a thresholded label.
+"""
+
+import numpy as np
+import pytest
+from pandas import DataFrame, Series
+from sklearn.pipeline import make_pipeline
+from sklearn.tree import DecisionTreeClassifier
+
+from mwmbl.tinysearchengine.ltr import FeatureExtractor, ThresholdPredictor, get_features_as_series
+
+
+def _results() -> DataFrame:
+ return DataFrame(
+ {
+ "query": ["python tutorial", "python tutorial", "cheap flights", "cheap flights"],
+ "title": ["Python Tutorial for beginners", "Gardening tips", "Cheap flights to Spain", "Python Tutorial"],
+ "url": [
+ "https://docs.python.org/tutorial",
+ "https://garden.example/tips",
+ "https://flights.example/spain",
+ "https://docs.python.org/tutorial",
+ ],
+ "extract": ["Learn python step by step", "Grow tomatoes", "Find cheap flights", "Learn python"],
+ "score": [10.0, 1.0, 9.0, 1.0],
+ }
+ )
+
+
+def test_feature_extractor_returns_one_float_row_per_result():
+ results = _results()
+
+ features = FeatureExtractor().fit(results).transform(results)
+
+ assert features.shape[0] == len(results)
+ assert features.dtype == np.float32
+ assert np.isfinite(features).all()
+
+
+def test_feature_extractor_distinguishes_matching_from_unrelated_results():
+ results = _results()
+
+ features = FeatureExtractor().fit_transform(results)
+
+ assert not np.array_equal(features[0], features[1])
+
+
+def test_features_as_series_names_each_feature():
+ features = get_features_as_series(_results().iloc[0])
+
+ assert isinstance(features, Series)
+ assert "match_term_proportion_whole" in features.index
+
+
+def test_threshold_predictor_learns_the_binarised_label():
+ results = _results()
+ labels = np.array([3.0, 0.0, 3.0, 0.0])
+ model = make_pipeline(FeatureExtractor(), ThresholdPredictor(0.0, DecisionTreeClassifier(random_state=0)))
+
+ model.fit(results, labels)
+ predictions = model.predict(results)
+
+ assert predictions.tolist() == [1.0, 0.0, 1.0, 0.0]
+
+
+def test_threshold_predictor_returns_the_whole_matrix_when_only_one_class_was_seen():
+ results = _results()
+ model = make_pipeline(FeatureExtractor(), ThresholdPredictor(10.0, DecisionTreeClassifier(random_state=0)))
+
+ model.fit(results, np.zeros(len(results)))
+ predictions = model.predict(results)
+
+ assert predictions.shape == (len(results), 1)
+
+
[email protected]("threshold, expected", [(0.0, [True, False]), (5.0, [True, False])])
+def test_threshold_predictor_binarises_labels_before_fitting(threshold, expected):
+ seen = []
+
+ class Recorder(DecisionTreeClassifier):
+ def fit(self, X, y, *args, **kwargs):
+ seen.append(list(y))
+ return super().fit(X, y, *args, **kwargs)
+
+ ThresholdPredictor(threshold, Recorder()).fit(np.array([[1.0], [0.0]]), np.array([6.0, 0.0]))
+
+ assert seen == [expected]
diff --git a/test/test_moderation_training.py b/test/test_moderation_training.py
new file mode 100644
index 0000000..ed500c9
--- /dev/null
+++ b/test/test_moderation_training.py
@@ -0,0 +1,221 @@
+"""
+Training the domain-moderation model on synthetic, separable data: the metrics it reports,
+the paired comparison against an incumbent, and the management command that drives it.
+"""
+
+import json
+
+import numpy as np
+import pytest
+from django.core.management import call_command
+
+from mwmbl.management.commands import train_domain_moderation_model as command
+from mwmbl.moderation.train import (
+ compare_models,
+ evaluate,
+ normalised_ap_of,
+ operating_point,
+ recall_at_precision,
+ split_by_time,
+ train,
+)
+from mwmbl.moderation.training_data import DERIVED, REAL, SEED, TrainingRow
+
+REJECT_TEXT = "cheap pills casino bonus click here win money fast"
+APPROVE_TEXT = "community garden recipes local history library volunteers"
+
+
+def _rows(count: int = 160) -> list[TrainingRow]:
+ """Alternating approve/reject decisions, oldest first, from a few known submitters then new ones."""
+ rows = []
+ for i in range(count):
+ rejected = i % 2 == 0
+ late = i >= count * 0.7
+ rows.append(
+ TrainingRow(
+ domain=f"{'spam' if rejected else 'site'}{i}.example",
+ rejected=rejected,
+ reason=("SPAM" if i % 4 == 0 else "OFFENSIVE") if rejected else "",
+ source=REAL,
+ page_texts=[REJECT_TEXT if rejected else APPROVE_TEXT],
+ timestamp=f"2026-01-01T00:{i // 60:02d}:{i % 60:02d}",
+ submitter=f"cold{i}" if late else f"known{i % 3}",
+ suggested_status="REJECTED" if i % 5 == 0 else "",
+ )
+ )
+ return rows
+
+
[email protected](scope="module")
+def trained():
+ return train(_rows(), "test-v1")
+
+
+def test_split_keeps_the_newest_real_rows_for_testing_and_all_other_sources_for_training():
+ other = [
+ TrainingRow(domain="seed.example", rejected=True, reason="SPAM", source=SEED, page_texts=[]),
+ TrainingRow(domain="derived.example", rejected=True, reason="SPAM", source=DERIVED, page_texts=[]),
+ ]
+
+ train_rows, test_rows = split_by_time(_rows(40) + other)
+
+ assert len(test_rows) == 10
+ assert {row.source for row in test_rows} == {REAL}
+ assert min(row.timestamp for row in test_rows) > max(row.timestamp for row in train_rows if row.source == REAL)
+ assert {row.domain for row in other} <= {row.domain for row in train_rows}
+
+
+def test_a_trained_model_separates_the_classes(trained):
+ model, metrics = trained
+
+ assert metrics["all"]["normalised_ap"] > 0.9
+ assert metrics["cold_start"]["rows"] > 0
+ assert metrics["uses_text"] is True
+ assert metrics["uses_has_text"] is False
+ assert metrics["train_rows_by_source"] == {REAL: 120}
+ assert "reason_head" in metrics
+ assert model.version == "test-v1"
+ assert "spam0.example" in model.train_domains
+
+
+def test_metrics_are_json_serialisable(trained):
+ _, metrics = trained
+
+ assert json.loads(json.dumps(metrics))["all"]["rows"] == metrics["all"]["rows"]
+
+
+def test_without_text_the_featuriser_has_no_text_block():
+ _, metrics = train(_rows(), "no-text", use_text=False)
+
+ assert metrics["uses_text"] is False
+
+
+def test_evaluating_with_no_held_out_rows_says_so(trained):
+ model, _ = trained
+
+ assert evaluate(model, [], []) == {"error": "no held-out real rows to evaluate on"}
+
+
+def test_candidate_is_compared_with_the_incumbent_on_the_same_rows(trained):
+ incumbent, _ = trained
+
+ _, metrics = train(_rows(), "test-v2", incumbent=incumbent)
+
+ comparison = metrics["versus_incumbent"]
+ assert comparison["incumbent_version"] == "test-v1"
+ assert comparison["rows"] > 0
+ assert comparison["difference_ci"][0] <= comparison["difference"] <= comparison["difference_ci"][1]
+
+
+def test_compare_models_runs_on_a_test_split(trained):
+ model, _ = trained
+ _, test_rows = split_by_time(_rows())
+ cold = np.array([True] * len(test_rows))
+ scores = np.array([prediction[0] for prediction in model.predict([row.to_example() for row in test_rows])])
+
+ comparison = compare_models(model, model, test_rows, cold, scores)
+
+ assert comparison["difference"] == pytest.approx(0.0)
+
+
+def test_operating_point_reports_none_where_a_threshold_selects_nothing():
+ truth = np.array([1, 0, 1, 0])
+ scores = np.array([0.5, 0.5, 0.5, 0.5])
+
+ point = operating_point(truth, scores)
+
+ assert point["reject_precision"] is None
+ assert point["approve_error_rate"] is None
+ assert point["unsure_share"] == 1.0
+
+
+def test_recall_at_precision_for_a_perfect_ranking():
+ truth = np.array([1, 1, 0, 0])
+ scores = np.array([0.9, 0.8, 0.2, 0.1])
+
+ assert recall_at_precision(truth, scores) == 1.0
+
+
+def test_normalised_ap_reads_both_metric_formats():
+ current = {"normalised_ap": 0.8, "normalised_ap_ci": [0.6, 0.9]}
+ legacy = {"rows": 100, "positives": 20, "pr_auc": 0.6, "pr_auc_ci": [0.5, 0.7]}
+
+ assert normalised_ap_of(current) == (0.8, 0.6)
+ point, floor = normalised_ap_of(legacy)
+ assert point == pytest.approx((0.6 - 0.2) / 0.8)
+ assert floor == pytest.approx((0.5 - 0.2) / 0.8)
+ assert normalised_ap_of({}) is None
+
+
+def patched_command(monkeypatch):
+ rows = _rows()
+ published = []
+ monkeypatch.setattr(command.training_data, "real_rows", lambda: rows)
+ monkeypatch.setattr(command.training_data, "seed_rows", lambda: [])
+ monkeypatch.setattr(command, "load_published_model", lambda: None)
+ monkeypatch.setattr(command, "load_metrics", lambda: {})
+ monkeypatch.setattr(command, "publish", lambda model, metrics: published.append(model.version))
+ monkeypatch.setattr(command, "rescore_pending_submissions", lambda schedule: published.append("rescore"))
+ return published
+
+
+def test_dry_run_trains_and_reports_without_publishing(patched_command, capsys):
+ call_command("train_domain_moderation_model", "--dry-run")
+
+ output = capsys.readouterr().out
+ assert "PASS" in output
+ assert "Dry run" in output
+ assert patched_command == []
+
+
+def test_a_passing_run_publishes_and_rescores_the_queue(patched_command, capsys):
+ call_command("train_domain_moderation_model")
+
+ assert patched_command[0].startswith("domain-mod-")
+ assert patched_command[1] == "rescore"
+
+
+def test_a_failing_gate_blocks_publishing_unless_forced(patched_command, monkeypatch, capsys):
+ monkeypatch.setattr(command, "passes_gate", lambda new, current: (False, "worse"))
+
+ call_command("train_domain_moderation_model")
+ assert patched_command == []
+
+ call_command("train_domain_moderation_model", "--force")
+ assert patched_command[1] == "rescore"
+
+
+def test_ablation_reports_each_variant_and_the_text_coverage(patched_command, capsys):
+ call_command("train_domain_moderation_model", "--dry-run", "--ablate")
+
+ output = capsys.readouterr().out
+ assert "domain name only" in output
+ assert "text + has_text" in output
+ assert "cold-start test rows" in output
+
+
+def test_no_decided_submissions_means_nothing_to_train(monkeypatch, capsys):
+ monkeypatch.setattr(command.training_data, "real_rows", lambda: [])
+
+ call_command("train_domain_moderation_model")
+
+ assert "No decided submissions" in capsys.readouterr().err
+
+
+def test_derived_rows_are_requested_for_reasons_short_of_real_data(patched_command, monkeypatch, capsys):
+ requested = []
+
+ def fake_derived(reasons, per_reason, exclude):
+ requested.append((set(reasons), per_reason))
+ return []
+
+ monkeypatch.setattr(command.training_data, "derived_rows", fake_derived)
+
+ call_command("train_domain_moderation_model", "--dry-run", "--derived")
+
+ assert requested
+ reasons, per_reason = requested[0]
+ assert per_reason == command.DERIVED_ROWS_PER_REASON
+ assert reasons
diff --git a/test/test_moderation_training_data.py b/test/test_moderation_training_data.py
new file mode 100644
index 0000000..ec872d4
--- /dev/null
+++ b/test/test_moderation_training_data.py
@@ -0,0 +1,152 @@
+"""
+The rows a domain-moderation model is trained on: real decisions, blocklist-derived
+rejections for reasons with little real data, and hand-written seed examples.
+"""
+
+import json
+from unittest.mock import MagicMock
+
+import pytest
+from django.utils import timezone
+
+from mwmbl.models import DomainEvidence, DomainSubmission, MwmblUser
+from mwmbl.moderation import training_data
+from mwmbl.moderation.training_data import (
+ DERIVED,
+ REAL,
+ SEED,
+ TrainingRow,
+ derived_rows,
+ is_trainable_domain,
+ real_rows,
+ seed_rows,
+)
+
+
+ "domain, trainable",
+ [
+ ("example.com", True),
+ ("", False),
+ ("Example.com", False),
+ ("https://example.com", False),
+ ("not a domain", False),
+ ],
+)
+def test_only_well_formed_lowercase_domains_are_trainable(domain, trainable):
+ assert is_trainable_domain(domain) is trainable
+
+
+def submitter(db):
+ return MwmblUser.objects.create_user(username="submitter", email="[email protected]", password="pw")
+
+
+def _submission(submitter, name, status, **extra):
+ return DomainSubmission.objects.create(
+ name=name, status=status, submitted_by=submitter, submitted_on=timezone.now(), **extra
+ )
+
+
+def test_real_rows_join_decisions_to_crawled_page_text(submitter):
+ _submission(submitter, "good.example", "APPROVED")
+ _submission(submitter, "bad.example", "REJECTED", rejection_reason="SPAM")
+ _submission(submitter, "undecided.example", "PENDING")
+ _submission(submitter, "Bad-Case.example", "APPROVED")
+ DomainEvidence.objects.create(
+ domain="bad.example",
+ state=DomainEvidence.State.READY,
+ pages=[{"title": "Buy now", "extract": "cheap pills"}],
+ )
+ DomainEvidence.objects.create(domain="good.example", state=DomainEvidence.State.PENDING, pages=[{"title": "x"}])
+
+ rows = {row.domain: row for row in real_rows()}
+
+ assert set(rows) == {"good.example", "bad.example"}
+ assert rows["bad.example"].rejected is True
+ assert rows["bad.example"].reason == "SPAM"
+ assert rows["bad.example"].page_texts == ["Buy now cheap pills"]
+ assert rows["bad.example"].source == REAL
+ assert rows["bad.example"].submitter == str(submitter.id)
+ assert rows["good.example"].rejected is False
+ assert rows["good.example"].reason == ""
+ assert rows["good.example"].page_texts == []
+
+
+def test_a_row_becomes_a_model_example():
+ row = TrainingRow(domain="a.example", rejected=True, reason="SPAM", source=REAL, page_texts=["text"])
+
+ example = row.to_example()
+
+ assert example.domain == "a.example"
+ assert example.page_texts == ["text"]
+
+
+BLOCKLIST = """\
+# a comment
+0.0.0.0 spam-one.example
+127.0.0.1 spam-two.example # trailing comment
+plain-three.example
+sub.domain.example
+has_underscore.example
+toolongtoolongtoolongtoolongtoolongtoolong.example
+
+"""
+
+
+def blocklist(monkeypatch):
+ response = MagicMock(text=BLOCKLIST)
+ get = MagicMock(return_value=response)
+ monkeypatch.setattr(training_data.requests, "get", get)
+ return get
+
+
+def test_apex_domains_are_read_from_hosts_and_plain_formats(blocklist):
+ domains = training_data._fetch_apex_domains("https://blocklist.test/list")
+
+ assert domains == ["spam-one.example", "spam-two.example", "plain-three.example"]
+ blocklist.return_value.raise_for_status.assert_called_once()
+
+
+def test_derived_rows_exclude_known_domains_and_cap_each_reason(blocklist):
+ rows = derived_rows(["SPAM", "OFFENSIVE"], per_reason=1, exclude={"spam-one.example"})
+
+ assert [row.reason for row in rows] == ["SPAM", "OFFENSIVE"]
+ assert all(row.source == DERIVED and row.rejected for row in rows)
+ assert all(row.domain != "spam-one.example" for row in rows)
+
+
+def test_derived_rows_are_reproducible_for_a_seed(blocklist):
+ first = derived_rows(["SPAM"], per_reason=2, exclude=set(), seed=7)
+ second = derived_rows(["SPAM"], per_reason=2, exclude=set(), seed=7)
+
+ assert [row.domain for row in first] == [row.domain for row in second]
+
+
+def test_reasons_without_a_source_are_skipped(blocklist):
+ assert derived_rows(["OTHER"], per_reason=5, exclude=set()) == []
+ blocklist.assert_not_called()
+
+
+def test_seed_rows_skip_blank_lines_and_comments(tmp_path):
+ path = tmp_path / "seed.jsonl"
+ path.write_text(
+ "# hand-written\n\n"
+ + json.dumps({"domain": "a.example", "status": "REJECTED", "reason": "SPAM", "text": "buy now"})
+ + "\n"
+ + json.dumps({"domain": "b.example", "status": "APPROVED"})
+ + "\n"
+ )
+
+ rows = seed_rows(path)
+
+ assert [(row.domain, row.rejected, row.reason, row.page_texts, row.source) for row in rows] == [
+ ("a.example", True, "SPAM", ["buy now"], SEED),
+ ("b.example", False, "", [], SEED),
+ ]
+
+
+def test_missing_seed_file_means_no_seed_rows(tmp_path):
+ assert seed_rows(tmp_path / "missing.jsonl") == []
diff --git a/test/test_platform_accounts_api.py b/test/test_platform_accounts_api.py
new file mode 100644
index 0000000..dde2498
--- /dev/null
+++ b/test/test_platform_accounts_api.py
@@ -0,0 +1,193 @@
+"""
+Account and submission endpoints of the platform API: registration conflicts, email
+confirmation, account deletion, and who may delete or decide a domain submission.
+"""
+
+import pytest
+from allauth.account.models import EmailAddress, EmailConfirmationHMAC
+from django.contrib.auth import get_user_model
+from django.contrib.auth.models import Permission
+from ninja_jwt.tokens import RefreshToken
+
+from mwmbl.models import DomainEvidence, DomainSubmission
+
+User = get_user_model()
+
+BASE = "/api/v1/platform"
+PAGE = {"url": "https://example.org/", "title": "Home", "extract": "Welcome"}
+
+
+def _user(username: str, verified: bool = True):
+ user = User.objects.create_user(username=username, email=f"{username}@example.com", password="correctpassword")
+ EmailAddress.objects.create(user=user, email=user.email, verified=verified, primary=True)
+ return user
+
+
+def _auth(user) -> dict:
+ return {"Authorization": f"Bearer {RefreshToken.for_user(user).access_token}"}
+
+
+def owner(db):
+ return _user("owner")
+
+
+def stranger(db):
+ return _user("stranger")
+
+
+def moderator(db):
+ user = _user("moderator")
+ user.user_permissions.add(Permission.objects.get(codename="change_domain_submission_status"))
+ return user
+
+
+def _register(client, **body):
+ payload = {"email": "[email protected]", "password": "correctpassword", **body}
+ return client.post(f"{BASE}/register", data=payload, content_type="application/json")
+
+
+def test_registering_an_existing_email_is_rejected(client, owner):
+ response = _register(client, email=owner.email)
+
+ assert response.status_code == 400
+ assert "Email already registered" in response.json()["message"]
+
+
+def test_registering_an_existing_username_is_rejected(client, owner):
+ response = _register(client, username=owner.username)
+
+ assert response.status_code == 400
+ assert "Username already exists" in response.json()["message"]
+
+
+def test_registration_records_accepted_agreements(client, db):
+ response = _register(client, agreements=["TERMS_OF_SERVICE_GUI"])
+
+ assert response.status_code == 200, response.content
+
+
+def test_confirming_with_an_unknown_key_is_rejected(client, db):
+ response = client.post(
+ f"{BASE}/confirm-email",
+ data={"email": "[email protected]", "key": "bogus"},
+ content_type="application/json",
+ )
+
+ assert response.status_code == 400
+
+
+def test_confirming_with_another_users_email_is_rejected(client, owner):
+ unverified = _user("unverified", verified=False)
+ address = EmailAddress.objects.get(user=unverified)
+ key = EmailConfirmationHMAC(address).key
+
+ response = client.post(
+ f"{BASE}/confirm-email",
+ data={"email": owner.email, "key": key},
+ content_type="application/json",
+ )
+
+ assert response.status_code == 400
+ address.refresh_from_db()
+ assert address.verified is False
+
+
+def test_confirming_with_the_right_key_verifies_the_address(client, db):
+ unverified = _user("unverified", verified=False)
+ address = EmailAddress.objects.get(user=unverified)
+ key = EmailConfirmationHMAC(address).key
+
+ response = client.post(
+ f"{BASE}/confirm-email",
+ data={"email": unverified.email, "key": key},
+ content_type="application/json",
+ )
+
+ assert response.status_code == 200
+ assert response.json()["username"] == "unverified"
+ address.refresh_from_db()
+ assert address.verified is True
+
+
+def test_protected_endpoint_accepts_a_verified_user_and_refuses_an_unverified_one(client, owner):
+ unverified = _user("unverified", verified=False)
+
+ ok = client.get(f"{BASE}/protected", headers=_auth(owner))
+ refused = client.get(f"{BASE}/protected", headers=_auth(unverified))
+
+ assert ok.status_code == 200
+ assert refused.status_code == 403
+
+
+def test_a_user_can_delete_their_own_account(client, owner):
+ response = client.delete(f"{BASE}/users/{owner.username}", headers=_auth(owner))
+
+ assert response.status_code == 200
+ assert not User.objects.filter(pk=owner.pk).exists()
+
+
+def test_a_user_cannot_delete_someone_elses_account(client, owner, stranger):
+ response = client.delete(f"{BASE}/users/{owner.username}", headers=_auth(stranger))
+
+ assert response.status_code == 400
+ assert User.objects.filter(pk=owner.pk).exists()
+
+
+def test_a_submitter_can_delete_their_own_submission(client, owner):
+ submission = DomainSubmission.objects.create(name="example.org", submitted_by=owner)
+
+ response = client.delete(f"{BASE}/domain-submissions/ids/{submission.id}", headers=_auth(owner))
+
+ assert response.status_code == 200
+ assert not DomainSubmission.objects.filter(id=submission.id).exists()
+
+
+def test_a_submission_cannot_be_deleted_by_someone_else(client, owner, stranger):
+ submission = DomainSubmission.objects.create(name="example.org", submitted_by=owner)
+
+ response = client.delete(f"{BASE}/domain-submissions/ids/{submission.id}", headers=_auth(stranger))
+
+ assert response.status_code == 400
+ assert DomainSubmission.objects.filter(id=submission.id).exists()
+
+
+def test_only_moderators_can_update_a_submission_status(client, owner, moderator):
+ submission = DomainSubmission.objects.create(name="example.org", submitted_by=owner)
+ body = {"status": "APPROVED", "rejection_reason": "", "rejection_detail": ""}
+ url = f"{BASE}/domain-submissions/ids/{submission.id}"
+
+ refused = client.post(url, data=body, content_type="application/json", headers=_auth(owner))
+ accepted = client.post(url, data=body, content_type="application/json", headers=_auth(moderator))
+
+ assert refused.status_code == 400
+ assert accepted.status_code == 200
+ submission.refresh_from_db()
+ assert submission.status == "APPROVED"
+
+
+def test_submission_detail_is_for_moderators_and_includes_the_evidence(client, owner, moderator):
+ submission = DomainSubmission.objects.create(name="example.org", submitted_by=owner)
+ DomainEvidence.objects.create(
+ domain="example.org",
+ state=DomainEvidence.State.READY,
+ pages=[PAGE],
+ )
+ url = f"{BASE}/domain-submissions/ids/{submission.id}"
+
+ refused = client.get(url, headers=_auth(owner))
+ detail = client.get(url, headers=_auth(moderator))
+
+ assert refused.status_code in (400, 403)
+ assert detail.status_code == 200, detail.content
+ assert detail.json()["name"] == "example.org"
+ assert detail.json()["evidence_state"] == "READY"
+ assert [page["url"] for page in detail.json()["pages"]] == [PAGE["url"]]
+
+
+def test_detail_for_a_missing_submission_is_a_404(client, moderator):
+ response = client.get(f"{BASE}/domain-submissions/ids/999999", headers=_auth(moderator))
+
+ assert response.status_code == 404
diff --git a/test/test_retrieve_robots_and_links.py b/test/test_retrieve_robots_and_links.py
new file mode 100644
index 0000000..e65baac
--- /dev/null
+++ b/test/test_retrieve_robots_and_links.py
@@ -0,0 +1,249 @@
+"""
+robots.txt handling and its Redis cache, link extraction, and the error results crawl_url
+returns instead of raising.
+"""
+
+import json
+import time
+
+import fakeredis
+import pytest
+
+from mwmbl.crawler import retrieve
+from mwmbl.crawler.retrieve import (
+ ROBOTS_CACHE_ERROR_TTL_SECONDS,
+ ROBOTS_CACHE_TTL_SECONDS,
+ crawl_counting_overlap,
+ crawl_url,
+ get_dom_links,
+ get_new_links,
+ record_overlap,
+ robots_allowed,
+)
+from mwmbl.justext.core import Paragraph, PathInfo, html_to_dom
+
+URL = "https://example.test/private/page"
+ROBOTS = b"User-agent: *\nDisallow: /private/\n"
+
+
+def redis():
+ return fakeredis.FakeStrictRedis()
+
+
+def _fetching(monkeypatch, status: int, content: bytes):
+ calls = []
+
+ def fake_fetch(url):
+ calls.append(url)
+ return status, content, url
+
+ monkeypatch.setattr(retrieve, "fetch", fake_fetch)
+ return calls
+
+
+def test_robots_disallow_is_obeyed_and_cached(monkeypatch, redis):
+ calls = _fetching(monkeypatch, 200, ROBOTS)
+
+ first = robots_allowed(URL, redis)
+ second = robots_allowed(URL, redis)
+
+ assert first is False and second is False
+ assert calls == ["https://example.test/robots.txt"]
+ assert ROBOTS_CACHE_TTL_SECONDS - 5 <= redis.ttl("robots:example.test") <= ROBOTS_CACHE_TTL_SECONDS
+
+
+def test_other_paths_stay_allowed(monkeypatch, redis):
+ _fetching(monkeypatch, 200, ROBOTS)
+
+ assert robots_allowed("https://example.test/public", redis) is True
+
+
+def test_unparseable_url_is_not_allowed(redis):
+ assert robots_allowed("http://[bad", redis) is False
+
+
+def test_missing_robots_allows_everything_and_is_cached_briefly(monkeypatch, redis):
+ _fetching(monkeypatch, 404, b"")
+
+ assert robots_allowed(URL, redis) is True
+ assert ROBOTS_CACHE_ERROR_TTL_SECONDS - 5 <= redis.ttl("robots:example.test") <= ROBOTS_CACHE_ERROR_TTL_SECONDS
+
+
+def test_unreachable_robots_allows_everything_and_is_cached_briefly(monkeypatch, redis):
+ def unreachable(url):
+ raise ConnectionError("refused")
+
+ monkeypatch.setattr(retrieve, "fetch", unreachable)
+
+ assert robots_allowed(URL, redis) is True
+ assert ROBOTS_CACHE_ERROR_TTL_SECONDS - 5 <= redis.ttl("robots:example.test") <= ROBOTS_CACHE_ERROR_TTL_SECONDS
+
+
+def test_robots_in_latin_1_are_decoded(monkeypatch, redis):
+ _fetching(monkeypatch, 200, "# caf\xe9\nUser-agent: *\nDisallow: /private/\n".encode("iso-8859-1"))
+
+ assert robots_allowed(URL, redis) is False
+
+
+def test_expired_cache_entry_is_refetched(monkeypatch, redis):
+ expired = {"content": [], "cached_at": 0, "expires_at": int(time.time()) - 10}
+ redis.set("robots:example.test", json.dumps(expired))
+ calls = _fetching(monkeypatch, 200, ROBOTS)
+
+ assert robots_allowed(URL, redis) is False
+ assert len(calls) == 1
+
+
[email protected]("entry", ["not json", json.dumps({"content": []})])
+def test_corrupt_cache_entry_is_dropped_and_refetched(monkeypatch, redis, entry):
+ redis.set("robots:example.test", entry)
+ calls = _fetching(monkeypatch, 200, ROBOTS)
+
+ assert robots_allowed(URL, redis) is False
+ assert len(calls) == 1
+
+
+def _paragraph(links: list[str], class_type: str) -> Paragraph:
+ paragraph = Paragraph(PathInfo())
+ paragraph.links = links
+ paragraph.class_type = class_type
+ return paragraph
+
+
+def test_good_paragraph_links_are_new_and_the_rest_extra():
+ paragraphs = [
+ _paragraph(["/a", "/skip.jpg", "mailto:[email protected]"], "good"),
+ _paragraph(["/b", "/a"], "bad"),
+ ]
+
+ new_links, extra_links = get_new_links(paragraphs, "https://example.test/")
+
+ assert new_links == {"https://example.test/a"}
+ assert extra_links == {"https://example.test/b"}
+
+
+def test_link_collection_stops_once_both_sets_are_full(monkeypatch):
+ monkeypatch.setattr(retrieve, "MAX_NEW_LINKS", 1)
+ monkeypatch.setattr(retrieve, "MAX_EXTRA_LINKS", 1)
+ paragraphs = [
+ _paragraph(["/a", "/a2"], "good"),
+ _paragraph(["/b", "/b2"], "bad"),
+ ]
+
+ new_links, extra_links = get_new_links(paragraphs, "https://example.test/")
+
+ assert len(new_links) == 1
+ assert len(extra_links) == 1
+
+
+def test_fragments_are_stripped_and_overlong_urls_dropped():
+ dom = html_to_dom(
+ (
+ '<html><body><a href="/page#section"><img src="x.gif"></a>'
+ '<a href="#top">top</a><a href=" ">blank</a>'
+ f'<a href="/{"x" * 200}">long</a></body></html>'
+ ).encode(),
+ "utf8",
+ None,
+ "replace",
+ )
+
+ assert get_dom_links(dom, "https://example.test/") == {"https://example.test/page"}
+
+
+def _error_name(result: dict) -> str:
+ return result["error"]["name"]
+
+
+def test_crawl_url_reports_robots_denial(monkeypatch, redis):
+ monkeypatch.setattr(retrieve, "robots_allowed", lambda url, redis: False)
+
+ result = crawl_url(URL, redis)
+
+ assert _error_name(result) == "RobotsDenied"
+ assert result["content"] is None
+
+
+def test_crawl_url_reports_fetch_failures(monkeypatch, redis):
+ def refuse(url):
+ raise ConnectionError("refused")
+
+ monkeypatch.setattr(retrieve, "robots_allowed", lambda url, redis: True)
+ monkeypatch.setattr(retrieve, "fetch", refuse)
+
+ result = crawl_url(URL, redis)
+
+ assert _error_name(result) == "AbortError"
+ assert result["error"]["message"] == "refused"
+
+
+def test_crawl_url_reports_an_empty_response(monkeypatch, redis):
+ monkeypatch.setattr(retrieve, "robots_allowed", lambda url, redis: True)
+ _fetching(monkeypatch, 200, b"")
+
+ assert _error_name(crawl_url(URL, redis)) == "NoResponseText"
+
+
+def test_crawl_url_reports_unparseable_html(monkeypatch, redis):
+ def broken(*args, **kwargs):
+ raise RuntimeError("cannot parse")
+
+ monkeypatch.setattr(retrieve, "robots_allowed", lambda url, redis: True)
+ _fetching(monkeypatch, 200, b"<html></html>")
+ monkeypatch.setattr(retrieve, "html_to_dom", broken)
+
+ result = crawl_url(URL, redis)
+
+ assert _error_name(result) == "RuntimeError"
+
+
+def test_crawl_url_reports_paragraph_extraction_failures(monkeypatch, redis):
+ def broken(*args, **kwargs):
+ raise RuntimeError("cannot classify")
+
+ monkeypatch.setattr(retrieve, "robots_allowed", lambda url, redis: True)
+ _fetching(monkeypatch, 200, b"<html><body><p>Hello</p></body></html>\x01")
+ monkeypatch.setattr(retrieve.core, "justext_from_dom", broken)
+
+ assert _error_name(crawl_url(URL, redis)) == "RuntimeError"
+
+
+def test_crawl_url_truncates_long_titles_and_extracts(monkeypatch, redis):
+ sentence = "This is a perfectly ordinary sentence about the history of the town and its people. "
+ html = f"<html><head><title>{'T' * 500}</title></head><body><p>{sentence * 60}</p></body></html>"
+ monkeypatch.setattr(retrieve, "robots_allowed", lambda url, redis: True)
+ _fetching(monkeypatch, 200, html.encode())
+
+ content = crawl_url(URL, redis)["content"]
+
+ assert len(content["title"]) == retrieve.NUM_TITLE_CHARS
+ assert content["title"].endswith("…")
+ assert content["extract"].endswith("…")
+
+
+def test_overlap_counter_is_released_after_the_crawl(monkeypatch, redis):
+ seen = []
+
+ def fake_crawl(url, redis):
+ seen.append(int(redis.get(retrieve.DOMAIN_IN_FLIGHT_KEY.format(domain="example.test"))))
+ return {"url": url}
+
+ monkeypatch.setattr(retrieve, "crawl_url", fake_crawl)
+
+ result, overlap = crawl_counting_overlap(URL, redis)
+
+ assert result == {"url": URL}
+ assert overlap == 0
+ assert seen == [1]
+ assert int(redis.get(retrieve.DOMAIN_IN_FLIGHT_KEY.format(domain="example.test"))) == 0
+
+
+def test_record_overlap_totals_accumulate(redis):
+ urls = ["https://a.test/1", "https://a.test/2", "https://b.test/"]
+
+ record_overlap(urls, [0, 1, 2], redis)
+ record_overlap(urls, [0, 0, 0], redis)
+
+ totals = {k.decode(): int(v) for k, v in redis.hgetall(retrieve.DOMAIN_OVERLAP_KEY).items()}
+ assert totals == {"fetches": 6, "overlapped": 2, "duplicate_domains": 2}
diff --git a/test/test_update_urls.py b/test/test_update_urls.py
index 547d351..00dd84a 100644
--- a/test/test_update_urls.py
+++ b/test/test_update_urls.py
@@ -1,74 +1,127 @@
+"""
+Recording the URLs found in crawled batches: which links are kept, who gets credit
+for them, and what is queued.
+"""
+
from collections import defaultdict
+from datetime import datetime, timezone
+from unittest.mock import MagicMock
-from mwmbl.crawler.batch import Link
-from mwmbl.indexer.blacklist_providers import CombinedBlacklistProvider, StaticBlacklistProvider
-from mwmbl.indexer.update_urls import process_link
+import pytest
+from mwmbl.crawler.batch import HashedBatch, Item, ItemContent, ItemError, Link
+from mwmbl.crawler.urls import URLStatus
+from mwmbl.indexer import update_urls
+from mwmbl.indexer.update_urls import get_datetime_from_timestamp, process_link, record_urls_in_database
-def test_process_link_normal():
- url_timestamps = {}
- url_users = {}
- domain_links = defaultdict(set)
- blacklist_provider = StaticBlacklistProvider(set())
+TIMESTAMP = datetime(2024, 1, 1, tzinfo=timezone.utc)
+
+
+class FakeBlacklist:
+ def is_domain_blacklisted(self, domain: str) -> bool:
+ return domain == "blocked.example"
+
+def _process(link_url: str):
+ url_users, url_timestamps = {}, {}
+ domain_links = defaultdict(set)
process_link(
- user_id_hash="abc123",
- crawled_page_domain="somewhere.com",
- link=Link(url="https://somesite.com/something.html", link_type="nav"),
- timestamp=1234,
- url_timestamps=url_timestamps,
- url_users=url_users,
- blacklist_provider=blacklist_provider,
- domain_links=domain_links,
- )
+ "user", "source.example", Link(url=link_url, link_type="content"), TIMESTAMP,
+ url_timestamps, url_users, FakeBlacklist(), domain_links,
+ ) # fmt: skip
+ return url_users, url_timestamps, domain_links
- assert domain_links == {"somewhere.com": {"somesite.com"}}
+def test_timestamp_is_converted_to_an_aware_datetime():
+ assert get_datetime_from_timestamp(1704067200.0) == TIMESTAMP
-def test_process_link_excludes_porn():
- url_timestamps = {}
- url_users = {}
- domain_links = {}
- # Create a blacklist provider that blocks porn sites
- blacklist_provider = StaticBlacklistProvider({"somepornsite.com"})
- process_link(
- user_id_hash="abc123",
- crawled_page_domain="somewhere.com",
- link=Link(url="https://somepornsite.com/something.html", link_type="content"),
- timestamp=1234,
- url_timestamps=url_timestamps,
- url_users=url_users,
- blacklist_provider=blacklist_provider,
- domain_links=domain_links,
- )
+def test_a_link_credits_the_user_and_its_root_url():
+ url_users, url_timestamps, domain_links = _process("https://target.example/page")
+
+ assert url_users == {"https://target.example/page": "user", "https://target.example/": "user"}
+ assert set(url_timestamps) == set(url_users)
+ assert domain_links == {"source.example": {"target.example"}}
+
+
[email protected]("link_url", ["https://blocked.example/page", "not a url"])
+def test_unparseable_and_blacklisted_links_are_dropped(link_url):
+ url_users, url_timestamps, domain_links = _process(link_url)
- assert url_timestamps == {}
assert url_users == {}
+ assert url_timestamps == {}
assert domain_links == {}
-def test_process_link_keeps_a_curated_domain():
- """The blocklists carry false positives that are wrong for a search index, so a domain
- a moderator has approved must survive link discovery. This is the crawler's path: it
- takes the approved names from the URL queue, which fetches them over HTTP."""
- url_timestamps = {}
- url_users = {}
- domain_links = defaultdict(set)
- blacklist_provider = CombinedBlacklistProvider(
- [StaticBlacklistProvider({"pudding.cool"})],
- get_exempt_domains=lambda: {"pudding.cool"},
- )
+def recorded(monkeypatch):
+ """Patch the database and blacklist, returning the URLs that would have been queued."""
+ found_urls = []
+ domain_link_db = MagicMock()
+ domain_link_db.__enter__.return_value = domain_link_db
- process_link(
- user_id_hash="abc123",
- crawled_page_domain="somewhere.com",
- link=Link(url="https://pudding.cool/2025/12/motifs", link_type="content"),
- timestamp=1234,
- url_timestamps=url_timestamps,
- url_users=url_users,
- blacklist_provider=blacklist_provider,
- domain_links=domain_links,
+ monkeypatch.setattr(update_urls, "get_default_blacklist_provider", lambda curated: FakeBlacklist())
+ monkeypatch.setattr(update_urls, "_add_found_urls_to_db_and_queue", lambda urls, queue: found_urls.extend(urls))
+ monkeypatch.setattr(update_urls, "DomainLinkDatabase", lambda: domain_link_db)
+ return found_urls, domain_link_db
+
+
+def _item(url, content=None, status=200, error=None):
+ return Item(url=url, status=status, timestamp=1704067200000.0, content=content, error=error)
+
+
+def test_recording_a_batch_classifies_every_url(recorded):
+ found_urls, domain_link_db = recorded
+ content = ItemContent(title="T", extract="E", links=["https://linked.example/a"])
+ batch = HashedBatch(
+ user_id_hash="hash",
+ timestamp=1704067200.0,
+ items=[
+ _item("https://ok.example/", content=content),
+ _item("https://gone.example/", status=404),
+ _item("https://slow.example/", error=ItemError(name="AbortError")),
+ _item("https://robots.example/", error=ItemError(name="RobotsDenied")),
+ _item("https://odd.example/", status=500),
+ ],
)
- assert domain_links == {"somewhere.com": {"pudding.cool"}}
+ record_urls_in_database([batch], MagicMock())
+
+ statuses = {found.url: found.status for found in found_urls}
+ assert statuses == {
+ "https://ok.example/": URLStatus.CRAWLED,
+ "https://gone.example/": URLStatus.ERROR_404,
+ "https://slow.example/": URLStatus.ERROR_TIMEOUT,
+ "https://robots.example/": URLStatus.ERROR_ROBOTS_DENIED,
+ "https://odd.example/": URLStatus.ERROR_OTHER,
+ "https://linked.example/a": URLStatus.NEW,
+ "https://linked.example/": URLStatus.NEW,
+ }
+ assert {found.user_id_hash for found in found_urls} == {"hash"}
+ domain_link_db.update_domain_links.assert_called_once_with("ok.example", {"linked.example"})
+
+
+def test_a_crawled_page_with_an_unparseable_url_contributes_no_links(recorded):
+ found_urls, domain_link_db = recorded
+ content = ItemContent(title="T", extract="E", links=["https://linked.example/a"])
+ batch = HashedBatch(user_id_hash="hash", timestamp=1704067200.0, items=[_item("no-scheme", content=content)])
+
+ record_urls_in_database([batch], MagicMock())
+
+ assert [found.url for found in found_urls] == ["no-scheme"]
+ domain_link_db.update_domain_links.assert_not_called()
+
+
+def test_hn_links_are_added_until_the_domain_limit(monkeypatch):
+ queue = MagicMock()
+ queue.get_domain_count.side_effect = [0, 100, 200]
+ monkeypatch.setattr(update_urls, "get_domain_max_urls", lambda domain, curated: 150)
+ monkeypatch.setattr(update_urls.requests, "get", lambda url: MagicMock(json=lambda: 1000))
+ added = []
+ monkeypatch.setattr(update_urls, "_add_found_urls_to_db_and_queue", lambda urls, q: added.append(urls))
+
+ update_urls.add_hn_links(queue)
+
+ assert len(added) == 2
+ assert added[0][0].url == "https://news.ycombinator.com/item?id=1000"
+ assert added[1][0].url == "https://news.ycombinator.com/item?id=900"
diff --git a/test/test_views_curation.py b/test/test_views_curation.py
new file mode 100644
index 0000000..6f57402
--- /dev/null
+++ b/test/test_views_curation.py
@@ -0,0 +1,365 @@
+"""
+Behaviour of the curation and domain pages in mwmbl.views: the state machine behind
+approving a result, the add-URL flow, reverting and flagging curations, and the
+domain submission pages.
+"""
+
+import pytest
+from django.contrib.auth.models import Permission
+from django.urls import reverse
+from django.utils import timezone
+
+from mwmbl.models import Curation, DomainSubmission, FlagCuration, MwmblUser
+from mwmbl.tinysearchengine.indexer import Document, DocumentState
+from mwmbl.views import _get_document_state, _insert_document, switch_state
+
+
+def curator(db):
+ return MwmblUser.objects.create_user(username="curator", email="[email protected]", password="pw")
+
+
+def moderator(db):
+ user = MwmblUser.objects.create_user(username="moderator", email="[email protected]", password="pw")
+ permissions = Permission.objects.filter(
+ codename__in=["change_flag_status", "change_domain_submission_status"],
+ )
+ user.user_permissions.set(permissions)
+ return user
+
+
+def curation(curator):
+ return Curation.objects.create(
+ user=curator,
+ timestamp=timezone.now(),
+ query="curation views",
+ original_index_results=[],
+ original_results=[
+ {"title": "Orig", "url": "https://example.com/orig", "extract": "e", "score": 1.0, "term": "curation view"}
+ ],
+ new_results=[],
+ num_changes=1,
+ )
+
+
+def _result(url: str, state: DocumentState | None = None) -> Document:
+ return Document(title=url, url=url, extract="extract", score=1.0, term="t", state=state)
+
+
+ "state, expected",
+ [
+ (None, DocumentState.ORGANIC_APPROVED),
+ (DocumentState.FROM_GOOGLE, DocumentState.FROM_GOOGLE_APPROVED),
+ (DocumentState.FROM_USER, DocumentState.FROM_USER_APPROVED),
+ (DocumentState.FROM_WIKI, DocumentState.FROM_WIKI_APPROVED),
+ (DocumentState.FROM_GOOGLE_APPROVED, DocumentState.FROM_GOOGLE),
+ (DocumentState.FROM_USER_APPROVED, DocumentState.FROM_USER),
+ (DocumentState.FROM_WIKI_APPROVED, DocumentState.FROM_WIKI),
+ (DocumentState.ORGANIC_APPROVED, None),
+ ],
+)
+def test_switch_state_toggles_approval(state, expected):
+ assert switch_state(state) == expected
+
+
+def test_switch_state_rejects_unknown_state():
+ with pytest.raises(ValueError):
+ switch_state("not a state")
+
+
+ "validated, source, expected",
+ [
+ (True, "user", DocumentState.FROM_USER_APPROVED),
+ (True, "Google", DocumentState.FROM_GOOGLE_APPROVED),
+ (True, "organic", DocumentState.ORGANIC_APPROVED),
+ (False, "USER", DocumentState.FROM_USER),
+ (False, "google", DocumentState.FROM_GOOGLE),
+ (False, "organic", None),
+ ],
+)
+def test_document_state_from_validation_and_source(validated, source, expected):
+ assert _get_document_state(validated, source) == expected
+
+
+def test_insert_document_goes_above_unapproved_results():
+ approved = _result("https://example.com/approved", DocumentState.ORGANIC_APPROVED)
+ documents = {
+ "https://example.com/a": _result("https://example.com/a", DocumentState.ORGANIC_APPROVED),
+ "https://example.com/b": _result("https://example.com/b"),
+ }
+
+ reranked = _insert_document(documents, approved)
+
+ assert [d.url for d in reranked] == [
+ "https://example.com/a",
+ "https://example.com/approved",
+ "https://example.com/b",
+ ]
+
+
+def test_insert_document_goes_last_when_everything_is_approved():
+ approved = _result("https://example.com/approved", DocumentState.ORGANIC_APPROVED)
+ documents = {"https://example.com/a": _result("https://example.com/a", DocumentState.ORGANIC_APPROVED)}
+
+ reranked = _insert_document(documents, approved)
+
+ assert [d.url for d in reranked] == ["https://example.com/a", "https://example.com/approved"]
+
+
+def test_insert_document_replaces_an_existing_copy_of_the_url():
+ approved = _result("https://example.com/a", DocumentState.ORGANIC_APPROVED)
+ documents = {"https://example.com/a": _result("https://example.com/a")}
+
+ reranked = _insert_document(documents, approved)
+
+ assert reranked == [approved]
+
+
+class FakeResponse:
+ encoding = "utf-8"
+ text = (
+ "<html><head><title>Fetched page</title></head><body><p>"
+ + "This is a long paragraph of good text that the extractor should keep for the extract. " * 12
+ + "</p></body></html>"
+ )
+
+
+def test_add_url_fetches_the_page_and_records_a_curation(client, curator, monkeypatch):
+ monkeypatch.setattr("mwmbl.views.validate_url", lambda url: None)
+ monkeypatch.setattr("mwmbl.views.requests.get", lambda *args, **kwargs: FakeResponse())
+ client.force_login(curator)
+
+ response = client.post(
+ reverse("add_url"),
+ {
+ "new_url": "https://example.com/fetched",
+ "query": "fetched page",
+ "url": ["https://example.com/other"],
+ "title": ["Other"],
+ "extract": ["Other extract"],
+ "state": [""],
+ "score": ["1.0"],
+ },
+ )
+
+ assert response.status_code == 200
+ curation = Curation.objects.get()
+ new_urls = [result["url"] for result in curation.new_results]
+ assert "https://example.com/fetched" in new_urls
+
+
+def test_add_url_reports_fetch_failures(client, curator, monkeypatch):
+ from requests import RequestException
+
+ def fail(*args, **kwargs):
+ raise RequestException("connection refused")
+
+ monkeypatch.setattr("mwmbl.views.validate_url", lambda url: None)
+ monkeypatch.setattr("mwmbl.views.requests.get", fail)
+ client.force_login(curator)
+
+ response = client.post(reverse("add_url"), {"new_url": "https://example.com/down", "query": "down"})
+
+ assert response.status_code == 400
+ assert "connection refused" in response.content.decode()
+
+
+def _approve(client, curation_id: int | None = None):
+ data = {
+ "query": "curation views",
+ "approve_url": "https://example.com/orig",
+ "url": ["https://example.com/orig"],
+ "title": ["Orig"],
+ "extract": ["e"],
+ "state": [""],
+ "score": ["1.0"],
+ }
+ if curation_id is not None:
+ data["curation_id"] = str(curation_id)
+ return client.post(reverse("approve"), data)
+
+
+def test_approving_again_updates_the_same_curation(client, curator):
+ client.force_login(curator)
+ _approve(client)
+ first = Curation.objects.get()
+
+ response = _approve(client, curation_id=first.id)
+
+ assert response.status_code == 200
+ first.refresh_from_db()
+ assert Curation.objects.count() == 1
+ assert first.num_changes == 2
+
+
+def test_reverting_a_curation_deletes_it_and_shows_the_original_results(client, curator, curation):
+ client.force_login(curator)
+
+ response = client.post(reverse("revert_current"), {"curation_id": curation.id})
+
+ assert response.status_code == 200
+ assert not Curation.objects.filter(id=curation.id).exists()
+ assert "Orig" in response.content.decode()
+
+
+def test_curation_pages_render(client, curator, curation):
+ FlagCuration.objects.create(user=curator, timestamp=timezone.now(), curation=curation, flag="OTHER")
+
+ list_response = client.get(reverse("curations"))
+ detail_response = client.get(reverse("curation", args=[curation.id]))
+
+ assert list_response.status_code == 200
+ assert detail_response.status_code == 200
+ assert [flag.flag for flag in detail_response.context["flags"]] == ["OTHER"]
+
+
+def test_flagging_requires_login(client, curation):
+ response = client.get(reverse("flag_curation", args=[curation.id]))
+
+ assert response.status_code == 302
+ assert "/login" in response["Location"]
+
+
+def test_flag_form_is_shown_and_rejects_an_invalid_flag(client, curator, curation):
+ client.force_login(curator)
+ url = reverse("flag_curation", args=[curation.id])
+
+ form_response = client.get(url)
+ invalid_response = client.post(url, {"flag": "NOT_A_FLAG"})
+
+ assert form_response.status_code == 200
+ assert invalid_response.status_code == 200
+ assert not FlagCuration.objects.exists()
+
+
+def test_pending_flags_are_listed_for_logged_in_users(client, curator, curation):
+ FlagCuration.objects.create(user=curator, timestamp=timezone.now(), curation=curation, flag="OTHER")
+ FlagCuration.objects.create(
+ user=curator, timestamp=timezone.now(), curation=curation, flag="OTHER", status="REJECTED"
+ )
+ client.force_login(curator)
+
+ response = client.get(reverse("flag_curation_list"))
+
+ assert response.status_code == 200
+ assert [flag.status for flag in response.context["object_list"]] == ["PENDING"]
+
+
+def test_flag_update_rejects_an_unknown_status(client, moderator, curation):
+ flag = FlagCuration.objects.create(user=moderator, timestamp=timezone.now(), curation=curation, flag="OTHER")
+ client.force_login(moderator)
+
+ response = client.post(reverse("flag_curation_update", args=[flag.id]), {"status": "BOGUS"})
+
+ assert response.status_code == 400
+
+
+def test_flag_update_requires_the_permission(client, curator, curation):
+ flag = FlagCuration.objects.create(user=curator, timestamp=timezone.now(), curation=curation, flag="OTHER")
+ client.force_login(curator)
+
+ response = client.post(reverse("flag_curation_update", args=[flag.id]), {"status": "REJECTED"})
+
+ assert response.status_code == 302
+ flag.refresh_from_db()
+ assert flag.status == "PENDING"
+
+
+def test_rejecting_a_flag_leaves_the_curation_alone(client, moderator, curation):
+ flag = FlagCuration.objects.create(user=moderator, timestamp=timezone.now(), curation=curation, flag="OTHER")
+ client.force_login(moderator)
+
+ response = client.post(reverse("flag_curation_update", args=[flag.id]), {"status": "REJECTED"})
+
+ assert response.status_code == 200
+ flag.refresh_from_db()
+ assert flag.status == "REJECTED"
+ assert Curation.objects.filter(id=curation.id).exists()
+
+
+def test_accepting_a_flag_reverts_the_curation(client, moderator, curation):
+ flag = FlagCuration.objects.create(user=moderator, timestamp=timezone.now(), curation=curation, flag="OTHER")
+ client.force_login(moderator)
+
+ response = client.post(reverse("flag_curation_update", args=[flag.id]), {"status": "ACCEPTED"})
+
+ assert response.status_code == 200
+ flag.refresh_from_db()
+ assert flag.status == "ACCEPTED"
+
+
+def test_submit_domain_form_and_submission(client, curator):
+ client.force_login(curator)
+ url = reverse("submit_domain")
+
+ form_response = client.get(url)
+ post_response = client.post(url, {"name": "https://www.example.org/some/page"})
+
+ assert form_response.status_code == 200
+ assert post_response.status_code == 302
+ submission = DomainSubmission.objects.get()
+ assert submission.name == "www.example.org"
+ assert submission.submitted_by == curator
+
+
+def test_invalid_domain_is_not_saved(client, curator):
+ client.force_login(curator)
+
+ response = client.post(reverse("submit_domain"), {"name": "not a domain"})
+
+ assert response.status_code == 200
+ assert not DomainSubmission.objects.exists()
+
+
+def test_moderator_can_decide_a_submission_on_the_domain_page(client, moderator, curator):
+ submission = DomainSubmission.objects.create(name="example.org", submitted_by=curator)
+ client.force_login(moderator)
+
+ response = client.post(
+ reverse("domain", args=["example.org"]),
+ {"id": submission.id, "status": "REJECTED", "rejection_reason": "OTHER", "rejection_detail": "spam"},
+ )
+
+ assert response.status_code == 200
+ submission.refresh_from_db()
+ assert submission.status == "REJECTED"
+
+
+def test_domain_page_hides_approval_forms_from_ordinary_users(client, curator):
+ DomainSubmission.objects.create(name="example.org", submitted_by=curator)
+ client.force_login(curator)
+
+ response = client.get(reverse("domain", args=["example.org"]))
+
+ assert response.status_code == 200
+ assert response.context["forms"] == []
+
+
+def test_domain_page_shows_pending_approval_forms_to_moderators(client, moderator, curator):
+ DomainSubmission.objects.create(name="example.org", submitted_by=curator)
+ client.force_login(moderator)
+
+ response = client.get(reverse("domain", args=["example.org"]))
+
+ assert len(response.context["forms"]) == 1