diff options
Diffstat (limited to 'test')
| -rw-r--r-- | test/helper.py | 38 | ||||
| -rw-r--r-- | test/test_age_restriction.py | 53 | ||||
| -rw-r--r-- | test/test_dailymotion_subtitles.py | 5 | ||||
| -rw-r--r-- | test/test_download.py | 32 | ||||
| -rw-r--r-- | test/test_playlists.py | 10 | ||||
| -rw-r--r-- | test/test_youtube_subtitles.py | 4 | 
6 files changed, 105 insertions, 37 deletions
diff --git a/test/helper.py b/test/helper.py index a2b468b50..ad1b74dd3 100644 --- a/test/helper.py +++ b/test/helper.py @@ -1,6 +1,9 @@ +import errno  import io  import json  import os.path +import re +import types  import youtube_dl.extractor  from youtube_dl import YoutubeDL, YoutubeDLHandler @@ -9,30 +12,47 @@ from youtube_dl.utils import (      compat_urllib_request,  ) -# General configuration (from __init__, not very elegant...) -jar = compat_cookiejar.CookieJar() -cookie_processor = compat_urllib_request.HTTPCookieProcessor(jar) -proxy_handler = compat_urllib_request.ProxyHandler() -opener = compat_urllib_request.build_opener(proxy_handler, cookie_processor, YoutubeDLHandler()) -compat_urllib_request.install_opener(opener) +youtube_dl._setup_opener(timeout=10)  PARAMETERS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "parameters.json")  with io.open(PARAMETERS_FILE, encoding='utf-8') as pf:      parameters = json.load(pf) + +def try_rm(filename): +    """ Remove a file if it exists """ +    try: +        os.remove(filename) +    except OSError as ose: +        if ose.errno != errno.ENOENT: +            raise + +  class FakeYDL(YoutubeDL):      def __init__(self): -        self.result = []          # Different instances of the downloader can't share the same dictionary          # some test set the "sublang" parameter, which would break the md5 checks. -        self.params = dict(parameters) -    def to_screen(self, s): +        params = dict(parameters) +        super(FakeYDL, self).__init__(params) +        self.result = [] +         +    def to_screen(self, s, skip_eol=None):          print(s) +      def trouble(self, s, tb=None):          raise Exception(s) +      def download(self, x):          self.result.append(x) +    def expect_warning(self, regex): +        # Silence an expected warning matching a regex +        old_report_warning = self.report_warning +        def report_warning(self, message): +            if re.match(regex, message): return +            old_report_warning(message) +        self.report_warning = types.MethodType(report_warning, self) +  def get_testcases():      for ie in youtube_dl.extractor.gen_extractors():          t = getattr(ie, '_TEST', None) diff --git a/test/test_age_restriction.py b/test/test_age_restriction.py new file mode 100644 index 000000000..943f9a315 --- /dev/null +++ b/test/test_age_restriction.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python + +import sys +import unittest + +# Allow direct execution +import os +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from youtube_dl import YoutubeDL +from helper import try_rm + + +def _download_restricted(url, filename, age): +    """ Returns true iff the file has been downloaded """ + +    params = { +        'age_limit': age, +        'skip_download': True, +        'writeinfojson': True, +        "outtmpl": "%(id)s.%(ext)s", +    } +    ydl = YoutubeDL(params) +    ydl.add_default_info_extractors() +    json_filename = filename + '.info.json' +    try_rm(json_filename) +    ydl.download([url]) +    res = os.path.exists(json_filename) +    try_rm(json_filename) +    return res + + +class TestAgeRestriction(unittest.TestCase): +    def _assert_restricted(self, url, filename, age, old_age=None): +        self.assertTrue(_download_restricted(url, filename, old_age)) +        self.assertFalse(_download_restricted(url, filename, age)) + +    def test_youtube(self): +        self._assert_restricted('07FYdnEawAQ', '07FYdnEawAQ.mp4', 10) + +    def test_youporn(self): +        self._assert_restricted( +            'http://www.youporn.com/watch/505835/sex-ed-is-it-safe-to-masturbate-daily/', +            '505835.mp4', 2, old_age=25) + +    def test_pornotube(self): +        self._assert_restricted( +            'http://pornotube.com/c/173/m/1689755/Marilyn-Monroe-Bathing', +            '1689755.flv', 13) + + +if __name__ == '__main__': +    unittest.main() diff --git a/test/test_dailymotion_subtitles.py b/test/test_dailymotion_subtitles.py index 83c65d57e..ed2ad311d 100644 --- a/test/test_dailymotion_subtitles.py +++ b/test/test_dailymotion_subtitles.py @@ -2,8 +2,6 @@  import sys  import unittest -import json -import io  import hashlib  # Allow direct execution @@ -45,15 +43,18 @@ class TestDailymotionSubtitles(unittest.TestCase):          subtitles = self.getSubtitles()          self.assertEqual(len(subtitles.keys()), 5)      def test_list_subtitles(self): +        self.DL.expect_warning(u'Automatic Captions not supported by this server')          self.DL.params['listsubtitles'] = True          info_dict = self.getInfoDict()          self.assertEqual(info_dict, None)      def test_automatic_captions(self): +        self.DL.expect_warning(u'Automatic Captions not supported by this server')          self.DL.params['writeautomaticsub'] = True          self.DL.params['subtitleslang'] = ['en']          subtitles = self.getSubtitles()          self.assertTrue(len(subtitles.keys()) == 0)      def test_nosubtitles(self): +        self.DL.expect_warning(u'video doesn\'t have subtitles')          self.url = 'http://www.dailymotion.com/video/x12u166_le-zapping-tele-star-du-08-aout-2013_tv'          self.DL.params['writesubtitles'] = True          self.DL.params['allsubtitles'] = True diff --git a/test/test_download.py b/test/test_download.py index 23a66254d..fdf59bb5c 100644 --- a/test/test_download.py +++ b/test/test_download.py @@ -1,6 +1,5 @@  #!/usr/bin/env python -import errno  import hashlib  import io  import os @@ -20,22 +19,6 @@ PARAMETERS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "para  RETRIES = 3 -# General configuration (from __init__, not very elegant...) -jar = compat_cookiejar.CookieJar() -cookie_processor = compat_urllib_request.HTTPCookieProcessor(jar) -proxy_handler = compat_urllib_request.ProxyHandler() -opener = compat_urllib_request.build_opener(proxy_handler, cookie_processor, YoutubeDLHandler()) -compat_urllib_request.install_opener(opener) -socket.setdefaulttimeout(10) - -def _try_rm(filename): -    """ Remove a file if it exists """ -    try: -        os.remove(filename) -    except OSError as ose: -        if ose.errno != errno.ENOENT: -            raise -  md5 = lambda s: hashlib.md5(s.encode('utf-8')).hexdigest()  class YoutubeDL(youtube_dl.YoutubeDL): @@ -54,7 +37,8 @@ def _file_md5(fn):      with open(fn, 'rb') as f:          return hashlib.md5(f.read()).hexdigest() -from helper import get_testcases +import helper  # Set up remaining global configuration +from helper import get_testcases, try_rm  defs = get_testcases()  with io.open(PARAMETERS_FILE, encoding='utf-8') as pf: @@ -97,9 +81,9 @@ def generator(test_case):          test_cases = test_case.get('playlist', [test_case])          for tc in test_cases: -            _try_rm(tc['file']) -            _try_rm(tc['file'] + '.part') -            _try_rm(tc['file'] + '.info.json') +            try_rm(tc['file']) +            try_rm(tc['file'] + '.part') +            try_rm(tc['file'] + '.info.json')          try:              for retry in range(1, RETRIES + 1):                  try: @@ -145,9 +129,9 @@ def generator(test_case):                      self.assertTrue(key in info_dict.keys() and info_dict[key])          finally:              for tc in test_cases: -                _try_rm(tc['file']) -                _try_rm(tc['file'] + '.part') -                _try_rm(tc['file'] + '.info.json') +                try_rm(tc['file']) +                try_rm(tc['file'] + '.part') +                try_rm(tc['file'] + '.info.json')      return test_template diff --git a/test/test_playlists.py b/test/test_playlists.py index c33511333..de8bd298a 100644 --- a/test/test_playlists.py +++ b/test/test_playlists.py @@ -16,6 +16,7 @@ from youtube_dl.extractor import (      UstreamChannelIE,      SoundcloudUserIE,      LivestreamIE, +    NHLVideocenterIE,  )  from youtube_dl.utils import * @@ -74,5 +75,14 @@ class TestPlaylists(unittest.TestCase):          self.assertEqual(result['title'], u'TEDCity2.0 (English)')          self.assertTrue(len(result['entries']) >= 4) +    def test_nhl_videocenter(self): +        dl = FakeYDL() +        ie = NHLVideocenterIE(dl) +        result = ie.extract('http://video.canucks.nhl.com/videocenter/console?catid=999') +        self.assertIsPlaylist(result) +        self.assertEqual(result['id'], u'999') +        self.assertEqual(result['title'], u'Highlights') +        self.assertEqual(len(result['entries']), 12) +  if __name__ == '__main__':      unittest.main() diff --git a/test/test_youtube_subtitles.py b/test/test_youtube_subtitles.py index 168e6c66c..f9b0c1ad0 100644 --- a/test/test_youtube_subtitles.py +++ b/test/test_youtube_subtitles.py @@ -2,8 +2,6 @@  import sys  import unittest -import json -import io  import hashlib  # Allow direct execution @@ -56,6 +54,7 @@ class TestYoutubeSubtitles(unittest.TestCase):          subtitles = self.getSubtitles()          self.assertEqual(md5(subtitles['en']), '356cdc577fde0c6783b9b822e7206ff7')      def test_youtube_list_subtitles(self): +        self.DL.expect_warning(u'Video doesn\'t have automatic captions')          self.DL.params['listsubtitles'] = True          info_dict = self.getInfoDict()          self.assertEqual(info_dict, None) @@ -66,6 +65,7 @@ class TestYoutubeSubtitles(unittest.TestCase):          subtitles = self.getSubtitles()          self.assertTrue(subtitles['it'] is not None)      def test_youtube_nosubtitles(self): +        self.DL.expect_warning(u'video doesn\'t have subtitles')          self.url = 'sAjKT8FhjI8'          self.DL.params['writesubtitles'] = True          self.DL.params['allsubtitles'] = True  | 
