CI / lint (push) Successful in 16s
CI / validate-monitoring (push) Successful in 21s
CI / federation-interop (push) Successful in 1m20s
CI / test (push) Successful in 5m50s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / trigger-deploy (push) Skipped
CI / notify (push) Successful in 9s
Corrections accept a release MBID as well as a release-group MBID, and the worker uses a scrobble's recording MBID to find the release-group before falling back to the text search. Counts matched/missed recording lookups. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
853 lines
33 KiB
Python
853 lines
33 KiB
Python
import io
|
|
import json
|
|
import pathlib
|
|
import threading
|
|
import time
|
|
import urllib.parse
|
|
from datetime import UTC, datetime, timedelta
|
|
|
|
import pytest
|
|
from werkzeug.serving import make_server
|
|
|
|
from scrobbler.extensions import db
|
|
from scrobbler.models import AlbumArt, UserAlbumArt
|
|
from scrobbler.services import art, scrobbles
|
|
from scrobbler.services.scrobbles import TrackInput
|
|
|
|
FOUND_MBID = "11111111-1111-1111-1111-111111111111" # a real-looking id the fake has art for
|
|
|
|
# Canned release-group matches, keyed by a substring of the Lucene search query we send.
|
|
_RELEASE_GROUPS = {
|
|
"In Rainbows": "rg-found", # has art
|
|
"No Art Album": "rg-no-art", # MB match, but Cover Art Archive has nothing
|
|
"Boom Album": "rg-boom", # MB match, but Cover Art Archive 500s on HEAD
|
|
"Download Fail Album": "rg-dl-fail", # HEAD succeeds, but the GET download 500s
|
|
}
|
|
|
|
|
|
# Canned recordings (a scrobble's MBID) and the releases MusicBrainz lists them on.
|
|
RECORDING_MBID = "22222222-2222-2222-2222-222222222222"
|
|
UNMATCHED_RECORDING_MBID = "33333333-3333-3333-3333-333333333333"
|
|
_RECORDINGS = {
|
|
RECORDING_MBID: [
|
|
{"title": "Some Compilation", "release-group": {"id": "rg-other"}},
|
|
{"title": "Mbid Album", "release-group": {"id": "rg-found"}},
|
|
],
|
|
UNMATCHED_RECORDING_MBID: [{"title": "Another Album", "release-group": {"id": "rg-other"}}],
|
|
}
|
|
|
|
|
|
def _fake_musicbrainz_caa(environ, start_response):
|
|
method, path = environ["REQUEST_METHOD"], environ["PATH_INFO"]
|
|
|
|
if path == "/release-group/" and method == "GET":
|
|
query = urllib.parse.parse_qs(environ.get("QUERY_STRING", ""))["query"][0]
|
|
if "Query Boom" in query:
|
|
start_response("500 Internal Server Error", [("Content-Type", "text/plain")])
|
|
return [b"boom"]
|
|
match = next((v for k, v in _RELEASE_GROUPS.items() if k in query), None)
|
|
groups = [{"id": match}] if match else []
|
|
body = json.dumps({"release-groups": groups}).encode()
|
|
start_response(
|
|
"200 OK", [("Content-Type", "application/json"), ("Content-Length", str(len(body)))]
|
|
)
|
|
return [body]
|
|
|
|
if path.startswith("/recording/"):
|
|
recording = path.rsplit("/", 1)[1]
|
|
releases = _RECORDINGS.get(recording)
|
|
if releases is None:
|
|
start_response("404 Not Found", [("Content-Type", "text/plain")])
|
|
return [b"not found"]
|
|
body = json.dumps({"releases": releases}).encode()
|
|
start_response(
|
|
"200 OK", [("Content-Type", "application/json"), ("Content-Length", str(len(body)))]
|
|
)
|
|
return [body]
|
|
|
|
if path in (
|
|
"/release-group/rg-found/front-500",
|
|
f"/release-group/{FOUND_MBID}/front-500",
|
|
f"/release/{FOUND_MBID}/front-500",
|
|
):
|
|
body = b"\xff\xd8\xff\xe0fake-jpeg-bytes"
|
|
headers = [("Content-Type", "image/jpeg"), ("Content-Length", str(len(body)))]
|
|
start_response("200 OK", headers)
|
|
return [] if method == "HEAD" else [body]
|
|
|
|
if path == "/release-group/rg-boom/front-500":
|
|
start_response("500 Internal Server Error", [("Content-Type", "text/plain")])
|
|
return [b"boom"]
|
|
|
|
if path == "/release-group/rg-dl-fail/front-500":
|
|
if method == "HEAD":
|
|
start_response("200 OK", [("Content-Type", "image/jpeg")])
|
|
return []
|
|
start_response("500 Internal Server Error", [("Content-Type", "text/plain")])
|
|
return [b"boom"]
|
|
|
|
start_response("404 Not Found", [("Content-Type", "text/plain")])
|
|
return [b"not found"]
|
|
|
|
|
|
@pytest.fixture(scope="module")
|
|
def fake_art_api():
|
|
server = make_server("127.0.0.1", 0, _fake_musicbrainz_caa, threaded=True)
|
|
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
|
thread.start()
|
|
yield f"http://127.0.0.1:{server.server_port}/"
|
|
server.shutdown()
|
|
|
|
|
|
@pytest.fixture
|
|
def art_config(app, fake_art_api, tmp_path):
|
|
keys = (
|
|
"MUSICBRAINZ_API_URL",
|
|
"COVERART_API_URL",
|
|
"MUSICBRAINZ_REQUEST_INTERVAL",
|
|
"MUSICBRAINZ_RETRIES",
|
|
"ART_STORAGE_DIR",
|
|
)
|
|
saved = {k: app.config[k] for k in keys}
|
|
app.config.update(
|
|
MUSICBRAINZ_API_URL=fake_art_api,
|
|
COVERART_API_URL=fake_art_api,
|
|
MUSICBRAINZ_REQUEST_INTERVAL=0,
|
|
MUSICBRAINZ_RETRIES=0,
|
|
ART_STORAGE_DIR=str(tmp_path),
|
|
)
|
|
yield
|
|
app.config.update(saved)
|
|
|
|
|
|
def row(artist, album):
|
|
return db.session.scalar(
|
|
db.select(AlbumArt).where(
|
|
db.func.lower(AlbumArt.artist) == artist.lower(),
|
|
db.func.lower(AlbumArt.album) == album.lower(),
|
|
)
|
|
)
|
|
|
|
|
|
def insert(artist, album, status, days_ago=0.0, image_url=None):
|
|
db.session.add(
|
|
AlbumArt(
|
|
artist=artist,
|
|
album=album,
|
|
status=status,
|
|
image_url=image_url,
|
|
checked_at=datetime.now(UTC) - timedelta(days=days_ago),
|
|
)
|
|
)
|
|
db.session.commit()
|
|
|
|
|
|
# --- lookup() (still live-resolving: used by ActivityPub posting, out of scope here) -----------
|
|
|
|
|
|
def test_lookup_finds_art(art_config):
|
|
result = art.lookup("Radiohead", "In Rainbows")
|
|
assert result.status == "found"
|
|
assert result.image_url.endswith("/release-group/rg-found/front-500")
|
|
assert row("Radiohead", "In Rainbows").status == "found"
|
|
|
|
|
|
def test_lookup_no_musicbrainz_match_is_not_found(art_config):
|
|
result = art.lookup("Nobody", "Nothing At All")
|
|
assert result == art.ArtResult("not_found")
|
|
|
|
|
|
def test_lookup_musicbrainz_match_but_no_cover_art_is_not_found(art_config):
|
|
result = art.lookup("Someone", "No Art Album")
|
|
assert result == art.ArtResult("not_found")
|
|
|
|
|
|
def test_lookup_upstream_error_is_cached_not_raised(app, art_config):
|
|
result = art.lookup("Someone", "Boom Album")
|
|
assert result.status == "error"
|
|
assert row("Someone", "Boom Album").error_code
|
|
|
|
|
|
def test_lookup_search_error_is_cached_not_raised(app, art_config):
|
|
result = art.lookup("Someone", "Query Boom")
|
|
assert result.status == "error"
|
|
|
|
|
|
def test_lookup_is_case_insensitive_and_cached(app, art_config):
|
|
art.lookup("Radiohead", "In Rainbows")
|
|
# Point at a port nothing listens on: if the different-cased call weren't a cache hit on
|
|
# the same row, it would fail to reach the network and come back as "error".
|
|
app.config.update(
|
|
MUSICBRAINZ_API_URL="http://127.0.0.1:1/", COVERART_API_URL="http://127.0.0.1:1/"
|
|
)
|
|
result = art.lookup("radiohead", "in rainbows")
|
|
assert result.status == "found"
|
|
|
|
|
|
def test_lookup_fresh_cache_hit_skips_the_network(app, art_config, fake_art_api):
|
|
insert("Fresh Artist", "Fresh Album", "not_found", days_ago=0)
|
|
app.config.update(
|
|
MUSICBRAINZ_API_URL="http://127.0.0.1:1/", COVERART_API_URL="http://127.0.0.1:1/"
|
|
)
|
|
result = art.lookup("Fresh Artist", "Fresh Album")
|
|
assert result.status == "not_found"
|
|
|
|
|
|
def test_stale_not_found_row_is_rechecked(app, art_config):
|
|
insert("Radiohead", "In Rainbows", "not_found", days_ago=31)
|
|
result = art.lookup("Radiohead", "In Rainbows")
|
|
assert result.status == "found" # the live fake server actually has art for this album
|
|
|
|
|
|
def test_fresh_not_found_row_is_not_rechecked(app, art_config):
|
|
insert("Radiohead", "In Rainbows", "not_found", days_ago=1)
|
|
result = art.lookup("Radiohead", "In Rainbows")
|
|
assert result.status == "not_found" # cache hit, even though the live server has art
|
|
|
|
|
|
def test_stale_error_row_is_rechecked(app, art_config):
|
|
db.session.add(
|
|
AlbumArt(
|
|
artist="Radiohead",
|
|
album="In Rainbows",
|
|
status="error",
|
|
error_code="TimeoutError",
|
|
checked_at=datetime.now(UTC) - timedelta(hours=2),
|
|
)
|
|
)
|
|
db.session.commit()
|
|
result = art.lookup("Radiohead", "In Rainbows")
|
|
assert result.status == "found"
|
|
|
|
|
|
def test_found_row_is_never_rechecked(app, art_config):
|
|
insert(
|
|
"Someone", "No Art Album", "found", days_ago=9999, image_url="https://example.com/old.jpg"
|
|
)
|
|
result = art.lookup("Someone", "No Art Album")
|
|
assert result.image_url == "https://example.com/old.jpg"
|
|
|
|
|
|
# --- fetch_image() -------------------------------------------------------------------------
|
|
|
|
|
|
def test_fetch_image_streams_the_bytes(art_config):
|
|
result = art.lookup("Radiohead", "In Rainbows")
|
|
image = art.fetch_image(result.image_url)
|
|
assert image.body == b"\xff\xd8\xff\xe0fake-jpeg-bytes"
|
|
assert image.content_type == "image/jpeg"
|
|
|
|
|
|
def test_fetch_image_raises_on_failure(art_config):
|
|
with pytest.raises(art.ArtFetchFailed):
|
|
art.fetch_image("http://127.0.0.1:1/nope.jpg")
|
|
|
|
|
|
# --- get_cached() / want() / requeue() / read_file() ----------------------------------------
|
|
|
|
|
|
def test_get_cached_returns_none_for_unseen_album(art_config):
|
|
assert art.get_cached("Nobody", "Nothing") is None
|
|
|
|
|
|
def test_get_cached_is_case_insensitive(art_config):
|
|
insert("Radiohead", "In Rainbows", "found", image_url="https://example.com/a.jpg")
|
|
assert art.get_cached("radiohead", "in rainbows").image_url == "https://example.com/a.jpg"
|
|
|
|
|
|
def test_want_creates_a_pending_row(art_config):
|
|
art.want("New Artist", "New Album")
|
|
assert row("New Artist", "New Album").status == "pending"
|
|
|
|
|
|
def test_want_is_a_noop_if_a_row_already_exists(art_config):
|
|
insert("Radiohead", "In Rainbows", "found", image_url="https://example.com/a.jpg")
|
|
art.want("Radiohead", "In Rainbows")
|
|
assert row("Radiohead", "In Rainbows").status == "found" # untouched, not reset to pending
|
|
|
|
|
|
def test_read_file_returns_none_when_not_downloaded(art_config):
|
|
assert art.read_file(999_999) is None
|
|
|
|
|
|
def test_read_file_returns_the_bytes(app, art_config):
|
|
path = pathlib.Path(app.config["ART_STORAGE_DIR"]) / "123.jpg"
|
|
path.write_bytes(b"hello")
|
|
assert art.read_file(123) == b"hello"
|
|
|
|
|
|
def test_requeue_marks_a_row_pending(art_config):
|
|
insert("Someone", "Old Album", "found", image_url="https://example.com/a.jpg")
|
|
art.requeue(row("Someone", "Old Album"))
|
|
assert row("Someone", "Old Album").status == "pending"
|
|
|
|
|
|
# --- resolve_one_pending() (the worker task) ------------------------------------------------
|
|
|
|
|
|
def test_resolve_one_pending_resolves_and_downloads(art_config):
|
|
art.want("Radiohead", "In Rainbows")
|
|
assert art.resolve_one_pending() is True
|
|
cached = row("Radiohead", "In Rainbows")
|
|
assert cached.status == "found"
|
|
assert art.read_file(cached.id) == b"\xff\xd8\xff\xe0fake-jpeg-bytes"
|
|
|
|
|
|
def test_resolve_one_pending_handles_not_found(art_config):
|
|
art.want("Nobody", "Nothing")
|
|
assert art.resolve_one_pending() is True
|
|
assert row("Nobody", "Nothing").status == "not_found"
|
|
|
|
|
|
def test_resolve_one_pending_handles_upstream_error(art_config):
|
|
art.want("Someone", "Boom Album")
|
|
assert art.resolve_one_pending() is True
|
|
cached = row("Someone", "Boom Album")
|
|
assert cached.status == "error"
|
|
assert cached.error_code
|
|
|
|
|
|
def test_resolve_one_pending_download_failure_is_cached_as_error(art_config):
|
|
art.want("Someone", "Download Fail Album")
|
|
assert art.resolve_one_pending() is True
|
|
cached = row("Someone", "Download Fail Album")
|
|
assert cached.status == "error" # not left "found" with no file on disk
|
|
assert art.read_file(cached.id) is None
|
|
|
|
|
|
def test_resolve_one_pending_returns_false_when_nothing_to_do(art_config):
|
|
assert art.resolve_one_pending() is False
|
|
|
|
|
|
def test_resolve_one_pending_picks_up_stale_not_found(art_config):
|
|
insert("Radiohead", "In Rainbows", "not_found", days_ago=31)
|
|
assert art.resolve_one_pending() is True
|
|
assert row("Radiohead", "In Rainbows").status == "found"
|
|
|
|
|
|
def test_resolve_one_pending_picks_up_stale_error(art_config):
|
|
db.session.add(
|
|
AlbumArt(
|
|
artist="Radiohead",
|
|
album="In Rainbows",
|
|
status="error",
|
|
error_code="TimeoutError",
|
|
checked_at=datetime.now(UTC) - timedelta(hours=2),
|
|
)
|
|
)
|
|
db.session.commit()
|
|
assert art.resolve_one_pending() is True
|
|
assert row("Radiohead", "In Rainbows").status == "found"
|
|
|
|
|
|
def test_resolve_one_pending_ignores_fresh_not_found(art_config):
|
|
insert("Radiohead", "In Rainbows", "not_found", days_ago=1)
|
|
assert art.resolve_one_pending() is False
|
|
|
|
|
|
# --- GET /api/v1/art/album -------------------------------------------------------------------
|
|
|
|
|
|
def test_album_art_requires_auth(client):
|
|
assert client.get("/api/v1/art/album?artist=A&album=B").status_code == 401
|
|
|
|
|
|
def test_album_art_requires_artist_and_album(client, auth):
|
|
assert client.get("/api/v1/art/album?artist=A", headers=auth).status_code == 422
|
|
assert client.get("/api/v1/art/album?album=B", headers=auth).status_code == 422
|
|
|
|
|
|
def test_album_art_404s_and_queues_an_unseen_album(client, auth, art_config):
|
|
response = client.get("/api/v1/art/album?artist=New+Artist&album=New+Album", headers=auth)
|
|
assert response.status_code == 404
|
|
assert response.get_json()["error"]["code"] == "no_album_art"
|
|
assert row("New Artist", "New Album").status == "pending"
|
|
|
|
|
|
def test_album_art_never_calls_the_network(client, auth, app, art_config):
|
|
# Point at a port nothing listens on: the endpoint must still respond (fast, 404)
|
|
# without ever trying to reach it — proof it's a cache-only read.
|
|
app.config.update(
|
|
MUSICBRAINZ_API_URL="http://127.0.0.1:1/", COVERART_API_URL="http://127.0.0.1:1/"
|
|
)
|
|
response = client.get("/api/v1/art/album?artist=Another&album=Album", headers=auth)
|
|
assert response.status_code == 404
|
|
|
|
|
|
def test_album_art_404s_while_pending(client, auth, art_config):
|
|
art.want("Radiohead", "In Rainbows")
|
|
response = client.get("/api/v1/art/album?artist=Radiohead&album=In+Rainbows", headers=auth)
|
|
assert response.status_code == 404
|
|
|
|
|
|
def test_album_art_returns_the_image_once_resolved(client, auth, art_config):
|
|
art.want("Radiohead", "In Rainbows")
|
|
art.resolve_one_pending()
|
|
response = client.get("/api/v1/art/album?artist=Radiohead&album=In+Rainbows", headers=auth)
|
|
assert response.status_code == 200
|
|
assert response.data == b"\xff\xd8\xff\xe0fake-jpeg-bytes"
|
|
assert response.content_type == "image/jpeg"
|
|
assert response.headers["Cache-Control"] == "private, max-age=604800"
|
|
|
|
|
|
def test_album_art_404s_when_resolved_not_found(client, auth, art_config):
|
|
art.want("Nobody", "Nothing")
|
|
art.resolve_one_pending()
|
|
response = client.get("/api/v1/art/album?artist=Nobody&album=Nothing", headers=auth)
|
|
assert response.status_code == 404
|
|
|
|
|
|
def test_album_art_requeues_a_found_row_with_a_missing_file(client, auth, art_config):
|
|
insert("Legacy", "Album", "found", image_url="https://example.com/old.jpg")
|
|
response = client.get("/api/v1/art/album?artist=Legacy&album=Album", headers=auth)
|
|
assert response.status_code == 404
|
|
assert row("Legacy", "Album").status == "pending" # requeued for the worker to redo
|
|
|
|
|
|
# --- metrics ------------------------------------------------------------------------------
|
|
|
|
|
|
def test_worker_counts_resolutions_and_times_upstreams(art_config, metric_delta):
|
|
found = metric_delta("scrobbler_art_resolutions_total", source="worker", result="found")
|
|
resolve = metric_delta("scrobbler_art_worker_resolve_seconds_count")
|
|
image = metric_delta("scrobbler_art_image_bytes_count")
|
|
musicbrainz = metric_delta(
|
|
"scrobbler_art_upstream_seconds_count", service="musicbrainz", outcome="ok"
|
|
)
|
|
download = metric_delta(
|
|
"scrobbler_art_upstream_seconds_count", service="download", outcome="ok"
|
|
)
|
|
art.want("Radiohead", "In Rainbows")
|
|
art.resolve_one_pending()
|
|
assert (found.delta, resolve.delta, image.delta) == (1, 1, 1)
|
|
assert musicbrainz.delta == 1
|
|
assert download.delta == 1
|
|
|
|
|
|
def test_worker_counts_download_failure_as_one_error(art_config, metric_delta):
|
|
errors = metric_delta("scrobbler_art_resolutions_total", source="worker", result="error")
|
|
found = metric_delta("scrobbler_art_resolutions_total", source="worker", result="found")
|
|
failed = metric_delta(
|
|
"scrobbler_art_upstream_errors_total", service="download", error="HTTPError"
|
|
)
|
|
art.want("Someone", "Download Fail Album")
|
|
art.resolve_one_pending()
|
|
assert (errors.delta, found.delta) == (1, 0)
|
|
assert failed.delta == 1
|
|
|
|
|
|
def test_endpoint_counts_queued_pending_and_unavailable(client, auth, art_config, metric_delta):
|
|
queued = metric_delta("scrobbler_art_requests_total", result="queued")
|
|
pending = metric_delta("scrobbler_art_requests_total", result="pending")
|
|
unavailable = metric_delta("scrobbler_art_requests_total", result="unavailable")
|
|
url = "/api/v1/art/album?artist=Nobody&album=Nothing"
|
|
client.get(url, headers=auth)
|
|
client.get(url, headers=auth)
|
|
art.resolve_one_pending()
|
|
client.get(url, headers=auth)
|
|
assert (queued.delta, pending.delta, unavailable.delta) == (1, 1, 1)
|
|
|
|
|
|
def test_endpoint_counts_served(client, auth, art_config, metric_delta):
|
|
served = metric_delta("scrobbler_art_requests_total", result="served")
|
|
url = "/api/v1/art/album?artist=Radiohead&album=In+Rainbows"
|
|
client.get(url, headers=auth)
|
|
art.resolve_one_pending()
|
|
assert client.get(url, headers=auth).status_code == 200
|
|
assert served.delta == 1
|
|
|
|
|
|
# --- per-user overrides (service + worker) ----------------------------------------------
|
|
|
|
BASE = int(time.time()) - 3600
|
|
JPEG = b"\xff\xd8\xff\xe0my-own-art"
|
|
|
|
|
|
def override(user, artist, album):
|
|
return art.get_override(user.id, artist, album)
|
|
|
|
|
|
def scrobble_album(user, artist, album, count=1, base=None):
|
|
scrobbles.submit_scrobbles(
|
|
user,
|
|
None,
|
|
[
|
|
TrackInput(artist=artist, track=f"t{i}", album=album, timestamp=(base or BASE) + i)
|
|
for i in range(count)
|
|
],
|
|
)
|
|
|
|
|
|
def test_sniff_image_type():
|
|
assert art.sniff_image_type(JPEG) == "image/jpeg"
|
|
assert art.sniff_image_type(b"\x89PNG\r\n\x1a\n....") == "image/png"
|
|
assert art.sniff_image_type(b"RIFF\x00\x00\x00\x00WEBPVP8 ") == "image/webp"
|
|
with pytest.raises(art.UnsupportedImage):
|
|
art.sniff_image_type(b"GIF89a")
|
|
|
|
|
|
def test_save_upload_stores_the_file_and_replaces_it(art_config, user):
|
|
art.save_upload(user.id, "Nobody", "Nothing", JPEG, "image/jpeg")
|
|
first = override(user, "nobody", "NOTHING") # case-insensitive
|
|
assert (first.kind, first.status, first.content_type) == ("upload", "found", "image/jpeg")
|
|
assert art.read_override_file(first) == JPEG
|
|
art.save_upload(user.id, "Nobody", "Nothing", b"\x89PNG\r\n\x1a\nnew", "image/png")
|
|
second = override(user, "Nobody", "Nothing")
|
|
assert second.id == first.id
|
|
assert art.read_override_file(second).endswith(b"new")
|
|
assert second.content_type == "image/png"
|
|
|
|
|
|
def test_overrides_are_per_user(art_config, user, make_user):
|
|
other = make_user(username="mallory")
|
|
art.save_upload(user.id, "Nobody", "Nothing", JPEG, "image/jpeg")
|
|
assert override(other, "Nobody", "Nothing") is None
|
|
|
|
|
|
def test_delete_override_removes_row_and_file(art_config, user):
|
|
art.save_upload(user.id, "Nobody", "Nothing", JPEG, "image/jpeg")
|
|
row_id = override(user, "Nobody", "Nothing").id
|
|
assert art.delete_override(user.id, "Nobody", "Nothing") is True
|
|
assert override(user, "Nobody", "Nothing") is None
|
|
assert not art._override_path(row_id).exists()
|
|
assert art.delete_override(user.id, "Nobody", "Nothing") is False
|
|
|
|
|
|
def test_retry_requeues_failures_only(art_config):
|
|
insert("A", "Failed", "not_found")
|
|
insert("A", "Fine", "found")
|
|
assert art.retry("A", "Failed") is True
|
|
assert row("A", "Failed").status == "pending"
|
|
assert art.retry("A", "Fine") is False
|
|
assert art.retry("Brand", "New") is True
|
|
assert row("Brand", "New").status == "pending"
|
|
|
|
|
|
def test_correction_by_mbid_is_resolved_by_the_worker(art_config, user, metric_delta):
|
|
resolved = metric_delta(
|
|
"scrobbler_art_correction_resolutions_total", input="mbid", result="found"
|
|
)
|
|
wait = metric_delta("scrobbler_art_correction_wait_seconds_count")
|
|
art.request_correction(user.id, "Radiohead", "Inrainbows", None, None, "rg-found")
|
|
assert override(user, "Radiohead", "Inrainbows").status == "pending"
|
|
assert art.resolve_one_pending() is True
|
|
fixed = override(user, "Radiohead", "Inrainbows")
|
|
assert (fixed.status, fixed.content_type) == ("found", "image/jpeg")
|
|
assert art.read_override_file(fixed) == b"\xff\xd8\xff\xe0fake-jpeg-bytes"
|
|
assert (resolved.delta, wait.delta) == (1, 1)
|
|
|
|
|
|
def test_correction_by_search_text_is_resolved_by_the_worker(art_config, user, metric_delta):
|
|
resolved = metric_delta(
|
|
"scrobbler_art_correction_resolutions_total", input="search", result="found"
|
|
)
|
|
art.request_correction(user.id, "Radiohead", "Inrainbows", "Radiohead", "In Rainbows", None)
|
|
art.resolve_one_pending()
|
|
assert override(user, "Radiohead", "Inrainbows").status == "found"
|
|
assert resolved.delta == 1
|
|
|
|
|
|
def test_correction_that_finds_nothing_is_an_error_on_the_override(art_config, user, metric_delta):
|
|
nothing = metric_delta(
|
|
"scrobbler_art_correction_resolutions_total", input="search", result="not_found"
|
|
)
|
|
art.request_correction(user.id, "Nobody", "Nothing", "Nobody", "Still Nothing", None)
|
|
art.resolve_one_pending()
|
|
failed = override(user, "Nobody", "Nothing")
|
|
assert (failed.status, failed.error_code) == ("error", "NotFound")
|
|
assert nothing.delta == 1
|
|
|
|
|
|
def test_correction_with_a_failing_upstream_records_the_error(art_config, user):
|
|
art.request_correction(user.id, "Someone", "Boom", None, None, "rg-boom")
|
|
art.resolve_one_pending()
|
|
failed = override(user, "Someone", "Boom")
|
|
assert (failed.status, failed.error_code) == ("error", "HTTPError")
|
|
|
|
|
|
def test_worker_resolves_corrections_before_the_global_queue(art_config, user):
|
|
art.want("Radiohead", "In Rainbows")
|
|
art.request_correction(user.id, "X", "Y", None, None, "rg-found")
|
|
art.resolve_one_pending()
|
|
assert override(user, "X", "Y").status == "found"
|
|
assert row("Radiohead", "In Rainbows").status == "pending"
|
|
|
|
|
|
def test_failures_lists_only_the_users_failed_albums(art_config, user, make_user):
|
|
other = make_user(username="mallory")
|
|
scrobble_album(user, "A", "Missing", count=3)
|
|
scrobble_album(user, "A", "Fine", count=1)
|
|
scrobble_album(user, "A", "Unlooked", count=1)
|
|
scrobble_album(other, "B", "Theirs", count=1)
|
|
insert("A", "Missing", "not_found")
|
|
insert("A", "Fine", "found")
|
|
insert("B", "Theirs", "error")
|
|
items, total = art.list_failures(user.id, 1, 50)
|
|
assert total == 1
|
|
assert [(i["artist"], i["album"], i["scrobbles"], i["status"]) for i in items] == [
|
|
("A", "Missing", 3, "not_found")
|
|
]
|
|
assert items[0]["override"] is None
|
|
|
|
|
|
def test_failures_drops_fixed_albums_and_keeps_failed_corrections(art_config, user):
|
|
scrobble_album(user, "A", "Uploaded")
|
|
scrobble_album(user, "A", "Wrong", base=BASE + 500)
|
|
insert("A", "Uploaded", "not_found")
|
|
insert("A", "Wrong", "not_found")
|
|
art.save_upload(user.id, "A", "Uploaded", JPEG, "image/jpeg")
|
|
art.request_correction(user.id, "A", "Wrong", None, None, "rg-boom")
|
|
art.resolve_one_pending()
|
|
items, total = art.list_failures(user.id, 1, 50)
|
|
assert total == 1
|
|
assert items[0]["album"] == "Wrong"
|
|
assert (items[0]["override"]["status"], items[0]["override"]["kind"]) == ("error", "correction")
|
|
|
|
|
|
def test_failures_paginates_most_scrobbled_first(art_config, user):
|
|
for i, count in enumerate((1, 3, 2)):
|
|
scrobble_album(user, "A", f"Album {i}", count=count, base=BASE + i * 100)
|
|
insert("A", f"Album {i}", "not_found")
|
|
items, total = art.list_failures(user.id, 1, 2)
|
|
assert (total, [i["album"] for i in items]) == (3, ["Album 1", "Album 2"])
|
|
items, _ = art.list_failures(user.id, 2, 2)
|
|
assert [i["album"] for i in items] == ["Album 0"]
|
|
|
|
|
|
# --- per-user override endpoints -----------------------------------------------------------
|
|
|
|
ALBUM = "artist=Nobody&album=Nothing"
|
|
|
|
|
|
def upload(client, auth, data=JPEG, name="cover.jpg", query=ALBUM):
|
|
return client.post(
|
|
f"/api/v1/art/album?{query}",
|
|
headers=auth,
|
|
data={"file": (io.BytesIO(data), name)},
|
|
content_type="multipart/form-data",
|
|
)
|
|
|
|
|
|
def test_upload_requires_auth(client):
|
|
assert client.post(f"/api/v1/art/album?{ALBUM}").status_code == 401
|
|
|
|
|
|
def test_upload_then_get_serves_the_users_image(client, auth, art_config, metric_delta):
|
|
ok = metric_delta("scrobbler_art_uploads_total", result="ok")
|
|
size = metric_delta("scrobbler_art_upload_bytes_count")
|
|
served = metric_delta("scrobbler_art_requests_total", result="override")
|
|
response = upload(client, auth)
|
|
assert response.status_code == 201
|
|
assert response.get_json()["status"] == "found"
|
|
image = client.get(f"/api/v1/art/album?{ALBUM}", headers=auth)
|
|
assert image.status_code == 200
|
|
assert image.data == JPEG
|
|
assert image.mimetype == "image/jpeg"
|
|
assert image.headers["Cache-Control"] == "private, no-cache"
|
|
assert (ok.delta, size.delta, served.delta) == (1, 1, 1)
|
|
|
|
|
|
def test_override_response_supports_conditional_requests(client, auth, art_config):
|
|
upload(client, auth)
|
|
first = client.get(f"/api/v1/art/album?{ALBUM}", headers=auth)
|
|
again = client.get(
|
|
f"/api/v1/art/album?{ALBUM}", headers={**auth, "If-None-Match": first.headers["ETag"]}
|
|
)
|
|
assert again.status_code == 304
|
|
|
|
|
|
def test_upload_keeps_the_png_content_type(client, auth, art_config):
|
|
upload(client, auth, data=b"\x89PNG\r\n\x1a\nxxxx", name="c.png")
|
|
assert client.get(f"/api/v1/art/album?{ALBUM}", headers=auth).mimetype == "image/png"
|
|
|
|
|
|
def test_upload_beats_the_shared_cache(client, auth, art_config):
|
|
insert("Nobody", "Nothing", "not_found")
|
|
upload(client, auth)
|
|
assert client.get(f"/api/v1/art/album?{ALBUM}", headers=auth).data == JPEG
|
|
|
|
|
|
def test_upload_is_only_visible_to_its_owner(client, auth, art_config, make_user):
|
|
from scrobbler.services.accounts import issue_ui_token
|
|
|
|
upload(client, auth)
|
|
token = issue_ui_token(make_user(username="mallory"))
|
|
other = client.get(f"/api/v1/art/album?{ALBUM}", headers={"Authorization": f"Bearer {token}"})
|
|
assert other.status_code == 404
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("data", "status", "result"),
|
|
[(b"", 400, "empty"), (b"GIF89a....", 415, "bad_type"), (JPEG + b"x" * 100, 413, "too_large")],
|
|
)
|
|
def test_upload_rejects_bad_files(
|
|
client, auth, app, art_config, metric_delta, data, status, result
|
|
):
|
|
app.config["ART_UPLOAD_MAX_BYTES"] = 50
|
|
try:
|
|
counted = metric_delta("scrobbler_art_uploads_total", result=result)
|
|
assert upload(client, auth, data=data).status_code == status
|
|
assert counted.delta == 1
|
|
assert override_row() is None
|
|
finally:
|
|
app.config["ART_UPLOAD_MAX_BYTES"] = 5 * 1024 * 1024
|
|
|
|
|
|
def override_row():
|
|
return db.session.scalar(db.select(UserAlbumArt))
|
|
|
|
|
|
def test_upload_requires_artist_and_album(client, auth, art_config):
|
|
assert upload(client, auth, query="artist=A").status_code == 422
|
|
|
|
|
|
def test_delete_override_reverts_to_the_shared_cache(client, auth, art_config, metric_delta):
|
|
deleted = metric_delta("scrobbler_art_override_actions_total", action="override_deleted")
|
|
upload(client, auth)
|
|
assert client.delete(f"/api/v1/art/album?{ALBUM}", headers=auth).status_code == 204
|
|
assert client.get(f"/api/v1/art/album?{ALBUM}", headers=auth).status_code == 404
|
|
assert client.delete(f"/api/v1/art/album?{ALBUM}", headers=auth).status_code == 404
|
|
assert deleted.delta == 1
|
|
|
|
|
|
def test_correction_is_queued_without_touching_the_network(
|
|
client, auth, app, art_config, metric_delta
|
|
):
|
|
app.config.update(
|
|
MUSICBRAINZ_API_URL="http://127.0.0.1:1/", COVERART_API_URL="http://127.0.0.1:1/"
|
|
)
|
|
queued = metric_delta("scrobbler_art_override_actions_total", action="correction_requested")
|
|
response = client.put(
|
|
"/api/v1/art/album/correction",
|
|
headers=auth,
|
|
json={"artist": "Radiohead", "album": "Inrainbows", "search_album": "In Rainbows"},
|
|
)
|
|
assert response.status_code == 202
|
|
body = response.get_json()
|
|
assert (body["kind"], body["status"], body["search_album"]) == (
|
|
"correction",
|
|
"pending",
|
|
"In Rainbows",
|
|
)
|
|
assert queued.delta == 1
|
|
|
|
|
|
def test_correction_then_worker_then_get(client, auth, art_config):
|
|
url = "/api/v1/art/album?artist=Radiohead&album=Inrainbows"
|
|
client.put(
|
|
"/api/v1/art/album/correction",
|
|
headers=auth,
|
|
json={"artist": "Radiohead", "album": "Inrainbows", "release_group_mbid": FOUND_MBID},
|
|
)
|
|
assert client.get(url, headers=auth).status_code == 404 # not resolved yet
|
|
art.resolve_one_pending()
|
|
assert client.get(url, headers=auth).data == b"\xff\xd8\xff\xe0fake-jpeg-bytes"
|
|
|
|
|
|
def test_correction_needs_something_to_correct_and_a_valid_mbid(client, auth):
|
|
url = "/api/v1/art/album/correction"
|
|
assert client.put(url, headers=auth, json={"artist": "A", "album": "B"}).status_code == 422
|
|
bad = {"artist": "A", "album": "B", "release_group_mbid": "nope"}
|
|
assert client.put(url, headers=auth, json=bad).status_code == 422
|
|
|
|
|
|
def test_retry_requeues_a_failed_lookup(client, auth, art_config, metric_delta):
|
|
retried = metric_delta("scrobbler_art_override_actions_total", action="retry_requested")
|
|
insert("Nobody", "Nothing", "not_found")
|
|
assert client.post(f"/api/v1/art/album/retry?{ALBUM}", headers=auth).status_code == 202
|
|
assert row("Nobody", "Nothing").status == "pending"
|
|
assert client.post(f"/api/v1/art/album/retry?{ALBUM}", headers=auth).status_code == 409
|
|
assert retried.delta == 1
|
|
|
|
|
|
def test_failures_endpoint(client, auth, art_config, user):
|
|
scrobble_album(user, "Nobody", "Nothing", count=2)
|
|
insert("Nobody", "Nothing", "not_found")
|
|
body = client.get("/api/v1/art/failures", headers=auth).get_json()
|
|
assert (body["total"], body["total_pages"], body["page"]) == (1, 1, 1)
|
|
assert body["items"][0]["album"] == "Nothing"
|
|
assert body["items"][0]["scrobbles"] == 2
|
|
assert body["items"][0]["override"] is None
|
|
upload(client, auth)
|
|
assert client.get("/api/v1/art/failures", headers=auth).get_json()["items"] == []
|
|
|
|
|
|
def test_failures_requires_auth(client):
|
|
assert client.get("/api/v1/art/failures").status_code == 401
|
|
|
|
|
|
def scrobble_with_mbid(user, artist, track, album, mbid):
|
|
scrobbles.submit_scrobbles(
|
|
user, None, [TrackInput(artist, track, album=album, mbid=mbid, timestamp=int(time.time()))]
|
|
)
|
|
|
|
|
|
def test_scrobble_mbid_finds_the_release_group_without_a_text_match(art_config, user, metric_delta):
|
|
# "Mbid Album" matches nothing in the fake's text search, so only the recording can find it
|
|
matched = metric_delta("scrobbler_art_mbid_lookups_total", result="matched")
|
|
scrobble_with_mbid(user, "Radiohead", "Track", "Mbid Album", RECORDING_MBID)
|
|
art.want("Radiohead", "Mbid Album")
|
|
assert art.resolve_one_pending() is True
|
|
found = row("Radiohead", "Mbid Album")
|
|
assert (found.status, found.release_group_mbid) == ("found", "rg-found")
|
|
assert matched.delta == 1
|
|
|
|
|
|
def test_scrobble_mbid_with_no_matching_release_falls_back_to_text_search(
|
|
art_config, user, metric_delta
|
|
):
|
|
missed = metric_delta("scrobbler_art_mbid_lookups_total", result="missed")
|
|
scrobble_with_mbid(user, "Radiohead", "Track", "In Rainbows", UNMATCHED_RECORDING_MBID)
|
|
art.want("Radiohead", "In Rainbows")
|
|
art.resolve_one_pending()
|
|
assert row("Radiohead", "In Rainbows").release_group_mbid == "rg-found"
|
|
assert missed.delta == 1
|
|
|
|
|
|
def test_unknown_scrobble_mbid_falls_back_to_text_search(art_config, user):
|
|
unknown = "44444444-4444-4444-4444-444444444444"
|
|
scrobble_with_mbid(user, "Radiohead", "Track", "In Rainbows", unknown)
|
|
art.want("Radiohead", "In Rainbows")
|
|
art.resolve_one_pending()
|
|
assert row("Radiohead", "In Rainbows").status == "found"
|
|
|
|
|
|
def test_no_scrobble_mbid_means_no_recording_lookup(art_config, user, metric_delta):
|
|
tried = metric_delta("scrobbler_art_mbid_lookups_total", result="missed")
|
|
scrobble_with_mbid(user, "Radiohead", "Track", "In Rainbows", None)
|
|
art.want("Radiohead", "In Rainbows")
|
|
art.resolve_one_pending()
|
|
assert row("Radiohead", "In Rainbows").status == "found"
|
|
assert tried.delta == 0
|
|
|
|
|
|
def test_correction_with_search_text_ignores_the_scrobble_mbid(art_config, user):
|
|
scrobble_with_mbid(user, "Radiohead", "Track", "Mbid Album", RECORDING_MBID)
|
|
art.request_correction(user.id, "Radiohead", "Mbid Album", None, "No Art Album", None)
|
|
art.resolve_one_pending()
|
|
assert override(user, "Radiohead", "Mbid Album").status == "error" # searched the text given
|
|
|
|
|
|
def test_correction_by_release_mbid_is_resolved_from_the_release(art_config, user, metric_delta):
|
|
resolved = metric_delta(
|
|
"scrobbler_art_correction_resolutions_total", input="release_mbid", result="found"
|
|
)
|
|
art.request_correction(user.id, "Radiohead", "Inrainbows", None, None, None, FOUND_MBID)
|
|
assert art.resolve_one_pending() is True
|
|
fixed = override(user, "Radiohead", "Inrainbows")
|
|
assert (fixed.status, fixed.release_mbid) == ("found", FOUND_MBID)
|
|
assert art.read_override_file(fixed) == b"\xff\xd8\xff\xe0fake-jpeg-bytes"
|
|
assert resolved.delta == 1
|
|
|
|
|
|
def test_correction_api_accepts_a_release_mbid_but_not_both_ids(client, auth):
|
|
url = "/api/v1/art/album/correction"
|
|
ok = {"artist": "A", "album": "B", "release_mbid": FOUND_MBID}
|
|
response = client.put(url, headers=auth, json=ok)
|
|
assert response.status_code == 202
|
|
assert response.get_json()["release_mbid"] == FOUND_MBID
|
|
both = {**ok, "release_group_mbid": FOUND_MBID}
|
|
assert client.put(url, headers=auth, json=both).status_code == 422
|
|
bad = {"artist": "A", "album": "B", "release_mbid": "nope"}
|
|
assert client.put(url, headers=auth, json=bad).status_code == 422
|