89 lines
2.7 KiB
Python
89 lines
2.7 KiB
Python
"""Tests for Wikipedia category searches."""
|
|
|
|
from unittest.mock import patch
|
|
|
|
import requests
|
|
|
|
from main import CategoryResult, app, get_articles_without_images
|
|
|
|
|
|
def test_api_failure_is_not_reported_as_an_empty_success():
|
|
with patch("main.requests.get", side_effect=requests.ConnectionError("offline")):
|
|
result = get_articles_without_images("Category:Example")
|
|
|
|
assert result.articles == []
|
|
assert result.error == "Unable to load articles. Wikipedia API error: offline"
|
|
|
|
|
|
def test_api_error_response_is_not_reported_as_an_empty_success():
|
|
error_response = type(
|
|
"Response",
|
|
(),
|
|
{
|
|
"raise_for_status": lambda self: None,
|
|
"json": lambda self: {
|
|
"error": {"code": "readonly", "info": "Wikipedia is read-only"}
|
|
},
|
|
},
|
|
)()
|
|
|
|
with patch("main.requests.get", return_value=error_response):
|
|
result = get_articles_without_images("Category:Example")
|
|
|
|
assert result.articles == []
|
|
assert result.error == (
|
|
"Unable to load articles. Wikipedia API error: "
|
|
"readonly: Wikipedia is read-only"
|
|
)
|
|
|
|
|
|
def test_api_failure_after_results_marks_them_as_partial():
|
|
first_response = type(
|
|
"Response",
|
|
(),
|
|
{
|
|
"raise_for_status": lambda self: None,
|
|
"json": lambda self: {
|
|
"query": {
|
|
"pages": {
|
|
"1": {"pageid": 1, "title": "No image", "images": []}
|
|
}
|
|
},
|
|
"continue": {
|
|
"gcmcontinue": "next-page",
|
|
"continue": "gcmcontinue||",
|
|
},
|
|
},
|
|
},
|
|
)()
|
|
|
|
with patch(
|
|
"main.requests.get",
|
|
side_effect=[first_response, requests.ConnectionError("offline")],
|
|
):
|
|
result = get_articles_without_images("Category:Example")
|
|
|
|
assert [article.title for article in result.articles] == ["No image"]
|
|
assert result.error is not None
|
|
assert "partial results" in result.error
|
|
assert "offline" in result.error
|
|
|
|
|
|
def test_category_page_does_not_claim_success_after_api_failure():
|
|
result = CategoryResult(
|
|
articles=[],
|
|
gcmcontinue=None,
|
|
error="Unable to load articles. Wikipedia API error: test failure",
|
|
)
|
|
|
|
with (
|
|
patch("main.get_articles_without_images", return_value=result),
|
|
patch("main.log_interaction"),
|
|
app.test_client() as client,
|
|
):
|
|
response = client.get("/category?cat=Category:Example")
|
|
|
|
page = response.get_data(as_text=True)
|
|
assert response.status_code == 200
|
|
assert "Wikipedia API error: test failure" in page
|
|
assert "All articles in this category have images" not in page
|