| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import os |
| 4 |
import shutil |
| 5 |
import tempfile |
| 6 |
import unittest |
| 7 |
from pathlib import Path |
| 8 |
from typing import TYPE_CHECKING |
| 9 |
from unittest.mock import MagicMock, patch |
| 10 |
|
| 11 |
import pytest |
| 12 |
from mediafile import MediaFile |
| 13 |
|
| 14 |
from beets import config, logging |
| 15 |
from beets.exceptions import UserError |
| 16 |
from beets.test import _common |
| 17 |
from beets.test.fixtures import DummyIMBackend |
| 18 |
from beets.test.helper import ( |
| 19 |
NEEDS_FFPROBE, |
| 20 |
FetchImageHelper, |
| 21 |
ImportHelper, |
| 22 |
IOMixin, |
| 23 |
PluginMixin, |
| 24 |
) |
| 25 |
from beets.util.artresizer import ArtResizer |
| 26 |
from beetsplug._utils import art |
| 27 |
|
| 28 |
if TYPE_CHECKING: |
| 29 |
from beets.test.helper import ImageRequestMocker |
| 30 |
|
| 31 |
|
| 32 |
def require_artresizer_compare(test): |
| 33 |
def wrapper(*args, **kwargs): |
| 34 |
if not ArtResizer.shared.can_compare: |
| 35 |
raise unittest.SkipTest("compare not available") |
| 36 |
|
| 37 |
# PHASH computation in ImageMagick changed at some point in an |
| 38 |
# undocumented way. Check at a low level that comparisons of our |
| 39 |
# fixtures give the expected results. Only then, plugin logic tests |
| 40 |
# below are meaningful. |
| 41 |
# cf. https://github.com/ImageMagick/ImageMagick/discussions/5191 |
| 42 |
# It would be better to investigate what exactly change in IM and |
| 43 |
# handle that in ArtResizer.IMBackend.{can_compare,compare}. |
| 44 |
# Skipping the tests as below is a quick fix to CI, but users may |
| 45 |
# still see unexpected behaviour. |
| 46 |
abbey_artpath = _common.RSRC / "abbey.jpg" |
| 47 |
abbey_similarpath = _common.RSRC / "abbey-similar.jpg" |
| 48 |
abbey_differentpath = _common.RSRC / "abbey-different.jpg" |
| 49 |
compare_threshold = 20 |
| 50 |
|
| 51 |
similar_compares_ok = ArtResizer.shared.compare( |
| 52 |
abbey_artpath, abbey_similarpath, compare_threshold |
| 53 |
) |
| 54 |
different_compares_ok = ArtResizer.shared.compare( |
| 55 |
abbey_artpath, abbey_differentpath, compare_threshold |
| 56 |
) |
| 57 |
if not similar_compares_ok or different_compares_ok: |
| 58 |
raise unittest.SkipTest("IM version with broken compare") |
| 59 |
|
| 60 |
return test(*args, **kwargs) |
| 61 |
|
| 62 |
wrapper.__name__ = test.__name__ |
| 63 |
return wrapper |
| 64 |
|
| 65 |
|
| 66 |
class TestEmbedartCli(PluginMixin, IOMixin, ImportHelper, FetchImageHelper): |
| 67 |
plugin = "embedart" |
| 68 |
small_artpath = _common.RSRC / "image-2x3.jpg" |
| 69 |
abbey_artpath = _common.RSRC / "abbey.jpg" |
| 70 |
abbey_similarpath = _common.RSRC / "abbey-similar.jpg" |
| 71 |
abbey_differentpath = _common.RSRC / "abbey-different.jpg" |
| 72 |
|
| 73 |
def _setup_data(self, artpath=None): |
| 74 |
if not artpath: |
| 75 |
artpath = self.small_artpath |
| 76 |
self.image_data = artpath.read_bytes() |
| 77 |
|
| 78 |
def test_embed_art_from_file_with_yes_input(self): |
| 79 |
self._setup_data() |
| 80 |
album = self.add_album_fixture() |
| 81 |
item = album.items()[0] |
| 82 |
self.io.addinput("y") |
| 83 |
self.run_command("embedart", "-f", self.small_artpath) |
| 84 |
mediafile = MediaFile(item.filepath) |
| 85 |
assert mediafile.images[0].data == self.image_data |
| 86 |
|
| 87 |
def test_embed_art_from_file_with_no_input(self): |
| 88 |
self._setup_data() |
| 89 |
album = self.add_album_fixture() |
| 90 |
item = album.items()[0] |
| 91 |
self.io.addinput("n") |
| 92 |
self.run_command("embedart", "-f", self.small_artpath) |
| 93 |
mediafile = MediaFile(item.filepath) |
| 94 |
# make sure that images array is empty (nothing embedded) |
| 95 |
assert not mediafile.images |
| 96 |
|
| 97 |
def test_embed_art_from_file(self): |
| 98 |
self._setup_data() |
| 99 |
album = self.add_album_fixture() |
| 100 |
item = album.items()[0] |
| 101 |
self.run_command("embedart", "-y", "-f", self.small_artpath) |
| 102 |
mediafile = MediaFile(item.filepath) |
| 103 |
assert mediafile.images[0].data == self.image_data |
| 104 |
|
| 105 |
def test_embed_art_from_album(self): |
| 106 |
self._setup_data() |
| 107 |
album = self.add_album_fixture() |
| 108 |
item = album.items()[0] |
| 109 |
album.artpath = self.small_artpath |
| 110 |
album.store() |
| 111 |
self.run_command("embedart", "-y") |
| 112 |
mediafile = MediaFile(item.filepath) |
| 113 |
assert mediafile.images[0].data == self.image_data |
| 114 |
|
| 115 |
def test_embed_art_remove_art_file(self): |
| 116 |
self._setup_data() |
| 117 |
album = self.add_album_fixture() |
| 118 |
|
| 119 |
logging.getLogger("beets.embedart").setLevel(logging.DEBUG) |
| 120 |
|
| 121 |
handle, tmp_path = tempfile.mkstemp() |
| 122 |
tmp_path = Path(tmp_path) |
| 123 |
os.write(handle, self.image_data) |
| 124 |
os.close(handle) |
| 125 |
|
| 126 |
album.artpath = tmp_path |
| 127 |
album.store() |
| 128 |
|
| 129 |
config["embedart"]["remove_art_file"] = True |
| 130 |
self.run_command("embedart", "-y") |
| 131 |
|
| 132 |
if tmp_path.is_file(): |
| 133 |
tmp_path.unlink() |
| 134 |
pytest.fail(f"Artwork file {tmp_path} was not deleted") |
| 135 |
|
| 136 |
def test_art_file_missing(self): |
| 137 |
self.add_album_fixture() |
| 138 |
logging.getLogger("beets.embedart").setLevel(logging.DEBUG) |
| 139 |
with pytest.raises(UserError): |
| 140 |
self.run_command("embedart", "-y", "-f", "/doesnotexist") |
| 141 |
|
| 142 |
def test_embed_non_image_file(self): |
| 143 |
album = self.add_album_fixture() |
| 144 |
logging.getLogger("beets.embedart").setLevel(logging.DEBUG) |
| 145 |
|
| 146 |
handle, tmp_path = tempfile.mkstemp() |
| 147 |
tmp_path = Path(tmp_path) |
| 148 |
os.write(handle, b"I am not an image.") |
| 149 |
os.close(handle) |
| 150 |
|
| 151 |
try: |
| 152 |
self.run_command("embedart", "-y", "-f", tmp_path) |
| 153 |
finally: |
| 154 |
tmp_path.unlink() |
| 155 |
|
| 156 |
mediafile = MediaFile(album.items()[0].filepath) |
| 157 |
assert not mediafile.images # No image added. |
| 158 |
|
| 159 |
@require_artresizer_compare |
| 160 |
def test_reject_different_art(self): |
| 161 |
self._setup_data(self.abbey_artpath) |
| 162 |
album = self.add_album_fixture() |
| 163 |
item = album.items()[0] |
| 164 |
self.run_command("embedart", "-y", "-f", self.abbey_artpath) |
| 165 |
config["embedart"]["compare_threshold"] = 20 |
| 166 |
self.run_command("embedart", "-y", "-f", self.abbey_differentpath) |
| 167 |
mediafile = MediaFile(item.filepath) |
| 168 |
|
| 169 |
assert mediafile.images[0].data == self.image_data, ( |
| 170 |
f"Image written is not {self.abbey_artpath}" |
| 171 |
) |
| 172 |
|
| 173 |
@require_artresizer_compare |
| 174 |
def test_accept_similar_art(self): |
| 175 |
self._setup_data(self.abbey_similarpath) |
| 176 |
album = self.add_album_fixture() |
| 177 |
item = album.items()[0] |
| 178 |
self.run_command("embedart", "-y", "-f", self.abbey_artpath) |
| 179 |
config["embedart"]["compare_threshold"] = 20 |
| 180 |
self.run_command("embedart", "-y", "-f", self.abbey_similarpath) |
| 181 |
mediafile = MediaFile(item.filepath) |
| 182 |
|
| 183 |
assert mediafile.images[0].data == self.image_data, ( |
| 184 |
f"Image written is not {self.abbey_similarpath}" |
| 185 |
) |
| 186 |
|
| 187 |
def test_non_ascii_album_path(self): |
| 188 |
resource_path = _common.RSRC / "image.mp3" |
| 189 |
album = self.add_album_fixture() |
| 190 |
trackpath = album.items()[0].filepath |
| 191 |
shutil.copy(resource_path, trackpath) |
| 192 |
|
| 193 |
self.run_command("extractart", "-a", "-n", "extracted") |
| 194 |
|
| 195 |
assert (album.filepath / "extracted.png").exists() |
| 196 |
|
| 197 |
def test_extracted_extension(self): |
| 198 |
resource_path = _common.RSRC / "image-jpeg.mp3" |
| 199 |
album = self.add_album_fixture() |
| 200 |
trackpath = album.items()[0].filepath |
| 201 |
shutil.copy(resource_path, trackpath) |
| 202 |
|
| 203 |
self.run_command("extractart", "-a", "-n", "extracted") |
| 204 |
|
| 205 |
assert (album.filepath / "extracted.jpg").exists() |
| 206 |
|
| 207 |
def test_clear_art_with_yes_input(self): |
| 208 |
self._setup_data() |
| 209 |
album = self.add_album_fixture() |
| 210 |
item = album.items()[0] |
| 211 |
self.io.addinput("y") |
| 212 |
self.run_command("embedart", "-f", self.small_artpath) |
| 213 |
embedded_time = item.filepath.stat().st_mtime |
| 214 |
|
| 215 |
self.io.addinput("y") |
| 216 |
self.run_command("clearart") |
| 217 |
mediafile = MediaFile(item.filepath) |
| 218 |
assert not mediafile.images |
| 219 |
clear_time = item.filepath.stat().st_mtime |
| 220 |
assert clear_time > embedded_time |
| 221 |
|
| 222 |
# A run on a file without an image should not be modified |
| 223 |
self.io.addinput("y") |
| 224 |
self.run_command("clearart") |
| 225 |
no_clear_time = item.filepath.stat().st_mtime |
| 226 |
assert no_clear_time == clear_time |
| 227 |
|
| 228 |
def test_clear_art_with_no_input(self): |
| 229 |
self._setup_data() |
| 230 |
album = self.add_album_fixture() |
| 231 |
item = album.items()[0] |
| 232 |
self.io.addinput("y") |
| 233 |
self.run_command("embedart", "-f", self.small_artpath) |
| 234 |
self.io.addinput("n") |
| 235 |
self.run_command("clearart") |
| 236 |
mediafile = MediaFile(item.filepath) |
| 237 |
assert mediafile.images[0].data == self.image_data |
| 238 |
|
| 239 |
def test_embed_art_from_url_with_yes_input( |
| 240 |
self, image_request_mock: ImageRequestMocker |
| 241 |
): |
| 242 |
self._setup_data() |
| 243 |
album = self.add_album_fixture() |
| 244 |
item = album.items()[0] |
| 245 |
image_request_mock.get( |
| 246 |
"http://example.com/test.jpg", content_type="image/jpeg" |
| 247 |
) |
| 248 |
self.io.addinput("y") |
| 249 |
self.run_command("embedart", "-u", "http://example.com/test.jpg") |
| 250 |
mediafile = MediaFile(item.filepath) |
| 251 |
assert mediafile.images[0].data == image_request_mock.IMAGE_HEADERS[ |
| 252 |
"image/jpeg" |
| 253 |
].ljust(32, b"\x00") |
| 254 |
|
| 255 |
def test_embed_art_from_url_png( |
| 256 |
self, image_request_mock: ImageRequestMocker |
| 257 |
): |
| 258 |
self._setup_data() |
| 259 |
album = self.add_album_fixture() |
| 260 |
item = album.items()[0] |
| 261 |
image_request_mock.get( |
| 262 |
"http://example.com/test.png", content_type="image/png" |
| 263 |
) |
| 264 |
self.run_command("embedart", "-y", "-u", "http://example.com/test.png") |
| 265 |
mediafile = MediaFile(item.filepath) |
| 266 |
assert mediafile.images[0].data == image_request_mock.IMAGE_HEADERS[ |
| 267 |
"image/png" |
| 268 |
].ljust(32, b"\x00") |
| 269 |
|
| 270 |
def test_embed_art_from_url_not_image( |
| 271 |
self, image_request_mock: ImageRequestMocker |
| 272 |
): |
| 273 |
self._setup_data() |
| 274 |
album = self.add_album_fixture() |
| 275 |
item = album.items()[0] |
| 276 |
image_request_mock.get( |
| 277 |
"http://example.com/test.html", content_type="text/html" |
| 278 |
) |
| 279 |
self.run_command("embedart", "-y", "-u", "http://example.com/test.html") |
| 280 |
mediafile = MediaFile(item.filepath) |
| 281 |
assert not mediafile.images |
| 282 |
|
| 283 |
@NEEDS_FFPROBE |
| 284 |
def test_clearart_on_import_disabled(self): |
| 285 |
file_path = self.create_mediafile_fixture( |
| 286 |
images=["jpg"], target_dir=self.import_path |
| 287 |
) |
| 288 |
self.import_media.append(file_path) |
| 289 |
with self.configure_plugin({"clearart_on_import": False}): |
| 290 |
importer = self.setup_importer(autotag=False, write=True) |
| 291 |
importer.run() |
| 292 |
|
| 293 |
item = self.lib.items()[0] |
| 294 |
assert MediaFile(item.filepath).images |
| 295 |
|
| 296 |
@NEEDS_FFPROBE |
| 297 |
def test_clearart_on_import_enabled(self): |
| 298 |
file_path = self.create_mediafile_fixture( |
| 299 |
images=["jpg"], target_dir=self.import_path |
| 300 |
) |
| 301 |
self.import_media.append(file_path) |
| 302 |
# Force re-init the plugin to register the listener |
| 303 |
self.unload_plugins() |
| 304 |
with self.configure_plugin({"clearart_on_import": True}): |
| 305 |
importer = self.setup_importer(autotag=False, write=True) |
| 306 |
importer.run() |
| 307 |
|
| 308 |
item = self.lib.items()[0] |
| 309 |
assert not MediaFile(item.filepath).images |
| 310 |
|
| 311 |
|
| 312 |
class DummyArtResizer(ArtResizer): |
| 313 |
"""An `ArtResizer` which pretends that ImageMagick is available, and has |
| 314 |
a sufficiently recent version to support image comparison. |
| 315 |
""" |
| 316 |
|
| 317 |
def __init__(self): |
| 318 |
self.local_method = DummyIMBackend() |
| 319 |
|
| 320 |
|
| 321 |
@patch("beets.util.artresizer.subprocess") |
| 322 |
@patch("beetsplug._utils.art.extract") |
| 323 |
class ArtSimilarityTest(unittest.TestCase): |
| 324 |
def setUp(self): |
| 325 |
self.item = _common.item() |
| 326 |
self.log = logging.getLogger("beets.embedart") |
| 327 |
self.artresizer = DummyArtResizer() |
| 328 |
|
| 329 |
def _similarity(self, threshold): |
| 330 |
return art.check_art_similarity( |
| 331 |
self.log, self.item, b"path", threshold, artresizer=self.artresizer |
| 332 |
) |
| 333 |
|
| 334 |
def _popen(self, status=0, stdout="", stderr=""): |
| 335 |
"""Create a mock `Popen` object.""" |
| 336 |
popen = MagicMock(returncode=status) |
| 337 |
popen.communicate.return_value = stdout, stderr |
| 338 |
return popen |
| 339 |
|
| 340 |
def _mock_popens( |
| 341 |
self, |
| 342 |
mock_extract, |
| 343 |
mock_subprocess, |
| 344 |
compare_status=0, |
| 345 |
compare_stdout=b"", |
| 346 |
compare_stderr=b"", |
| 347 |
convert_status=0, |
| 348 |
): |
| 349 |
mock_extract.return_value = b"extracted_path" |
| 350 |
mock_subprocess.Popen.side_effect = [ |
| 351 |
# The `convert` call. |
| 352 |
self._popen(convert_status), |
| 353 |
# The `compare` call. |
| 354 |
self._popen(compare_status, compare_stdout, compare_stderr), |
| 355 |
] |
| 356 |
|
| 357 |
def test_compare_success_similar(self, mock_extract, mock_subprocess): |
| 358 |
self._mock_popens(mock_extract, mock_subprocess, 0, b"10", b"err") |
| 359 |
assert self._similarity(20) |
| 360 |
|
| 361 |
def test_compare_success_different(self, mock_extract, mock_subprocess): |
| 362 |
self._mock_popens(mock_extract, mock_subprocess, 0, b"10", b"err") |
| 363 |
assert not self._similarity(5) |
| 364 |
|
| 365 |
def test_compare_status1_similar(self, mock_extract, mock_subprocess): |
| 366 |
self._mock_popens(mock_extract, mock_subprocess, 1, b"out", b"10") |
| 367 |
assert self._similarity(20) |
| 368 |
|
| 369 |
def test_compare_status1_different(self, mock_extract, mock_subprocess): |
| 370 |
self._mock_popens(mock_extract, mock_subprocess, 1, b"out", b"10") |
| 371 |
assert not self._similarity(5) |
| 372 |
|
| 373 |
def test_compare_failed(self, mock_extract, mock_subprocess): |
| 374 |
self._mock_popens(mock_extract, mock_subprocess, 2, b"out", b"10") |
| 375 |
assert self._similarity(20) is None |
| 376 |
|
| 377 |
def test_compare_parsing_error(self, mock_extract, mock_subprocess): |
| 378 |
self._mock_popens(mock_extract, mock_subprocess, 0, b"foo", b"bar") |
| 379 |
assert self._similarity(20) is None |
| 380 |
|
| 381 |
def test_compare_parsing_error_and_failure( |
| 382 |
self, mock_extract, mock_subprocess |
| 383 |
): |
| 384 |
self._mock_popens(mock_extract, mock_subprocess, 1, b"foo", b"bar") |
| 385 |
assert self._similarity(20) is None |
| 386 |
|
| 387 |
def test_convert_failure(self, mock_extract, mock_subprocess): |
| 388 |
self._mock_popens(mock_extract, mock_subprocess, convert_status=1) |
| 389 |
assert self._similarity(20) is None |