@Test public void concurrent_download() throws IOException { FileHashes hashes = mock(FileHashes.class); when(hashes.of(any(File.class))).thenReturn("ABCDE"); final FileCache cache = new FileCache(tempFolder.newFolder(), log, hashes); FileCache.Downloader downloader = new FileCache.Downloader() { public void download(String filename, File toFile) throws IOException { // Emulate a concurrent download that adds file to cache before File cachedFile = new File(new File(cache.getDir(), "ABCDE"), "sonar-foo-plugin-1.5.jar"); FileUtils.write(cachedFile, "downloaded by other"); FileUtils.write(toFile, "downloaded by me"); } }; // do not fail File cachedFile = cache.get("sonar-foo-plugin-1.5.jar", "ABCDE", downloader); assertThat(cachedFile).isNotNull().exists().isFile(); assertThat(cachedFile.getName()).isEqualTo("sonar-foo-plugin-1.5.jar"); assertThat(cachedFile.getParentFile().getParentFile()).isEqualTo(cache.getDir()); assertThat(FileUtils.readFileToString(cachedFile)).contains("downloaded by"); }
@Override @CheckForNull public String getLineHash() { if (getLine() == null || hashes == null) { return null; } int line = getLine(); Preconditions.checkState( line <= hashes.length(), "Invalid line number for issue %s. File has only %s line(s)", this, hashes.length()); return hashes.getHash(line); }
@Test public void download_corrupted_file() throws IOException { thrown.expect(IllegalStateException.class); thrown.expectMessage("INVALID HASH"); FileHashes hashes = mock(FileHashes.class); FileCache cache = new FileCache(tempFolder.newFolder(), log, hashes); when(hashes.of(any(File.class))).thenReturn("VWXYZ"); FileCache.Downloader downloader = new FileCache.Downloader() { public void download(String filename, File toFile) throws IOException { FileUtils.write(toFile, "corrupted body"); } }; cache.get("sonar-foo-plugin-1.5.jar", "ABCDE", downloader); }
@Test public void download_and_add_to_cache() throws IOException { FileHashes hashes = mock(FileHashes.class); FileCache cache = new FileCache(tempFolder.newFolder(), log, hashes); when(hashes.of(any(File.class))).thenReturn("ABCDE"); FileCache.Downloader downloader = new FileCache.Downloader() { public void download(String filename, File toFile) throws IOException { FileUtils.write(toFile, "body"); } }; File cachedFile = cache.get("sonar-foo-plugin-1.5.jar", "ABCDE", downloader); assertThat(cachedFile).isNotNull().exists().isFile(); assertThat(cachedFile.getName()).isEqualTo("sonar-foo-plugin-1.5.jar"); assertThat(cachedFile.getParentFile().getParentFile()).isEqualTo(cache.getDir()); assertThat(FileUtils.readFileToString(cachedFile)).isEqualTo("body"); }