"""Run against the fake Spotify Web API in fake_spotify.py: python3 -m unittest discover -s tests -t . """ import sys import unittest from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from spotify import SpotifyClient, SpotifyError # noqa: E402 from tests.fake_spotify import FakeSpotify # noqa: E402 class SpotifyTest(unittest.TestCase): def setUp(self): self.fake = FakeSpotify() self.addCleanup(self.fake.stop) self.client = SpotifyClient( "client-id", "client-secret", "refresh-token", accounts_url=self.fake.base_url, api_url=self.fake.base_url, ) def test_devices_lists_what_spotify_reports(self): names = [d["name"] for d in self.client.devices()] self.assertEqual(names, ["Lego Room", "Home Cinema"]) self.assertEqual(self.fake.tokens_issued, 1) # one refresh for the whole call def test_resume_transfers_playback_to_the_matched_device(self): device = self.client.resume("Lego Room") self.assertEqual(device["id"], "dev-1") self.assertEqual(self.fake.transfers, [{"device_ids": ["dev-1"], "play": True}]) def test_resume_raises_when_no_device_has_that_name(self): with self.assertRaises(SpotifyError): self.client.resume("Kitchen") self.assertEqual(self.fake.transfers, []) def test_playback_reports_the_device_and_whether_it_plays(self): self.fake.player = {"device": {"id": "dev-1", "name": "Lego Room"}, "is_playing": True} player = self.client.playback() self.assertEqual(player["device"]["name"], "Lego Room") self.assertTrue(player["is_playing"]) def test_playback_is_empty_without_a_session(self): self.assertEqual(self.client.playback(), {}) def test_a_rejected_access_token_is_refreshed_and_retried_once(self): self.client.devices() # get a real token first self.assertEqual(self.fake.tokens_issued, 1) self.client._access_token = "stale-but-not-yet-expired" # _expires_at is untouched, so only the 401 -- not the pre-call # expiry check -- can be what forces this to work. names = [d["name"] for d in self.client.devices()] self.assertEqual(names, ["Lego Room", "Home Cinema"]) self.assertEqual(self.fake.tokens_issued, 2) def test_a_revoked_refresh_token_raises_a_clear_error(self): self.fake.reject_refresh = True with self.assertRaises(SpotifyError): self.client.devices() if __name__ == "__main__": unittest.main()