test_YoutubeDLCookieJar.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/env python3
  2. # Allow direct execution
  3. import os
  4. import sys
  5. import unittest
  6. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  7. import re
  8. import tempfile
  9. from yt_dlp.cookies import YoutubeDLCookieJar
  10. class TestYoutubeDLCookieJar(unittest.TestCase):
  11. def test_keep_session_cookies(self):
  12. cookiejar = YoutubeDLCookieJar('./test/testdata/cookies/session_cookies.txt')
  13. cookiejar.load()
  14. tf = tempfile.NamedTemporaryFile(delete=False)
  15. try:
  16. cookiejar.save(filename=tf.name)
  17. temp = tf.read().decode()
  18. self.assertTrue(re.search(
  19. r'www\.foobar\.foobar\s+FALSE\s+/\s+TRUE\s+0\s+YoutubeDLExpiresEmpty\s+YoutubeDLExpiresEmptyValue', temp))
  20. self.assertTrue(re.search(
  21. r'www\.foobar\.foobar\s+FALSE\s+/\s+TRUE\s+0\s+YoutubeDLExpires0\s+YoutubeDLExpires0Value', temp))
  22. finally:
  23. tf.close()
  24. os.remove(tf.name)
  25. def test_strip_httponly_prefix(self):
  26. cookiejar = YoutubeDLCookieJar('./test/testdata/cookies/httponly_cookies.txt')
  27. cookiejar.load()
  28. def assert_cookie_has_value(key):
  29. self.assertEqual(cookiejar._cookies['www.foobar.foobar']['/'][key].value, key + '_VALUE')
  30. assert_cookie_has_value('HTTPONLY_COOKIE')
  31. assert_cookie_has_value('JS_ACCESSIBLE_COOKIE')
  32. def test_malformed_cookies(self):
  33. cookiejar = YoutubeDLCookieJar('./test/testdata/cookies/malformed_cookies.txt')
  34. cookiejar.load()
  35. # Cookies should be empty since all malformed cookie file entries
  36. # will be ignored
  37. self.assertFalse(cookiejar._cookies)
  38. def test_get_cookie_header(self):
  39. cookiejar = YoutubeDLCookieJar('./test/testdata/cookies/httponly_cookies.txt')
  40. cookiejar.load()
  41. header = cookiejar.get_cookie_header('https://www.foobar.foobar')
  42. self.assertIn('HTTPONLY_COOKIE', header)
  43. def test_get_cookies_for_url(self):
  44. cookiejar = YoutubeDLCookieJar('./test/testdata/cookies/session_cookies.txt')
  45. cookiejar.load()
  46. cookies = cookiejar.get_cookies_for_url('https://www.foobar.foobar/')
  47. self.assertEqual(len(cookies), 2)
  48. cookies = cookiejar.get_cookies_for_url('https://foobar.foobar/')
  49. self.assertFalse(cookies)
  50. if __name__ == '__main__':
  51. unittest.main()