Best Python code snippet using playwright-python
test_download.py
Source:test_download.py
...39async def test_should_report_downloads_with_accept_downloads_false(page: Page, server):40 await page.set_content(41 f'<a href="{server.PREFIX}/downloadWithFilename">download</a>'42 )43 async with page.expect_download() as download_info:44 await page.click("a")45 download = await download_info.value46 assert download.url == f"{server.PREFIX}/downloadWithFilename"47 assert download.suggested_filename == "file.txt"48 error: Optional[Error] = None49 try:50 await download.path()51 except Error as exc:52 error = exc53 assert "accept_downloads" in await download.failure()54 assert error55 assert "accept_downloads: True" in error.message56async def test_should_report_downloads_with_accept_downloads_true(browser, server):57 page = await browser.new_page(accept_downloads=True)58 await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')59 async with page.expect_download() as download_info:60 await page.click("a")61 download = await download_info.value62 path = await download.path()63 assert os.path.isfile(path)64 assert_file_content(path, "Hello world")65 await page.close()66async def test_should_save_to_user_specified_path(tmpdir: Path, browser, server):67 page = await browser.new_page(accept_downloads=True)68 await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')69 async with page.expect_download() as download_info:70 await page.click("a")71 download = await download_info.value72 user_path = tmpdir / "download.txt"73 await download.save_as(user_path)74 assert user_path.exists()75 assert user_path.read_text("utf-8") == "Hello world"76 await page.close()77async def test_should_save_to_user_specified_path_without_updating_original_path(78 tmpdir, browser, server79):80 page = await browser.new_page(accept_downloads=True)81 await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')82 async with page.expect_download() as download_info:83 await page.click("a")84 download = await download_info.value85 user_path = tmpdir / "download.txt"86 await download.save_as(user_path)87 assert user_path.exists()88 assert user_path.read_text("utf-8") == "Hello world"89 originalPath = Path(await download.path())90 assert originalPath.exists()91 assert originalPath.read_text("utf-8") == "Hello world"92 await page.close()93async def test_should_save_to_two_different_paths_with_multiple_save_as_calls(94 tmpdir, browser, server95):96 page = await browser.new_page(accept_downloads=True)97 await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')98 async with page.expect_download() as download_info:99 await page.click("a")100 download = await download_info.value101 user_path = tmpdir / "download.txt"102 await download.save_as(user_path)103 assert user_path.exists()104 assert user_path.read_text("utf-8") == "Hello world"105 anotheruser_path = tmpdir / "download (2).txt"106 await download.save_as(anotheruser_path)107 assert anotheruser_path.exists()108 assert anotheruser_path.read_text("utf-8") == "Hello world"109 await page.close()110async def test_should_save_to_overwritten_filepath(tmpdir: Path, browser, server):111 page = await browser.new_page(accept_downloads=True)112 await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')113 async with page.expect_download() as download_info:114 await page.click("a")115 download = await download_info.value116 user_path = tmpdir / "download.txt"117 await download.save_as(user_path)118 assert len(list(Path(tmpdir).glob("*.*"))) == 1119 await download.save_as(user_path)120 assert len(list(Path(tmpdir).glob("*.*"))) == 1121 assert user_path.exists()122 assert user_path.read_text("utf-8") == "Hello world"123 await page.close()124async def test_should_create_subdirectories_when_saving_to_non_existent_user_specified_path(125 tmpdir, browser, server126):127 page = await browser.new_page(accept_downloads=True)128 await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')129 async with page.expect_download() as download_info:130 await page.click("a")131 download = await download_info.value132 nested_path = tmpdir / "these" / "are" / "directories" / "download.txt"133 await download.save_as(nested_path)134 assert nested_path.exists()135 assert nested_path.read_text("utf-8") == "Hello world"136 await page.close()137async def test_should_error_when_saving_with_downloads_disabled(138 tmpdir, browser, server139):140 page = await browser.new_page(accept_downloads=False)141 await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')142 async with page.expect_download() as download_info:143 await page.click("a")144 download = await download_info.value145 user_path = tmpdir / "download.txt"146 with pytest.raises(Error) as exc:147 await download.save_as(user_path)148 assert (149 "Pass { accept_downloads: True } when you are creating your browser context"150 in exc.value.message151 )152 await page.close()153async def test_should_error_when_saving_after_deletion(tmpdir, browser, server):154 page = await browser.new_page(accept_downloads=True)155 await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')156 async with page.expect_download() as download_info:157 await page.click("a")158 download = await download_info.value159 user_path = tmpdir / "download.txt"160 await download.delete()161 with pytest.raises(Error) as exc:162 await download.save_as(user_path)163 assert "Download already deleted. Save before deleting." in exc.value.message164 await page.close()165async def test_should_report_non_navigation_downloads(browser, server):166 # Mac WebKit embedder does not download in this case, although Safari does.167 def handle_download(request):168 request.setHeader("Content-Type", "application/octet-stream")169 request.write(b"Hello world")170 request.finish()171 server.set_route("/download", handle_download)172 page = await browser.new_page(accept_downloads=True)173 await page.goto(server.EMPTY_PAGE)174 await page.set_content(175 f'<a download="file.txt" href="{server.PREFIX}/download">download</a>'176 )177 async with page.expect_download() as download_info:178 await page.click("a")179 download = await download_info.value180 assert download.suggested_filename == "file.txt"181 path = await download.path()182 assert os.path.exists(path)183 assert_file_content(path, "Hello world")184 await page.close()185async def test_report_download_path_within_page_on_download_handler_for_files(186 browser: Browser, server187):188 page = await browser.new_page(accept_downloads=True)189 on_download_path: Future[str] = asyncio.Future()190 async def on_download(download):191 on_download_path.set_result(await download.path())192 page.once(193 "download",194 lambda res: asyncio.create_task(on_download(res)),195 )196 await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')197 await page.click("a")198 path = await on_download_path199 assert_file_content(path, "Hello world")200 await page.close()201async def test_download_report_download_path_within_page_on_handle_for_blobs(202 browser, server203):204 page = await browser.new_page(accept_downloads=True)205 on_download_path = asyncio.Future()206 async def on_download(download):207 on_download_path.set_result(await download.path())208 page.once(209 "download",210 lambda res: asyncio.create_task(on_download(res)),211 )212 await page.goto(server.PREFIX + "/download-blob.html")213 await page.click("a")214 path = await on_download_path215 assert_file_content(path, "Hello world")216 await page.close()217@pytest.mark.only_browser("chromium")218async def test_should_report_alt_click_downloads(browser, server):219 # Firefox does not download on alt-click by default.220 # Our WebKit embedder does not download on alt-click, although Safari does.221 def handle_download(request):222 request.setHeader("Content-Type", "application/octet-stream")223 request.write(b"Hello world")224 request.finish()225 server.set_route("/download", handle_download)226 page = await browser.new_page(accept_downloads=True)227 await page.goto(server.EMPTY_PAGE)228 await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')229 async with page.expect_download() as download_info:230 await page.click("a", modifiers=["Alt"])231 download = await download_info.value232 path = await download.path()233 assert os.path.exists(path)234 assert_file_content(path, "Hello world")235 await page.close()236async def test_should_report_new_window_downloads(browser, server):237 # TODO: - the test fails in headful Chromium as the popup page gets closed along238 # with the session before download completed event arrives.239 # - WebKit doesn't close the popup page240 page = await browser.new_page(accept_downloads=True)241 await page.set_content(242 f'<a target=_blank href="{server.PREFIX}/download">download</a>'243 )244 async with page.expect_download() as download_info:245 await page.click("a")246 download = await download_info.value247 path = await download.path()248 assert os.path.exists(path)249 await page.close()250async def test_should_delete_file(browser, server):251 page = await browser.new_page(accept_downloads=True)252 await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')253 async with page.expect_download() as download_info:254 await page.click("a")255 download = await download_info.value256 path = await download.path()257 assert os.path.exists(path)258 await download.delete()259 assert os.path.exists(path) is False260 await page.close()261async def test_should_delete_downloads_on_context_destruction(browser, server):262 page = await browser.new_page(accept_downloads=True)263 await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')264 async with page.expect_download() as download_info:265 await page.click("a")266 download1 = await download_info.value267 async with page.expect_download() as download_info:268 await page.click("a")269 download2 = await download_info.value270 path1 = await download1.path()271 path2 = await download2.path()272 assert os.path.exists(path1)273 assert os.path.exists(path2)274 await page.context.close()275 assert os.path.exists(path1) is False276 assert os.path.exists(path2) is False277async def test_should_delete_downloads_on_browser_gone(browser_factory, server):278 browser = await browser_factory()279 page = await browser.new_page(accept_downloads=True)280 await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')281 async with page.expect_download() as download_info:282 await page.click("a")283 download1 = await download_info.value284 async with page.expect_download() as download_info:285 await page.click("a")286 download2 = await download_info.value287 path1 = await download1.path()288 path2 = await download2.path()289 assert os.path.exists(path1)290 assert os.path.exists(path2)291 await browser.close()292 assert os.path.exists(path1) is False293 assert os.path.exists(path2) is False...
test_download_with_metadata.py
Source:test_download_with_metadata.py
1import subprocess2import os3from spotdl import const4from spotdl import internals5from spotdl import spotify_tools6from spotdl import youtube_tools7from spotdl import convert8from spotdl import metadata9from spotdl import downloader10import pytest11import loader12loader.load_defaults()13SPOTIFY_TRACK_URL = "https://open.spotify.com/track/3SipFlNddvL0XNZRLXvdZD"14EXPECTED_YOUTUBE_TITLE = "Janji - Heroes Tonight (feat. Johnning) [NCS Release]"15EXPECTED_SPOTIFY_TITLE = "Janji - Heroes Tonight"16EXPECTED_YOUTUBE_URL = "http://youtube.com/watch?v=3nQNiWdeH2Q"17# GIST_URL is the monkeypatched version of: https://www.youtube.com/results?search_query=janji+-+heroes18# so that we get same results even if YouTube changes the list/order of videos on their page.19GIST_URL = "https://gist.githubusercontent.com/ritiek/e731338e9810e31c2f00f13c249a45f5/raw/c11a27f3b5d11a8d082976f1cdd237bd605ec2c2/search_results.html"20def pytest_namespace():21 # XXX: We override the value of `content_fixture` later in the tests.22 # We do not use an acutal @pytest.fixture because it does not accept23 # the monkeypatch parameter and we need to monkeypatch the network24 # request before creating the Pafy object.25 return {"content_fixture": None}26@pytest.fixture(scope="module")27def metadata_fixture():28 meta_tags = spotify_tools.generate_metadata(SPOTIFY_TRACK_URL)29 return meta_tags30def test_metadata(metadata_fixture):31 expect_number = 2432 assert len(metadata_fixture) == expect_number33class TestFileFormat:34 def test_with_spaces(self, metadata_fixture):35 title = internals.format_string(const.args.file_format, metadata_fixture)36 assert title == EXPECTED_SPOTIFY_TITLE37 def test_without_spaces(self, metadata_fixture):38 const.args.no_spaces = True39 title = internals.format_string(const.args.file_format, metadata_fixture)40 assert title == EXPECTED_SPOTIFY_TITLE.replace(" ", "_")41def test_youtube_url(metadata_fixture, monkeypatch):42 monkeypatch.setattr(43 youtube_tools.GenerateYouTubeURL,44 "_fetch_response",45 loader.monkeypatch_youtube_search_page,46 )47 url = youtube_tools.generate_youtube_url(SPOTIFY_TRACK_URL, metadata_fixture)48 assert url == EXPECTED_YOUTUBE_URL49def test_youtube_title(metadata_fixture, monkeypatch):50 monkeypatch.setattr(51 youtube_tools.GenerateYouTubeURL,52 "_fetch_response",53 loader.monkeypatch_youtube_search_page,54 )55 content = youtube_tools.go_pafy(SPOTIFY_TRACK_URL, metadata_fixture)56 pytest.content_fixture = content57 title = youtube_tools.get_youtube_title(content)58 assert title == EXPECTED_YOUTUBE_TITLE59@pytest.fixture(scope="module")60def filename_fixture(metadata_fixture):61 songname = internals.format_string(const.args.file_format, metadata_fixture)62 filename = internals.sanitize_title(songname)63 return filename64def test_check_track_exists_before_download(tmpdir, metadata_fixture, filename_fixture):65 expect_check = False66 const.args.folder = str(tmpdir)67 # prerequisites for determining filename68 track_existence = downloader.CheckExists(filename_fixture, metadata_fixture)69 check = track_existence.already_exists(SPOTIFY_TRACK_URL)70 assert check == expect_check71class TestDownload:72 def blank_audio_generator(self, filepath):73 if filepath.endswith(".m4a"):74 cmd = "ffmpeg -f lavfi -i anullsrc -t 1 -c:a aac {}".format(filepath)75 elif filepath.endswith(".webm"):76 cmd = "ffmpeg -f lavfi -i anullsrc -t 1 -c:a libopus {}".format(filepath)77 subprocess.call(cmd.split(" "))78 def test_m4a(self, monkeypatch, filename_fixture):79 expect_download = True80 monkeypatch.setattr(81 "pafy.backend_shared.BaseStream.download", self.blank_audio_generator82 )83 monkeypatch.setattr(84 "pafy.backend_youtube_dl.YtdlStream.download", self.blank_audio_generator85 )86 download = youtube_tools.download_song(87 filename_fixture + ".m4a", pytest.content_fixture88 )89 assert download == expect_download90 def test_webm(self, monkeypatch, filename_fixture):91 expect_download = True92 monkeypatch.setattr(93 "pafy.backend_shared.BaseStream.download", self.blank_audio_generator94 )95 monkeypatch.setattr(96 "pafy.backend_youtube_dl.YtdlStream.download", self.blank_audio_generator97 )98 download = youtube_tools.download_song(99 filename_fixture + ".webm", pytest.content_fixture100 )101 assert download == expect_download102class TestFFmpeg:103 def test_convert_from_webm_to_mp3(self, filename_fixture, monkeypatch):104 expect_command = "ffmpeg -y -nostdin -hide_banner -nostats -v panic -i {0}.webm -codec:a libmp3lame -ar 44100 -b:a 192k -vn {0}.mp3".format(105 os.path.join(const.args.folder, filename_fixture)106 )107 monkeypatch.setattr("os.remove", lambda x: None)108 _, command = convert.song(109 filename_fixture + ".webm", filename_fixture + ".mp3", const.args.folder110 )111 assert " ".join(command) == expect_command112 def test_convert_from_webm_to_m4a(self, filename_fixture, monkeypatch):113 expect_command = "ffmpeg -y -nostdin -hide_banner -nostats -v panic -i {0}.webm -cutoff 20000 -codec:a aac -ar 44100 -b:a 192k -vn {0}.m4a".format(114 os.path.join(const.args.folder, filename_fixture)115 )116 monkeypatch.setattr("os.remove", lambda x: None)117 _, command = convert.song(118 filename_fixture + ".webm", filename_fixture + ".m4a", const.args.folder119 )120 assert " ".join(command) == expect_command121 def test_convert_from_m4a_to_mp3(self, filename_fixture, monkeypatch):122 expect_command = "ffmpeg -y -nostdin -hide_banner -nostats -v panic -i {0}.m4a -codec:v copy -codec:a libmp3lame -ar 44100 -b:a 192k -vn {0}.mp3".format(123 os.path.join(const.args.folder, filename_fixture)124 )125 monkeypatch.setattr("os.remove", lambda x: None)126 _, command = convert.song(127 filename_fixture + ".m4a", filename_fixture + ".mp3", const.args.folder128 )129 assert " ".join(command) == expect_command130 def test_convert_from_m4a_to_webm(self, filename_fixture, monkeypatch):131 expect_command = "ffmpeg -y -nostdin -hide_banner -nostats -v panic -i {0}.m4a -codec:a libopus -vbr on -b:a 192k -vn {0}.webm".format(132 os.path.join(const.args.folder, filename_fixture)133 )134 monkeypatch.setattr("os.remove", lambda x: None)135 _, command = convert.song(136 filename_fixture + ".m4a", filename_fixture + ".webm", const.args.folder137 )138 assert " ".join(command) == expect_command139 def test_convert_from_m4a_to_flac(self, filename_fixture, monkeypatch):140 expect_command = "ffmpeg -y -nostdin -hide_banner -nostats -v panic -i {0}.m4a -codec:a flac -ar 44100 -b:a 192k -vn {0}.flac".format(141 os.path.join(const.args.folder, filename_fixture)142 )143 monkeypatch.setattr("os.remove", lambda x: None)144 _, command = convert.song(145 filename_fixture + ".m4a", filename_fixture + ".flac", const.args.folder146 )147 assert " ".join(command) == expect_command148 def test_correct_container_for_m4a(self, filename_fixture, monkeypatch):149 expect_command = "ffmpeg -y -nostdin -hide_banner -nostats -v panic -i {0}.m4a.temp -acodec copy -b:a 192k -vn {0}.m4a".format(150 os.path.join(const.args.folder, filename_fixture)151 )152 _, command = convert.song(153 filename_fixture + ".m4a", filename_fixture + ".m4a", const.args.folder154 )155 assert " ".join(command) == expect_command156class TestAvconv:157 @pytest.mark.skip(reason="avconv is no longer provided with FFmpeg")158 def test_convert_from_m4a_to_mp3(self, filename_fixture, monkeypatch):159 monkeypatch.setattr("os.remove", lambda x: None)160 expect_command = "avconv -loglevel 0 -i {0}.m4a -ab 192k {0}.mp3 -y".format(161 os.path.join(const.args.folder, filename_fixture)162 )163 _, command = convert.song(164 filename_fixture + ".m4a",165 filename_fixture + ".mp3",166 const.args.folder,167 avconv=True,168 )169 assert " ".join(command) == expect_command170@pytest.fixture(scope="module")171def trackpath_fixture(filename_fixture):172 trackpath = os.path.join(const.args.folder, filename_fixture)173 return trackpath174class TestEmbedMetadata:175 def test_embed_in_mp3(self, metadata_fixture, trackpath_fixture):176 expect_embed = True177 embed = metadata.embed(trackpath_fixture + ".mp3", metadata_fixture)178 assert embed == expect_embed179 def test_embed_in_m4a(self, metadata_fixture, trackpath_fixture):180 expect_embed = True181 embed = metadata.embed(trackpath_fixture + ".m4a", metadata_fixture)182 os.remove(trackpath_fixture + ".m4a")183 assert embed == expect_embed184 def test_embed_in_webm(self, metadata_fixture, trackpath_fixture):185 expect_embed = False186 embed = metadata.embed(trackpath_fixture + ".webm", metadata_fixture)187 os.remove(trackpath_fixture + ".webm")188 assert embed == expect_embed189 def test_embed_in_flac(self, metadata_fixture, trackpath_fixture):190 expect_embed = True191 embed = metadata.embed(trackpath_fixture + ".flac", metadata_fixture)192 os.remove(trackpath_fixture + ".flac")193 assert embed == expect_embed194def test_check_track_exists_after_download(195 metadata_fixture, filename_fixture, trackpath_fixture196):197 expect_check = True198 track_existence = downloader.CheckExists(filename_fixture, metadata_fixture)199 check = track_existence.already_exists(SPOTIFY_TRACK_URL)200 os.remove(trackpath_fixture + ".mp3")...
test_youtube_tools.py
Source:test_youtube_tools.py
1import os2import builtins3from spotdl import const4from spotdl import internals5from spotdl import spotify_tools6from spotdl import youtube_tools7from spotdl import downloader8import loader9import pytest10loader.load_defaults()11YT_API_KEY = "AIzaSyAnItl3udec-Q1d5bkjKJGL-RgrKO_vU90"12TRACK_SEARCH = "Tony's Videos VERY SHORT VIDEO 28.10.2016"13EXPECTED_TITLE = TRACK_SEARCH14EXPECTED_YT_URL = "http://youtube.com/watch?v=qOOcy2-tmbk"15RESULT_COUNT_SEARCH = "she is still sleeping SAO"16EXPECTED_YT_API_KEY = "AIzaSyC6cEeKlxtOPybk9sEe5ksFN5sB-7wzYp0"17EXPECTED_YT_API_KEY_CUSTOM = "some_api_key"18class TestYouTubeAPIKeys:19 def test_custom(self):20 const.args.youtube_api_key = EXPECTED_YT_API_KEY_CUSTOM21 youtube_tools.set_api_key()22 key = youtube_tools.pafy.g.api_key23 assert key == EXPECTED_YT_API_KEY_CUSTOM24 def test_default(self):25 const.args.youtube_api_key = None26 youtube_tools.set_api_key()27 key = youtube_tools.pafy.g.api_key28 assert key == EXPECTED_YT_API_KEY29@pytest.fixture(scope="module")30def metadata_fixture():31 metadata = spotify_tools.generate_metadata(TRACK_SEARCH)32 return metadata33def test_metadata(metadata_fixture):34 expect_metadata = None35 assert metadata_fixture == expect_metadata36class TestArgsManualResultCount:37 # Regresson test for issue #26438 def test_scrape(self):39 const.args.manual = True40 url = youtube_tools.GenerateYouTubeURL(RESULT_COUNT_SEARCH, meta_tags=None)41 video_ids = url.scrape(bestmatch=False)42 # Web scraping gives us all videos on the 1st page43 assert len(video_ids) == 2044 def test_api(self):45 url = youtube_tools.GenerateYouTubeURL(RESULT_COUNT_SEARCH, meta_tags=None)46 video_ids = url.api(bestmatch=False)47 const.args.manual = False48 # API gives us 50 videos (or as requested)49 assert len(video_ids) == 5050class TestYouTubeURL:51 def test_only_music_category(self, metadata_fixture):52 const.args.music_videos_only = True53 url = youtube_tools.generate_youtube_url(TRACK_SEARCH, metadata_fixture)54 assert url == EXPECTED_YT_URL55 def test_all_categories(self, metadata_fixture):56 const.args.music_videos_only = False57 url = youtube_tools.generate_youtube_url(TRACK_SEARCH, metadata_fixture)58 assert url == EXPECTED_YT_URL59 def test_args_manual(self, metadata_fixture, monkeypatch):60 const.args.manual = True61 monkeypatch.setattr("builtins.input", lambda x: "1")62 url = youtube_tools.generate_youtube_url(TRACK_SEARCH, metadata_fixture)63 assert url == EXPECTED_YT_URL64 def test_args_manual_none(self, metadata_fixture, monkeypatch):65 expect_url = None66 monkeypatch.setattr("builtins.input", lambda x: "0")67 url = youtube_tools.generate_youtube_url(TRACK_SEARCH, metadata_fixture)68 const.args.manual = False69 assert url == expect_url70@pytest.fixture(scope="module")71def content_fixture(metadata_fixture):72 content = youtube_tools.go_pafy(TRACK_SEARCH, metadata_fixture)73 return content74# True = Metadata must be fetched from Spotify75# False = Metadata must be fetched from YouTube76# None = Metadata must be `None`77MATCH_METADATA_NO_FALLBACK_TEST_TABLE = [78 ("https://open.spotify.com/track/5nWduGwBGBn1PSqYTJUDbS", True),79 ("http://youtube.com/watch?v=3nQNiWdeH2Q", None),80 ("Linux Talk | Working with Drives and Filesystems", None),81]82MATCH_METADATA_FALLBACK_TEST_TABLE = [83 ("https://open.spotify.com/track/5nWduGwBGBn1PSqYTJUDbS", True),84 ("http://youtube.com/watch?v=3nQNiWdeH2Q", False),85 ("Linux Talk | Working with Drives and Filesystems", False),86]87MATCH_METADATA_NO_METADATA_TEST_TABLE = [88 ("https://open.spotify.com/track/5nWduGwBGBn1PSqYTJUDbS", None),89 ("http://youtube.com/watch?v=3nQNiWdeH2Q", None),90 ("Linux Talk | Working with Drives and Filesystems", None),91]92class TestMetadataOrigin:93 def match_metadata(self, track, metadata_type):94 _, metadata = youtube_tools.match_video_and_metadata(track)95 if metadata_type is None:96 assert metadata == metadata_type97 else:98 assert metadata["spotify_metadata"] == metadata_type99 @pytest.mark.parametrize(100 "track, metadata_type", MATCH_METADATA_NO_FALLBACK_TEST_TABLE101 )102 def test_match_metadata_with_no_fallback(103 self, track, metadata_type, content_fixture, monkeypatch104 ):105 monkeypatch.setattr(106 youtube_tools, "go_pafy", lambda track, meta_tags: content_fixture107 )108 const.args.no_fallback_metadata = True109 self.match_metadata(track, metadata_type)110 @pytest.mark.parametrize("track, metadata_type", MATCH_METADATA_FALLBACK_TEST_TABLE)111 def test_match_metadata_with_fallback(112 self, track, metadata_type, content_fixture, monkeypatch113 ):114 monkeypatch.setattr(115 youtube_tools, "go_pafy", lambda track, meta_tags: content_fixture116 )117 const.args.no_fallback_metadata = False118 self.match_metadata(track, metadata_type)119 @pytest.mark.parametrize(120 "track, metadata_type", MATCH_METADATA_NO_METADATA_TEST_TABLE121 )122 def test_match_metadata_with_no_metadata(123 self, track, metadata_type, content_fixture, monkeypatch124 ):125 monkeypatch.setattr(126 youtube_tools, "go_pafy", lambda track, meta_tags: content_fixture127 )128 const.args.no_metadata = True129 self.match_metadata(track, metadata_type)130@pytest.fixture(scope="module")131def title_fixture(content_fixture):132 title = youtube_tools.get_youtube_title(content_fixture)133 return title134class TestYouTubeTitle:135 def test_single_download_with_youtube_api(self, title_fixture):136 const.args.youtube_api_key = YT_API_KEY137 youtube_tools.set_api_key()138 assert title_fixture == EXPECTED_TITLE139 def test_download_from_list_without_youtube_api(140 self, metadata_fixture, content_fixture141 ):142 const.args.youtube_api_key = None143 youtube_tools.set_api_key()144 content_fixture = youtube_tools.go_pafy(TRACK_SEARCH, metadata_fixture)145 title = youtube_tools.get_youtube_title(content_fixture, 1)146 assert title == "1. {0}".format(EXPECTED_TITLE)147@pytest.fixture(scope="module")148def filename_fixture(title_fixture):149 filename = internals.sanitize_title(title_fixture)150 return filename151def test_check_exists(metadata_fixture, filename_fixture, tmpdir):152 expect_check = False153 const.args.folder = str(tmpdir)154 # prerequisites for determining filename155 track_existence = downloader.CheckExists(filename_fixture, metadata_fixture)156 check = track_existence.already_exists(TRACK_SEARCH)157 assert check == expect_check158def test_generate_m3u(tmpdir, monkeypatch):159 monkeypatch.setattr(160 youtube_tools.GenerateYouTubeURL,161 "_fetch_response",162 loader.monkeypatch_youtube_search_page,163 )164 expect_m3u = (165 "#EXTM3U\n\n"166 "#EXTINF:208,Janji - Heroes Tonight (feat. Johnning) [NCS Release]\n"167 "http://www.youtube.com/watch?v=3nQNiWdeH2Q\n"168 "#EXTINF:226,Alan Walker - Spectre [NCS Release]\n"169 "http://www.youtube.com/watch?v=AOeY-nDp7hI\n"170 )171 m3u_track_file = os.path.join(str(tmpdir), "m3u_test.txt")172 with open(m3u_track_file, "w") as track_file:173 track_file.write("\nhttps://open.spotify.com/track/3SipFlNddvL0XNZRLXvdZD")174 track_file.write("\nhttp://www.youtube.com/watch?v=AOeY-nDp7hI")175 youtube_tools.generate_m3u(m3u_track_file)176 m3u_file = "{}.m3u".format(m3u_track_file.split(".")[0])177 with open(m3u_file, "r") as m3u_in:178 m3u = m3u_in.readlines()179 assert "".join(m3u) == expect_m3u180class TestDownload:181 def test_webm(self, content_fixture, filename_fixture, monkeypatch):182 # content_fixture does not have any .webm audiostream183 expect_download = False184 monkeypatch.setattr("pafy.backend_shared.BaseStream.download", lambda x: None)185 download = youtube_tools.download_song(186 filename_fixture + ".webm", content_fixture187 )188 assert download == expect_download189 def test_other(self, content_fixture, filename_fixture, monkeypatch):190 expect_download = False191 monkeypatch.setattr("pafy.backend_shared.BaseStream.download", lambda x: None)192 download = youtube_tools.download_song(193 filename_fixture + ".fake_extension", content_fixture194 )...
test_fetcher.py
Source:test_fetcher.py
...122 self.fetcher.fetch('http://foo',123 self.listener,124 chunk_size_bytes=1024,125 timeout_secs=60)126 def expect_download(self, path_or_fd=None):127 downloaded = ''128 for chunk in self.expect_get('http://1', chunk_size_bytes=13, timeout_secs=13, listener=False):129 downloaded += chunk130 self.response.close()131 self.mox.ReplayAll()132 path = self.fetcher.download('http://1',133 path_or_fd=path_or_fd,134 chunk_size_bytes=13,135 timeout_secs=13)136 return downloaded, path137 def test_download(self):138 downloaded, path = self.expect_download()139 try:140 with open(path) as fp:141 self.assertEqual(downloaded, fp.read())142 finally:143 os.unlink(path)144 def test_download_fd(self):145 with temporary_file() as fd:146 downloaded, path = self.expect_download(path_or_fd=fd)147 self.assertEqual(path, fd.name)148 fd.close()149 with open(path) as fp:150 self.assertEqual(downloaded, fp.read())151 def test_download_path(self):152 with temporary_file() as fd:153 fd.close()154 downloaded, path = self.expect_download(path_or_fd=fd.name)155 self.assertEqual(path, fd.name)156 with open(path) as fp:...
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!