package com.octo.android.robospice.persistence.binary; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.util.Arrays; import org.apache.commons.io.IOUtils; import android.app.Application; import android.test.AndroidTestCase; import android.test.suitebuilder.annotation.MediumTest; import com.octo.android.robospice.persistence.DurationInMillis; @MediumTest public class InFileBigInputStreamObjectPersisterTest extends AndroidTestCase { private static final long FIVE_SECONDS = 5 * DurationInMillis.ONE_SECOND; private static final String TEST_CACHE_KEY = "TEST_CACHE_KEY"; private static final long SMALL_THREAD_SLEEP = 50; private InFileBigInputStreamObjectPersister inputStreamPersister; @Override protected void setUp() throws Exception { super.setUp(); Thread.sleep(SMALL_THREAD_SLEEP); Application application = (Application) getContext().getApplicationContext(); inputStreamPersister = new InFileBigInputStreamObjectPersister(application); } public void testSaveDataToCacheAndReturnData() throws Exception { inputStreamPersister.saveDataToCacheAndReturnData(new ByteArrayInputStream("coucou".getBytes()), TEST_CACHE_KEY); File cachedFile = inputStreamPersister.getCacheFile(TEST_CACHE_KEY); assertTrue(cachedFile.exists()); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(new FileInputStream(cachedFile), bos); assertTrue(Arrays.equals("coucou".getBytes(), bos.toByteArray())); } public void testLoadDataFromCache_no_expiracy() throws Exception { File cachedFile = inputStreamPersister.getCacheFile(TEST_CACHE_KEY); IOUtils.write("coucou", new FileOutputStream(cachedFile)); InputStream inputStream = inputStreamPersister.loadDataFromCache(TEST_CACHE_KEY, DurationInMillis.ALWAYS_RETURNED); byte[] actual = IOUtils.toByteArray(inputStream); assertTrue(Arrays.equals("coucou".getBytes(), actual)); } public void testLoadDataFromCache_not_expired() throws Exception { File cachedFile = inputStreamPersister.getCacheFile(TEST_CACHE_KEY); IOUtils.write("coucou", new FileOutputStream(cachedFile)); InputStream inputStream = inputStreamPersister.loadDataFromCache(TEST_CACHE_KEY, FIVE_SECONDS); byte[] actual = IOUtils.toByteArray(inputStream); assertTrue(Arrays.equals("coucou".getBytes(), actual)); } public void testLoadDataFromCache_expired() throws Exception { File cachedFile = inputStreamPersister.getCacheFile(TEST_CACHE_KEY); IOUtils.write("coucou", new FileOutputStream(cachedFile)); cachedFile.setLastModified(System.currentTimeMillis() - FIVE_SECONDS); InputStream inputStream = inputStreamPersister.loadDataFromCache(TEST_CACHE_KEY, DurationInMillis.ONE_SECOND); assertNull(inputStream); } @Override protected void tearDown() throws Exception { inputStreamPersister.removeAllDataFromCache(); super.tearDown(); } }