test_write_annotations.py 2.6 KB

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