test_cache.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. """
  2. Test all things related to the ``jedi.cache`` module.
  3. """
  4. import os
  5. import pytest
  6. import time
  7. from pathlib import Path
  8. from parso.cache import (_CACHED_FILE_MAXIMUM_SURVIVAL, _VERSION_TAG,
  9. _get_cache_clear_lock_path, _get_hashed_path,
  10. _load_from_file_system, _NodeCacheItem,
  11. _remove_cache_and_update_lock, _save_to_file_system,
  12. load_module, parser_cache, try_to_save_module)
  13. from parso._compatibility import is_pypy
  14. from parso import load_grammar
  15. from parso import cache
  16. from parso import file_io
  17. from parso import parse
  18. skip_pypy = pytest.mark.skipif(
  19. is_pypy,
  20. reason="pickling in pypy is slow, since we don't pickle,"
  21. "we never go into path of auto-collecting garbage"
  22. )
  23. @pytest.fixture()
  24. def isolated_parso_cache(monkeypatch, tmpdir):
  25. """Set `parso.cache._default_cache_path` to a temporary directory
  26. during the test. """
  27. cache_path = Path(str(tmpdir), "__parso_cache")
  28. monkeypatch.setattr(cache, '_default_cache_path', cache_path)
  29. return cache_path
  30. @pytest.mark.skip("SUBBOTNIK-2721 Disable load cache from disk")
  31. def test_modulepickling_change_cache_dir(tmpdir):
  32. """
  33. ParserPickling should not save old cache when cache_directory is changed.
  34. See: `#168 <https://github.com/davidhalter/jedi/pull/168>`_
  35. """
  36. dir_1 = Path(str(tmpdir.mkdir('first')))
  37. dir_2 = Path(str(tmpdir.mkdir('second')))
  38. item_1 = _NodeCacheItem('bla', [])
  39. item_2 = _NodeCacheItem('bla', [])
  40. path_1 = Path('fake path 1')
  41. path_2 = Path('fake path 2')
  42. hashed_grammar = load_grammar()._hashed
  43. _save_to_file_system(hashed_grammar, path_1, item_1, cache_path=dir_1)
  44. parser_cache.clear()
  45. cached = load_stored_item(hashed_grammar, path_1, item_1, cache_path=dir_1)
  46. assert cached == item_1.node
  47. _save_to_file_system(hashed_grammar, path_2, item_2, cache_path=dir_2)
  48. cached = load_stored_item(hashed_grammar, path_1, item_1, cache_path=dir_2)
  49. assert cached is None
  50. def load_stored_item(hashed_grammar, path, item, cache_path):
  51. """Load `item` stored at `path` in `cache`."""
  52. item = _load_from_file_system(hashed_grammar, path, item.change_time - 1, cache_path)
  53. return item
  54. @pytest.mark.usefixtures("isolated_parso_cache")
  55. def test_modulepickling_simulate_deleted_cache(tmpdir):
  56. """
  57. Tests loading from a cache file after it is deleted.
  58. According to macOS `dev docs`__,
  59. Note that the system may delete the Caches/ directory to free up disk
  60. space, so your app must be able to re-create or download these files as
  61. needed.
  62. It is possible that other supported platforms treat cache files the same
  63. way.
  64. __ https://developer.apple.com/library/content/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html
  65. """ # noqa
  66. grammar = load_grammar()
  67. module = 'fake parser'
  68. # Create the file
  69. path = Path(str(tmpdir.dirname), 'some_path')
  70. with open(path, 'w'):
  71. pass
  72. io = file_io.FileIO(path)
  73. try_to_save_module(grammar._hashed, io, module, lines=[])
  74. assert load_module(grammar._hashed, io) == module
  75. os.unlink(_get_hashed_path(grammar._hashed, path))
  76. parser_cache.clear()
  77. cached2 = load_module(grammar._hashed, io)
  78. assert cached2 is None
  79. @pytest.mark.skip
  80. def test_cache_limit():
  81. def cache_size():
  82. return sum(len(v) for v in parser_cache.values())
  83. try:
  84. parser_cache.clear()
  85. future_node_cache_item = _NodeCacheItem('bla', [], change_time=time.time() + 10e6)
  86. old_node_cache_item = _NodeCacheItem('bla', [], change_time=time.time() - 10e4)
  87. parser_cache['some_hash_old'] = {
  88. '/path/%s' % i: old_node_cache_item for i in range(300)
  89. }
  90. parser_cache['some_hash_new'] = {
  91. '/path/%s' % i: future_node_cache_item for i in range(300)
  92. }
  93. assert cache_size() == 600
  94. parse('somecode', cache=True, path='/path/somepath')
  95. assert cache_size() == 301
  96. finally:
  97. parser_cache.clear()
  98. class _FixedTimeFileIO(file_io.KnownContentFileIO):
  99. def __init__(self, path, content, last_modified):
  100. super().__init__(path, content)
  101. self._last_modified = last_modified
  102. def get_last_modified(self):
  103. return self._last_modified
  104. @pytest.mark.skip
  105. @pytest.mark.parametrize('diff_cache', [False, True])
  106. @pytest.mark.parametrize('use_file_io', [False, True])
  107. def test_cache_last_used_update(diff_cache, use_file_io):
  108. p = Path('/path/last-used')
  109. parser_cache.clear() # Clear, because then it's easier to find stuff.
  110. parse('somecode', cache=True, path=p)
  111. node_cache_item = next(iter(parser_cache.values()))[p]
  112. now = time.time()
  113. assert node_cache_item.last_used <= now
  114. if use_file_io:
  115. f = _FixedTimeFileIO(p, 'code', node_cache_item.last_used - 10)
  116. parse(file_io=f, cache=True, diff_cache=diff_cache)
  117. else:
  118. parse('somecode2', cache=True, path=p, diff_cache=diff_cache)
  119. node_cache_item = next(iter(parser_cache.values()))[p]
  120. assert now <= node_cache_item.last_used <= time.time()
  121. @skip_pypy
  122. def test_inactive_cache(tmpdir, isolated_parso_cache):
  123. parser_cache.clear()
  124. test_subjects = "abcdef"
  125. for path in test_subjects:
  126. parse('somecode', cache=True, path=os.path.join(str(tmpdir), path))
  127. raw_cache_path = isolated_parso_cache.joinpath(_VERSION_TAG)
  128. assert raw_cache_path.exists()
  129. dir_names = os.listdir(raw_cache_path)
  130. a_while_ago = time.time() - _CACHED_FILE_MAXIMUM_SURVIVAL
  131. old_paths = set()
  132. for dir_name in dir_names[:len(test_subjects) // 2]: # make certain number of paths old
  133. os.utime(raw_cache_path.joinpath(dir_name), (a_while_ago, a_while_ago))
  134. old_paths.add(dir_name)
  135. # nothing should be cleared while the lock is on
  136. assert _get_cache_clear_lock_path().exists()
  137. _remove_cache_and_update_lock() # it shouldn't clear anything
  138. assert len(os.listdir(raw_cache_path)) == len(test_subjects)
  139. assert old_paths.issubset(os.listdir(raw_cache_path))
  140. os.utime(_get_cache_clear_lock_path(), (a_while_ago, a_while_ago))
  141. _remove_cache_and_update_lock()
  142. assert len(os.listdir(raw_cache_path)) == len(test_subjects) // 2
  143. assert not old_paths.intersection(os.listdir(raw_cache_path))
  144. @pytest.mark.skip
  145. @skip_pypy
  146. def test_permission_error(monkeypatch):
  147. def save(*args, **kwargs):
  148. nonlocal was_called
  149. was_called = True
  150. raise PermissionError
  151. was_called = False
  152. monkeypatch.setattr(cache, '_save_to_file_system', save)
  153. try:
  154. with pytest.warns(Warning):
  155. parse(path=__file__, cache=True, diff_cache=True)
  156. assert was_called
  157. finally:
  158. parser_cache.clear()