"""Tests for Apple Music Analytics Utils tool.""" import datetime import os from unittest import mock, TestCase import command as cmd from feed_ingestion.util.apple_music_analytics import \ EmptyReportException, MusicAnalyticsAPI, \ MusicAnalyticsUtils, PrivateKeyFilePath VALID_CREDS = ['musicanalytics-utils-0.2.0.jar', 'HDBLWK420V', '9204nfsf-s94n-fsj0-13jeew-829h24fnfs', '123456'] INVALID_CREDS = ['analytics-0.2.0.jar', 'HD420V', '9204nfsf-s94n-fsj0', '123956'] class MockResponse(): """Response mock class.""" def __init__(self, text, code): """Initialise.""" self.text = text self.status_code = code def __iter__(self): """Iterate.""" self.r = 0 return self def __next__(self): """Return next.""" if self.r <= len(self.text): res = self.text[self.r] self.r += 1 return res else: raise StopIteration class TestMusicAnalyticsUtils(TestCase): """Test class for MusicAnalyticsUtils.""" utils = MusicAnalyticsUtils(*VALID_CREDS) def test_validators(self): """Test ValueError for vars validators.""" self.assertEqual([self.utils.music_analytics_jar, self.utils.key_id, self.utils.team_id], VALID_CREDS[:-1]) with self.assertRaises(ValueError): MusicAnalyticsUtils(*INVALID_CREDS) def test_get_private_key_file(self): """Test get_private_key_file method.""" self.utils.get_private_key_file() private_key = PrivateKeyFilePath( VALID_CREDS[1]).file self.assertTrue(os.path.exists(private_key)) pk_file = open(private_key, 'r') self.assertEqual(pk_file.readlines()[1].replace('\n', ''), VALID_CREDS[3]) os.remove(private_key) def test_generate_fresh_token(self): """Test generate_fresh_token method.""" self.utils.get_private_key_file() private_key = PrivateKeyFilePath( VALID_CREDS[1]).file with self.assertRaises(cmd.core.CommandException): # cannot access the .jar file musicanalytics-utils-0.2.0.jar. self.utils.generate_fresh_token(private_key) class TestMusicAnalyticsAPI(TestCase): """Test call for MusicAnalyticsUtils.""" utils = MusicAnalyticsUtils(*VALID_CREDS) api = MusicAnalyticsAPI(utils) @mock.patch('requests.get') @mock.patch('feed_ingestion.util.apple_music_analytics.' 'MusicAnalyticsAPI.generate_key_and_set_token') def test_get_empty_in_review_report(self, mock_token, mock_call): """Test get_in_review_report method with invalid report.""" rptg_date = (datetime.datetime.today() + datetime.timedelta(days=5)).strftime('%Y-%m-%d') mock_call.return_value = MockResponse('text', 200) with self.assertRaises(EmptyReportException): self.api.get_in_review_report(rptg_date) @mock.patch('requests.get') @mock.patch('feed_ingestion.util.apple_music_analytics.' 'MusicAnalyticsAPI.generate_key_and_set_token') def test_get_in_review_report(self, mock_token, mock_call): """Test get_in_review_report method with normal-length report.""" rptg_date = '2022-12-07' mock_call.return_value = MockResponse('text\t' * 247, 200) # todo update the parsing by headers and date report = self.api.get_in_review_report(rptg_date) self.assertEqual(report, mock_call.return_value.text)