def test_download_metadata_with_url_error(): with patch('urllib.request.urlopen', side_effect=urllib.error.URLError('test-msg')): with pytest.raises(ApitError, match='due to error: <urlopen error test-msg>'): download_metadata(LOOKUP_URL) with patch('urllib.request.urlopen', side_effect=urllib.error.HTTPError(url=None, code=500, msg='test-msg', hdrs=None, fp=None)): with pytest.raises(ApitError, match='due to error: HTTP Error 500: test-msg'): download_metadata(LOOKUP_URL)
def test_downloaded_metadata_json_is_saved_using_unicode_chars(tmp_path): cache_file = tmp_path / 'test-file.json' json_str = download_metadata(REAL_LOOKUP_URL) save_metadata_to_cache(json_str, cache_file) data_read = cache_file.read_text() assert data_read == json_str data = json.loads(data_read) assert data['results'][0]['copyright'] == '℗ 2010 Roc-A-Fella Records, LLC'
def get_metadata_json(source: str) -> str: logging.info('Input source: %s', source) if Path(source).exists(): logging.info('Use downloaded metadata file: %s', source) try: return Path(source).read_text() except Exception: raise ApitError('Error while reading metadata file: %s' % Path(source)) elif is_url(source): logging.info('Use URL to download metadata: %s', source) query_url = generate_lookup_url_by_url(source) logging.info('Query URL: %s', query_url) return download_metadata(query_url) elif isinstance(source, str): logging.info('Use URL composition to download metadata: %s', source) query_url = generate_lookup_url_by_str(source) logging.info('Query URL: %s', query_url) return download_metadata(query_url) raise ApitError(f"Invalid input source: {source}")
def test_download_metadata(): response_attrs = { 'read.return_value': b'{"resultCount":12, "results": [{}]}' } mock = MagicMock() mock.__enter__.return_value = MagicMock(**response_attrs) with patch('urllib.request.urlopen', return_value=mock): json = download_metadata(LOOKUP_URL) assert '{"resultCount":12, "results": [{}]}' == json
def test_download_metadata_using_real_itunes_data(): json_str = download_metadata(REAL_LOOKUP_URL) data = json.loads(json_str) assert data['resultCount'] == 15 # test some album data assert data['results'][0]['collectionId'] == 1440742903 assert data['results'][0]['collectionType'] == 'Album' assert data['results'][0]['artistName'] == 'Kanye West' assert data['results'][0][ 'collectionName'] == 'My Beautiful Dark Twisted Fantasy' assert data['results'][0]['copyright'] == '℗ 2010 Roc-A-Fella Records, LLC' # test some song data assert data['results'][1]['kind'] == 'song' assert data['results'][1]['trackName'] == 'Dark Fantasy' assert data['results'][1]['trackNumber'] == 1 assert data['results'][1]['trackCount'] == 13