Skip to content

Commit

Permalink
added test for delete-history, and added assertions for delete-all test
Browse files Browse the repository at this point in the history
  • Loading branch information
apastel committed May 12, 2024
1 parent 2093a40 commit e9000dc
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 8 deletions.
17 changes: 16 additions & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import time
from pathlib import Path
from typing import Dict
from typing import List

import pytest
from ytmusic_deleter import constants
Expand Down Expand Up @@ -42,6 +43,11 @@ def fixture_sample_video() -> str:
return "hpSrLjc5SMs"


@pytest.fixture(name="sample_song_list")
def fixture_sample_song_list() -> List[str]:
return ["hpSrLjc5SMs", "PIuAFrLeXfY", "9gi4WwQcPW8", "beX-9wW5rL0", "8ay_BkRuv-o", "HGorCGszxZU", "t2rsf8SiMJY"]


@pytest.fixture(name="sample_public_playlist")
def fixture_sample_playlist() -> str:
"""'00s Metal"""
Expand Down Expand Up @@ -117,7 +123,7 @@ def fixture_upload_song(config, yt_browser: YTMusic) -> Dict | None:
# Wait for upload to finish processing
retries_remaining = 20
while retries_remaining:
time.sleep(2)
time.sleep(3)
songs = yt_browser.get_library_upload_songs(limit=None)
for song in songs:
if song.get("title") in config["uploads"]["file"]:
Expand Down Expand Up @@ -204,3 +210,12 @@ def fixture_playlist_with_dupes(yt_oauth: YTMusic, create_playlist):
yield playlist_id

yt_oauth.delete_playlist(playlist_id)


@pytest.fixture(name="add_history_items")
def fixture_add_history_items(yt_oauth: YTMusic, sample_song_list):
timestamp = yt_oauth.get_signatureTimestamp()
for song in sample_song_list:
song = yt_oauth.get_song(song, timestamp)
response = yt_oauth.add_history_item(song)
assert response.status_code == 204
30 changes: 29 additions & 1 deletion tests/test_cli.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import time

import pytest
from click.testing import CliRunner
from ytmusic_deleter.cli import check_for_duplicates
from ytmusic_deleter.cli import cli
Expand Down Expand Up @@ -55,6 +56,15 @@ def test_unlike_all_songs(self, yt_oauth: YTMusic, like_song):
likes_remaining = yt_oauth.get_liked_songs(limit=None)["tracks"]
assert len(likes_remaining) == 0, f"There were still {len(likes_remaining)} liked songs remaining"

def test_delete_history(self, yt_oauth: YTMusic, add_history_items):
runner = CliRunner()
result = runner.invoke(cli, ["delete-history"], standalone_mode=False, obj=yt_oauth)
print(result.stdout)
assert result.exit_code == 0

items_deleted = result.return_value
assert items_deleted == 7, "One or more history items were not deleted"

def test_delete_playlists(self, yt_oauth: YTMusic, create_playlist):
runner = CliRunner()
result = runner.invoke(cli, ["delete-playlists"], standalone_mode=False, obj=yt_oauth)
Expand All @@ -77,9 +87,27 @@ def test_delete_playlist_duplicates(self, yt_oauth: YTMusic, playlist_with_dupes
assert len(check_for_duplicates(playlist_without_dupes, yt_oauth)) == 0, "Playlist still contained duplicates"

def test_delete_all(
self, yt_browser: YTMusic, upload_song, add_library_album, add_podcast, create_playlist, like_song
self,
yt_browser: YTMusic,
upload_song,
add_library_album,
add_podcast,
create_playlist,
like_song,
add_history_items,
):
runner = CliRunner()
result = runner.invoke(cli, ["delete-all"], standalone_mode=False, obj=yt_browser)
print(result.stdout)
assert result.exit_code == 0

# Verify everything was deleted
assert 0 == len(yt_browser.get_library_upload_songs())
assert 0 == len(yt_browser.get_library_songs())
assert 1 == len(yt_browser.get_library_podcasts())
assert "Episodes you save for later" == yt_browser.get_library_podcasts()[0].get("channel").get("name")
assert 1 == len(yt_browser.get_library_playlists())
assert "Episodes you save for later" == yt_browser.get_library_playlists()[0].get("description")
assert 0 == len(yt_browser.get_liked_songs()["tracks"])
with pytest.raises(Exception, match="None"):
yt_browser.get_history()
21 changes: 15 additions & 6 deletions ytmusic_deleter/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import os
import re
import sys
import time
from itertools import groupby
from operator import itemgetter
from pathlib import Path
Expand Down Expand Up @@ -304,7 +305,7 @@ def delete_playlists(ctx: click.Context):

@cli.command()
@click.pass_context
def delete_history(ctx: click.Context):
def delete_history(ctx: click.Context, items_deleted: int = 0):
"""
Delete your play history. This does not currently work with brand accounts.
The API can only retrieve 200 history items at a time, so the process will appear to
Expand All @@ -316,10 +317,11 @@ def delete_history(ctx: click.Context):
history_items = yt_auth.get_history()
except Exception as e:
if str(e) == "None":
logging.info("History is empty, nothing to delete.")
logging.info("History is empty, nothing left to delete.")
else:
logging.exception(e)
return False
logging.info(f"Deleted {items_deleted} history items.")
return items_deleted
global progress_bar
progress_bar = manager.counter(
total=len(history_items),
Expand All @@ -334,10 +336,17 @@ def delete_history(ctx: click.Context):
if item.get("artists") # Using `get` ensures key exists and isn't []
else const.UNKNOWN_ARTIST
)
logging.info(f"Processing {artist} - {item['title']}")
yt_auth.remove_history_items(item["feedbackToken"])
logging.info(f"\tProcessing history item: {artist} - {item['title']!r}")
response = yt_auth.remove_history_items(item["feedbackToken"])
if response.get("feedbackResponses")[0].get("isProcessed"):
logging.info(f"\tDeleted history item: {artist} - {item['title']!r}")
items_deleted += 1
else:
logging.info(f"\tFailed to delete history item: {response}")
update_progress()
ctx.invoke(delete_history) # repeat until history is empty
logging.info("Restarting history deletion to ensure all songs are deleted.")
time.sleep(5) # Wait before checking for new items as they take time to disappear
return ctx.invoke(delete_history, items_deleted) # repeat until history is empty


@cli.command()
Expand Down

0 comments on commit e9000dc

Please sign in to comment.