A plugin to use tango.info with MusicBrainz picard
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

200 lines
5.5 KiB

# -*- coding: utf-8 -*-
"""
Testing for tangoinfo.py, with some fixes to get around the wrong version
error when running headless.
Run with `pytest tests.py`
"""
import os
from urllib.request import urlopen
class FakeModule(object):
"""
Fake the picard.metadata module so that the import does not fail
"""
@staticmethod
def register_track_metadata_processor(dummy):
return True
# Path manipulation
import sys # noqa
import picard # noqa
sys.modules['picard.metadata'] = FakeModule()
# Importing tangoinfo plugin relies on (mocked) picard module being present
import tangoinfo # noqa
sample_albums = {
# Key = barcode
'7798145106390': {
'shortname': '23-grandes-exitos',
'offline_file': '23-grandes-exitos.html',
'url': 'https://tango.info/07798145106390',
'barcode': '7798145106390',
'tinp': '07798145106390', # NOT TINT!
'nr_of_tracks': 23,
},
}
class FakeDataObject(): # noqa
def __init__(self, data):
self._data = data
def data(self): # noqa
return self._data
def get_album(barcode, offline=True):
if offline:
fp = os.path.join("testdata", sample_albums[barcode]['offline_file'])
# Read in binary mode
with open(fp, 'rb') as f:
fakedataobj = FakeDataObject(f.read())
# return bytes (emulating a QByteArray)
return fakedataobj
else:
url = sample_albums[barcode]['url']
# urlopen.read() will already return a stream of bytes
response = urlopen(url).read()
fakedataobj = FakeDataObject(response)
return fakedataobj
class FakeTagger(tangoinfo.TangoInfoTagger):
"""
Fake the TangoInfoTagger class to intercept some calls
"""
def website_add_track(self, album, track, barcode, tint, zeros=0):
self.album_add_request(album)
response = get_album(barcode, offline=True)
if self.albumpage_queue.append(barcode, (track, album, tint)):
return self.website_process(
barcode=barcode,
zeros=zeros,
response_bytes=response,
reply=None,
error=False
)
class FakeTrack(object):
"""
A fake track object providing dummy iterfiles() and metadata.
"""
def __init__(self, id_, metadata=None):
assert isinstance(metadata, dict)
self.metadata = metadata
self._id = id_
def iterfiles(self):
# No need to test writing to files
return []
def __repr__(self):
fmtstr = "Disc: %s, Track: %2s, Barcode: %s, Genre: %7s, Date: %10s"
return '<FakeTrack %-18s> %s' % (
self._id,
fmtstr % tuple(map(
lambda x: str(self.metadata.get(x, '')),
('discnumber', 'tracknumber', 'barcode', 'genre', 'date')
))
)
class FakeAlbum(object):
def __init__(self, id_, new_tracks):
self._id = id_
self._requests = 0
self._new_tracks = new_tracks
def _finalize_loading(self, dummy):
return
# Test album:
# 23 Grandes Exitos by Juan D'Arienzo
# http://musicbrainz.org/release/65617e20-d445-41a3-a476-9868e6154317
# Barcode: 7798145106390
# tango.info: https://tango.info/07798145106390
# Metadata:
# 23 tracks, genre and performance date given but no vocalists
def test_extract_data():
"""
Test extract_data()
"""
taggerclass = tangoinfo.TangoInfoTagger()
barcode = '7798145106390'
page = get_album(barcode, offline=True).data().decode('utf-8')
albuminfo = taggerclass.extract_data(barcode, page)
assert albuminfo['7798145106390-1-19'].get('date') == '1937-12-09'
assert len(albuminfo.keys()) == 23
# For visual inspection
return "\n".join(str(i) for i in sorted(albuminfo.items()))
def test_add_tangoinfo_data():
"""
Test add_tangoinfo_data()
"""
taggerclass = FakeTagger()
barcode = '7798145106390'
track = 'faketrack'
release = 'fakerelease'
nr_of_tracks = sample_albums[barcode]['nr_of_tracks']
disc_nr = 1
# Set up fake album
albumtracks = []
for i in range(1, (nr_of_tracks + 1)):
fakealbumtrack = FakeTrack(
id_='%s-%d-%d' % (barcode, disc_nr, i),
metadata=dict(tracknumber=i,
barcode=barcode,
discnumber=disc_nr),
)
albumtracks.append(fakealbumtrack)
album = FakeAlbum(id_='fakeid', new_tracks=albumtracks)
# Run plugin
loaded_tracks = []
for i in range(1, (nr_of_tracks + 1)):
taggerclass.add_tangoinfo_data(album, album._new_tracks[-1].metadata,
track, release)
loaded_track = album._new_tracks.pop()
loaded_tracks.append(loaded_track)
loaded_tracks = sorted(loaded_tracks,
key=lambda track: track.metadata['tracknumber'])
# Start assertions
# Track 1: Don Juan
assert loaded_tracks[0].metadata.get('genre') == 'Tango'
# Track 2: Pasión
assert loaded_tracks[1].metadata.get('genre') == 'Vals'
# Track 22: Valsecito de antes
assert loaded_tracks[21].metadata.get('date') == '1937-08-31'
# Output test data for visual inspection
return '\n'.join([str(t) for t in loaded_tracks])
if __name__ == '__main__':
print("Testing extract_data()")
print(test_extract_data())
print("")
print("Testing add_tangoinfo_data()")
print(test_add_tangoinfo_data())