1#!/usr/bin/env python3 2# Copyright 2018 the V8 project authors. All rights reserved. 3# Use of this source code is governed by a BSD-style license that can be 4# found in the LICENSE file. 5 6import os 7import sys 8import tempfile 9import unittest 10 11# Configuring the path for the v8_presubmit module 12TOOLS_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 13sys.path.append(TOOLS_ROOT) 14 15from v8_presubmit import FileContentsCache, CacheableSourceFileProcessor 16 17 18class FakeCachedProcessor(CacheableSourceFileProcessor): 19 def __init__(self, cache_file_path): 20 super(FakeCachedProcessor, self).__init__( 21 use_cache=True, cache_file_path=cache_file_path, file_type='.test') 22 def GetProcessorWorker(self): 23 return object 24 def GetProcessorScript(self): 25 return "echo", [] 26 def DetectUnformattedFiles(_, cmd, worker, files): 27 raise NotImplementedError 28 29class FileContentsCacheTest(unittest.TestCase): 30 def setUp(self): 31 _, self.cache_file_path = tempfile.mkstemp() 32 cache = FileContentsCache(self.cache_file_path) 33 cache.Load() 34 35 def generate_file(): 36 _, file_name = tempfile.mkstemp() 37 with open(file_name, "w") as f: 38 f.write(file_name) 39 40 return file_name 41 42 self.target_files = [generate_file() for _ in range(2)] 43 unchanged_files = cache.FilterUnchangedFiles(self.target_files) 44 self.assertEqual(len(unchanged_files), 2) 45 cache.Save() 46 47 def tearDown(self): 48 for file in [self.cache_file_path] + self.target_files: 49 os.remove(file) 50 51 def testCachesFiles(self): 52 cache = FileContentsCache(self.cache_file_path) 53 cache.Load() 54 55 changed_files = cache.FilterUnchangedFiles(self.target_files) 56 self.assertListEqual(changed_files, []) 57 58 modified_file = self.target_files[0] 59 with open(modified_file, "w") as f: 60 f.write("modification") 61 62 changed_files = cache.FilterUnchangedFiles(self.target_files) 63 self.assertListEqual(changed_files, [modified_file]) 64 65 def testCacheableSourceFileProcessor(self): 66 class CachedProcessor(FakeCachedProcessor): 67 def DetectFilesToChange(_, files): 68 self.assertListEqual(files, []) 69 return [] 70 71 cached_processor = CachedProcessor(cache_file_path=self.cache_file_path) 72 cached_processor.ProcessFiles(self.target_files) 73 74 def testCacheableSourceFileProcessorWithModifications(self): 75 modified_file = self.target_files[0] 76 with open(modified_file, "w") as f: 77 f.write("modification") 78 79 class CachedProcessor(FakeCachedProcessor): 80 def DetectFilesToChange(_, files): 81 self.assertListEqual(files, [modified_file]) 82 return [] 83 84 cached_processor = CachedProcessor( 85 cache_file_path=self.cache_file_path, 86 ) 87 cached_processor.ProcessFiles(self.target_files) 88 89 90if __name__ == '__main__': 91 unittest.main() 92