test_write_annotations.py 2.5 KB

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