@Before public void setUp() { MockitoAnnotations.initMocks(this); MemoryCacheParams params = new MemoryCacheParams( 4 * ByteConstants.MB, 256, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE); when(mMemoryCacheParamsSupplier.get()).thenReturn(params); CountingMemoryCache<CacheKey, CloseableImage> countingMemoryCache = BitmapCountingMemoryCacheFactory.get( mMemoryCacheParamsSupplier, mMemoryTrimmableRegistry, mPlatformBitmapFactory, true); mCacheKey = new SimpleCacheKey("key"); mAnimatedFrameCache = new AnimatedFrameCache(mCacheKey, countingMemoryCache); mFrame1 = CloseableReference.of(mock(CloseableImage.class)); mFrame2 = CloseableReference.of(mock(CloseableImage.class)); }
@Test public void testWithMultiCacheKeys() throws Exception { CacheKey insertKey1 = new SimpleCacheKey("foo"); byte[] value1 = new byte[101]; value1[50] = 'a'; // just so it's not all zeros for the equality test below. mCache.insert(insertKey1, WriterCallbacks.from(value1)); List<CacheKey> keys1 = new ArrayList<>(2); keys1.add(new SimpleCacheKey("bar")); keys1.add(new SimpleCacheKey("foo")); MultiCacheKey matchingMultiKey = new MultiCacheKey(keys1); assertArrayEquals(value1, getContents(mCache.getResource(matchingMultiKey))); List<CacheKey> keys2 = new ArrayList<>(2); keys2.add(new SimpleCacheKey("one")); keys2.add(new SimpleCacheKey("two")); MultiCacheKey insertKey2 = new MultiCacheKey(keys2); byte[] value2 = new byte[101]; value1[50] = 'b'; // just so it's not all zeros for the equality test below. mCache.insert(insertKey2, WriterCallbacks.from(value2)); CacheKey matchingSimpleKey = new SimpleCacheKey("one"); assertArrayEquals(value2, getContents(mCache.getResource(matchingSimpleKey))); }
@Test public void testCleanOldCacheNoEntriesRemaining() throws IOException { long cacheExpirationMs = TimeUnit.DAYS.toMillis(5); CacheKey key1 = new SimpleCacheKey("aaa"); byte[] value1 = new byte[41]; mCache.insert(key1, WriterCallbacks.from(value1)); CacheKey key2 = new SimpleCacheKey("bbb"); byte[] value2 = new byte[42]; mCache.insert(key2, WriterCallbacks.from(value2)); // Increment clock by default expiration time + 1 day when(mClock.now()) .thenReturn(cacheExpirationMs+ TimeUnit.DAYS.toMillis(1)); long oldestEntry = mCache.clearOldEntries(cacheExpirationMs); assertEquals(0L, oldestEntry); }
/** * Verify that multiple threads can write to the cache at the same time. */ @Test public void testConcurrency() throws Exception { final CyclicBarrier barrier = new CyclicBarrier(3); WriterCallback writerCallback = new WriterCallback() { @Override public void write(OutputStream os) throws IOException { try { // Both threads will need to hit this barrier. If writing is serialized, // the second thread will never reach here as the first will hold // the write lock forever. barrier.await(10, TimeUnit.SECONDS); } catch (Exception e) { throw new RuntimeException(e); } } }; CacheKey key1 = new SimpleCacheKey("concurrent1"); CacheKey key2 = new SimpleCacheKey("concurrent2"); Thread t1 = runInsertionInSeparateThread(key1, writerCallback); Thread t2 = runInsertionInSeparateThread(key2, writerCallback); barrier.await(10, TimeUnit.SECONDS); t1.join(1000); t2.join(1000); }
@Test public void testSizeEvictionClearsIndex() throws Exception { when(mClock.now()).thenReturn(TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS)); CacheKey key1 = putOneThingInCache(); CacheKey key2 = new SimpleCacheKey("bar"); CacheKey key3 = new SimpleCacheKey("duck"); byte[] value2 = new byte[(int) FILE_CACHE_MAX_SIZE_HIGH_LIMIT]; value2[80] = 'c'; WriterCallback callback = WriterCallbacks.from(value2); when(mClock.now()).thenReturn(TimeUnit.MILLISECONDS.convert(2, TimeUnit.DAYS)); mCache.insert(key2, callback); // now over limit. Next write will evict key1 when(mClock.now()).thenReturn(TimeUnit.MILLISECONDS.convert(3, TimeUnit.DAYS)); mCache.insert(key3, callback); assertFalse(mCache.hasKeySync(key1)); assertFalse(mCache.hasKey(key1)); assertTrue(mCache.hasKeySync(key3)); assertTrue(mCache.hasKey(key3)); }
@Before public void setUp() { MockitoAnnotations.initMocks(this); mMemoryCacheProducer = new PostprocessedBitmapMemoryCacheProducer(mMemoryCache, mCacheKeyFactory, mInputProducer); mPostProcessorCacheKey = new SimpleCacheKey("blur"); mPostprocessedBitmapCacheKey = new SimpleCacheKey("http://dummy.uri:blur"); mImageRef2 = CloseableReference.of(mImage1); mImageRef1 = CloseableReference.of(mImage2); mImageRef2Clone = mImageRef2.clone(); mImageRef1Clone = mImageRef1.clone(); when(mProducerContext.getImageRequest()).thenReturn(mImageRequest); when(mProducerContext.getListener()).thenReturn(mProducerListener); when(mProducerListener.requiresExtraMap(mRequestId)).thenReturn(true); when(mProducerContext.getId()).thenReturn(mRequestId); when(mProducerContext.getCallerContext()).thenReturn(PRODUCER_NAME); when(mImageRequest.getPostprocessor()).thenReturn(mPostprocessor); when(mPostprocessor.getPostprocessorCacheKey()).thenReturn(mPostProcessorCacheKey); when(mRepeatedPostprocessor.getPostprocessorCacheKey()).thenReturn(mPostProcessorCacheKey); when(mCacheKeyFactory.getPostprocessedBitmapCacheKey(mImageRequest, PRODUCER_NAME)) .thenReturn(mPostprocessedBitmapCacheKey); }
@Override public String getCachePath(String uri) { if(VanGogh.isHttpUrl(uri)){ ///自己没摸索出来 // ImageRequest r = ImageRequestBuilder.newBuilderWithSource(Uri.parse(uri)).build(); // DiskStorageCache cache = Fresco.getImagePipelineFactory().getMainDiskStorageCache(); // CacheKey key = DefaultCacheKeyFactory.getInstance().getEncodedCacheKey(r); // if(cache.hasKey(key)){ // return cache.getResource(). // } ///网上找的方法,说是不推荐 FileBinaryResource resource = (FileBinaryResource)Fresco.getImagePipelineFactory() .getMainDiskStorageCache().getResource(new SimpleCacheKey(uri.toString())); File file = resource.getFile(); return file.getAbsolutePath(); }else{ return uri; } }
@Test public void testCacheEventListener() throws Exception { // 1. Add first cache file CacheKey key1 = new SimpleCacheKey("foo"); int value1Size = 101; byte[] value1 = new byte[value1Size]; value1[80] = 'c'; // just so it's not all zeros for the equality test below. BinaryResource resource1 = mCache.insert(key1, WriterCallbacks.from(value1)); verifyListenerOnWriteAttempt(key1); String resourceId1 = verifyListenerOnWriteSuccessAndGetResourceId(key1, value1Size); BinaryResource resource1Again = mCache.getResource(key1); assertEquals(resource1, resource1Again); verifyListenerOnHit(key1, resourceId1); BinaryResource resource1Again2 = mCache.getResource(key1); assertEquals(resource1, resource1Again2); verifyListenerOnHit(key1, resourceId1); SimpleCacheKey missingKey = new SimpleCacheKey("nonexistent_key"); BinaryResource res2 = mCache.getResource(missingKey); assertNull(res2); verifyListenerOnMiss(missingKey); mCache.clearAll(); verify(mCacheEventListener).onCleared(); verifyNoMoreInteractions(mCacheEventListener); }
/** * Test to make sure that the same item stored with two different versions * of the cache will be stored with two different file names. * * @throws UnsupportedEncodingException */ @Test public void testVersioning() throws IOException { // Define data that will be written to cache CacheKey key = new SimpleCacheKey("version_test"); byte[] value = new byte[32]; value[0] = 'v'; // Set up cache with version == 1 DiskStorage storage1 = createDiskStorage(TESTCACHE_CURRENT_VERSION); DiskStorageCache cache1 = createDiskCache(storage1, false); // Write test data to cache 1 cache1.insert(key, WriterCallbacks.from(value)); // Get cached file BinaryResource resource1 = getResource(storage1, key); assertNotNull(resource1); // Set up cache with version == 2 DiskStorage storageSupplier2 = createDiskStorage(TESTCACHE_NEXT_VERSION); DiskStorageCache cache2 = createDiskCache(storageSupplier2, false); // Write test data to cache 2 cache2.insert(key, WriterCallbacks.from(value)); // Get cached file BinaryResource resource2 = getResource(storageSupplier2, key); assertNotNull(resource2); // Make sure filenames of the two file are different assertFalse(resource2.equals(resource1)); }
private CacheKey putOneThingInCache(DiskStorageCache cache) throws IOException { CacheKey key = new SimpleCacheKey("foo"); byte[] value1 = new byte[101]; value1[80] = 'c'; cache.insert(key, WriterCallbacks.from(value1)); return key; }
@Override public CacheKey getEncodedCacheKey( ImageRequest request, Uri sourceUri, @Nullable Object callerContext) { return new SimpleCacheKey(getCacheKeySourceUri(sourceUri).toString()); }
@Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); mCloseableReference = CloseableReference.of(mPooledByteBuffer); mEncodedImage = new EncodedImage(mCloseableReference); List<CacheKey> keys = new ArrayList<>(); keys.add(new SimpleCacheKey("http://test.uri")); keys.add(new SimpleCacheKey("http://tyrone.uri")); keys.add(new SimpleCacheKey("http://ian.uri")); mCacheKey = new MultiCacheKey(keys); mIsCancelled = new AtomicBoolean(false); FakeClock fakeClock = new FakeClock(); mReadPriorityExecutor = new TestExecutorService(fakeClock); mWritePriorityExecutor = new TestExecutorService(fakeClock); when(mBinaryResource.openStream()).thenReturn(mInputStream); when(mBinaryResource.size()).thenReturn(123L); when(mByteBufferFactory.newByteBuffer(same(mInputStream), eq(123))) .thenReturn(mPooledByteBuffer); mockStatic(StagingArea.class); when(StagingArea.getInstance()).thenReturn(mStagingArea); mBufferedDiskCache = new BufferedDiskCache( mFileCache, mByteBufferFactory, mPooledByteStreams, mReadPriorityExecutor, mWritePriorityExecutor, mImageCacheStatsTracker); }
@Before public void setUp() { mStagingArea = StagingArea.getInstance(); mCloseableReference = CloseableReference.of(mock(PooledByteBuffer.class)); mCloseableReference2 = CloseableReference.of(mock(PooledByteBuffer.class)); mEncodedImage = new EncodedImage(mCloseableReference); mSecondEncodedImage = new EncodedImage(mCloseableReference2); mCacheKey = new SimpleCacheKey("http://this.is/uri"); mStagingArea.put(mCacheKey, mEncodedImage); }
@Test public void testClearAll() { mStagingArea.put(new SimpleCacheKey("second"), mSecondEncodedImage); mStagingArea.clearAll(); assertEquals(2, mCloseableReference.getUnderlyingReferenceTestOnly().getRefCountTestOnly()); assertEquals(2, mCloseableReference2.getUnderlyingReferenceTestOnly().getRefCountTestOnly()); assertFalse(mStagingArea.remove(mCacheKey)); }
@Before public void setUp() { MockitoAnnotations.initMocks(this); mEncodedMemoryCacheProducer = new EncodedMemoryCacheProducer(mMemoryCache, mCacheKeyFactory, mInputProducer); mPooledByteBuffer1 = mock(PooledByteBuffer.class); mPooledByteBuffer2 = mock(PooledByteBuffer.class); mFinalImageReference = CloseableReference.of(mPooledByteBuffer1); mIntermediateImageReference = CloseableReference.of(mPooledByteBuffer2); mFinalImageReferenceClone = mFinalImageReference.clone(); mFinalEncodedImage = new EncodedImage(mFinalImageReference); mIntermediateEncodedImage = new EncodedImage(mIntermediateImageReference); mFinalEncodedImageClone = new EncodedImage(mFinalImageReferenceClone); List<CacheKey> list = new ArrayList<>(); list.add(new SimpleCacheKey("http://dummy.uri")); mCacheKey = new MultiCacheKey(list); when(mCacheKeyFactory.getEncodedCacheKey(mImageRequest, mCallerContext)).thenReturn(mCacheKey); when(mMemoryCache.cache(mCacheKey, mFinalImageReference)).thenReturn(mFinalImageReferenceClone); when(mProducerContext.getImageRequest()).thenReturn(mImageRequest); when(mProducerContext.getCallerContext()).thenReturn(mCallerContext); when(mProducerContext.getListener()).thenReturn(mProducerListener); when(mProducerListener.requiresExtraMap(mRequestId)).thenReturn(true); when(mProducerContext.getId()).thenReturn(mRequestId); when(mProducerContext.getLowestPermittedRequestLevel()) .thenReturn(ImageRequest.RequestLevel.FULL_FETCH); }
@Test public void testEvictFromMemoryCache() { String uriString = "http://dummy/string"; Uri uri = Uri.parse(uriString); mImagePipeline.evictFromMemoryCache(uri); CacheKey dummyCacheKey = mock(CacheKey.class); ArgumentCaptor<Predicate> bitmapCachePredicateCaptor = ArgumentCaptor.forClass(Predicate.class); verify(mBitmapMemoryCache).removeAll(bitmapCachePredicateCaptor.capture()); Predicate<CacheKey> bitmapMemoryCacheKeyPredicate = bitmapCachePredicateCaptor.getValue(); BitmapMemoryCacheKey bitmapMemoryCacheKey1 = mock(BitmapMemoryCacheKey.class); BitmapMemoryCacheKey bitmapMemoryCacheKey2 = mock(BitmapMemoryCacheKey.class); when(bitmapMemoryCacheKey1.containsUri(uri)).thenReturn(true); when(bitmapMemoryCacheKey2.containsUri(uri)).thenReturn(false); assertTrue(bitmapMemoryCacheKeyPredicate.apply(bitmapMemoryCacheKey1)); assertFalse(bitmapMemoryCacheKeyPredicate.apply(bitmapMemoryCacheKey2)); assertFalse(bitmapMemoryCacheKeyPredicate.apply(dummyCacheKey)); ArgumentCaptor<Predicate> encodedMemoryCachePredicateCaptor = ArgumentCaptor.forClass(Predicate.class); verify(mEncodedMemoryCache).removeAll(encodedMemoryCachePredicateCaptor.capture()); Predicate<CacheKey> encodedMemoryCacheKeyPredicate = encodedMemoryCachePredicateCaptor.getValue(); SimpleCacheKey simpleCacheKey1 = new SimpleCacheKey(uriString); SimpleCacheKey simpleCacheKey2 = new SimpleCacheKey("rubbish"); assertTrue(encodedMemoryCacheKeyPredicate.apply(simpleCacheKey1)); assertFalse(encodedMemoryCacheKeyPredicate.apply(simpleCacheKey2)); assertFalse(encodedMemoryCacheKeyPredicate.apply(dummyCacheKey)); }
@Test public void testClearMemoryCaches() { String uriString = "http://dummy/string"; Uri uri = Uri.parse(uriString); CacheKey dummyCacheKey = mock(CacheKey.class); mImagePipeline.clearMemoryCaches(); ArgumentCaptor<Predicate> bitmapCachePredicateCaptor = ArgumentCaptor.forClass(Predicate.class); verify(mBitmapMemoryCache).removeAll(bitmapCachePredicateCaptor.capture()); Predicate<CacheKey> bitmapMemoryCacheKeyPredicate = bitmapCachePredicateCaptor.getValue(); BitmapMemoryCacheKey bitmapMemoryCacheKey1 = mock(BitmapMemoryCacheKey.class); BitmapMemoryCacheKey bitmapMemoryCacheKey2 = mock(BitmapMemoryCacheKey.class); when(bitmapMemoryCacheKey1.containsUri(uri)).thenReturn(true); when(bitmapMemoryCacheKey2.containsUri(uri)).thenReturn(false); assertTrue(bitmapMemoryCacheKeyPredicate.apply(bitmapMemoryCacheKey1)); assertTrue(bitmapMemoryCacheKeyPredicate.apply(bitmapMemoryCacheKey2)); assertTrue(bitmapMemoryCacheKeyPredicate.apply(dummyCacheKey)); ArgumentCaptor<Predicate> encodedMemoryCachePredicateCaptor = ArgumentCaptor.forClass(Predicate.class); verify(mEncodedMemoryCache).removeAll(encodedMemoryCachePredicateCaptor.capture()); Predicate<CacheKey> encodedMemoryCacheKeyPredicate = encodedMemoryCachePredicateCaptor.getValue(); SimpleCacheKey simpleCacheKey1 = new SimpleCacheKey(uriString); SimpleCacheKey simpleCacheKey2 = new SimpleCacheKey("rubbish"); assertTrue(encodedMemoryCacheKeyPredicate.apply(simpleCacheKey1)); assertTrue(encodedMemoryCacheKeyPredicate.apply(simpleCacheKey2)); assertTrue(encodedMemoryCacheKeyPredicate.apply(dummyCacheKey)); }
@Override public CacheKey getPostprocessorCacheKey() { return new SimpleCacheKey(String.format( (Locale) null, "text=%s,count=%d", mWatermarkText, mCount)); }
/** * 获取磁盘缓存的文件路径 * * @param url 文件url * @return 文件路径 */ private static String getDiskCacheFilePath(String url) { FileBinaryResource resource = (FileBinaryResource) Fresco.getImagePipelineFactory() .getMainFileCache() .getResource(new SimpleCacheKey(url)); // 防止中途清除磁盘缓存 导致获取不到 if (resource == null) { return ""; } File file = resource.getFile(); return file.getAbsolutePath(); }
@Override public CacheKey getEncodedCacheKey( ImageRequest request, Uri sourceUri, Object callerContext) { return new SimpleCacheKey(getCacheKeySourceUri(sourceUri)); }
@Override public CacheKey getEncodedCacheKey(ImageRequest request, @Nullable Object callerContext) { if (request instanceof LJImageRequest) { LJImageRequest ljImageRequest = (LJImageRequest) request; String xpCacheKey = getCacheKey(ljImageRequest); if (!TextUtils.isEmpty(xpCacheKey)) { return new SimpleCacheKey(xpCacheKey); } } return super.getEncodedCacheKey(request, callerContext); }
@Test public void testCacheFileWithIOException() throws IOException { CacheKey key1 = new SimpleCacheKey("aaa"); // Before inserting, make sure files not exist. final BinaryResource resource1 = getResource(key1); assertNull(resource1); // 1. Should not create cache files if IOException happens in the middle. final IOException writeException = new IOException(); try { mCache.insert( key1, new WriterCallback() { @Override public void write(OutputStream os) throws IOException { throw writeException; } }); fail(); } catch (IOException e) { assertNull(getResource(key1)); } verifyListenerOnWriteAttempt(key1); verifyListenerOnWriteException(key1, writeException); // 2. Test a read failure from DiskStorage CacheKey key2 = new SimpleCacheKey("bbb"); int value2Size = 42; byte[] value2 = new byte[value2Size]; value2[25] = 'b'; mCache.insert(key2, WriterCallbacks.from(value2)); verifyListenerOnWriteAttempt(key2); String resourceId2 = verifyListenerOnWriteSuccessAndGetResourceId(key2, value2Size); ((DiskStorageWithReadFailures) mStorage).setPoisonResourceId(resourceId2); assertNull(mCache.getResource(key2)); verifyListenerOnReadException(key2, DiskStorageWithReadFailures.POISON_EXCEPTION); assertFalse(mCache.probe(key2)); verifyListenerOnReadException(key2, DiskStorageWithReadFailures.POISON_EXCEPTION); verifyNoMoreInteractions(mCacheEventListener); }