3 # Allow direct execution
8 sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11 import xml.etree.ElementTree
13 import yt_dlp.extractor
14 import yt_dlp.YoutubeDL
15 from test.helper import get_params, is_download_test, try_rm
18 class YoutubeDL(yt_dlp.YoutubeDL):
19 def __init__(self, *args, **kwargs):
20 super().__init__(*args, **kwargs)
21 self.to_stderr = self.to_screen
25 'writeannotations': True,
26 'skip_download': True,
27 'writeinfojson': False,
32 TEST_ID = 'gr51aVj-mLg'
33 ANNOTATIONS_FILE = TEST_ID + '.annotations.xml'
34 EXPECTED_ANNOTATIONS = ['Speech bubble', 'Note', 'Title', 'Spotlight', 'Label']
38 class TestAnnotations(unittest.TestCase):
43 def test_info_json(self):
44 expected = list(EXPECTED_ANNOTATIONS) # Two annotations could have the same text.
45 ie = yt_dlp.extractor.YoutubeIE()
46 ydl = YoutubeDL(params)
47 ydl.add_info_extractor(ie)
48 ydl.download([TEST_ID])
49 self.assertTrue(os.path.exists(ANNOTATIONS_FILE))
51 with open(ANNOTATIONS_FILE, encoding='utf-8') as annof:
52 annoxml = xml.etree.ElementTree.parse(annof)
53 self.assertTrue(annoxml is not None, 'Failed to parse annotations XML')
54 root = annoxml.getroot()
55 self.assertEqual(root.tag, 'document')
56 annotationsTag = root.find('annotations')
57 self.assertEqual(annotationsTag.tag, 'annotations')
58 annotations = annotationsTag.findall('annotation')
60 # Not all the annotations have TEXT children and the annotations are returned unsorted.
62 self.assertEqual(a.tag, 'annotation')
63 if a.get('type') == 'text':
64 textTag = a.find('TEXT')
66 self.assertTrue(text in expected) # assertIn only added in python 2.7
67 # remove the first occurrence, there could be more than one annotation with the same text
69 # We should have seen (and removed) all the expected annotation texts.
70 self.assertEqual(len(expected), 0, 'Not all expected annotations were found.')
73 try_rm(ANNOTATIONS_FILE)
76 if __name__ == '__main__':