Merge remote-tracking branch 'jtwaleson/master'
[youtube-dl] / test / test_write_annotations.py
1 #!/usr/bin/env python
2 # coding: utf-8
3
4 # Allow direct execution
5 import os
6 import sys
7 import unittest
8 sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
9
10 from test.helper import get_params, try_rm
11
12
13 import io
14
15 import xml.etree.ElementTree
16
17 import youtube_dl.YoutubeDL
18 import youtube_dl.extractor
19
20
21 class YoutubeDL(youtube_dl.YoutubeDL):
22     def __init__(self, *args, **kwargs):
23         super(YoutubeDL, self).__init__(*args, **kwargs)
24         self.to_stderr = self.to_screen
25
26 params = get_params({
27     'writeannotations': True,
28     'skip_download': True,
29     'writeinfojson': False,
30     'format': 'flv',
31 })
32
33
34 TEST_ID = 'gr51aVj-mLg'
35 ANNOTATIONS_FILE = TEST_ID + '.flv.annotations.xml'
36 EXPECTED_ANNOTATIONS = ['Speech bubble', 'Note', 'Title', 'Spotlight', 'Label']
37
38
39 class TestAnnotations(unittest.TestCase):
40     def setUp(self):
41         # Clear old files
42         self.tearDown()
43
44     def test_info_json(self):
45         expected = list(EXPECTED_ANNOTATIONS)  # Two annotations could have the same text.
46         ie = youtube_dl.extractor.YoutubeIE()
47         ydl = YoutubeDL(params)
48         ydl.add_info_extractor(ie)
49         ydl.download([TEST_ID])
50         self.assertTrue(os.path.exists(ANNOTATIONS_FILE))
51         annoxml = None
52         with io.open(ANNOTATIONS_FILE, 'r', encoding='utf-8') as annof:
53             annoxml = xml.etree.ElementTree.parse(annof)
54         self.assertTrue(annoxml is not None, 'Failed to parse annotations XML')
55         root = annoxml.getroot()
56         self.assertEqual(root.tag, 'document')
57         annotationsTag = root.find('annotations')
58         self.assertEqual(annotationsTag.tag, 'annotations')
59         annotations = annotationsTag.findall('annotation')
60
61         # Not all the annotations have TEXT children and the annotations are returned unsorted.
62         for a in annotations:
63             self.assertEqual(a.tag, 'annotation')
64             if a.get('type') == 'text':
65                 textTag = a.find('TEXT')
66                 text = textTag.text
67                 self.assertTrue(text in expected)  # assertIn only added in python 2.7
68                 # remove the first occurance, there could be more than one annotation with the same text
69                 expected.remove(text)
70         # We should have seen (and removed) all the expected annotation texts.
71         self.assertEqual(len(expected), 0, 'Not all expected annotations were found.')
72
73     def tearDown(self):
74         try_rm(ANNOTATIONS_FILE)
75
76 if __name__ == '__main__':
77     unittest.main()