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