diff options
Diffstat (limited to 'app/src/androidTest/java')
20 files changed, 71 insertions, 2182 deletions
diff --git a/app/src/androidTest/java/de/test/antennapod/EspressoTestUtils.java b/app/src/androidTest/java/de/test/antennapod/EspressoTestUtils.java index 3c8c5d7f0..21498effd 100644 --- a/app/src/androidTest/java/de/test/antennapod/EspressoTestUtils.java +++ b/app/src/androidTest/java/de/test/antennapod/EspressoTestUtils.java @@ -3,8 +3,10 @@ package de.test.antennapod; import android.content.Context; import android.content.Intent; import androidx.annotation.IdRes; +import androidx.annotation.NonNull; import androidx.annotation.StringRes; import androidx.preference.PreferenceManager; +import androidx.test.espresso.NoMatchingViewException; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.espresso.PerformException; import androidx.test.espresso.UiController; @@ -15,6 +17,9 @@ import androidx.test.espresso.contrib.RecyclerViewActions; import androidx.test.espresso.util.HumanReadables; import androidx.test.espresso.util.TreeIterables; import android.view.View; + +import junit.framework.AssertionFailedError; + import de.danoeh.antennapod.R; import de.danoeh.antennapod.activity.MainActivity; import de.danoeh.antennapod.core.preferences.UserPreferences; @@ -33,6 +38,7 @@ import java.util.concurrent.TimeoutException; import static androidx.test.espresso.Espresso.onView; import static androidx.test.espresso.action.ViewActions.click; +import static androidx.test.espresso.assertion.ViewAssertions.matches; import static androidx.test.espresso.matcher.ViewMatchers.hasDescendant; import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed; import static androidx.test.espresso.matcher.ViewMatchers.isRoot; @@ -57,7 +63,7 @@ public class EspressoTestUtils { @Override public String getDescription() { - return "wait for a specific view for" + millis + " millis."; + return "wait for a specific view for " + millis + " millis."; } @Override @@ -88,6 +94,33 @@ public class EspressoTestUtils { } /** + * Wait until a certain view becomes visible, but at the longest until the timeout. + * Unlike {@link #waitForView(Matcher, long)} it doesn't stick to the initial root view. + * + * @param viewMatcher The view to wait for. + * @param timeoutMillis Maximum waiting period in milliseconds. + * @throws Exception Throws an Exception in case of a timeout. + */ + public static void waitForViewGlobally(@NonNull Matcher<View> viewMatcher, long timeoutMillis) throws Exception { + long startTime = System.currentTimeMillis(); + long endTime = startTime + timeoutMillis; + + do { + try { + onView(viewMatcher).check(matches(isDisplayed())); + // no Exception thrown -> check successful + return; + } catch (NoMatchingViewException | AssertionFailedError ignore) { + // check was not successful "not found" -> continue waiting + } + //noinspection BusyWait + Thread.sleep(50); + } while (System.currentTimeMillis() < endTime); + + throw new Exception("Timeout after " + timeoutMillis + " ms"); + } + + /** * Perform action of waiting for a specific view id. * https://stackoverflow.com/a/30338665/ * @param id The id of the child to click. @@ -113,7 +146,7 @@ public class EspressoTestUtils { } /** - * Clear all app databases + * Clear all app databases. */ public static void clearPreferences() { File root = InstrumentationRegistry.getInstrumentation().getTargetContext().getFilesDir().getParentFile(); diff --git a/app/src/androidTest/java/de/test/antennapod/entities/ExternalMediaTest.java b/app/src/androidTest/java/de/test/antennapod/entities/ExternalMediaTest.java deleted file mode 100644 index 83d7a4d22..000000000 --- a/app/src/androidTest/java/de/test/antennapod/entities/ExternalMediaTest.java +++ /dev/null @@ -1,56 +0,0 @@ -package de.test.antennapod.entities; - -import android.annotation.SuppressLint; -import android.content.SharedPreferences; -import androidx.preference.PreferenceManager; - -import androidx.test.platform.app.InstrumentationRegistry; -import androidx.test.filters.LargeTest; -import androidx.test.filters.SmallTest; -import de.danoeh.antennapod.core.feed.MediaType; -import de.danoeh.antennapod.core.util.playback.ExternalMedia; -import org.junit.After; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -/** - * Tests for {@link ExternalMedia} entity. - */ -@SmallTest -public class ExternalMediaTest { - - private static final int NOT_SET = -1; - - @After - public void tearDown() throws Exception { - clearSharedPrefs(); - } - - @SuppressLint("CommitPrefEdits") - private void clearSharedPrefs() { - SharedPreferences prefs = getDefaultSharedPrefs(); - SharedPreferences.Editor editor = prefs.edit(); - editor.clear(); - editor.commit(); - } - - private SharedPreferences getDefaultSharedPrefs() { - return PreferenceManager.getDefaultSharedPreferences(InstrumentationRegistry.getInstrumentation().getTargetContext()); - } - - @Test - public void testSaveCurrentPositionUpdatesPreferences() { - final int POSITION = 50; - final int LAST_PLAYED_TIME = 1650; - - assertEquals(NOT_SET, getDefaultSharedPrefs().getInt(ExternalMedia.PREF_POSITION, NOT_SET)); - assertEquals(NOT_SET, getDefaultSharedPrefs().getLong(ExternalMedia.PREF_LAST_PLAYED_TIME, NOT_SET)); - - ExternalMedia media = new ExternalMedia("source", MediaType.AUDIO); - media.saveCurrentPosition(getDefaultSharedPrefs(), POSITION, LAST_PLAYED_TIME); - - assertEquals(POSITION, getDefaultSharedPrefs().getInt(ExternalMedia.PREF_POSITION, NOT_SET)); - assertEquals(LAST_PLAYED_TIME, getDefaultSharedPrefs().getLong(ExternalMedia.PREF_LAST_PLAYED_TIME, NOT_SET)); - } -} diff --git a/app/src/androidTest/java/de/test/antennapod/feed/FeedFilterTest.java b/app/src/androidTest/java/de/test/antennapod/feed/FeedFilterTest.java deleted file mode 100644 index fc2943205..000000000 --- a/app/src/androidTest/java/de/test/antennapod/feed/FeedFilterTest.java +++ /dev/null @@ -1,130 +0,0 @@ -package de.test.antennapod.feed; - -import androidx.test.filters.SmallTest; -import de.danoeh.antennapod.core.feed.FeedFilter; -import de.danoeh.antennapod.core.feed.FeedItem; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -@SmallTest -public class FeedFilterTest { - - @Test - public void testNullFilter() throws Exception { - FeedFilter filter = new FeedFilter(); - FeedItem item = new FeedItem(); - item.setTitle("Hello world"); - - assertFalse(filter.excludeOnly()); - assertFalse(filter.includeOnly()); - assertEquals("", filter.getExcludeFilter()); - assertEquals("", filter.getIncludeFilter()); - assertTrue(filter.shouldAutoDownload(item)); - } - - @Test - public void testBasicIncludeFilter() throws Exception { - String includeFilter = "Hello"; - FeedFilter filter = new FeedFilter(includeFilter, ""); - FeedItem item = new FeedItem(); - item.setTitle("Hello world"); - - FeedItem item2 = new FeedItem(); - item2.setTitle("Don't include me"); - - assertFalse(filter.excludeOnly()); - assertTrue(filter.includeOnly()); - assertEquals("", filter.getExcludeFilter()); - assertEquals(includeFilter, filter.getIncludeFilter()); - assertTrue(filter.shouldAutoDownload(item)); - assertFalse(filter.shouldAutoDownload(item2)); - } - - @Test - public void testBasicExcludeFilter() throws Exception { - String excludeFilter = "Hello"; - FeedFilter filter = new FeedFilter("", excludeFilter); - FeedItem item = new FeedItem(); - item.setTitle("Hello world"); - - FeedItem item2 = new FeedItem(); - item2.setTitle("Item2"); - - assertTrue(filter.excludeOnly()); - assertFalse(filter.includeOnly()); - assertEquals(excludeFilter, filter.getExcludeFilter()); - assertEquals("", filter.getIncludeFilter()); - assertFalse(filter.shouldAutoDownload(item)); - assertTrue(filter.shouldAutoDownload(item2)); - } - - @Test - public void testComplexIncludeFilter() throws Exception { - String includeFilter = "Hello \n\"Two words\""; - FeedFilter filter = new FeedFilter(includeFilter, ""); - FeedItem item = new FeedItem(); - item.setTitle("hello world"); - - FeedItem item2 = new FeedItem(); - item2.setTitle("Two three words"); - - FeedItem item3 = new FeedItem(); - item3.setTitle("One two words"); - - assertFalse(filter.excludeOnly()); - assertTrue(filter.includeOnly()); - assertEquals("", filter.getExcludeFilter()); - assertEquals(includeFilter, filter.getIncludeFilter()); - assertTrue(filter.shouldAutoDownload(item)); - assertFalse(filter.shouldAutoDownload(item2)); - assertTrue(filter.shouldAutoDownload(item3)); - } - - @Test - public void testComplexExcludeFilter() throws Exception { - String excludeFilter = "Hello \"Two words\""; - FeedFilter filter = new FeedFilter("", excludeFilter); - FeedItem item = new FeedItem(); - item.setTitle("hello world"); - - FeedItem item2 = new FeedItem(); - item2.setTitle("One three words"); - - FeedItem item3 = new FeedItem(); - item3.setTitle("One two words"); - - assertTrue(filter.excludeOnly()); - assertFalse(filter.includeOnly()); - assertEquals(excludeFilter, filter.getExcludeFilter()); - assertEquals("", filter.getIncludeFilter()); - assertFalse(filter.shouldAutoDownload(item)); - assertTrue(filter.shouldAutoDownload(item2)); - assertFalse(filter.shouldAutoDownload(item3)); - } - - @Test - public void testComboFilter() throws Exception { - String includeFilter = "Hello world"; - String excludeFilter = "dislike"; - FeedFilter filter = new FeedFilter(includeFilter, excludeFilter); - - FeedItem download = new FeedItem(); - download.setTitle("Hello everyone!"); - // because, while it has words from the include filter it also has exclude words - FeedItem doNotDownload = new FeedItem(); - doNotDownload.setTitle("I dislike the world"); - // because it has no words from the include filter - FeedItem doNotDownload2 = new FeedItem(); - doNotDownload2.setTitle("no words to include"); - - assertTrue(filter.hasExcludeFilter()); - assertTrue(filter.hasIncludeFilter()); - assertTrue(filter.shouldAutoDownload(download)); - assertFalse(filter.shouldAutoDownload(doNotDownload)); - assertFalse(filter.shouldAutoDownload(doNotDownload2)); - } - -} diff --git a/app/src/androidTest/java/de/test/antennapod/feed/FeedItemTest.java b/app/src/androidTest/java/de/test/antennapod/feed/FeedItemTest.java deleted file mode 100644 index 0b9a67d0a..000000000 --- a/app/src/androidTest/java/de/test/antennapod/feed/FeedItemTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package de.test.antennapod.feed; - -import androidx.test.filters.SmallTest; -import de.danoeh.antennapod.core.feed.FeedItem; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -@SmallTest -public class FeedItemTest { - private static final String TEXT_LONG = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."; - private static final String TEXT_SHORT = "Lorem ipsum"; - - /** - * If one of `description` or `content:encoded` is null, use the other one. - */ - @Test - public void testShownotesNullValues() throws Exception { - testShownotes(null, TEXT_LONG); - testShownotes(TEXT_LONG, null); - } - - /** - * If `description` is reasonably longer than `content:encoded`, use `description`. - */ - @Test - public void testShownotesLength() throws Exception { - testShownotes(TEXT_SHORT, TEXT_LONG); - testShownotes(TEXT_LONG, TEXT_SHORT); - } - - /** - * Checks if the shownotes equal TEXT_LONG, using the given `description` and `content:encoded` - * @param description Description of the feed item - * @param contentEncoded `content:encoded` of the feed item - */ - private void testShownotes(String description, String contentEncoded) throws Exception { - FeedItem item = new FeedItem(); - item.setDescription(description); - item.setContentEncoded(contentEncoded); - assertEquals(TEXT_LONG, item.loadShownotes().call()); - } -} diff --git a/app/src/androidTest/java/de/test/antennapod/service/download/DownloadServiceTest.java b/app/src/androidTest/java/de/test/antennapod/service/download/DownloadServiceTest.java index fd395f7c1..70cf4166b 100644 --- a/app/src/androidTest/java/de/test/antennapod/service/download/DownloadServiceTest.java +++ b/app/src/androidTest/java/de/test/antennapod/service/download/DownloadServiceTest.java @@ -17,10 +17,8 @@ import org.junit.Test; import org.junit.runner.RunWith; import java.util.ArrayList; -import java.util.Arrays; import java.util.Date; import java.util.List; -import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import de.danoeh.antennapod.core.feed.Feed; diff --git a/app/src/androidTest/java/de/test/antennapod/storage/AutoDownloadTest.java b/app/src/androidTest/java/de/test/antennapod/storage/AutoDownloadTest.java index 5396b218d..1d2e3d9e8 100644 --- a/app/src/androidTest/java/de/test/antennapod/storage/AutoDownloadTest.java +++ b/app/src/androidTest/java/de/test/antennapod/storage/AutoDownloadTest.java @@ -4,14 +4,12 @@ import android.content.Context; import androidx.annotation.NonNull; import androidx.test.core.app.ApplicationProvider; import de.danoeh.antennapod.core.ClientConfig; -import de.danoeh.antennapod.core.DBTasksCallbacks; import de.danoeh.antennapod.core.feed.FeedItem; import de.danoeh.antennapod.core.feed.FeedMedia; import de.danoeh.antennapod.core.preferences.PlaybackPreferences; import de.danoeh.antennapod.core.preferences.UserPreferences; import de.danoeh.antennapod.core.storage.AutomaticDownloadAlgorithm; import de.danoeh.antennapod.core.storage.DBReader; -import de.danoeh.antennapod.core.storage.EpisodeCleanupAlgorithm; import de.danoeh.antennapod.core.util.playback.PlaybackServiceStarter; import de.test.antennapod.EspressoTestUtils; import de.test.antennapod.ui.UITestUtils; @@ -32,7 +30,7 @@ public class AutoDownloadTest { private Context context; private UITestUtils stubFeedsServer; - private DBTasksCallbacks dbTasksCallbacksOrig; + private AutomaticDownloadAlgorithm automaticDownloadAlgorithmOrig; @Before public void setUp() throws Exception { @@ -41,7 +39,7 @@ public class AutoDownloadTest { stubFeedsServer = new UITestUtils(context); stubFeedsServer.setup(); - dbTasksCallbacksOrig = ClientConfig.dbTasksCallbacks; + automaticDownloadAlgorithmOrig = ClientConfig.automaticDownloadAlgorithm; EspressoTestUtils.clearPreferences(); EspressoTestUtils.clearDatabase(); @@ -50,7 +48,7 @@ public class AutoDownloadTest { @After public void tearDown() throws Exception { - ClientConfig.dbTasksCallbacks = dbTasksCallbacksOrig; + ClientConfig.automaticDownloadAlgorithm = automaticDownloadAlgorithmOrig; EspressoTestUtils.tryKillPlaybackService(); stubFeedsServer.tearDown(); } @@ -79,7 +77,7 @@ public class AutoDownloadTest { // Setup: enable automatic download // it is not needed, as the actual automatic download is stubbed. StubDownloadAlgorithm stubDownloadAlgorithm = new StubDownloadAlgorithm(); - useDownloadAlgorithm(stubDownloadAlgorithm); + ClientConfig.automaticDownloadAlgorithm = stubDownloadAlgorithm; // Actual test // Play the first one in the queue @@ -113,20 +111,6 @@ public class AutoDownloadTest { .until(() -> item.getMedia().getId() == PlaybackPreferences.getCurrentlyPlayingFeedMediaId()); } - private void useDownloadAlgorithm(final AutomaticDownloadAlgorithm downloadAlgorithm) { - ClientConfig.dbTasksCallbacks = new DBTasksCallbacks() { - @Override - public AutomaticDownloadAlgorithm getAutomaticDownloadAlgorithm() { - return downloadAlgorithm; - } - - @Override - public EpisodeCleanupAlgorithm getEpisodeCacheCleanupAlgorithm() { - return dbTasksCallbacksOrig.getEpisodeCacheCleanupAlgorithm(); - } - }; - } - private static class StubDownloadAlgorithm implements AutomaticDownloadAlgorithm { private long currentlyPlaying = -1; diff --git a/app/src/androidTest/java/de/test/antennapod/storage/DBCleanupTests.java b/app/src/androidTest/java/de/test/antennapod/storage/DBCleanupTests.java index 6c36da13e..339d3cea9 100644 --- a/app/src/androidTest/java/de/test/antennapod/storage/DBCleanupTests.java +++ b/app/src/androidTest/java/de/test/antennapod/storage/DBCleanupTests.java @@ -11,7 +11,6 @@ import java.util.Date; import java.util.List; import androidx.test.platform.app.InstrumentationRegistry; -import androidx.test.filters.LargeTest; import androidx.test.filters.SmallTest; import de.danoeh.antennapod.core.feed.Feed; import de.danoeh.antennapod.core.feed.FeedItem; diff --git a/app/src/androidTest/java/de/test/antennapod/storage/DBNullCleanupAlgorithmTest.java b/app/src/androidTest/java/de/test/antennapod/storage/DBNullCleanupAlgorithmTest.java deleted file mode 100644 index d7ebf2351..000000000 --- a/app/src/androidTest/java/de/test/antennapod/storage/DBNullCleanupAlgorithmTest.java +++ /dev/null @@ -1,119 +0,0 @@ -package de.test.antennapod.storage; - -import android.content.Context; -import android.content.SharedPreferences; -import androidx.preference.PreferenceManager; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import androidx.test.platform.app.InstrumentationRegistry; -import androidx.test.filters.LargeTest; -import androidx.test.filters.SmallTest; -import de.danoeh.antennapod.core.feed.Feed; -import de.danoeh.antennapod.core.feed.FeedItem; -import de.danoeh.antennapod.core.feed.FeedMedia; -import de.danoeh.antennapod.core.preferences.UserPreferences; -import de.danoeh.antennapod.core.storage.DBTasks; -import de.danoeh.antennapod.core.storage.PodDBAdapter; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -/** - * Tests that the APNullCleanupAlgorithm is working correctly. - */ -@SmallTest -public class DBNullCleanupAlgorithmTest { - - private static final String TAG = "DBNullCleanupAlgorithmTest"; - private static final int EPISODE_CACHE_SIZE = 5; - - private Context context; - - private File destFolder; - - @After - public void tearDown() throws Exception { - assertTrue(PodDBAdapter.deleteDatabase()); - - cleanupDestFolder(destFolder); - assertTrue(destFolder.delete()); - } - - private void cleanupDestFolder(File destFolder) { - for (File f : destFolder.listFiles()) { - assertTrue(f.delete()); - } - } - - @Before - public void setUp() throws Exception { - context = InstrumentationRegistry.getInstrumentation().getTargetContext(); - destFolder = context.getExternalCacheDir(); - cleanupDestFolder(destFolder); - assertNotNull(destFolder); - assertTrue(destFolder.exists()); - assertTrue(destFolder.canWrite()); - - // create new database - PodDBAdapter.init(context); - PodDBAdapter.deleteDatabase(); - PodDBAdapter adapter = PodDBAdapter.getInstance(); - adapter.open(); - adapter.close(); - - SharedPreferences.Editor prefEdit = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext()).edit(); - prefEdit.putString(UserPreferences.PREF_EPISODE_CACHE_SIZE, Integer.toString(EPISODE_CACHE_SIZE)); - prefEdit.putString(UserPreferences.PREF_EPISODE_CLEANUP, Integer.toString(UserPreferences.EPISODE_CLEANUP_NULL)); - prefEdit.commit(); - - UserPreferences.init(context); - } - - /** - * A test with no items in the queue, but multiple items downloaded. - * The null algorithm should never delete any items, even if they're played and not in the queue. - * @throws IOException - */ - @Test - public void testPerformAutoCleanupShouldNotDelete() throws IOException { - final int NUM_ITEMS = EPISODE_CACHE_SIZE * 2; - - Feed feed = new Feed("url", null, "title"); - List<FeedItem> items = new ArrayList<>(); - feed.setItems(items); - List<File> files = new ArrayList<>(); - for (int i = 0; i < NUM_ITEMS; i++) { - FeedItem item = new FeedItem(0, "title", "id", "link", new Date(), FeedItem.PLAYED, feed); - - File f = new File(destFolder, "file " + i); - assertTrue(f.createNewFile()); - files.add(f); - item.setMedia(new FeedMedia(0, item, 1, 0, 1L, "m", f.getAbsolutePath(), "url", true, - new Date(NUM_ITEMS - i), 0, 0)); - items.add(item); - } - - PodDBAdapter adapter = PodDBAdapter.getInstance(); - adapter.open(); - adapter.setCompleteFeed(feed); - adapter.close(); - - assertTrue(feed.getId() != 0); - for (FeedItem item : items) { - assertTrue(item.getId() != 0); - assertTrue(item.getMedia().getId() != 0); - } - DBTasks.performAutoCleanup(context); - for (int i = 0; i < files.size(); i++) { - assertTrue(files.get(i).exists()); - } - } -} diff --git a/app/src/androidTest/java/de/test/antennapod/storage/DBTasksTest.java b/app/src/androidTest/java/de/test/antennapod/storage/DBTasksTest.java deleted file mode 100644 index c28ce5003..000000000 --- a/app/src/androidTest/java/de/test/antennapod/storage/DBTasksTest.java +++ /dev/null @@ -1,289 +0,0 @@ -package de.test.antennapod.storage; - -import android.content.Context; - -import androidx.test.platform.app.InstrumentationRegistry; -import androidx.test.filters.SmallTest; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Date; -import java.util.List; - -import de.danoeh.antennapod.core.feed.Feed; -import de.danoeh.antennapod.core.feed.FeedItem; -import de.danoeh.antennapod.core.feed.FeedMedia; -import de.danoeh.antennapod.core.preferences.UserPreferences; -import de.danoeh.antennapod.core.storage.DBReader; -import de.danoeh.antennapod.core.storage.DBTasks; -import de.danoeh.antennapod.core.storage.DBWriter; -import de.danoeh.antennapod.core.storage.PodDBAdapter; - -import static de.danoeh.antennapod.core.util.FeedItemUtil.getIdList; -import static java.util.Collections.singletonList; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -/** - * Test class for DBTasks - */ -@SmallTest -public class DBTasksTest { - private Context context; - - @After - public void tearDown() throws Exception { - assertTrue(PodDBAdapter.deleteDatabase()); - } - - @Before - public void setUp() throws Exception { - context = InstrumentationRegistry.getInstrumentation().getTargetContext(); - - // create new database - PodDBAdapter.init(context); - PodDBAdapter.deleteDatabase(); - PodDBAdapter adapter = PodDBAdapter.getInstance(); - adapter.open(); - adapter.close(); - - UserPreferences.init(context); - } - - @Test - public void testUpdateFeedNewFeed() { - final int NUM_ITEMS = 10; - - Feed feed = new Feed("url", null, "title"); - feed.setItems(new ArrayList<>()); - for (int i = 0; i < NUM_ITEMS; i++) { - feed.getItems().add(new FeedItem(0, "item " + i, "id " + i, "link " + i, new Date(), FeedItem.UNPLAYED, feed)); - } - Feed newFeed = DBTasks.updateFeed(context, feed, false); - - assertEquals(feed.getId(), newFeed.getId()); - assertTrue(feed.getId() != 0); - for (FeedItem item : feed.getItems()) { - assertFalse(item.isPlayed()); - assertTrue(item.getId() != 0); - } - } - - /** Two feeds with the same title, but different download URLs should be treated as different feeds. */ - @Test - public void testUpdateFeedSameTitle() { - - Feed feed1 = new Feed("url1", null, "title"); - Feed feed2 = new Feed("url2", null, "title"); - - feed1.setItems(new ArrayList<>()); - feed2.setItems(new ArrayList<>()); - - Feed savedFeed1 = DBTasks.updateFeed(context, feed1, false); - Feed savedFeed2 = DBTasks.updateFeed(context, feed2, false); - - assertTrue(savedFeed1.getId() != savedFeed2.getId()); - } - - @Test - public void testUpdateFeedUpdatedFeed() { - final int NUM_ITEMS_OLD = 10; - final int NUM_ITEMS_NEW = 10; - - final Feed feed = new Feed("url", null, "title"); - feed.setItems(new ArrayList<>()); - for (int i = 0; i < NUM_ITEMS_OLD; i++) { - feed.getItems().add(new FeedItem(0, "item " + i, "id " + i, "link " + i, new Date(i), FeedItem.PLAYED, feed)); - } - PodDBAdapter adapter = PodDBAdapter.getInstance(); - adapter.open(); - adapter.setCompleteFeed(feed); - adapter.close(); - - // ensure that objects have been saved in db, then reset - assertTrue(feed.getId() != 0); - final long feedID = feed.getId(); - feed.setId(0); - List<Long> itemIDs = new ArrayList<>(); - for (FeedItem item : feed.getItems()) { - assertTrue(item.getId() != 0); - itemIDs.add(item.getId()); - item.setId(0); - } - - for (int i = NUM_ITEMS_OLD; i < NUM_ITEMS_NEW + NUM_ITEMS_OLD; i++) { - feed.getItems().add(0, new FeedItem(0, "item " + i, "id " + i, "link " + i, new Date(i), FeedItem.UNPLAYED, feed)); - } - - final Feed newFeed = DBTasks.updateFeed(context, feed, false); - assertNotSame(newFeed, feed); - - updatedFeedTest(newFeed, feedID, itemIDs, NUM_ITEMS_OLD, NUM_ITEMS_NEW); - - final Feed feedFromDB = DBReader.getFeed(newFeed.getId()); - assertNotNull(feedFromDB); - assertEquals(newFeed.getId(), feedFromDB.getId()); - updatedFeedTest(feedFromDB, feedID, itemIDs, NUM_ITEMS_OLD, NUM_ITEMS_NEW); - } - - @Test - public void testUpdateFeedMediaUrlResetState() { - final Feed feed = new Feed("url", null, "title"); - FeedItem item = new FeedItem(0, "item", "id", "link", new Date(), FeedItem.PLAYED, feed); - feed.setItems(singletonList(item)); - - PodDBAdapter adapter = PodDBAdapter.getInstance(); - adapter.open(); - adapter.setCompleteFeed(feed); - adapter.close(); - - // ensure that objects have been saved in db, then reset - assertTrue(feed.getId() != 0); - assertTrue(item.getId() != 0); - - FeedMedia media = new FeedMedia(item, "url", 1024, "mime/type"); - item.setMedia(media); - List<FeedItem> list = new ArrayList<>(); - list.add(item); - feed.setItems(list); - - final Feed newFeed = DBTasks.updateFeed(context, feed, false); - assertNotSame(newFeed, feed); - - final Feed feedFromDB = DBReader.getFeed(newFeed.getId()); - final FeedItem feedItemFromDB = feedFromDB.getItems().get(0); - assertTrue("state: " + feedItemFromDB.getState(), feedItemFromDB.isNew()); - } - - @Test - public void testUpdateFeedRemoveUnlistedItems() { - final Feed feed = new Feed("url", null, "title"); - feed.setItems(new ArrayList<>()); - for (int i = 0; i < 10; i++) { - feed.getItems().add( - new FeedItem(0, "item " + i, "id " + i, "link " + i, new Date(i), FeedItem.PLAYED, feed)); - } - PodDBAdapter adapter = PodDBAdapter.getInstance(); - adapter.open(); - adapter.setCompleteFeed(feed); - adapter.close(); - - // delete some items - feed.getItems().subList(0, 2).clear(); - Feed newFeed = DBTasks.updateFeed(context, feed, true); - assertEquals(8, newFeed.getItems().size()); // 10 - 2 = 8 items - - Feed feedFromDB = DBReader.getFeed(newFeed.getId()); - assertEquals(8, feedFromDB.getItems().size()); // 10 - 2 = 8 items - } - - private void updatedFeedTest(final Feed newFeed, long feedID, List<Long> itemIDs, final int NUM_ITEMS_OLD, final int NUM_ITEMS_NEW) { - assertEquals(feedID, newFeed.getId()); - assertEquals(NUM_ITEMS_NEW + NUM_ITEMS_OLD, newFeed.getItems().size()); - Collections.reverse(newFeed.getItems()); - Date lastDate = new Date(0); - for (int i = 0; i < NUM_ITEMS_OLD; i++) { - FeedItem item = newFeed.getItems().get(i); - assertSame(newFeed, item.getFeed()); - assertEquals((long) itemIDs.get(i), item.getId()); - assertTrue(item.isPlayed()); - assertTrue(item.getPubDate().getTime() >= lastDate.getTime()); - lastDate = item.getPubDate(); - } - for (int i = NUM_ITEMS_OLD; i < NUM_ITEMS_NEW + NUM_ITEMS_OLD; i++) { - FeedItem item = newFeed.getItems().get(i); - assertSame(newFeed, item.getFeed()); - assertTrue(item.getId() != 0); - assertFalse(item.isPlayed()); - assertTrue(item.getPubDate().getTime() >= lastDate.getTime()); - lastDate = item.getPubDate(); - } - } - - @Test - public void testAddQueueItemsInDownload_EnqueueEnabled() throws Exception { - // Setup test data / environment - UserPreferences.setEnqueueDownloadedEpisodes(true); - UserPreferences.setEnqueueLocation(UserPreferences.EnqueueLocation.BACK); - - List<FeedItem> fis1 = createSavedFeed("Feed 1", 2).getItems(); - List<FeedItem> fis2 = createSavedFeed("Feed 2", 3).getItems(); - - DBWriter.addQueueItem(context, fis1.get(0), fis2.get(0)).get(); - // the first item fis1.get(0) is already in the queue - FeedItem[] itemsToDownload = new FeedItem[]{ fis1.get(0), fis1.get(1), fis2.get(2), fis2.get(1) }; - - // Expectations: - List<FeedItem> expectedEnqueued = Arrays.asList(fis1.get(1), fis2.get(2), fis2.get(1)); - List<FeedItem> expectedQueue = new ArrayList<>(); - expectedQueue.addAll(DBReader.getQueue()); - expectedQueue.addAll(expectedEnqueued); - - // Run actual test and assert results - List<? extends FeedItem> actualEnqueued = - DBTasks.enqueueFeedItemsToDownload(context, Arrays.asList(itemsToDownload)); - - assertEqualsByIds("Only items not in the queue are enqueued", expectedEnqueued, actualEnqueued); - assertEqualsByIds("Queue has new items appended", expectedQueue, DBReader.getQueue()); - } - - @Test - public void testAddQueueItemsInDownload_EnqueueDisabled() throws Exception { - // Setup test data / environment - UserPreferences.setEnqueueDownloadedEpisodes(false); - - List<FeedItem> fis1 = createSavedFeed("Feed 1", 2).getItems(); - List<FeedItem> fis2 = createSavedFeed("Feed 2", 3).getItems(); - - DBWriter.addQueueItem(context, fis1.get(0), fis2.get(0)).get(); - FeedItem[] itemsToDownload = new FeedItem[]{ fis1.get(0), fis1.get(1), fis2.get(2), fis2.get(1) }; - - // Expectations: - List<FeedItem> expectedEnqueued = Collections.emptyList(); - List<FeedItem> expectedQueue = DBReader.getQueue(); - - // Run actual test and assert results - List<? extends FeedItem> actualEnqueued = - DBTasks.enqueueFeedItemsToDownload(context, Arrays.asList(itemsToDownload)); - - assertEqualsByIds("No item is enqueued", expectedEnqueued, actualEnqueued); - assertEqualsByIds("Queue is unchanged", expectedQueue, DBReader.getQueue()); - } - - private void assertEqualsByIds(String msg, List<? extends FeedItem> expected, List<? extends FeedItem> actual) { - // assert only the IDs, so that any differences are easily to spot. - List<Long> expectedIds = getIdList(expected); - List<Long> actualIds = getIdList(actual); - assertEquals(msg, expectedIds, actualIds); - } - - private Feed createSavedFeed(String title, int numFeedItems) { - final Feed feed = new Feed("url", null, title); - - if (numFeedItems > 0) { - List<FeedItem> items = new ArrayList<>(numFeedItems); - for (int i = 1; i <= numFeedItems; i++) { - FeedItem item = new FeedItem(0, "item " + i + " of " + title, "id", "link", - new Date(), FeedItem.UNPLAYED, feed); - items.add(item); - } - feed.setItems(items); - } - - PodDBAdapter adapter = PodDBAdapter.getInstance(); - adapter.open(); - adapter.setCompleteFeed(feed); - adapter.close(); - return feed; - } - -} diff --git a/app/src/androidTest/java/de/test/antennapod/storage/DBWriterTest.java b/app/src/androidTest/java/de/test/antennapod/storage/DBWriterTest.java deleted file mode 100644 index 652389d00..000000000 --- a/app/src/androidTest/java/de/test/antennapod/storage/DBWriterTest.java +++ /dev/null @@ -1,857 +0,0 @@ -package de.test.antennapod.storage; - -import android.content.Context; -import android.content.SharedPreferences; -import android.database.Cursor; -import androidx.preference.PreferenceManager; -import android.util.Log; - -import androidx.core.util.Consumer; -import androidx.test.platform.app.InstrumentationRegistry; -import androidx.test.filters.MediumTest; - -import org.awaitility.Awaitility; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Locale; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -import de.danoeh.antennapod.core.feed.Feed; -import de.danoeh.antennapod.core.feed.FeedItem; -import de.danoeh.antennapod.core.feed.FeedMedia; -import de.danoeh.antennapod.core.preferences.UserPreferences; -import de.danoeh.antennapod.core.storage.DBReader; -import de.danoeh.antennapod.core.storage.DBWriter; -import de.danoeh.antennapod.core.storage.PodDBAdapter; -import de.danoeh.antennapod.core.util.FeedItemUtil; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -/** - * Test class for DBWriter - */ -@MediumTest -public class DBWriterTest { - - private static final String TAG = "DBWriterTest"; - private static final String TEST_FOLDER = "testDBWriter"; - private static final long TIMEOUT = 5L; - - @After - public void tearDown() throws Exception { - assertTrue(PodDBAdapter.deleteDatabase()); - - final Context context = InstrumentationRegistry.getInstrumentation().getTargetContext(); - File testDir = context.getExternalFilesDir(TEST_FOLDER); - assertNotNull(testDir); - for (File f : testDir.listFiles()) { - f.delete(); - } - } - - @Before - public void setUp() throws Exception { - // create new database - PodDBAdapter.init(InstrumentationRegistry.getInstrumentation().getTargetContext()); - PodDBAdapter.deleteDatabase(); - PodDBAdapter adapter = PodDBAdapter.getInstance(); - adapter.open(); - adapter.close(); - - Context context = InstrumentationRegistry.getInstrumentation().getTargetContext(); - SharedPreferences.Editor prefEdit = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext()).edit(); - prefEdit.putBoolean(UserPreferences.PREF_DELETE_REMOVES_FROM_QUEUE, true).commit(); - - UserPreferences.init(context); - } - - @Test - public void testSetFeedMediaPlaybackInformation() - throws IOException, ExecutionException, InterruptedException, TimeoutException { - final int POSITION = 50; - final long LAST_PLAYED_TIME = 1000; - final int PLAYED_DURATION = 60; - final int DURATION = 100; - - Feed feed = new Feed("url", null, "title"); - List<FeedItem> items = new ArrayList<>(); - feed.setItems(items); - FeedItem item = new FeedItem(0, "Item", "Item", "url", new Date(), FeedItem.PLAYED, feed); - items.add(item); - FeedMedia media = new FeedMedia(0, item, DURATION, 1, 1, "mime_type", "dummy path", "download_url", true, null, 0, 0); - item.setMedia(media); - - DBWriter.setFeedItem(item).get(TIMEOUT, TimeUnit.SECONDS); - - media.setPosition(POSITION); - media.setLastPlayedTime(LAST_PLAYED_TIME); - media.setPlayedDuration(PLAYED_DURATION); - - DBWriter.setFeedMediaPlaybackInformation(item.getMedia()).get(TIMEOUT, TimeUnit.SECONDS); - - FeedItem itemFromDb = DBReader.getFeedItem(item.getId()); - FeedMedia mediaFromDb = itemFromDb.getMedia(); - - assertEquals(POSITION, mediaFromDb.getPosition()); - assertEquals(LAST_PLAYED_TIME, mediaFromDb.getLastPlayedTime()); - assertEquals(PLAYED_DURATION, mediaFromDb.getPlayedDuration()); - assertEquals(DURATION, mediaFromDb.getDuration()); - } - - @Test - public void testDeleteFeedMediaOfItemFileExists() - throws IOException, ExecutionException, InterruptedException, TimeoutException { - File dest = new File(InstrumentationRegistry - .getInstrumentation().getTargetContext().getExternalFilesDir(TEST_FOLDER), "testFile"); - - assertTrue(dest.createNewFile()); - - Feed feed = new Feed("url", null, "title"); - List<FeedItem> items = new ArrayList<>(); - feed.setItems(items); - FeedItem item = new FeedItem(0, "Item", "Item", "url", new Date(), FeedItem.PLAYED, feed); - - FeedMedia media = new FeedMedia(0, item, 1, 1, 1, "mime_type", dest.getAbsolutePath(), "download_url", true, null, 0, 0); - item.setMedia(media); - - items.add(item); - - PodDBAdapter adapter = PodDBAdapter.getInstance(); - adapter.open(); - adapter.setCompleteFeed(feed); - adapter.close(); - assertTrue(media.getId() != 0); - assertTrue(item.getId() != 0); - - DBWriter.deleteFeedMediaOfItem(InstrumentationRegistry.getInstrumentation().getTargetContext(), media.getId()) - .get(TIMEOUT, TimeUnit.SECONDS); - media = DBReader.getFeedMedia(media.getId()); - assertNotNull(media); - assertFalse(dest.exists()); - assertFalse(media.isDownloaded()); - assertNull(media.getFile_url()); - } - - @Test - public void testDeleteFeedMediaOfItemRemoveFromQueue() - throws IOException, ExecutionException, InterruptedException, TimeoutException { - assertTrue(UserPreferences.shouldDeleteRemoveFromQueue()); - - File dest = new File(InstrumentationRegistry - .getInstrumentation().getTargetContext().getExternalFilesDir(TEST_FOLDER), "testFile"); - - assertTrue(dest.createNewFile()); - - Feed feed = new Feed("url", null, "title"); - List<FeedItem> items = new ArrayList<>(); - List<FeedItem> queue = new ArrayList<>(); - feed.setItems(items); - FeedItem item = new FeedItem(0, "Item", "Item", "url", new Date(), FeedItem.UNPLAYED, feed); - - FeedMedia media = new FeedMedia(0, item, 1, 1, 1, "mime_type", dest.getAbsolutePath(), "download_url", true, null, 0, 0); - item.setMedia(media); - - items.add(item); - queue.add(item); - - PodDBAdapter adapter = PodDBAdapter.getInstance(); - adapter.open(); - adapter.setCompleteFeed(feed); - adapter.setQueue(queue); - adapter.close(); - assertTrue(media.getId() != 0); - assertTrue(item.getId() != 0); - queue = DBReader.getQueue(); - assertTrue(queue.size() != 0); - - DBWriter.deleteFeedMediaOfItem(InstrumentationRegistry.getInstrumentation().getTargetContext(), media.getId()); - Awaitility.await().until(() -> !dest.exists()); - media = DBReader.getFeedMedia(media.getId()); - assertNotNull(media); - assertFalse(dest.exists()); - assertFalse(media.isDownloaded()); - assertNull(media.getFile_url()); - queue = DBReader.getQueue(); - assertEquals(0, queue.size()); - } - - @Test - public void testDeleteFeed() throws ExecutionException, InterruptedException, IOException, TimeoutException { - File destFolder = InstrumentationRegistry.getInstrumentation().getTargetContext().getExternalFilesDir(TEST_FOLDER); - assertNotNull(destFolder); - - Feed feed = new Feed("url", null, "title"); - feed.setItems(new ArrayList<>()); - - List<File> itemFiles = new ArrayList<>(); - // create items with downloaded media files - for (int i = 0; i < 10; i++) { - FeedItem item = new FeedItem(0, "Item " + i, "Item" + i, "url", new Date(), FeedItem.PLAYED, feed); - feed.getItems().add(item); - - File enc = new File(destFolder, "file " + i); - assertTrue(enc.createNewFile()); - - itemFiles.add(enc); - FeedMedia media = new FeedMedia(0, item, 1, 1, 1, "mime_type", enc.getAbsolutePath(), "download_url", true, null, 0, 0); - item.setMedia(media); - } - - PodDBAdapter adapter = PodDBAdapter.getInstance(); - adapter.open(); - adapter.setCompleteFeed(feed); - adapter.close(); - - assertTrue(feed.getId() != 0); - for (FeedItem item : feed.getItems()) { - assertTrue(item.getId() != 0); - assertTrue(item.getMedia().getId() != 0); - } - - DBWriter.deleteFeed(InstrumentationRegistry - .getInstrumentation().getTargetContext(), feed.getId()).get(TIMEOUT, TimeUnit.SECONDS); - - // check if files still exist - for (File f : itemFiles) { - assertFalse(f.exists()); - } - - adapter = PodDBAdapter.getInstance(); - adapter.open(); - Cursor c = adapter.getFeedCursor(feed.getId()); - assertEquals(0, c.getCount()); - c.close(); - for (FeedItem item : feed.getItems()) { - c = adapter.getFeedItemCursor(String.valueOf(item.getId())); - assertEquals(0, c.getCount()); - c.close(); - c = adapter.getSingleFeedMediaCursor(item.getMedia().getId()); - assertEquals(0, c.getCount()); - c.close(); - } - adapter.close(); - } - - @Test - public void testDeleteFeedNoItems() throws IOException, ExecutionException, InterruptedException, TimeoutException { - File destFolder = InstrumentationRegistry.getInstrumentation().getTargetContext().getExternalFilesDir(TEST_FOLDER); - assertNotNull(destFolder); - - Feed feed = new Feed("url", null, "title"); - feed.setItems(null); - feed.setImageUrl("url"); - - PodDBAdapter adapter = PodDBAdapter.getInstance(); - adapter.open(); - adapter.setCompleteFeed(feed); - adapter.close(); - - assertTrue(feed.getId() != 0); - - DBWriter.deleteFeed(InstrumentationRegistry - .getInstrumentation().getTargetContext(), feed.getId()).get(TIMEOUT, TimeUnit.SECONDS); - - adapter = PodDBAdapter.getInstance(); - adapter.open(); - Cursor c = adapter.getFeedCursor(feed.getId()); - assertEquals(0, c.getCount()); - c.close(); - adapter.close(); - } - - @Test - public void testDeleteFeedNoFeedMedia() throws IOException, ExecutionException, InterruptedException, TimeoutException { - File destFolder = InstrumentationRegistry.getInstrumentation().getTargetContext().getExternalFilesDir(TEST_FOLDER); - assertNotNull(destFolder); - - Feed feed = new Feed("url", null, "title"); - feed.setItems(new ArrayList<>()); - - feed.setImageUrl("url"); - - // create items - for (int i = 0; i < 10; i++) { - FeedItem item = new FeedItem(0, "Item " + i, "Item" + i, "url", new Date(), FeedItem.PLAYED, feed); - feed.getItems().add(item); - - } - - PodDBAdapter adapter = PodDBAdapter.getInstance(); - adapter.open(); - adapter.setCompleteFeed(feed); - adapter.close(); - - assertTrue(feed.getId() != 0); - for (FeedItem item : feed.getItems()) { - assertTrue(item.getId() != 0); - } - - DBWriter.deleteFeed(InstrumentationRegistry - .getInstrumentation().getTargetContext(), feed.getId()).get(TIMEOUT, TimeUnit.SECONDS); - - - adapter = PodDBAdapter.getInstance(); - adapter.open(); - Cursor c = adapter.getFeedCursor(feed.getId()); - assertEquals(0, c.getCount()); - c.close(); - for (FeedItem item : feed.getItems()) { - c = adapter.getFeedItemCursor(String.valueOf(item.getId())); - assertEquals(0, c.getCount()); - c.close(); - } - adapter.close(); - } - - @Test - public void testDeleteFeedWithQueueItems() throws ExecutionException, InterruptedException, TimeoutException { - File destFolder = InstrumentationRegistry.getInstrumentation().getTargetContext().getExternalFilesDir(TEST_FOLDER); - assertNotNull(destFolder); - - Feed feed = new Feed("url", null, "title"); - feed.setItems(new ArrayList<>()); - - feed.setImageUrl("url"); - - // create items with downloaded media files - for (int i = 0; i < 10; i++) { - FeedItem item = new FeedItem(0, "Item " + i, "Item" + i, "url", new Date(), FeedItem.PLAYED, feed); - feed.getItems().add(item); - File enc = new File(destFolder, "file " + i); - FeedMedia media = new FeedMedia(0, item, 1, 1, 1, "mime_type", enc.getAbsolutePath(), "download_url", false, null, 0, 0); - item.setMedia(media); - } - - PodDBAdapter adapter = PodDBAdapter.getInstance(); - adapter.open(); - adapter.setCompleteFeed(feed); - adapter.close(); - - assertTrue(feed.getId() != 0); - for (FeedItem item : feed.getItems()) { - assertTrue(item.getId() != 0); - assertTrue(item.getMedia().getId() != 0); - } - - - List<FeedItem> queue = new ArrayList<>(feed.getItems()); - adapter.open(); - adapter.setQueue(queue); - - Cursor queueCursor = adapter.getQueueIDCursor(); - assertEquals(queue.size(), queueCursor.getCount()); - queueCursor.close(); - - adapter.close(); - DBWriter.deleteFeed(InstrumentationRegistry - .getInstrumentation().getTargetContext(), feed.getId()).get(TIMEOUT, TimeUnit.SECONDS); - adapter.open(); - - Cursor c = adapter.getFeedCursor(feed.getId()); - assertEquals(0, c.getCount()); - c.close(); - for (FeedItem item : feed.getItems()) { - c = adapter.getFeedItemCursor(String.valueOf(item.getId())); - assertEquals(0, c.getCount()); - c.close(); - c = adapter.getSingleFeedMediaCursor(item.getMedia().getId()); - assertEquals(0, c.getCount()); - c.close(); - } - c = adapter.getQueueCursor(); - assertEquals(0, c.getCount()); - c.close(); - adapter.close(); - } - - @Test - public void testDeleteFeedNoDownloadedFiles() throws ExecutionException, InterruptedException, TimeoutException { - File destFolder = InstrumentationRegistry.getInstrumentation().getTargetContext().getExternalFilesDir(TEST_FOLDER); - assertNotNull(destFolder); - - Feed feed = new Feed("url", null, "title"); - feed.setItems(new ArrayList<>()); - - feed.setImageUrl("url"); - - // create items with downloaded media files - for (int i = 0; i < 10; i++) { - FeedItem item = new FeedItem(0, "Item " + i, "Item" + i, "url", new Date(), FeedItem.PLAYED, feed); - feed.getItems().add(item); - File enc = new File(destFolder, "file " + i); - FeedMedia media = new FeedMedia(0, item, 1, 1, 1, "mime_type", enc.getAbsolutePath(), "download_url", false, null, 0, 0); - item.setMedia(media); - } - - PodDBAdapter adapter = PodDBAdapter.getInstance(); - adapter.open(); - adapter.setCompleteFeed(feed); - adapter.close(); - - assertTrue(feed.getId() != 0); - for (FeedItem item : feed.getItems()) { - assertTrue(item.getId() != 0); - assertTrue(item.getMedia().getId() != 0); - } - - DBWriter.deleteFeed(InstrumentationRegistry - .getInstrumentation().getTargetContext(), feed.getId()).get(TIMEOUT, TimeUnit.SECONDS); - - adapter = PodDBAdapter.getInstance(); - adapter.open(); - Cursor c = adapter.getFeedCursor(feed.getId()); - assertEquals(0, c.getCount()); - c.close(); - for (FeedItem item : feed.getItems()) { - c = adapter.getFeedItemCursor(String.valueOf(item.getId())); - assertEquals(0, c.getCount()); - c.close(); - c = adapter.getSingleFeedMediaCursor(item.getMedia().getId()); - assertEquals(0, c.getCount()); - c.close(); - } - adapter.close(); - } - - @Test - public void testDeleteFeedItems() throws Exception { - Feed feed = new Feed("url", null, "title"); - feed.setItems(new ArrayList<>()); - feed.setImageUrl("url"); - - // create items - for (int i = 0; i < 10; i++) { - FeedItem item = new FeedItem(0, "Item " + i, "Item" + i, "url", new Date(), FeedItem.PLAYED, feed); - feed.getItems().add(item); - } - - PodDBAdapter adapter = PodDBAdapter.getInstance(); - adapter.open(); - adapter.setCompleteFeed(feed); - adapter.close(); - - List<FeedItem> itemsToDelete = feed.getItems().subList(0, 2); - DBWriter.deleteFeedItems(InstrumentationRegistry.getInstrumentation() - .getTargetContext(), itemsToDelete).get(TIMEOUT, TimeUnit.SECONDS); - - adapter = PodDBAdapter.getInstance(); - adapter.open(); - for (int i = 0; i < feed.getItems().size(); i++) { - FeedItem feedItem = feed.getItems().get(i); - Cursor c = adapter.getFeedItemCursor(String.valueOf(feedItem.getId())); - if (i < 2) { - assertEquals(0, c.getCount()); - } else { - assertEquals(1, c.getCount()); - } - c.close(); - } - adapter.close(); - } - - private FeedMedia playbackHistorySetup(Date playbackCompletionDate) { - Feed feed = new Feed("url", null, "title"); - feed.setItems(new ArrayList<>()); - FeedItem item = new FeedItem(0, "title", "id", "link", new Date(), FeedItem.PLAYED, feed); - FeedMedia media = new FeedMedia(0, item, 10, 0, 1, "mime", null, "url", false, playbackCompletionDate, 0, 0); - feed.getItems().add(item); - item.setMedia(media); - PodDBAdapter adapter = PodDBAdapter.getInstance(); - adapter.open(); - adapter.setCompleteFeed(feed); - adapter.close(); - assertTrue(media.getId() != 0); - return media; - } - - @Test - public void testAddItemToPlaybackHistoryNotPlayedYet() - throws ExecutionException, InterruptedException, TimeoutException { - FeedMedia media = playbackHistorySetup(null); - DBWriter.addItemToPlaybackHistory(media).get(TIMEOUT, TimeUnit.SECONDS); - PodDBAdapter adapter = PodDBAdapter.getInstance(); - adapter.open(); - media = DBReader.getFeedMedia(media.getId()); - adapter.close(); - - assertNotNull(media); - assertNotNull(media.getPlaybackCompletionDate()); - } - - @Test - public void testAddItemToPlaybackHistoryAlreadyPlayed() - throws ExecutionException, InterruptedException, TimeoutException { - final long OLD_DATE = 0; - - FeedMedia media = playbackHistorySetup(new Date(OLD_DATE)); - DBWriter.addItemToPlaybackHistory(media).get(TIMEOUT, TimeUnit.SECONDS); - PodDBAdapter adapter = PodDBAdapter.getInstance(); - adapter.open(); - media = DBReader.getFeedMedia(media.getId()); - adapter.close(); - - assertNotNull(media); - assertNotNull(media.getPlaybackCompletionDate()); - assertNotEquals(media.getPlaybackCompletionDate().getTime(), OLD_DATE); - } - - private Feed queueTestSetupMultipleItems(final int numItems) throws InterruptedException, ExecutionException, TimeoutException { - final Context context = InstrumentationRegistry.getInstrumentation().getTargetContext(); - UserPreferences.setEnqueueLocation(UserPreferences.EnqueueLocation.BACK); - Feed feed = new Feed("url", null, "title"); - feed.setItems(new ArrayList<>()); - for (int i = 0; i < numItems; i++) { - FeedItem item = new FeedItem(0, "title " + i, "id " + i, "link " + i, new Date(), FeedItem.PLAYED, feed); - feed.getItems().add(item); - } - - PodDBAdapter adapter = PodDBAdapter.getInstance(); - adapter.open(); - adapter.setCompleteFeed(feed); - adapter.close(); - - for (FeedItem item : feed.getItems()) { - assertTrue(item.getId() != 0); - } - List<Future<?>> futures = new ArrayList<>(); - for (FeedItem item : feed.getItems()) { - futures.add(DBWriter.addQueueItem(context, item)); - } - for (Future<?> f : futures) { - f.get(TIMEOUT, TimeUnit.SECONDS); - } - return feed; - } - - @Test - public void testAddQueueItemSingleItem() throws InterruptedException, ExecutionException, TimeoutException { - final Context context = InstrumentationRegistry.getInstrumentation().getTargetContext(); - Feed feed = new Feed("url", null, "title"); - feed.setItems(new ArrayList<>()); - FeedItem item = new FeedItem(0, "title", "id", "link", new Date(), FeedItem.PLAYED, feed); - feed.getItems().add(item); - - PodDBAdapter adapter = PodDBAdapter.getInstance(); - adapter.open(); - adapter.setCompleteFeed(feed); - adapter.close(); - - assertTrue(item.getId() != 0); - DBWriter.addQueueItem(context, item).get(TIMEOUT, TimeUnit.SECONDS); - - adapter = PodDBAdapter.getInstance(); - adapter.open(); - Cursor cursor = adapter.getQueueIDCursor(); - assertTrue(cursor.moveToFirst()); - assertEquals(item.getId(), cursor.getLong(0)); - cursor.close(); - adapter.close(); - } - - @Test - public void testAddQueueItemSingleItemAlreadyInQueue() throws InterruptedException, ExecutionException, TimeoutException { - final Context context = InstrumentationRegistry.getInstrumentation().getTargetContext(); - Feed feed = new Feed("url", null, "title"); - feed.setItems(new ArrayList<>()); - FeedItem item = new FeedItem(0, "title", "id", "link", new Date(), FeedItem.PLAYED, feed); - feed.getItems().add(item); - - PodDBAdapter adapter = PodDBAdapter.getInstance(); - adapter.open(); - adapter.setCompleteFeed(feed); - adapter.close(); - - assertTrue(item.getId() != 0); - DBWriter.addQueueItem(context, item).get(TIMEOUT, TimeUnit.SECONDS); - - adapter = PodDBAdapter.getInstance(); - adapter.open(); - Cursor cursor = adapter.getQueueIDCursor(); - assertTrue(cursor.moveToFirst()); - assertEquals(item.getId(), cursor.getLong(0)); - cursor.close(); - adapter.close(); - - DBWriter.addQueueItem(context, item).get(TIMEOUT, TimeUnit.SECONDS); - adapter = PodDBAdapter.getInstance(); - adapter.open(); - cursor = adapter.getQueueIDCursor(); - assertTrue(cursor.moveToFirst()); - assertEquals(item.getId(), cursor.getLong(0)); - assertEquals(1, cursor.getCount()); - cursor.close(); - adapter.close(); - } - - @Test - public void testAddQueueItemMultipleItems() throws InterruptedException, ExecutionException, TimeoutException { - final int NUM_ITEMS = 10; - - Feed feed = queueTestSetupMultipleItems(NUM_ITEMS); - PodDBAdapter adapter = PodDBAdapter.getInstance(); - adapter.open(); - Cursor cursor = adapter.getQueueIDCursor(); - assertTrue(cursor.moveToFirst()); - assertEquals(NUM_ITEMS, cursor.getCount()); - List<Long> expectedIds = FeedItemUtil.getIdList(feed.getItems()); - List<Long> actualIds = new ArrayList<>(); - for (int i = 0; i < NUM_ITEMS; i++) { - assertTrue(cursor.moveToPosition(i)); - actualIds.add(cursor.getLong(0)); - } - cursor.close(); - adapter.close(); - assertEquals("Bulk add to queue: result order should be the same as the order given", - expectedIds, actualIds); - } - - @Test - public void testClearQueue() throws InterruptedException, ExecutionException, TimeoutException { - final int NUM_ITEMS = 10; - - queueTestSetupMultipleItems(NUM_ITEMS); - DBWriter.clearQueue().get(TIMEOUT, TimeUnit.SECONDS); - PodDBAdapter adapter = PodDBAdapter.getInstance(); - adapter.open(); - Cursor cursor = adapter.getQueueIDCursor(); - assertFalse(cursor.moveToFirst()); - cursor.close(); - adapter.close(); - } - - @Test - public void testRemoveQueueItem() throws InterruptedException, ExecutionException, TimeoutException { - final int NUM_ITEMS = 10; - final Context context = InstrumentationRegistry.getInstrumentation().getTargetContext(); - Feed feed = createTestFeed(NUM_ITEMS); - - for (int removeIndex = 0; removeIndex < NUM_ITEMS; removeIndex++) { - final FeedItem item = feed.getItems().get(removeIndex); - PodDBAdapter adapter = PodDBAdapter.getInstance(); - adapter.open(); - adapter.setQueue(feed.getItems()); - adapter.close(); - - DBWriter.removeQueueItem(context, false, item).get(TIMEOUT, TimeUnit.SECONDS); - adapter = PodDBAdapter.getInstance(); - adapter.open(); - Cursor queue = adapter.getQueueIDCursor(); - assertEquals(NUM_ITEMS - 1, queue.getCount()); - for (int i = 0; i < queue.getCount(); i++) { - assertTrue(queue.moveToPosition(i)); - final long queueID = queue.getLong(0); - assertTrue(queueID != item.getId()); // removed item is no longer in queue - boolean idFound = false; - for (FeedItem other : feed.getItems()) { // items that were not removed are still in the queue - idFound = idFound | (other.getId() == queueID); - } - assertTrue(idFound); - } - queue.close(); - adapter.close(); - } - } - - @Test - public void testRemoveQueueItemMultipleItems() throws InterruptedException, ExecutionException, TimeoutException { - // Setup test data - // - final int NUM_ITEMS = 5; - final int NUM_IN_QUEUE = NUM_ITEMS - 1; // the last one not in queue for boundary condition - final Context context = InstrumentationRegistry.getInstrumentation().getTargetContext(); - Feed feed = createTestFeed(NUM_ITEMS); - - List<FeedItem> itemsToAdd = feed.getItems().subList(0, NUM_IN_QUEUE); - withPodDB(adapter -> adapter.setQueue(itemsToAdd) ); - - // Actual tests - // - - // Use array rather than List to make codes more succinct - Long[] itemIds = toItemIds(feed.getItems()).toArray(new Long[0]); - - DBWriter.removeQueueItem(context, false, - itemIds[1], itemIds[3]).get(TIMEOUT, TimeUnit.SECONDS); - assertQueueByItemIds("Average case - 2 items removed successfully", - itemIds[0], itemIds[2]); - - DBWriter.removeQueueItem(context, false).get(TIMEOUT, TimeUnit.SECONDS); - assertQueueByItemIds("Boundary case - no items supplied. queue should see no change", - itemIds[0], itemIds[2]); - - DBWriter.removeQueueItem(context, false, - itemIds[0], itemIds[4], -1L).get(TIMEOUT, TimeUnit.SECONDS); - assertQueueByItemIds("Boundary case - items not in queue ignored", - itemIds[2]); - - DBWriter.removeQueueItem(context, false, - itemIds[2], -1L).get(TIMEOUT, TimeUnit.SECONDS); - assertQueueByItemIds("Boundary case - invalid itemIds ignored"); // the queue is empty - - } - - @Test - public void testMoveQueueItem() throws InterruptedException, ExecutionException, TimeoutException { - final int NUM_ITEMS = 10; - Feed feed = new Feed("url", null, "title"); - feed.setItems(new ArrayList<>()); - for (int i = 0; i < NUM_ITEMS; i++) { - FeedItem item = new FeedItem(0, "title " + i, "id " + i, "link " + i, new Date(), FeedItem.PLAYED, feed); - feed.getItems().add(item); - } - - PodDBAdapter adapter = PodDBAdapter.getInstance(); - adapter.open(); - adapter.setCompleteFeed(feed); - adapter.close(); - - for (FeedItem item : feed.getItems()) { - assertTrue(item.getId() != 0); - } - for (int from = 0; from < NUM_ITEMS; from++) { - for (int to = 0; to < NUM_ITEMS; to++) { - if (from == to) { - continue; - } - Log.d(TAG, String.format(Locale.US, "testMoveQueueItem: From=%d, To=%d", from, to)); - final long fromID = feed.getItems().get(from).getId(); - - adapter = PodDBAdapter.getInstance(); - adapter.open(); - adapter.setQueue(feed.getItems()); - adapter.close(); - - DBWriter.moveQueueItem(from, to, false).get(TIMEOUT, TimeUnit.SECONDS); - adapter = PodDBAdapter.getInstance(); - adapter.open(); - Cursor queue = adapter.getQueueIDCursor(); - assertEquals(NUM_ITEMS, queue.getCount()); - assertTrue(queue.moveToPosition(from)); - assertNotEquals(fromID, queue.getLong(0)); - assertTrue(queue.moveToPosition(to)); - assertEquals(fromID, queue.getLong(0)); - - queue.close(); - adapter.close(); - } - } - } - - @Test - public void testMarkFeedRead() throws InterruptedException, ExecutionException, TimeoutException { - final int NUM_ITEMS = 10; - Feed feed = new Feed("url", null, "title"); - feed.setItems(new ArrayList<>()); - for (int i = 0; i < NUM_ITEMS; i++) { - FeedItem item = new FeedItem(0, "title " + i, "id " + i, "link " + i, new Date(), FeedItem.UNPLAYED, feed); - feed.getItems().add(item); - } - - PodDBAdapter adapter = PodDBAdapter.getInstance(); - adapter.open(); - adapter.setCompleteFeed(feed); - adapter.close(); - - assertTrue(feed.getId() != 0); - for (FeedItem item : feed.getItems()) { - assertTrue(item.getId() != 0); - } - - DBWriter.markFeedRead(feed.getId()).get(TIMEOUT, TimeUnit.SECONDS); - List<FeedItem> loadedItems = DBReader.getFeedItemList(feed); - for (FeedItem item : loadedItems) { - assertTrue(item.isPlayed()); - } - } - - @Test - public void testMarkAllItemsReadSameFeed() throws InterruptedException, ExecutionException, TimeoutException { - final int NUM_ITEMS = 10; - Feed feed = new Feed("url", null, "title"); - feed.setItems(new ArrayList<>()); - for (int i = 0; i < NUM_ITEMS; i++) { - FeedItem item = new FeedItem(0, "title " + i, "id " + i, "link " + i, new Date(), FeedItem.UNPLAYED, feed); - feed.getItems().add(item); - } - - PodDBAdapter adapter = PodDBAdapter.getInstance(); - adapter.open(); - adapter.setCompleteFeed(feed); - adapter.close(); - - assertTrue(feed.getId() != 0); - for (FeedItem item : feed.getItems()) { - assertTrue(item.getId() != 0); - } - - DBWriter.markAllItemsRead().get(TIMEOUT, TimeUnit.SECONDS); - List<FeedItem> loadedItems = DBReader.getFeedItemList(feed); - for (FeedItem item : loadedItems) { - assertTrue(item.isPlayed()); - } - } - - private static Feed createTestFeed(int numItems) { - Feed feed = new Feed("url", null, "title"); - feed.setItems(new ArrayList<>()); - for (int i = 0; i < numItems; i++) { - FeedItem item = new FeedItem(0, "title " + i, "id " + i, "link " + i, new Date(), FeedItem.PLAYED, feed); - feed.getItems().add(item); - } - - withPodDB(adapter -> adapter.setCompleteFeed(feed)); - - for (FeedItem item : feed.getItems()) { - assertTrue(item.getId() != 0); - } - return feed; - } - - private static void withPodDB(Consumer<PodDBAdapter> action) { - PodDBAdapter adapter = PodDBAdapter.getInstance(); - try { - adapter.open(); - action.accept(adapter); - } finally { - adapter.close(); - } - } - - private static void assertQueueByItemIds( - String message, - long... itemIdsExpected - ) { - List<FeedItem> queue = DBReader.getQueue(); - List<Long> itemIdsActualList = toItemIds(queue); - List<Long> itemIdsExpectedList = new ArrayList<>(itemIdsExpected.length); - for (long id : itemIdsExpected) { - itemIdsExpectedList.add(id); - } - - assertEquals(message, itemIdsExpectedList, itemIdsActualList); - } - - private static List<Long> toItemIds(List<FeedItem> items) { - List<Long> itemIds = new ArrayList<>(items.size()); - for(FeedItem item : items) { - itemIds.add(item.getId()); - } - return itemIds; - } - -} diff --git a/app/src/androidTest/java/de/test/antennapod/ui/MainActivityTest.java b/app/src/androidTest/java/de/test/antennapod/ui/MainActivityTest.java index be1ed6cc2..417a78f02 100644 --- a/app/src/androidTest/java/de/test/antennapod/ui/MainActivityTest.java +++ b/app/src/androidTest/java/de/test/antennapod/ui/MainActivityTest.java @@ -2,16 +2,14 @@ package de.test.antennapod.ui; import android.app.Activity; import android.content.Intent; -import androidx.test.platform.app.InstrumentationRegistry; + import androidx.test.espresso.Espresso; import androidx.test.espresso.intent.rule.IntentsTestRule; import androidx.test.ext.junit.runners.AndroidJUnit4; +import androidx.test.platform.app.InstrumentationRegistry; + import com.robotium.solo.Solo; -import de.danoeh.antennapod.R; -import de.danoeh.antennapod.activity.MainActivity; -import de.danoeh.antennapod.core.feed.Feed; -import de.danoeh.antennapod.core.storage.PodDBAdapter; -import de.test.antennapod.EspressoTestUtils; + import org.junit.After; import org.junit.Before; import org.junit.Rule; @@ -20,6 +18,12 @@ import org.junit.runner.RunWith; import java.io.IOException; +import de.danoeh.antennapod.R; +import de.danoeh.antennapod.activity.MainActivity; +import de.danoeh.antennapod.core.feed.Feed; +import de.danoeh.antennapod.core.storage.PodDBAdapter; +import de.test.antennapod.EspressoTestUtils; + import static androidx.test.espresso.Espresso.onView; import static androidx.test.espresso.action.ViewActions.click; import static androidx.test.espresso.action.ViewActions.replaceText; @@ -28,18 +32,17 @@ import static androidx.test.espresso.assertion.ViewAssertions.matches; import static androidx.test.espresso.contrib.ActivityResultMatchers.hasResultCode; import static androidx.test.espresso.matcher.ViewMatchers.hasDescendant; import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed; -import static androidx.test.espresso.matcher.ViewMatchers.isRoot; import static androidx.test.espresso.matcher.ViewMatchers.withId; import static androidx.test.espresso.matcher.ViewMatchers.withText; import static de.test.antennapod.EspressoTestUtils.clickPreference; import static de.test.antennapod.EspressoTestUtils.openNavDrawer; -import static de.test.antennapod.EspressoTestUtils.waitForView; -import static junit.framework.TestCase.assertTrue; +import static de.test.antennapod.EspressoTestUtils.waitForViewGlobally; import static org.hamcrest.Matchers.allOf; import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; /** - * User interface tests for MainActivity + * User interface tests for MainActivity. */ @RunWith(AndroidJUnit4.class) public class MainActivityTest { @@ -48,19 +51,19 @@ public class MainActivityTest { private UITestUtils uiTestUtils; @Rule - public IntentsTestRule<MainActivity> mActivityRule = new IntentsTestRule<>(MainActivity.class, false, false); + public IntentsTestRule<MainActivity> activityRule = new IntentsTestRule<>(MainActivity.class, false, false); @Before public void setUp() throws IOException { EspressoTestUtils.clearPreferences(); EspressoTestUtils.clearDatabase(); - mActivityRule.launchActivity(new Intent()); + activityRule.launchActivity(new Intent()); uiTestUtils = new UITestUtils(InstrumentationRegistry.getInstrumentation().getTargetContext()); uiTestUtils.setup(); - solo = new Solo(InstrumentationRegistry.getInstrumentation(), mActivityRule.getActivity()); + solo = new Solo(InstrumentationRegistry.getInstrumentation(), activityRule.getActivity()); } @After @@ -71,16 +74,22 @@ public class MainActivityTest { @Test public void testAddFeed() throws Exception { + // connect to podcast feed uiTestUtils.addHostedFeedData(); final Feed feed = uiTestUtils.hostedFeeds.get(0); openNavDrawer(); onView(withText(R.string.add_feed_label)).perform(click()); - onView(withId(R.id.btn_add_via_url)).perform(scrollTo(), click()); - onView(withId(R.id.text)).perform(replaceText(feed.getDownload_url())); + onView(withId(R.id.addViaUrlButton)).perform(scrollTo(), click()); + onView(withId(R.id.urlEditText)).perform(replaceText(feed.getDownload_url())); onView(withText(R.string.confirm_label)).perform(scrollTo(), click()); + + // subscribe podcast Espresso.closeSoftKeyboard(); + waitForViewGlobally(withText(R.string.subscribe_label), 15000); onView(withText(R.string.subscribe_label)).perform(click()); - onView(isRoot()).perform(waitForView(withId(R.id.butShowSettings), 5000)); + + // wait for podcast feed item list + waitForViewGlobally(withId(R.id.butShowSettings), 15000); } @Test @@ -100,7 +109,7 @@ public class MainActivityTest { onView(allOf(withId(R.id.toolbar), isDisplayed())).check( matches(hasDescendant(withText(R.string.subscriptions_label)))); solo.goBack(); - assertThat(mActivityRule.getActivityResult(), hasResultCode(Activity.RESULT_CANCELED)); + assertThat(activityRule.getActivityResult(), hasResultCode(Activity.RESULT_CANCELED)); } @Test @@ -113,7 +122,7 @@ public class MainActivityTest { solo.goBackToActivity(MainActivity.class.getSimpleName()); solo.goBack(); solo.goBack(); - assertTrue(((MainActivity)solo.getCurrentActivity()).isDrawerOpen()); + assertTrue(((MainActivity) solo.getCurrentActivity()).isDrawerOpen()); } @Test @@ -127,7 +136,7 @@ public class MainActivityTest { solo.goBack(); solo.goBack(); solo.goBack(); - assertThat(mActivityRule.getActivityResult(), hasResultCode(Activity.RESULT_CANCELED)); + assertThat(activityRule.getActivityResult(), hasResultCode(Activity.RESULT_CANCELED)); } @Test @@ -142,7 +151,7 @@ public class MainActivityTest { solo.goBack(); onView(withText(R.string.yes)).perform(click()); Thread.sleep(100); - assertThat(mActivityRule.getActivityResult(), hasResultCode(Activity.RESULT_CANCELED)); + assertThat(activityRule.getActivityResult(), hasResultCode(Activity.RESULT_CANCELED)); } @Test @@ -155,6 +164,6 @@ public class MainActivityTest { solo.goBackToActivity(MainActivity.class.getSimpleName()); solo.goBack(); solo.goBack(); - assertThat(mActivityRule.getActivityResult(), hasResultCode(Activity.RESULT_CANCELED)); + assertThat(activityRule.getActivityResult(), hasResultCode(Activity.RESULT_CANCELED)); } } diff --git a/app/src/androidTest/java/de/test/antennapod/ui/NavigationDrawerTest.java b/app/src/androidTest/java/de/test/antennapod/ui/NavigationDrawerTest.java index ade5ea298..53396372a 100644 --- a/app/src/androidTest/java/de/test/antennapod/ui/NavigationDrawerTest.java +++ b/app/src/androidTest/java/de/test/antennapod/ui/NavigationDrawerTest.java @@ -42,9 +42,9 @@ import static androidx.test.espresso.matcher.ViewMatchers.withText; import static de.test.antennapod.EspressoTestUtils.onDrawerItem; import static de.test.antennapod.EspressoTestUtils.waitForView; import static de.test.antennapod.NthMatcher.first; -import static junit.framework.TestCase.assertTrue; import static org.hamcrest.Matchers.allOf; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; /** * User interface tests for MainActivity drawer. diff --git a/app/src/androidTest/java/de/test/antennapod/ui/PreferencesTest.java b/app/src/androidTest/java/de/test/antennapod/ui/PreferencesTest.java index 9bf89980c..3cdb09605 100644 --- a/app/src/androidTest/java/de/test/antennapod/ui/PreferencesTest.java +++ b/app/src/androidTest/java/de/test/antennapod/ui/PreferencesTest.java @@ -43,9 +43,9 @@ import static androidx.test.espresso.matcher.ViewMatchers.withText; import static de.test.antennapod.EspressoTestUtils.clickPreference; import static de.test.antennapod.EspressoTestUtils.waitForView; import static java.util.concurrent.TimeUnit.MILLISECONDS; -import static junit.framework.TestCase.assertTrue; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertTrue; @LargeTest public class PreferencesTest { diff --git a/app/src/androidTest/java/de/test/antennapod/ui/QueueFragmentTest.java b/app/src/androidTest/java/de/test/antennapod/ui/QueueFragmentTest.java index 634904f71..5b291752d 100644 --- a/app/src/androidTest/java/de/test/antennapod/ui/QueueFragmentTest.java +++ b/app/src/androidTest/java/de/test/antennapod/ui/QueueFragmentTest.java @@ -1,15 +1,12 @@ package de.test.antennapod.ui; import android.content.Intent; -import android.view.View; -import androidx.test.espresso.Espresso; import androidx.test.espresso.intent.rule.IntentsTestRule; import androidx.test.ext.junit.runners.AndroidJUnit4; import de.danoeh.antennapod.R; import de.danoeh.antennapod.activity.MainActivity; import de.danoeh.antennapod.fragment.QueueFragment; import de.test.antennapod.EspressoTestUtils; -import org.hamcrest.Matcher; import org.junit.Before; import org.junit.Rule; import org.junit.Test; diff --git a/app/src/androidTest/java/de/test/antennapod/ui/SpeedChangeTest.java b/app/src/androidTest/java/de/test/antennapod/ui/SpeedChangeTest.java index 5f79e935c..904e17ebf 100644 --- a/app/src/androidTest/java/de/test/antennapod/ui/SpeedChangeTest.java +++ b/app/src/androidTest/java/de/test/antennapod/ui/SpeedChangeTest.java @@ -14,7 +14,6 @@ import de.danoeh.antennapod.core.preferences.UserPreferences; import de.danoeh.antennapod.core.service.playback.PlayerStatus; import de.danoeh.antennapod.core.storage.DBReader; import de.danoeh.antennapod.core.util.playback.PlaybackController; -import de.danoeh.antennapod.fragment.ExternalPlayerFragment; import de.danoeh.antennapod.fragment.QueueFragment; import de.test.antennapod.EspressoTestUtils; import de.test.antennapod.IgnoreOnCi; @@ -37,8 +36,6 @@ import static androidx.test.espresso.matcher.ViewMatchers.withId; import static androidx.test.espresso.matcher.ViewMatchers.withText; import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation; import static de.test.antennapod.EspressoTestUtils.waitForView; -import static de.test.antennapod.NthMatcher.first; -import static org.hamcrest.Matchers.allOf; /** * User interface tests for changing the playback speed. diff --git a/app/src/androidTest/java/de/test/antennapod/ui/UITestUtilsTest.java b/app/src/androidTest/java/de/test/antennapod/ui/UITestUtilsTest.java index 60516454f..54592df0b 100644 --- a/app/src/androidTest/java/de/test/antennapod/ui/UITestUtilsTest.java +++ b/app/src/androidTest/java/de/test/antennapod/ui/UITestUtilsTest.java @@ -6,7 +6,6 @@ import java.net.URL; import java.util.List; import androidx.test.platform.app.InstrumentationRegistry; -import androidx.test.filters.LargeTest; import androidx.test.filters.MediumTest; import de.danoeh.antennapod.core.feed.Feed; import de.danoeh.antennapod.core.feed.FeedItem; diff --git a/app/src/androidTest/java/de/test/antennapod/util/FilenameGeneratorTest.java b/app/src/androidTest/java/de/test/antennapod/util/FilenameGeneratorTest.java deleted file mode 100644 index 93e5bcb74..000000000 --- a/app/src/androidTest/java/de/test/antennapod/util/FilenameGeneratorTest.java +++ /dev/null @@ -1,104 +0,0 @@ -package de.test.antennapod.util; - -import android.content.Context; -import androidx.test.platform.app.InstrumentationRegistry; -import androidx.test.filters.SmallTest; -import android.text.TextUtils; - -import java.io.File; -import java.io.IOException; - -import de.danoeh.antennapod.core.util.FileNameGenerator; -import org.apache.commons.lang3.StringUtils; -import org.junit.After; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; - -@SmallTest -public class FilenameGeneratorTest { - - public FilenameGeneratorTest() { - super(); - } - - @Test - public void testGenerateFileName() throws IOException { - String result = FileNameGenerator.generateFileName("abc abc"); - assertEquals(result, "abc abc"); - createFiles(result); - } - - @Test - public void testGenerateFileName1() throws IOException { - String result = FileNameGenerator.generateFileName("ab/c: <abc"); - assertEquals(result, "abc abc"); - createFiles(result); - } - - @Test - public void testGenerateFileName2() throws IOException { - String result = FileNameGenerator.generateFileName("abc abc "); - assertEquals(result, "abc abc"); - createFiles(result); - } - - @Test - public void testFeedTitleContainsApostrophe() { - String result = FileNameGenerator.generateFileName("Feed's Title ..."); - assertEquals("Feeds Title", result); - } - - @Test - public void testFeedTitleContainsDash() { - String result = FileNameGenerator.generateFileName("Left - Right"); - assertEquals("Left - Right", result); - } - - @Test - public void testFeedTitleContainsAccents() { - String result = FileNameGenerator.generateFileName("Äàáâãå"); - assertEquals("Aaaaaa", result); - } - - @Test - public void testInvalidInput() { - String result = FileNameGenerator.generateFileName("???"); - assertFalse(TextUtils.isEmpty(result)); - } - - @Test - public void testLongFilename() throws IOException { - String longName = StringUtils.repeat("x", 20 + FileNameGenerator.MAX_FILENAME_LENGTH); - String result = FileNameGenerator.generateFileName(longName); - assertTrue(result.length() <= FileNameGenerator.MAX_FILENAME_LENGTH); - createFiles(result); - } - - @Test - public void testLongFilenameNotEquals() { - // Verify that the name is not just trimmed and different suffixes end up with the same name - String longName = StringUtils.repeat("x", 20 + FileNameGenerator.MAX_FILENAME_LENGTH); - String result1 = FileNameGenerator.generateFileName(longName + "a"); - String result2 = FileNameGenerator.generateFileName(longName + "b"); - assertNotEquals(result1, result2); - } - - /** - * Tests if files can be created. - * - * @throws IOException - */ - private void createFiles(String name) throws IOException { - File cache = InstrumentationRegistry.getInstrumentation().getTargetContext().getExternalCacheDir(); - File testFile = new File(cache, name); - testFile.mkdir(); - assertTrue(testFile.exists()); - testFile.delete(); - assertTrue(testFile.createNewFile()); - } - -} diff --git a/app/src/androidTest/java/de/test/antennapod/util/URLCheckerTest.java b/app/src/androidTest/java/de/test/antennapod/util/URLCheckerTest.java deleted file mode 100644 index 7f26ff612..000000000 --- a/app/src/androidTest/java/de/test/antennapod/util/URLCheckerTest.java +++ /dev/null @@ -1,157 +0,0 @@ -package de.test.antennapod.util; - -import androidx.test.filters.SmallTest; -import de.danoeh.antennapod.core.util.URLChecker; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -/** - * Test class for URLChecker - */ -@SmallTest -public class URLCheckerTest { - - @Test - public void testCorrectURLHttp() { - final String in = "http://example.com"; - final String out = URLChecker.prepareURL(in); - assertEquals(in, out); - } - - @Test - public void testCorrectURLHttps() { - final String in = "https://example.com"; - final String out = URLChecker.prepareURL(in); - assertEquals(in, out); - } - - @Test - public void testMissingProtocol() { - final String in = "example.com"; - final String out = URLChecker.prepareURL(in); - assertEquals("http://example.com", out); - } - - @Test - public void testFeedProtocol() { - final String in = "feed://example.com"; - final String out = URLChecker.prepareURL(in); - assertEquals("http://example.com", out); - } - - @Test - public void testPcastProtocolNoScheme() { - final String in = "pcast://example.com"; - final String out = URLChecker.prepareURL(in); - assertEquals("http://example.com", out); - } - - @Test - public void testItpcProtocol() { - final String in = "itpc://example.com"; - final String out = URLChecker.prepareURL(in); - assertEquals("http://example.com", out); - } - - @Test - public void testItpcProtocolWithScheme() { - final String in = "itpc://https://example.com"; - final String out = URLChecker.prepareURL(in); - assertEquals("https://example.com", out); - } - - @Test - public void testWhiteSpaceUrlShouldNotAppend() { - final String in = "\n http://example.com \t"; - final String out = URLChecker.prepareURL(in); - assertEquals("http://example.com", out); - } - - @Test - public void testWhiteSpaceShouldAppend() { - final String in = "\n example.com \t"; - final String out = URLChecker.prepareURL(in); - assertEquals("http://example.com", out); - } - - @Test - public void testAntennaPodSubscribeProtocolNoScheme() throws Exception { - final String in = "antennapod-subscribe://example.com"; - final String out = URLChecker.prepareURL(in); - assertEquals("http://example.com", out); - } - - @Test - public void testPcastProtocolWithScheme() { - final String in = "pcast://https://example.com"; - final String out = URLChecker.prepareURL(in); - assertEquals("https://example.com", out); - } - - @Test - public void testAntennaPodSubscribeProtocolWithScheme() throws Exception { - final String in = "antennapod-subscribe://https://example.com"; - final String out = URLChecker.prepareURL(in); - assertEquals("https://example.com", out); - } - - @Test - public void testProtocolRelativeUrlIsAbsolute() throws Exception { - final String in = "https://example.com"; - final String inBase = "http://examplebase.com"; - final String out = URLChecker.prepareURL(in, inBase); - assertEquals(in, out); - } - - @Test - public void testProtocolRelativeUrlIsRelativeHttps() throws Exception { - final String in = "//example.com"; - final String inBase = "https://examplebase.com"; - final String out = URLChecker.prepareURL(in, inBase); - assertEquals("https://example.com", out); - } - - @Test - public void testProtocolRelativeUrlIsHttpsWithAPSubscribeProtocol() throws Exception { - final String in = "//example.com"; - final String inBase = "antennapod-subscribe://https://examplebase.com"; - final String out = URLChecker.prepareURL(in, inBase); - assertEquals("https://example.com", out); - } - - @Test - public void testProtocolRelativeUrlBaseUrlNull() throws Exception { - final String in = "example.com"; - final String out = URLChecker.prepareURL(in, null); - assertEquals("http://example.com", out); - } - - @Test - public void testUrlEqualsSame() { - assertTrue(URLChecker.urlEquals("https://www.example.com/test", "https://www.example.com/test")); - assertTrue(URLChecker.urlEquals("https://www.example.com/test", "https://www.example.com/test/")); - assertTrue(URLChecker.urlEquals("https://www.example.com/test", "https://www.example.com//test")); - assertTrue(URLChecker.urlEquals("https://www.example.com", "https://www.example.com/")); - assertTrue(URLChecker.urlEquals("https://www.example.com", "http://www.example.com")); - assertTrue(URLChecker.urlEquals("http://www.example.com/", "https://www.example.com/")); - assertTrue(URLChecker.urlEquals("https://www.example.com/?id=42", "https://www.example.com/?id=42")); - assertTrue(URLChecker.urlEquals("https://example.com/podcast%20test", "https://example.com/podcast test")); - assertTrue(URLChecker.urlEquals("https://example.com/?a=podcast%20test", "https://example.com/?a=podcast test")); - assertTrue(URLChecker.urlEquals("https://example.com/?", "https://example.com/")); - assertTrue(URLChecker.urlEquals("https://example.com/?", "https://example.com")); - assertTrue(URLChecker.urlEquals("https://Example.com", "https://example.com")); - assertTrue(URLChecker.urlEquals("https://example.com/test", "https://example.com/Test")); - } - - @Test - public void testUrlEqualsDifferent() { - assertFalse(URLChecker.urlEquals("https://www.example.com/test", "https://www.example2.com/test")); - assertFalse(URLChecker.urlEquals("https://www.example.com/test", "https://www.example.de/test")); - assertFalse(URLChecker.urlEquals("https://example.com/", "https://otherpodcast.example.com/")); - assertFalse(URLChecker.urlEquals("https://www.example.com/?id=42&a=b", "https://www.example.com/?id=43&a=b")); - assertFalse(URLChecker.urlEquals("https://example.com/podcast%25test", "https://example.com/podcast test")); - } -} diff --git a/app/src/androidTest/java/de/test/antennapod/util/playback/TimelineTest.java b/app/src/androidTest/java/de/test/antennapod/util/playback/TimelineTest.java deleted file mode 100644 index ed37b7daa..000000000 --- a/app/src/androidTest/java/de/test/antennapod/util/playback/TimelineTest.java +++ /dev/null @@ -1,248 +0,0 @@ -package de.test.antennapod.util.playback; - -import android.content.Context; - -import androidx.test.platform.app.InstrumentationRegistry; -import androidx.test.filters.SmallTest; -import org.jsoup.Jsoup; -import org.jsoup.nodes.Document; -import org.jsoup.nodes.Element; -import org.jsoup.select.Elements; - -import java.util.Date; -import java.util.List; - -import de.danoeh.antennapod.core.feed.Chapter; -import de.danoeh.antennapod.core.feed.FeedItem; -import de.danoeh.antennapod.core.feed.FeedMedia; -import de.danoeh.antennapod.core.util.playback.Playable; -import de.danoeh.antennapod.core.util.playback.Timeline; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -/** - * Test class for timeline. - */ -@SmallTest -public class TimelineTest { - - private Context context; - - @Before - public void setUp() { - context = InstrumentationRegistry.getInstrumentation().getTargetContext(); - } - - private Playable newTestPlayable(List<Chapter> chapters, String shownotes, int duration) { - FeedItem item = new FeedItem(0, "Item", "item-id", "http://example.com/item", new Date(), FeedItem.PLAYED, null); - item.setChapters(chapters); - item.setContentEncoded(shownotes); - FeedMedia media = new FeedMedia(item, "http://example.com/episode", 100, "audio/mp3"); - media.setDuration(duration); - item.setMedia(media); - return media; - } - - @Test - public void testProcessShownotesAddTimecodeHHMMSSNoChapters() { - final String timeStr = "10:11:12"; - final long time = 3600 * 1000 * 10 + 60 * 1000 * 11 + 12 * 1000; - - Playable p = newTestPlayable(null, "<p> Some test text with a timecode " - + timeStr + " here.</p>", Integer.MAX_VALUE); - Timeline t = new Timeline(context, p); - String res = t.processShownotes(); - checkLinkCorrect(res, new long[]{time}, new String[]{timeStr}); - } - - @Test - public void testProcessShownotesAddTimecodeHHMMSSMoreThen24HoursNoChapters() { - final String timeStr = "25:00:00"; - final long time = 25 * 60 * 60 * 1000; - - Playable p = newTestPlayable(null, "<p> Some test text with a timecode " - + timeStr + " here.</p>", Integer.MAX_VALUE); - Timeline t = new Timeline(context, p); - String res = t.processShownotes(); - checkLinkCorrect(res, new long[]{time}, new String[]{timeStr}); - } - - @Test - public void testProcessShownotesAddTimecodeHHMMNoChapters() { - final String timeStr = "10:11"; - final long time = 3600 * 1000 * 10 + 60 * 1000 * 11; - - Playable p = newTestPlayable(null, "<p> Some test text with a timecode " - + timeStr + " here.</p>", Integer.MAX_VALUE); - Timeline t = new Timeline(context, p); - String res = t.processShownotes(); - checkLinkCorrect(res, new long[]{time}, new String[]{timeStr}); - } - - @Test - public void testProcessShownotesAddTimecodeMMSSNoChapters() { - final String timeStr = "10:11"; - final long time = 10 * 60 * 1000 + 11 * 1000; - - Playable p = newTestPlayable(null, "<p> Some test text with a timecode " - + timeStr + " here.</p>", 11 * 60 * 1000); - Timeline t = new Timeline(context, p); - String res = t.processShownotes(); - checkLinkCorrect(res, new long[]{time}, new String[]{timeStr}); - } - - @Test - public void testProcessShownotesAddTimecodeHMMSSNoChapters() { - final String timeStr = "2:11:12"; - final long time = 2 * 60 * 60 * 1000 + 11 * 60 * 1000 + 12 * 1000; - Playable p = newTestPlayable(null, "<p> Some test text with a timecode " - + timeStr + " here.</p>", Integer.MAX_VALUE); - Timeline t = new Timeline(context, p); - String res = t.processShownotes(); - checkLinkCorrect(res, new long[]{time}, new String[]{timeStr}); - } - - @Test - public void testProcessShownotesAddTimecodeMSSNoChapters() { - final String timeStr = "1:12"; - final long time = 60 * 1000 + 12 * 1000; - - Playable p = newTestPlayable(null, "<p> Some test text with a timecode " - + timeStr + " here.</p>", 2 * 60 * 1000); - Timeline t = new Timeline(context, p); - String res = t.processShownotes(); - checkLinkCorrect(res, new long[]{time}, new String[]{timeStr}); - } - - @Test - public void testProcessShownotesAddNoTimecodeDuration() { - final String timeStr = "2:11:12"; - final int time = 2 * 60 * 60 * 1000 + 11 * 60 * 1000 + 12 * 1000; - String originalText = "<p> Some test text with a timecode " + timeStr + " here.</p>"; - Playable p = newTestPlayable(null, originalText, time); - Timeline t = new Timeline(context, p); - String res = t.processShownotes(); - Document d = Jsoup.parse(res); - assertEquals("Should not parse time codes that equal duration", 0, d.body().getElementsByTag("a").size()); - } - - @Test - public void testProcessShownotesAddTimecodeMultipleFormatsNoChapters() { - final String[] timeStrings = new String[]{ "10:12", "1:10:12" }; - - Playable p = newTestPlayable(null, "<p> Some test text with a timecode " - + timeStrings[0] + " here. Hey look another one " + timeStrings[1] + " here!</p>", 2 * 60 * 60 * 1000); - Timeline t = new Timeline(context, p); - String res = t.processShownotes(); - checkLinkCorrect(res, new long[]{ 10 * 60 * 1000 + 12 * 1000, - 60 * 60 * 1000 + 10 * 60 * 1000 + 12 * 1000 }, timeStrings); - } - - @Test - public void testProcessShownotesAddTimecodeMultipleShortFormatNoChapters() { - - // One of these timecodes fits as HH:MM and one does not so both should be parsed as MM:SS. - final String[] timeStrings = new String[]{ "10:12", "2:12" }; - - Playable p = newTestPlayable(null, "<p> Some test text with a timecode " - + timeStrings[0] + " here. Hey look another one " + timeStrings[1] + " here!</p>", 3 * 60 * 60 * 1000); - Timeline t = new Timeline(context, p); - String res = t.processShownotes(); - checkLinkCorrect(res, new long[]{ 10 * 60 * 1000 + 12 * 1000, 2 * 60 * 1000 + 12 * 1000 }, timeStrings); - } - - @Test - public void testProcessShownotesAddTimecodeParentheses() { - final String timeStr = "10:11"; - final long time = 3600 * 1000 * 10 + 60 * 1000 * 11; - - Playable p = newTestPlayable(null, "<p> Some test text with a timecode (" - + timeStr + ") here.</p>", Integer.MAX_VALUE); - Timeline t = new Timeline(context, p); - String res = t.processShownotes(); - checkLinkCorrect(res, new long[]{time}, new String[]{timeStr}); - } - - @Test - public void testProcessShownotesAddTimecodeBrackets() { - final String timeStr = "10:11"; - final long time = 3600 * 1000 * 10 + 60 * 1000 * 11; - - Playable p = newTestPlayable(null, "<p> Some test text with a timecode [" - + timeStr + "] here.</p>", Integer.MAX_VALUE); - Timeline t = new Timeline(context, p); - String res = t.processShownotes(); - checkLinkCorrect(res, new long[]{time}, new String[]{timeStr}); - } - - @Test - public void testProcessShownotesAddTimecodeAngleBrackets() { - final String timeStr = "10:11"; - final long time = 3600 * 1000 * 10 + 60 * 1000 * 11; - - Playable p = newTestPlayable(null, "<p> Some test text with a timecode <" - + timeStr + "> here.</p>", Integer.MAX_VALUE); - Timeline t = new Timeline(context, p); - String res = t.processShownotes(); - checkLinkCorrect(res, new long[]{time}, new String[]{timeStr}); - } - - @Test - public void testProcessShownotesAndInvalidTimecode() { - final String[] timeStrs = new String[] {"2:1", "0:0", "000", "00", "00:000"}; - - StringBuilder shownotes = new StringBuilder("<p> Some test text with timecodes "); - for (String timeStr : timeStrs) { - shownotes.append(timeStr).append(" "); - } - shownotes.append("here.</p>"); - - Playable p = newTestPlayable(null, shownotes.toString(), Integer.MAX_VALUE); - Timeline t = new Timeline(context, p); - String res = t.processShownotes(); - checkLinkCorrect(res, new long[0], new String[0]); - } - - private void checkLinkCorrect(String res, long[] timecodes, String[] timecodeStr) { - assertNotNull(res); - Document d = Jsoup.parse(res); - Elements links = d.body().getElementsByTag("a"); - int countedLinks = 0; - for (Element link : links) { - String href = link.attributes().get("href"); - String text = link.text(); - if (href.startsWith("antennapod://")) { - assertTrue(href.endsWith(String.valueOf(timecodes[countedLinks]))); - assertEquals(timecodeStr[countedLinks], text); - countedLinks++; - assertTrue("Contains too many links: " + countedLinks + " > " - + timecodes.length, countedLinks <= timecodes.length); - } - } - assertEquals(timecodes.length, countedLinks); - } - - @Test - public void testIsTimecodeLink() { - assertFalse(Timeline.isTimecodeLink(null)); - assertFalse(Timeline.isTimecodeLink("http://antennapod/timecode/123123")); - assertFalse(Timeline.isTimecodeLink("antennapod://timecode/")); - assertFalse(Timeline.isTimecodeLink("antennapod://123123")); - assertFalse(Timeline.isTimecodeLink("antennapod://timecode/123123a")); - assertTrue(Timeline.isTimecodeLink("antennapod://timecode/123")); - assertTrue(Timeline.isTimecodeLink("antennapod://timecode/1")); - } - - @Test - public void testGetTimecodeLinkTime() { - assertEquals(-1, Timeline.getTimecodeLinkTime(null)); - assertEquals(-1, Timeline.getTimecodeLinkTime("http://timecode/123")); - assertEquals(123, Timeline.getTimecodeLinkTime("antennapod://timecode/123")); - - } -} diff --git a/app/src/androidTest/java/de/test/antennapod/util/syndication/FeedDiscovererTest.java b/app/src/androidTest/java/de/test/antennapod/util/syndication/FeedDiscovererTest.java deleted file mode 100644 index b213a5efa..000000000 --- a/app/src/androidTest/java/de/test/antennapod/util/syndication/FeedDiscovererTest.java +++ /dev/null @@ -1,124 +0,0 @@ -package de.test.antennapod.util.syndication; - -import androidx.test.platform.app.InstrumentationRegistry; -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.IOUtils; - -import java.io.File; -import java.io.FileOutputStream; -import java.nio.charset.Charset; -import java.util.Map; - -import de.danoeh.antennapod.core.util.syndication.FeedDiscoverer; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -/** - * Test class for FeedDiscoverer - */ -public class FeedDiscovererTest { - - private FeedDiscoverer fd; - - private File testDir; - - @Before - public void setUp() throws Exception { - fd = new FeedDiscoverer(); - testDir = new File(InstrumentationRegistry - .getInstrumentation().getTargetContext().getFilesDir(), "FeedDiscovererTest"); - testDir.mkdir(); - assertTrue(testDir.exists()); - } - - @After - public void tearDown() throws Exception { - FileUtils.deleteDirectory(testDir); - } - - private String createTestHtmlString(String rel, String type, String href, String title) { - return String.format("<html><head><title>Test</title><link rel=\"%s\" type=\"%s\" href=\"%s\" title=\"%s\"></head><body></body></html>", - rel, type, href, title); - } - - private String createTestHtmlString(String rel, String type, String href) { - return String.format("<html><head><title>Test</title><link rel=\"%s\" type=\"%s\" href=\"%s\"></head><body></body></html>", - rel, type, href); - } - - private void checkFindUrls(boolean isAlternate, boolean isRss, boolean withTitle, boolean isAbsolute, boolean fromString) throws Exception { - final String title = "Test title"; - final String hrefAbs = "http://example.com/feed"; - final String hrefRel = "/feed"; - final String base = "http://example.com"; - - final String rel = (isAlternate) ? "alternate" : "feed"; - final String type = (isRss) ? "application/rss+xml" : "application/atom+xml"; - final String href = (isAbsolute) ? hrefAbs : hrefRel; - - Map<String, String> res; - String html = (withTitle) ? createTestHtmlString(rel, type, href, title) - : createTestHtmlString(rel, type, href); - if (fromString) { - res = fd.findLinks(html, base); - } else { - File testFile = new File(testDir, "feed"); - FileOutputStream out = new FileOutputStream(testFile); - IOUtils.write(html, out, Charset.forName("UTF-8")); - out.close(); - res = fd.findLinks(testFile, base); - } - - assertNotNull(res); - assertEquals(1, res.size()); - for (String key : res.keySet()) { - assertEquals(hrefAbs, key); - } - assertTrue(res.containsKey(hrefAbs)); - if (withTitle) { - assertEquals(title, res.get(hrefAbs)); - } else { - assertEquals(href, res.get(hrefAbs)); - } - } - - @Test - public void testAlternateRSSWithTitleAbsolute() throws Exception { - checkFindUrls(true, true, true, true, true); - } - - @Test - public void testAlternateRSSWithTitleRelative() throws Exception { - checkFindUrls(true, true, true, false, true); - } - - @Test - public void testAlternateRSSNoTitleAbsolute() throws Exception { - checkFindUrls(true, true, false, true, true); - } - - @Test - public void testAlternateRSSNoTitleRelative() throws Exception { - checkFindUrls(true, true, false, false, true); - } - - @Test - public void testAlternateAtomWithTitleAbsolute() throws Exception { - checkFindUrls(true, false, true, true, true); - } - - @Test - public void testFeedAtomWithTitleAbsolute() throws Exception { - checkFindUrls(false, false, true, true, true); - } - - @Test - public void testAlternateRSSWithTitleAbsoluteFromFile() throws Exception { - checkFindUrls(true, true, true, true, false); - } -} |