test_cache.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. import shutil
  10. from test.helper import FakeYDL
  11. from youtube_dl.cache import Cache
  12. from youtube_dl.utils import version_tuple
  13. from youtube_dl.version import __version__
  14. def _is_empty(d):
  15. return not bool(os.listdir(d))
  16. def _mkdir(d):
  17. if not os.path.exists(d):
  18. os.mkdir(d)
  19. class TestCache(unittest.TestCase):
  20. def setUp(self):
  21. TEST_DIR = os.path.dirname(os.path.abspath(__file__))
  22. TESTDATA_DIR = os.path.join(TEST_DIR, 'testdata')
  23. _mkdir(TESTDATA_DIR)
  24. self.test_dir = os.path.join(TESTDATA_DIR, 'cache_test')
  25. self.tearDown()
  26. def tearDown(self):
  27. if os.path.exists(self.test_dir):
  28. shutil.rmtree(self.test_dir)
  29. def test_cache(self):
  30. ydl = FakeYDL({
  31. 'cachedir': self.test_dir,
  32. })
  33. c = Cache(ydl)
  34. obj = {'x': 1, 'y': ['ä', '\\a', True]}
  35. self.assertEqual(c.load('test_cache', 'k.'), None)
  36. c.store('test_cache', 'k.', obj)
  37. self.assertEqual(c.load('test_cache', 'k2'), None)
  38. self.assertFalse(_is_empty(self.test_dir))
  39. self.assertEqual(c.load('test_cache', 'k.'), obj)
  40. self.assertEqual(c.load('test_cache', 'y'), None)
  41. self.assertEqual(c.load('test_cache2', 'k.'), None)
  42. c.remove()
  43. self.assertFalse(os.path.exists(self.test_dir))
  44. self.assertEqual(c.load('test_cache', 'k.'), None)
  45. def test_cache_validation(self):
  46. ydl = FakeYDL({
  47. 'cachedir': self.test_dir,
  48. })
  49. c = Cache(ydl)
  50. obj = {'x': 1, 'y': ['ä', '\\a', True]}
  51. c.store('test_cache', 'k.', obj)
  52. self.assertEqual(c.load('test_cache', 'k.', min_ver='1970.01.01'), obj)
  53. new_version = '.'.join(('%d' % ((v + 1) if i == 0 else v, )) for i, v in enumerate(version_tuple(__version__)))
  54. self.assertIs(c.load('test_cache', 'k.', min_ver=new_version), None)
  55. if __name__ == '__main__':
  56. unittest.main()