diff options
Diffstat (limited to 'tests/src')
28 files changed, 704 insertions, 240 deletions
diff --git a/tests/src/cgeo/CGeoTestCase.java b/tests/src/cgeo/CGeoTestCase.java index 6a63cbc..7dd5956 100644 --- a/tests/src/cgeo/CGeoTestCase.java +++ b/tests/src/cgeo/CGeoTestCase.java @@ -1,15 +1,24 @@ package cgeo; -import cgeo.geocaching.cgData; -import cgeo.geocaching.cgeoapplication; +import cgeo.geocaching.CgeoApplication; +import cgeo.geocaching.DataStore; import cgeo.geocaching.enumerations.LoadFlags; +import cgeo.geocaching.enumerations.LoadFlags.RemoveFlag; +import cgeo.geocaching.settings.Settings; +import cgeo.geocaching.settings.TestSettings; import android.test.ApplicationTestCase; -public abstract class CGeoTestCase extends ApplicationTestCase<cgeoapplication> { +import java.util.EnumSet; + +public abstract class CGeoTestCase extends ApplicationTestCase<CgeoApplication> { + + private boolean oldStoreMapsFlag; + private boolean oldStoreWpMapsFlag; + private boolean oldMapStoreFlagsRecorded = false; public CGeoTestCase() { - super(cgeoapplication.class); + super(CgeoApplication.class); } @Override @@ -20,7 +29,58 @@ public abstract class CGeoTestCase extends ApplicationTestCase<cgeoapplication> /** Remove cache from DB and cache to ensure that the cache is not loaded from the database */ protected static void deleteCacheFromDB(String geocode) { - cgData.removeCache(geocode, LoadFlags.REMOVE_ALL); + DataStore.removeCache(geocode, LoadFlags.REMOVE_ALL); + } + + /** + * remove cache from database and file system + * + * @param geocode + */ + protected static void removeCacheCompletely(final String geocode) { + final EnumSet<RemoveFlag> flags = EnumSet.copyOf(LoadFlags.REMOVE_ALL); + flags.add(RemoveFlag.REMOVE_OWN_WAYPOINTS_ONLY_FOR_TESTING); + DataStore.removeCache(geocode, flags); + } + + /** + * must be called once before setting the flags + * can be called again after restoring the flags + */ + protected void recordMapStoreFlags() { + if (oldMapStoreFlagsRecorded) { + throw new IllegalStateException("MapStoreFlags already recorded!"); + } + oldStoreMapsFlag = Settings.isStoreOfflineMaps(); + oldStoreWpMapsFlag = Settings.isStoreOfflineWpMaps(); + oldMapStoreFlagsRecorded = true; } + /** + * can be called after recordMapStoreFlags, + * to set the flags for map storing as necessary + * @param storeCacheMap + * @param storeWpMaps + */ + protected void setMapStoreFlags(boolean storeCacheMap, boolean storeWpMaps) { + if (!oldMapStoreFlagsRecorded) { + throw new IllegalStateException("Previous MapStoreFlags havn't been recorded! Setting not allowed"); + } + + TestSettings.setStoreOfflineMaps(storeCacheMap); + TestSettings.setStoreOfflineWpMaps(storeWpMaps); + } + + /** + * has to be called after completion of the test (preferably in the finally part of a try statement) + */ + protected void restoreMapStoreFlags() { + if (!oldMapStoreFlagsRecorded) { + throw new IllegalStateException("Previous MapStoreFlags havn't been recorded. Restore not possible"); + } + + TestSettings.setStoreOfflineMaps(oldStoreMapsFlag); + TestSettings.setStoreOfflineWpMaps(oldStoreWpMapsFlag); + oldMapStoreFlagsRecorded = false; + } } diff --git a/tests/src/cgeo/geocaching/cgDataTest.java b/tests/src/cgeo/geocaching/DataStoreTest.java index cacf061..7dc3016 100644 --- a/tests/src/cgeo/geocaching/cgDataTest.java +++ b/tests/src/cgeo/geocaching/DataStoreTest.java @@ -8,6 +8,7 @@ import cgeo.geocaching.enumerations.LoadFlags; import cgeo.geocaching.enumerations.LoadFlags.SaveFlag; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.geopoint.Viewport; +import cgeo.geocaching.list.StoredList; import org.apache.commons.lang3.StringUtils; @@ -18,7 +19,7 @@ import java.util.HashSet; import java.util.List; import java.util.Set; -public class cgDataTest extends CGeoTestCase { +public class DataStoreTest extends CGeoTestCase { public static void testStoredLists() { @@ -35,11 +36,11 @@ public class cgDataTest extends CGeoTestCase { try { // create lists - listId1 = cgData.createList("cgData Test"); + listId1 = DataStore.createList("DataStore Test"); assertTrue(listId1 > StoredList.STANDARD_LIST_ID); - listId2 = cgData.createList("cgDataTest"); + listId2 = DataStore.createList("DataStoreTest"); assertTrue(listId2 > StoredList.STANDARD_LIST_ID); - assertTrue(cgData.getLists().size() >= 2); + assertTrue(DataStore.getLists().size() >= 2); cache1.setDetailed(true); cache1.setListId(listId1); @@ -47,33 +48,33 @@ public class cgDataTest extends CGeoTestCase { cache2.setListId(listId1); // save caches to DB (cache1=listId1, cache2=listId1) - cgData.saveCache(cache1, LoadFlags.SAVE_ALL); - cgData.saveCache(cache2, LoadFlags.SAVE_ALL); - assertTrue(cgData.getAllCachesCount() >= 2); + DataStore.saveCache(cache1, LoadFlags.SAVE_ALL); + DataStore.saveCache(cache2, LoadFlags.SAVE_ALL); + assertTrue(DataStore.getAllCachesCount() >= 2); // rename list (cache1=listId1, cache2=listId1) - assertEquals(1, cgData.renameList(listId1, "cgData Test (renamed)")); + assertEquals(1, DataStore.renameList(listId1, "DataStore Test (renamed)")); // get list - final StoredList list1 = cgData.getList(listId1); - assertEquals("cgData Test (renamed)", list1.title); + final StoredList list1 = DataStore.getList(listId1); + assertEquals("DataStore Test (renamed)", list1.title); // move to list (cache1=listId2, cache2=listId2) - cgData.moveToList(Collections.singletonList(cache1), listId2); - assertEquals(1, cgData.getAllStoredCachesCount(CacheType.ALL, listId2)); + DataStore.moveToList(Collections.singletonList(cache1), listId2); + assertEquals(1, DataStore.getAllStoredCachesCount(CacheType.ALL, listId2)); // remove list (cache1=listId2, cache2=listId2) - assertTrue(cgData.removeList(listId1)); + assertTrue(DataStore.removeList(listId1)); // mark dropped (cache1=1, cache2=0) - cgData.markDropped(Collections.singletonList(cache2)); + DataStore.markDropped(Collections.singletonList(cache2)); // mark stored (cache1=1, cache2=listId2) - cgData.moveToList(Collections.singletonList(cache2), listId2); - assertEquals(2, cgData.getAllStoredCachesCount(CacheType.ALL, listId2)); + DataStore.moveToList(Collections.singletonList(cache2), listId2); + assertEquals(2, DataStore.getAllStoredCachesCount(CacheType.ALL, listId2)); // drop stored (cache1=0, cache2=0) - cgData.removeList(listId2); + DataStore.removeList(listId2); } finally { @@ -81,25 +82,25 @@ public class cgDataTest extends CGeoTestCase { final Set<String> geocodes = new HashSet<String>(); geocodes.add(cache1.getGeocode()); geocodes.add(cache2.getGeocode()); - cgData.removeCaches(geocodes, LoadFlags.REMOVE_ALL); + DataStore.removeCaches(geocodes, LoadFlags.REMOVE_ALL); // remove list - cgData.removeList(listId1); - cgData.removeList(listId2); + DataStore.removeList(listId1); + DataStore.removeList(listId2); } } // Check that queries don't throw an exception (see issue #1429). public static void testLoadWaypoints() { final Viewport viewport = new Viewport(new Geopoint(-1, -2), new Geopoint(3, 4)); - cgData.loadWaypoints(viewport, false, false, CacheType.ALL); - cgData.loadWaypoints(viewport, false, true, CacheType.ALL); - cgData.loadWaypoints(viewport, true, false, CacheType.ALL); - cgData.loadWaypoints(viewport, true, true, CacheType.ALL); - cgData.loadWaypoints(viewport, false, false, CacheType.TRADITIONAL); - cgData.loadWaypoints(viewport, false, true, CacheType.TRADITIONAL); - cgData.loadWaypoints(viewport, true, false, CacheType.TRADITIONAL); - cgData.loadWaypoints(viewport, true, true, CacheType.TRADITIONAL); + DataStore.loadWaypoints(viewport, false, false, CacheType.ALL); + DataStore.loadWaypoints(viewport, false, true, CacheType.ALL); + DataStore.loadWaypoints(viewport, true, false, CacheType.ALL); + DataStore.loadWaypoints(viewport, true, true, CacheType.ALL); + DataStore.loadWaypoints(viewport, false, false, CacheType.TRADITIONAL); + DataStore.loadWaypoints(viewport, false, true, CacheType.TRADITIONAL); + DataStore.loadWaypoints(viewport, true, false, CacheType.TRADITIONAL); + DataStore.loadWaypoints(viewport, true, true, CacheType.TRADITIONAL); } // Check that saving a cache and trackable without logs works (see #2199) @@ -118,12 +119,12 @@ public class cgDataTest extends CGeoTestCase { cache.setInventory(inventory); try { - cgData.saveCache(cache, EnumSet.of(SaveFlag.SAVE_DB)); - final Geocache loadedCache = cgData.loadCache(GEOCODE_CACHE, LoadFlags.LOAD_ALL_DB_ONLY); + DataStore.saveCache(cache, EnumSet.of(SaveFlag.SAVE_DB)); + final Geocache loadedCache = DataStore.loadCache(GEOCODE_CACHE, LoadFlags.LOAD_ALL_DB_ONLY); assertNotNull("Cache was not saved!", loadedCache); assertEquals(1, loadedCache.getInventory().size()); } finally { - cgData.removeCache(GEOCODE_CACHE, LoadFlags.REMOVE_ALL); + DataStore.removeCache(GEOCODE_CACHE, LoadFlags.REMOVE_ALL); } } @@ -141,25 +142,25 @@ public class cgDataTest extends CGeoTestCase { cache.setDetailed(true); try { - final Geocache oldCache = cgData.loadCache(upperCase, LoadFlags.LOAD_ALL_DB_ONLY); + final Geocache oldCache = DataStore.loadCache(upperCase, LoadFlags.LOAD_ALL_DB_ONLY); assertNull("Database contained old cache!", oldCache); - cgData.saveCache(cache, EnumSet.of(SaveFlag.SAVE_DB)); - final Geocache cacheWithOriginalCode = cgData.loadCache(upperCase, LoadFlags.LOAD_ALL_DB_ONLY); + DataStore.saveCache(cache, EnumSet.of(SaveFlag.SAVE_DB)); + final Geocache cacheWithOriginalCode = DataStore.loadCache(upperCase, LoadFlags.LOAD_ALL_DB_ONLY); assertNotNull("Cache was not saved correctly!", cacheWithOriginalCode); - final Geocache cacheLowerCase = cgData.loadCache(lowerCase, LoadFlags.LOAD_ALL_DB_ONLY); + final Geocache cacheLowerCase = DataStore.loadCache(lowerCase, LoadFlags.LOAD_ALL_DB_ONLY); assertNotNull("Could not find cache by case insensitive geocode", cacheLowerCase); } finally { - cgData.removeCache(upperCase, LoadFlags.REMOVE_ALL); + DataStore.removeCache(upperCase, LoadFlags.REMOVE_ALL); } } // Loading logs for an empty geocode should return an empty list, not null! public static void testLoadLogsFromEmptyGeocode() { - final List<LogEntry> logs = cgData.loadLogs(""); + final List<LogEntry> logs = DataStore.loadLogs(""); assertNotNull("Logs must not be null", logs); assertEquals("Logs from empty geocode must be empty", 0, logs.size()); @@ -169,7 +170,7 @@ public class cgDataTest extends CGeoTestCase { int sumCaches = 0; int allCaches = 0; for (CacheType cacheType : CacheType.values()) { - SearchResult historyOfType = cgData.getHistoryOfCaches(false, cacheType); + SearchResult historyOfType = DataStore.getHistoryOfCaches(false, cacheType); assertNotNull(historyOfType); if (cacheType != CacheType.ALL) { sumCaches += historyOfType.getCount(); @@ -180,7 +181,7 @@ public class cgDataTest extends CGeoTestCase { // check that sum of types equals 'all' assertEquals(sumCaches, allCaches); // check that two different routines behave the same - assertEquals(cgData.getAllHistoryCachesCount(), sumCaches); + assertEquals(DataStore.getAllHistoryCachesCount(), sumCaches); } public static void testCachedMissing() { @@ -208,15 +209,15 @@ public class cgDataTest extends CGeoTestCase { inTileHighZoom.setCoords(new Geopoint("N49 44.001 E8 37.001"), Tile.ZOOMLEVEL_MIN_PERSONALIZED + 1); // put in cache - cgData.saveCache(main, EnumSet.of(SaveFlag.SAVE_CACHE)); - cgData.saveCache(inTileLowZoom, EnumSet.of(SaveFlag.SAVE_CACHE)); - cgData.saveCache(inTileHighZoom, EnumSet.of(SaveFlag.SAVE_CACHE)); - cgData.saveCache(outTile, EnumSet.of(SaveFlag.SAVE_CACHE)); - cgData.saveCache(otherConnector, EnumSet.of(SaveFlag.SAVE_CACHE)); + DataStore.saveCache(main, EnumSet.of(SaveFlag.SAVE_CACHE)); + DataStore.saveCache(inTileLowZoom, EnumSet.of(SaveFlag.SAVE_CACHE)); + DataStore.saveCache(inTileHighZoom, EnumSet.of(SaveFlag.SAVE_CACHE)); + DataStore.saveCache(outTile, EnumSet.of(SaveFlag.SAVE_CACHE)); + DataStore.saveCache(otherConnector, EnumSet.of(SaveFlag.SAVE_CACHE)); final SearchResult search = new SearchResult(main); - Set<String> filteredGeoCodes = cgData.getCachedMissingFromSearch(search, tiles, GCConnector.getInstance(), Tile.ZOOMLEVEL_MIN_PERSONALIZED - 1); + Set<String> filteredGeoCodes = DataStore.getCachedMissingFromSearch(search, tiles, GCConnector.getInstance(), Tile.ZOOMLEVEL_MIN_PERSONALIZED - 1); assertTrue(filteredGeoCodes.contains(inTileLowZoom.getGeocode())); assertFalse(filteredGeoCodes.contains(inTileHighZoom.getGeocode())); diff --git a/tests/src/cgeo/geocaching/GeocacheTest.java b/tests/src/cgeo/geocaching/GeocacheTest.java index 4c09594..2f5281c 100644 --- a/tests/src/cgeo/geocaching/GeocacheTest.java +++ b/tests/src/cgeo/geocaching/GeocacheTest.java @@ -1,16 +1,15 @@ package cgeo.geocaching; +import cgeo.CGeoTestCase; import cgeo.geocaching.enumerations.CacheType; import cgeo.geocaching.geopoint.Geopoint; - -import android.os.Handler; -import android.test.AndroidTestCase; +import cgeo.geocaching.list.StoredList; import java.util.ArrayList; import java.util.Date; import java.util.List; -public class GeocacheTest extends AndroidTestCase { +public class GeocacheTest extends CGeoTestCase { final static private class MockedEventCache extends Geocache { public MockedEventCache(final Date date) { @@ -52,31 +51,41 @@ public class GeocacheTest extends AndroidTestCase { assertEquals("GC1234", cache.getGeocode()); } - public static void testUpdateWaypointFromNote() { + public void testUpdateWaypointFromNote() { assertWaypointsParsed("Test N51 13.888 E007 03.444", 1); } - public static void testUpdateWaypointsFromNote() { + public void testUpdateWaypointsFromNote() { assertWaypointsParsed("Test N51 13.888 E007 03.444 Test N51 13.233 E007 03.444 Test N51 09.123 E007 03.444", 3); } - private static void assertWaypointsParsed(String note, int expectedWaypoints) { - Geocache cache = new Geocache(); - cache.setGeocode("Test" + System.nanoTime()); - cache.setWaypoints(new ArrayList<Waypoint>(), false); - for (int i = 0; i < 2; i++) { - cache.setPersonalNote(note); - cache.parseWaypointsFromNote(); - final List<Waypoint> waypoints = cache.getWaypoints(); - assertNotNull(waypoints); - assertEquals(expectedWaypoints, waypoints.size()); - final Waypoint waypoint = waypoints.get(0); - assertEquals(new Geopoint("N51 13.888 E007 03.444"), waypoint.getCoords()); - // assertEquals("Test", waypoint.getNote()); - assertEquals(cgeoapplication.getInstance().getString(R.string.cache_personal_note) + " 1", waypoint.getName()); - cache.store(StoredList.TEMPORARY_LIST_ID, null); + private void assertWaypointsParsed(String note, int expectedWaypoints) { + + recordMapStoreFlags(); + + try { + setMapStoreFlags(false, false); + + Geocache cache = new Geocache(); + final String geocode = "Test" + System.nanoTime(); + cache.setGeocode(geocode); + cache.setWaypoints(new ArrayList<Waypoint>(), false); + for (int i = 0; i < 2; i++) { + cache.setPersonalNote(note); + cache.parseWaypointsFromNote(); + final List<Waypoint> waypoints = cache.getWaypoints(); + assertNotNull(waypoints); + assertEquals(expectedWaypoints, waypoints.size()); + final Waypoint waypoint = waypoints.get(0); + assertEquals(new Geopoint("N51 13.888 E007 03.444"), waypoint.getCoords()); + // assertEquals("Test", waypoint.getNote()); + assertEquals(CgeoApplication.getInstance().getString(R.string.cache_personal_note) + " 1", waypoint.getName()); + cache.store(StoredList.TEMPORARY_LIST_ID, null); + } + removeCacheCompletely(geocode); + } finally { + restoreMapStoreFlags(); } - cache.drop(new Handler()); } public static void testMergeDownloadedStored() { diff --git a/tests/src/cgeo/geocaching/PersonalNoteTest.java b/tests/src/cgeo/geocaching/PersonalNoteTest.java index c8aa8ba..c31662f 100644 --- a/tests/src/cgeo/geocaching/PersonalNoteTest.java +++ b/tests/src/cgeo/geocaching/PersonalNoteTest.java @@ -1,5 +1,7 @@ package cgeo.geocaching; +import cgeo.geocaching.list.StoredList; + import junit.framework.TestCase; public class PersonalNoteTest extends TestCase { diff --git a/tests/src/cgeo/geocaching/StoredListTest.java b/tests/src/cgeo/geocaching/StoredListTest.java deleted file mode 100644 index dd8b6c7..0000000 --- a/tests/src/cgeo/geocaching/StoredListTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package cgeo.geocaching; - -import junit.framework.TestCase; - -public class StoredListTest extends TestCase { - - public static void testStandardListExists() { - final StoredList list = cgData.getList(StoredList.STANDARD_LIST_ID); - assertNotNull(list); - } - - public static void testEquals() { - final StoredList list1 = cgData.getList(StoredList.STANDARD_LIST_ID); - final StoredList list2 = cgData.getList(StoredList.STANDARD_LIST_ID); - assertEquals(list1, list2); - } - -} diff --git a/tests/src/cgeo/geocaching/activity/ProgressTest.java b/tests/src/cgeo/geocaching/activity/ProgressTest.java index e4b4289..9dab166 100644 --- a/tests/src/cgeo/geocaching/activity/ProgressTest.java +++ b/tests/src/cgeo/geocaching/activity/ProgressTest.java @@ -1,14 +1,18 @@ package cgeo.geocaching.activity; -import cgeo.geocaching.MainActivity; +import cgeo.geocaching.AboutActivity; import android.annotation.TargetApi; import android.test.ActivityInstrumentationTestCase2; +/** + * This test uses the about activity to avoid side effects like network and GPS being triggered by the main activity. + * + */ @TargetApi(8) -public class ProgressTest extends ActivityInstrumentationTestCase2<MainActivity> { +public class ProgressTest extends ActivityInstrumentationTestCase2<AboutActivity> { public ProgressTest() { - super(MainActivity.class); + super(AboutActivity.class); } public void testProgressWrapper() { diff --git a/tests/src/cgeo/geocaching/cgeoApplicationTest.java b/tests/src/cgeo/geocaching/cgeoApplicationTest.java index 83bf28d..b2537a3 100644 --- a/tests/src/cgeo/geocaching/cgeoApplicationTest.java +++ b/tests/src/cgeo/geocaching/cgeoApplicationTest.java @@ -12,6 +12,7 @@ import cgeo.geocaching.enumerations.LogType; import cgeo.geocaching.enumerations.StatusCode; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.geopoint.Viewport; +import cgeo.geocaching.list.StoredList; import cgeo.geocaching.loaders.RecaptchaReceiver; import cgeo.geocaching.settings.Settings; import cgeo.geocaching.settings.TestSettings; @@ -111,7 +112,7 @@ public class cgeoApplicationTest extends CGeoTestCase { if (Settings.isPremiumMember() || search.getError() == null) { assertEquals(1, search.getGeocodes().size()); assertTrue(search.getGeocodes().contains(geocode)); - return cgData.loadCache(geocode, LoadFlags.LOAD_CACHE_OR_DB); + return DataStore.loadCache(geocode, LoadFlags.LOAD_CACHE_OR_DB); } assertEquals(0, search.getGeocodes().size()); return null; @@ -128,36 +129,16 @@ public class cgeoApplicationTest extends CGeoTestCase { } /** - * Test {@link Geocache#searchByGeocode(String, String, int, boolean, CancellableHandler)} + * Set the login data to the cgeo login, run the given Runnable, and restore the login. + * + * @param runnable */ - @MediumTest - public static void testSearchByGeocodeNotLoggedIn() { + private static void withMockedLoginDo(final Runnable runnable) { final ImmutablePair<String, String> login = Settings.getGcLogin(); final String memberStatus = Settings.getMemberStatus(); try { - // non premium cache - MockedCache cache = new GC2CJPF(); - - deleteCacheFromDBAndLogout(cache.getGeocode()); - - SearchResult search = Geocache.searchByGeocode(cache.getGeocode(), null, StoredList.TEMPORARY_LIST_ID, true, null); - assertNotNull(search); - assertEquals(1, search.getGeocodes().size()); - assertTrue(search.getGeocodes().contains(cache.getGeocode())); - final Geocache searchedCache = search.getFirstCacheFromResult(LoadFlags.LOAD_CACHE_OR_DB); - // coords must be null if the user is not logged in - assertNull(searchedCache.getCoords()); - - // premium cache. Not visible to guests - cache = new GC2JVEH(); - - deleteCacheFromDBAndLogout(cache.getGeocode()); - - search = Geocache.searchByGeocode(cache.getGeocode(), null, StoredList.TEMPORARY_LIST_ID, true, null); - assertNotNull(search); - assertEquals(0, search.getGeocodes().size()); - + runnable.run(); } finally { // restore user and password TestSettings.setLogin(login.left, login.right); @@ -170,26 +151,53 @@ public class cgeoApplicationTest extends CGeoTestCase { * Test {@link Geocache#searchByGeocode(String, String, int, boolean, CancellableHandler)} */ @MediumTest - public static void testSearchErrorOccured() { - final ImmutablePair<String, String> login = Settings.getGcLogin(); - final String memberStatus = Settings.getMemberStatus(); + public static void testSearchByGeocodeNotLoggedIn() { + withMockedLoginDo(new Runnable() { - try { - // non premium cache - final MockedCache cache = new GC1ZXX2(); + public void run() { + // non premium cache + MockedCache cache = new GC2CJPF(); - deleteCacheFromDBAndLogout(cache.getGeocode()); + deleteCacheFromDBAndLogout(cache.getGeocode()); - final SearchResult search = Geocache.searchByGeocode(cache.getGeocode(), null, StoredList.TEMPORARY_LIST_ID, true, null); - assertNotNull(search); - assertEquals(0, search.getGeocodes().size()); + SearchResult search = Geocache.searchByGeocode(cache.getGeocode(), null, StoredList.TEMPORARY_LIST_ID, true, null); + assertNotNull(search); + assertEquals(1, search.getGeocodes().size()); + assertTrue(search.getGeocodes().contains(cache.getGeocode())); + final Geocache searchedCache = search.getFirstCacheFromResult(LoadFlags.LOAD_CACHE_OR_DB); + // coords must be null if the user is not logged in + assertNull(searchedCache.getCoords()); - } finally { - // restore user and password - TestSettings.setLogin(login.left, login.right); - Settings.setMemberStatus(memberStatus); - Login.login(); - } + // premium cache. Not visible to guests + cache = new GC2JVEH(); + + deleteCacheFromDBAndLogout(cache.getGeocode()); + + search = Geocache.searchByGeocode(cache.getGeocode(), null, StoredList.TEMPORARY_LIST_ID, true, null); + assertNotNull(search); + assertEquals(0, search.getGeocodes().size()); + } + }); + } + + /** + * Test {@link Geocache#searchByGeocode(String, String, int, boolean, CancellableHandler)} + */ + @MediumTest + public static void testSearchErrorOccured() { + withMockedLoginDo(new Runnable() { + + public void run() { + // non premium cache + final MockedCache cache = new GC1ZXX2(); + + deleteCacheFromDBAndLogout(cache.getGeocode()); + + final SearchResult search = Geocache.searchByGeocode(cache.getGeocode(), null, StoredList.TEMPORARY_LIST_ID, true, null); + assertNotNull(search); + assertEquals(0, search.getGeocodes().size()); + } + }); } /** @@ -295,7 +303,7 @@ public class cgeoApplicationTest extends CGeoTestCase { SearchResult search = ConnectorFactory.searchByViewport(viewport, tokens); assertNotNull(search); assertTrue(search.getGeocodes().contains(mockedCache.getGeocode())); - Geocache parsedCache = cgData.loadCache(mockedCache.getGeocode(), LoadFlags.LOAD_CACHE_OR_DB); + Geocache parsedCache = DataStore.loadCache(mockedCache.getGeocode(), LoadFlags.LOAD_CACHE_OR_DB); assertEquals(Settings.isPremiumMember(), mockedCache.getCoords().equals(parsedCache.getCoords())); assertEquals(Settings.isPremiumMember(), parsedCache.isReliableLatLon()); @@ -307,7 +315,7 @@ public class cgeoApplicationTest extends CGeoTestCase { search = ConnectorFactory.searchByViewport(viewport, tokens); assertNotNull(search); assertTrue(search.getGeocodes().contains(mockedCache.getGeocode())); - parsedCache = cgData.loadCache(mockedCache.getGeocode(), LoadFlags.LOAD_CACHE_OR_DB); + parsedCache = DataStore.loadCache(mockedCache.getGeocode(), LoadFlags.LOAD_CACHE_OR_DB); assertEquals(Settings.isPremiumMember(), mockedCache.getCoords().equals(parsedCache.getCoords())); assertEquals(Settings.isPremiumMember(), parsedCache.isReliableLatLon()); @@ -326,56 +334,54 @@ public class cgeoApplicationTest extends CGeoTestCase { */ @MediumTest public static void testSearchByViewportNotLoggedIn() { + withMockedLoginDo(new Runnable() { - final ImmutablePair<String, String> login = Settings.getGcLogin(); - final String memberStatus = Settings.getMemberStatus(); - final Strategy strategy = Settings.getLiveMapStrategy(); - final Strategy testStrategy = Strategy.FAST; // FASTEST, FAST or DETAILED for tests - Settings.setLiveMapStrategy(testStrategy); - final CacheType cacheType = Settings.getCacheType(); - - try { - - final String[] tokens = null; // without a valid token we are "logged off" + public void run() { + final Strategy strategy = Settings.getLiveMapStrategy(); + final Strategy testStrategy = Strategy.FAST; // FASTEST, FAST or DETAILED for tests + Settings.setLiveMapStrategy(testStrategy); + final CacheType cacheType = Settings.getCacheType(); - // non premium cache - MockedCache cache = new GC2CJPF(); - deleteCacheFromDBAndLogout(cache.getGeocode()); - Tile.Cache.removeFromTileCache(cache); - Settings.setCacheType(CacheType.ALL); + try { - Viewport viewport = new Viewport(cache, 0.003, 0.003); - SearchResult search = ConnectorFactory.searchByViewport(viewport, tokens); + final String[] tokens = null; // without a valid token we are "logged off" - assertNotNull(search); - assertTrue(search.getGeocodes().contains(cache.getGeocode())); - // coords differ - final Geocache cacheFromViewport = cgData.loadCache(cache.getGeocode(), LoadFlags.LOAD_CACHE_OR_DB); - Log.d("cgeoApplicationTest.testSearchByViewportNotLoggedIn: Coords expected = " + cache.getCoords()); - Log.d("cgeoApplicationTest.testSearchByViewportNotLoggedIn: Coords actual = " + cacheFromViewport.getCoords()); - assertFalse(cache.getCoords().isEqualTo(cacheFromViewport.getCoords(), 1e-3)); - // depending on the chosen strategy the coords can be reliable or not - assertEquals(testStrategy == Strategy.DETAILED, cacheFromViewport.isReliableLatLon()); + // non premium cache + MockedCache cache = new GC2CJPF(); + deleteCacheFromDBAndLogout(cache.getGeocode()); + Tile.Cache.removeFromTileCache(cache); + Settings.setCacheType(CacheType.ALL); - // premium cache - cache = new GC2JVEH(); - deleteCacheFromDBAndLogout(cache.getGeocode()); + Viewport viewport = new Viewport(cache, 0.003, 0.003); + SearchResult search = ConnectorFactory.searchByViewport(viewport, tokens); - viewport = new Viewport(cache, 0.003, 0.003); - search = ConnectorFactory.searchByViewport(viewport, tokens); + assertNotNull(search); + assertTrue(search.getGeocodes().contains(cache.getGeocode())); + // coords differ + final Geocache cacheFromViewport = DataStore.loadCache(cache.getGeocode(), LoadFlags.LOAD_CACHE_OR_DB); + Log.d("cgeoApplicationTest.testSearchByViewportNotLoggedIn: Coords expected = " + cache.getCoords()); + Log.d("cgeoApplicationTest.testSearchByViewportNotLoggedIn: Coords actual = " + cacheFromViewport.getCoords()); + assertFalse(cache.getCoords().isEqualTo(cacheFromViewport.getCoords(), 1e-3)); + // depending on the chosen strategy the coords can be reliable or not + assertEquals(testStrategy == Strategy.DETAILED, cacheFromViewport.isReliableLatLon()); + + // premium cache + cache = new GC2JVEH(); + deleteCacheFromDBAndLogout(cache.getGeocode()); + + viewport = new Viewport(cache, 0.003, 0.003); + search = ConnectorFactory.searchByViewport(viewport, tokens); - assertNotNull(search); - // depending on the chosen strategy the cache is part of the search or not - assertEquals(testStrategy == Strategy.DETAILED, search.getGeocodes().contains(cache.getGeocode())); + assertNotNull(search); + // depending on the chosen strategy the cache is part of the search or not + assertEquals(testStrategy == Strategy.DETAILED, search.getGeocodes().contains(cache.getGeocode())); - } finally { - // restore user and password - TestSettings.setLogin(login.left, login.right); - Settings.setMemberStatus(memberStatus); - Login.login(); - Settings.setLiveMapStrategy(strategy); - Settings.setCacheType(cacheType); - } + } finally { + Settings.setLiveMapStrategy(strategy); + Settings.setCacheType(cacheType); + } + } + }); } /** diff --git a/tests/src/cgeo/geocaching/connector/gc/GCBaseTest.java b/tests/src/cgeo/geocaching/connector/gc/GCBaseTest.java index d70ab9b..29fd886 100644 --- a/tests/src/cgeo/geocaching/connector/gc/GCBaseTest.java +++ b/tests/src/cgeo/geocaching/connector/gc/GCBaseTest.java @@ -14,19 +14,6 @@ import junit.framework.TestCase; public class GCBaseTest extends TestCase { - public static void testSplitJSONKey() { - assertKey("(1, 2)", 1, 2); - assertKey("(12, 34)", 12, 34); - assertKey("(1234,56)", 1234, 56); - assertKey("(1234, 567)", 1234, 567); - } - - private static void assertKey(String key, int x, int y) { - final UTFGridPosition pos = UTFGridPosition.fromString(key); - assertEquals(x, pos.getX()); - assertEquals(y, pos.getY()); - } - public static void testSearchFromMap() { final MockedCache mockedCache = new GC2CJPF(); diff --git a/tests/src/cgeo/geocaching/connector/gc/GCParserTest.java b/tests/src/cgeo/geocaching/connector/gc/GCParserTest.java index de52171..163cbe7 100644 --- a/tests/src/cgeo/geocaching/connector/gc/GCParserTest.java +++ b/tests/src/cgeo/geocaching/connector/gc/GCParserTest.java @@ -1,11 +1,11 @@ package cgeo.geocaching.connector.gc; +import cgeo.geocaching.CgeoApplication; import cgeo.geocaching.Geocache; import cgeo.geocaching.Image; import cgeo.geocaching.SearchResult; import cgeo.geocaching.Trackable; import cgeo.geocaching.Waypoint; -import cgeo.geocaching.cgeoapplication; import cgeo.geocaching.enumerations.LoadFlags; import cgeo.geocaching.enumerations.StatusCode; import cgeo.geocaching.enumerations.WaypointType; @@ -18,7 +18,7 @@ import cgeo.geocaching.test.mock.MockedCache; import cgeo.geocaching.utils.CancellableHandler; import cgeo.test.Compare; -import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import android.os.Handler; @@ -34,11 +34,6 @@ public class GCParserTest extends AbstractResourceInstrumentationTestCase { assertUnpublished(cache); } - public void testUnpublishedCacheOwner() { - final int cache = R.raw.gc433yc_owner_unpublished; - assertUnpublished(cache); - } - private void assertUnpublished(final int cache) { final String page = getFileContent(cache); final SearchResult result = GCParser.parseCacheFromText(page, null); @@ -220,7 +215,7 @@ public class GCParserTest extends AbstractResourceInstrumentationTestCase { final Trackable trackable = GCParser.parseTrackable(page, "TB123E"); assertNotNull(trackable); assertEquals("TB123E", trackable.getGeocode()); - final String expectedDetails = cgeoapplication.getInstance().getString(cgeo.geocaching.R.string.trackable_not_activated); + final String expectedDetails = CgeoApplication.getInstance().getString(cgeo.geocaching.R.string.trackable_not_activated); assertEquals(expectedDetails, trackable.getDetails()); } } diff --git a/tests/src/cgeo/geocaching/connector/gc/UTFGridPositionTest.java b/tests/src/cgeo/geocaching/connector/gc/UTFGridPositionTest.java new file mode 100644 index 0000000..a742faf --- /dev/null +++ b/tests/src/cgeo/geocaching/connector/gc/UTFGridPositionTest.java @@ -0,0 +1,34 @@ +package cgeo.geocaching.connector.gc; + +import junit.framework.TestCase; + +public class UTFGridPositionTest extends TestCase { + + public static void testValidUTFGridPosition() { + assertNotNull(new UTFGridPosition(0, 0)); + } + + public static void testInvalidUTFGridPosition() { + boolean valid = true; + try { + assertNotNull(new UTFGridPosition(-1, 0)); + } catch (Exception e) { + valid = false; + } + assertFalse(valid); + } + + public static void testFromString() throws Exception { + assertXYFromString("(1, 2)", 1, 2); + assertXYFromString("(12, 34)", 12, 34); + assertXYFromString("(34,56)", 34, 56); + assertXYFromString("(34, 56)", 34, 56); + } + + private static void assertXYFromString(final String key, int x, int y) { + final UTFGridPosition pos = UTFGridPosition.fromString(key); + assertEquals(x, pos.getX()); + assertEquals(y, pos.getY()); + } + +} diff --git a/tests/src/cgeo/geocaching/connector/gc/WaypointsTest.java b/tests/src/cgeo/geocaching/connector/gc/WaypointsTest.java index d186526..19acd7c 100644 --- a/tests/src/cgeo/geocaching/connector/gc/WaypointsTest.java +++ b/tests/src/cgeo/geocaching/connector/gc/WaypointsTest.java @@ -1,9 +1,9 @@ package cgeo.geocaching.connector.gc; import cgeo.CGeoTestCase; +import cgeo.geocaching.DataStore; import cgeo.geocaching.Geocache; import cgeo.geocaching.SearchResult; -import cgeo.geocaching.cgData; import cgeo.geocaching.enumerations.LoadFlags; import cgeo.geocaching.utils.CancellableHandler; @@ -27,7 +27,7 @@ public class WaypointsTest extends CGeoTestCase { public static void testDownloadWaypoints() { // Check that repeated loads of "GC33HXE" hold the right number of waypoints (issue #2430). final String GEOCODE = "GC33HXE"; - cgData.removeCache(GEOCODE, LoadFlags.REMOVE_ALL); + DataStore.removeCache(GEOCODE, LoadFlags.REMOVE_ALL); assertEquals(9, downloadCache(GEOCODE).getWaypoints().size()); assertEquals(9, downloadCache(GEOCODE).getWaypoints().size()); } diff --git a/tests/src/cgeo/geocaching/connector/oc/OCConnectorTest.java b/tests/src/cgeo/geocaching/connector/oc/OCConnectorTest.java new file mode 100644 index 0000000..bbbd710 --- /dev/null +++ b/tests/src/cgeo/geocaching/connector/oc/OCConnectorTest.java @@ -0,0 +1,25 @@ +package cgeo.geocaching.connector.oc; + +import cgeo.geocaching.connector.ConnectorFactory; +import cgeo.geocaching.connector.IConnector; + +import junit.framework.TestCase; + +public class OCConnectorTest extends TestCase { + + /** + * OC.DE used up the 4 digit/character name space and switched over to 5 recently + */ + public static void testCanHandleNew5DigitCodes() { + final IConnector ocConnector = getOcDeConnector(); + assertTrue(ocConnector.canHandle("OCFFFF")); + assertTrue(ocConnector.canHandle("OC10000")); + } + + private static IConnector getOcDeConnector() { + final IConnector ocConnector = ConnectorFactory.getConnector("OCXXX"); + assertTrue(ocConnector.getHost().contains(".de")); + return ocConnector; + } + +} diff --git a/tests/src/cgeo/geocaching/connector/oc/OkapiClientTest.java b/tests/src/cgeo/geocaching/connector/oc/OkapiClientTest.java index 410252f..eb797c2 100644 --- a/tests/src/cgeo/geocaching/connector/oc/OkapiClientTest.java +++ b/tests/src/cgeo/geocaching/connector/oc/OkapiClientTest.java @@ -2,7 +2,7 @@ package cgeo.geocaching.connector.oc; import cgeo.CGeoTestCase; import cgeo.geocaching.Geocache; -import cgeo.geocaching.cgData; +import cgeo.geocaching.DataStore; import cgeo.geocaching.enumerations.LoadFlags; public class OkapiClientTest extends CGeoTestCase { @@ -10,12 +10,12 @@ public class OkapiClientTest extends CGeoTestCase { public static void testGetOCCache() { final String geoCode = "OU0331"; Geocache cache = OkapiClient.getCache(geoCode); - assertNotNull(cache); - assertEquals(geoCode, cache.getGeocode()); + assertNotNull("Did not get cache from OKAPI", cache); + assertEquals("Unexpected geo code", geoCode, cache.getGeocode()); assertEquals("Oshkosh Municipal Tank", cache.getName()); assertTrue(cache.isDetailed()); // cache should be stored to DB (to listID 0) when loaded above - cache = cgData.loadCache(geoCode, LoadFlags.LOAD_ALL_DB_ONLY); + cache = DataStore.loadCache(geoCode, LoadFlags.LOAD_ALL_DB_ONLY); assertNotNull(cache); assertEquals(geoCode, cache.getGeocode()); assertEquals("Oshkosh Municipal Tank", cache.getName()); diff --git a/tests/src/cgeo/geocaching/connector/trackable/GeokretyParserTest.java b/tests/src/cgeo/geocaching/connector/trackable/GeokretyParserTest.java index 3915993..8f21342 100644 --- a/tests/src/cgeo/geocaching/connector/trackable/GeokretyParserTest.java +++ b/tests/src/cgeo/geocaching/connector/trackable/GeokretyParserTest.java @@ -1,7 +1,7 @@ package cgeo.geocaching.connector.trackable; +import cgeo.geocaching.CgeoApplication; import cgeo.geocaching.Trackable; -import cgeo.geocaching.cgeoapplication; import cgeo.geocaching.test.AbstractResourceInstrumentationTestCase; import cgeo.geocaching.test.R; @@ -13,7 +13,7 @@ public class GeokretyParserTest extends AbstractResourceInstrumentationTestCase assertEquals("WeltenbummlerKret", trackable.getName()); assertEquals("GK008D", trackable.getGeocode()); assertEquals(2235f, trackable.getDistance()); - assertEquals(cgeoapplication.getInstance().getString(cgeo.geocaching.R.string.geokret_type_traditional), trackable.getType()); + assertEquals(CgeoApplication.getInstance().getString(cgeo.geocaching.R.string.geokret_type_traditional), trackable.getType()); } } diff --git a/tests/src/cgeo/geocaching/export/ExportTest.java b/tests/src/cgeo/geocaching/export/ExportTest.java index 3e5505a..6d39f8d 100644 --- a/tests/src/cgeo/geocaching/export/ExportTest.java +++ b/tests/src/cgeo/geocaching/export/ExportTest.java @@ -1,9 +1,9 @@ package cgeo.geocaching.export; import cgeo.CGeoTestCase; +import cgeo.geocaching.DataStore; import cgeo.geocaching.Geocache; import cgeo.geocaching.LogEntry; -import cgeo.geocaching.cgData; import cgeo.geocaching.enumerations.LoadFlags; import cgeo.geocaching.enumerations.LogType; import cgeo.geocaching.geopoint.Geopoint; @@ -30,7 +30,7 @@ public class ExportTest extends CGeoTestCase { cache.setCoords(new Geopoint("N 49 44.000 E 8 37.000")); final LogEntry log = new LogEntry(1353244820000L, LogType.FOUND_IT, "Smile: \ud83d\ude0a"); cache.getLogs().add(log); - cgData.saveCache(cache, LoadFlags.SAVE_ALL); + DataStore.saveCache(cache, LoadFlags.SAVE_ALL); ArrayList<Geocache> exportList = new ArrayList<Geocache>(); exportList.add(cache); GpxExportTester gpxExport = new GpxExportTester(); @@ -38,7 +38,7 @@ public class ExportTest extends CGeoTestCase { try { result = gpxExport.testExportSync(exportList); } finally { - cgData.removeCache(cache.getGeocode(), LoadFlags.REMOVE_ALL); + DataStore.removeCache(cache.getGeocode(), LoadFlags.REMOVE_ALL); } assertNotNull(result); diff --git a/tests/src/cgeo/geocaching/export/GpxSerializerTest.java b/tests/src/cgeo/geocaching/export/GpxSerializerTest.java index 0080b76..5c83b35 100644 --- a/tests/src/cgeo/geocaching/export/GpxSerializerTest.java +++ b/tests/src/cgeo/geocaching/export/GpxSerializerTest.java @@ -1,12 +1,19 @@ package cgeo.geocaching.export; import cgeo.geocaching.Geocache; +import cgeo.geocaching.files.GPX10Parser; import cgeo.geocaching.files.ParserException; +import cgeo.geocaching.list.StoredList; import cgeo.geocaching.test.AbstractResourceInstrumentationTestCase; import cgeo.geocaching.test.R; +import org.apache.commons.lang3.CharEncoding; + +import java.io.ByteArrayInputStream; import java.io.IOException; +import java.io.InputStream; import java.io.StringWriter; +import java.util.Collection; import java.util.Collections; import java.util.concurrent.atomic.AtomicReference; @@ -34,4 +41,42 @@ public class GpxSerializerTest extends AbstractResourceInstrumentationTestCase { }); assertEquals("Progress listener not called", 1, importedCount.get().intValue()); } + + /** + * This test verifies that a loop of import, export, import leads to the same cache information. + * + * @throws IOException + * @throws ParserException + */ + public void testStableExportImportExport() throws IOException, ParserException { + final String geocode = "GC1BKP3"; + final int cacheResource = R.raw.gc1bkp3_gpx101; + final Geocache cache = loadCacheFromResource(cacheResource); + assertNotNull(cache); + + final String gpxFirst = getGPXFromCache(geocode); + + assertTrue(gpxFirst.length() > 0); + + final GPX10Parser parser = new GPX10Parser(StoredList.TEMPORARY_LIST_ID); + + final InputStream stream = new ByteArrayInputStream(gpxFirst.getBytes(CharEncoding.UTF_8)); + Collection<Geocache> caches = parser.parse(stream, null); + assertNotNull(caches); + assertEquals(1, caches.size()); + + final String gpxSecond = getGPXFromCache(geocode); + assertEquals(replaceLogIds(gpxFirst), replaceLogIds(gpxSecond)); + } + + private static String replaceLogIds(String gpx) { + return gpx.replaceAll("log id=\"\\d*\"", ""); + } + + private static String getGPXFromCache(String geocode) throws IOException { + final StringWriter writer = new StringWriter(); + new GpxSerializer().writeGPX(Collections.singletonList(geocode), writer, null); + return writer.toString(); + } + } diff --git a/tests/src/cgeo/geocaching/files/GPXImporterTest.java b/tests/src/cgeo/geocaching/files/GPXImporterTest.java index 03f917c..8f5d821 100644 --- a/tests/src/cgeo/geocaching/files/GPXImporterTest.java +++ b/tests/src/cgeo/geocaching/files/GPXImporterTest.java @@ -1,8 +1,8 @@ package cgeo.geocaching.files; +import cgeo.geocaching.DataStore; import cgeo.geocaching.Geocache; import cgeo.geocaching.SearchResult; -import cgeo.geocaching.cgData; import cgeo.geocaching.enumerations.CacheType; import cgeo.geocaching.enumerations.LoadFlags; import cgeo.geocaching.settings.Settings; @@ -74,7 +74,7 @@ public class GPXImporterTest extends AbstractResourceInstrumentationTestCase { assertEquals(GPXImporter.IMPORT_STEP_FINISHED, iMsg.next().what); final SearchResult search = (SearchResult) importStepHandler.messages.get(3).obj; assertEquals(Collections.singletonList(geocode), new ArrayList<String>(search.getGeocodes())); - final Geocache cache = cgData.loadCache(geocode, LoadFlags.LOAD_CACHE_OR_DB); + final Geocache cache = DataStore.loadCache(geocode, LoadFlags.LOAD_CACHE_OR_DB); assertCacheProperties(cache); assertTrue(cache.getWaypoints().isEmpty()); @@ -101,7 +101,7 @@ public class GPXImporterTest extends AbstractResourceInstrumentationTestCase { assertImportStepMessages(GPXImporter.IMPORT_STEP_START, GPXImporter.IMPORT_STEP_READ_FILE, GPXImporter.IMPORT_STEP_READ_WPT_FILE, GPXImporter.IMPORT_STEP_STORE_STATIC_MAPS, GPXImporter.IMPORT_STEP_FINISHED); final SearchResult search = (SearchResult) importStepHandler.messages.get(4).obj; assertEquals(Collections.singletonList("GC31J2H"), new ArrayList<String>(search.getGeocodes())); - final Geocache cache = cgData.loadCache("GC31J2H", LoadFlags.LOAD_CACHE_OR_DB); + final Geocache cache = DataStore.loadCache("GC31J2H", LoadFlags.LOAD_CACHE_OR_DB); assertCacheProperties(cache); assertEquals(2, cache.getWaypoints().size()); } @@ -114,7 +114,7 @@ public class GPXImporterTest extends AbstractResourceInstrumentationTestCase { runImportThread(importThread); assertImportStepMessages(GPXImporter.IMPORT_STEP_START, GPXImporter.IMPORT_STEP_READ_FILE, GPXImporter.IMPORT_STEP_STORE_STATIC_MAPS, GPXImporter.IMPORT_STEP_FINISHED); - final Geocache cache = cgData.loadCache("AID1", LoadFlags.LOAD_CACHE_OR_DB); + final Geocache cache = DataStore.loadCache("AID1", LoadFlags.LOAD_CACHE_OR_DB); assertCacheProperties(cache); assertEquals("First Aid Station #1", cache.getName()); } @@ -136,7 +136,7 @@ public class GPXImporterTest extends AbstractResourceInstrumentationTestCase { assertImportStepMessages(GPXImporter.IMPORT_STEP_START, GPXImporter.IMPORT_STEP_READ_FILE, GPXImporter.IMPORT_STEP_STORE_STATIC_MAPS, GPXImporter.IMPORT_STEP_FINISHED); final SearchResult search = (SearchResult) importStepHandler.messages.get(3).obj; assertEquals(Collections.singletonList("OC5952"), new ArrayList<String>(search.getGeocodes())); - final Geocache cache = cgData.loadCache("OC5952", LoadFlags.LOAD_CACHE_OR_DB); + final Geocache cache = DataStore.loadCache("OC5952", LoadFlags.LOAD_CACHE_OR_DB); assertCacheProperties(cache); } @@ -178,7 +178,7 @@ public class GPXImporterTest extends AbstractResourceInstrumentationTestCase { assertImportStepMessages(GPXImporter.IMPORT_STEP_START, GPXImporter.IMPORT_STEP_READ_FILE, GPXImporter.IMPORT_STEP_STORE_STATIC_MAPS, GPXImporter.IMPORT_STEP_FINISHED); final SearchResult search = (SearchResult) importStepHandler.messages.get(3).obj; assertEquals(Collections.singletonList(geocode), new ArrayList<String>(search.getGeocodes())); - final Geocache cache = cgData.loadCache(geocode, LoadFlags.LOAD_CACHE_OR_DB); + final Geocache cache = DataStore.loadCache(geocode, LoadFlags.LOAD_CACHE_OR_DB); assertCacheProperties(cache); assertTrue(cache.getWaypoints().isEmpty()); @@ -196,7 +196,7 @@ public class GPXImporterTest extends AbstractResourceInstrumentationTestCase { assertImportStepMessages(GPXImporter.IMPORT_STEP_START, GPXImporter.IMPORT_STEP_READ_FILE, GPXImporter.IMPORT_STEP_READ_WPT_FILE, GPXImporter.IMPORT_STEP_STORE_STATIC_MAPS, GPXImporter.IMPORT_STEP_FINISHED); final SearchResult search = (SearchResult) importStepHandler.messages.get(4).obj; assertEquals(Collections.singletonList(geocode), new ArrayList<String>(search.getGeocodes())); - final Geocache cache = cgData.loadCache(geocode, LoadFlags.LOAD_CACHE_OR_DB); + final Geocache cache = DataStore.loadCache(geocode, LoadFlags.LOAD_CACHE_OR_DB); assertCacheProperties(cache); assertEquals(1, cache.getWaypoints().size()); // this is the original pocket query result without test waypoint } @@ -222,7 +222,7 @@ public class GPXImporterTest extends AbstractResourceInstrumentationTestCase { assertImportStepMessages(GPXImporter.IMPORT_STEP_START, GPXImporter.IMPORT_STEP_READ_FILE, GPXImporter.IMPORT_STEP_READ_WPT_FILE, GPXImporter.IMPORT_STEP_STORE_STATIC_MAPS, GPXImporter.IMPORT_STEP_FINISHED); final SearchResult search = (SearchResult) importStepHandler.messages.get(4).obj; assertEquals(Collections.singletonList(geocode), new ArrayList<String>(search.getGeocodes())); - final Geocache cache = cgData.loadCache(geocode, LoadFlags.LOAD_CACHE_OR_DB); + final Geocache cache = DataStore.loadCache(geocode, LoadFlags.LOAD_CACHE_OR_DB); assertCacheProperties(cache); assertEquals(1, cache.getWaypoints().size()); // this is the original pocket query result without test waypoint } @@ -267,8 +267,8 @@ public class GPXImporterTest extends AbstractResourceInstrumentationTestCase { tempDir.mkdir(); assertTrue("Could not create directory " + tempDir.getPath(), tempDir.exists()); // workaround to get storage initialized - cgData.getAllHistoryCachesCount(); - listId = cgData.createList("cgeogpxesTest"); + DataStore.getAllHistoryCachesCount(); + listId = DataStore.createList("cgeogpxesTest"); importCacheStaticMaps = Settings.isStoreOfflineMaps(); TestSettings.setStoreOfflineMaps(true); @@ -278,11 +278,11 @@ public class GPXImporterTest extends AbstractResourceInstrumentationTestCase { @Override protected void tearDown() throws Exception { - final SearchResult search = cgData.getBatchOfStoredCaches(null, CacheType.ALL, listId); + final SearchResult search = DataStore.getBatchOfStoredCaches(null, CacheType.ALL, listId); final List<Geocache> cachesInList = new ArrayList<Geocache>(); cachesInList.addAll(search.getCachesFromSearchResult(LoadFlags.LOAD_CACHE_OR_DB)); - cgData.markDropped(cachesInList); - cgData.removeList(listId); + DataStore.markDropped(cachesInList); + DataStore.removeList(listId); deleteDirectory(tempDir); TestSettings.setStoreOfflineMaps(importCacheStaticMaps); TestSettings.setStoreOfflineWpMaps(importWpStaticMaps); diff --git a/tests/src/cgeo/geocaching/files/GPXParserTest.java b/tests/src/cgeo/geocaching/files/GPXParserTest.java index 892b2a0..9604519 100644 --- a/tests/src/cgeo/geocaching/files/GPXParserTest.java +++ b/tests/src/cgeo/geocaching/files/GPXParserTest.java @@ -1,9 +1,9 @@ package cgeo.geocaching.files; +import cgeo.geocaching.DataStore; import cgeo.geocaching.Geocache; import cgeo.geocaching.LogEntry; import cgeo.geocaching.Waypoint; -import cgeo.geocaching.cgData; import cgeo.geocaching.enumerations.CacheSize; import cgeo.geocaching.enumerations.CacheType; import cgeo.geocaching.enumerations.LoadFlags; @@ -150,6 +150,9 @@ public class GPXParserTest extends AbstractResourceInstrumentationTestCase { assertEquals(parseTime("2011-09-11T07:00:00Z"), log.date); assertEquals(-1, log.found); assertEquals("Sehr schöne Runde und wir haben wieder etwas Neues über Hockenheim gelernt. Super Tarnung.\nTFTC, Geoteufel", log.log); + assertFalse(log.isOwn()); + assertEquals(log.log, log.getDisplayText()); + assertTrue(log.daysSinceLog() > 700); // following info is not contained in pocket query gpx file assertEquals(0, cache.getAttributes().size()); @@ -212,7 +215,7 @@ public class GPXParserTest extends AbstractResourceInstrumentationTestCase { } } // reload caches, because the parser only returns the minimum version of each cache - return new ArrayList<Geocache>(cgData.loadCaches(result, LoadFlags.LOAD_ALL_DB_ONLY)); + return new ArrayList<Geocache>(DataStore.loadCaches(result, LoadFlags.LOAD_ALL_DB_ONLY)); } public static void testParseDateWithFractionalSeconds() throws ParseException { @@ -255,9 +258,9 @@ public class GPXParserTest extends AbstractResourceInstrumentationTestCase { removeCacheCompletely(geocode); final List<Geocache> caches = readGPX10(R.raw.lazy); assertEquals(1, caches.size()); - cgData.removeAllFromCache(); + DataStore.removeAllFromCache(); // load only the minimum cache, it has several members missing - final Geocache minimalCache = cgData.loadCache(geocode, EnumSet.of(LoadFlag.LOAD_DB_MINIMAL)); + final Geocache minimalCache = DataStore.loadCache(geocode, EnumSet.of(LoadFlag.LOAD_DB_MINIMAL)); // now check that we load lazy members on demand assertFalse(minimalCache.getAttributes().isEmpty()); diff --git a/tests/src/cgeo/geocaching/list/PseudoListTest.java b/tests/src/cgeo/geocaching/list/PseudoListTest.java new file mode 100644 index 0000000..8a138ef --- /dev/null +++ b/tests/src/cgeo/geocaching/list/PseudoListTest.java @@ -0,0 +1,18 @@ +package cgeo.geocaching.list; + +import junit.framework.TestCase; + +public class PseudoListTest extends TestCase { + + public static void testGetTitleAndCount() throws Exception { + final String title = PseudoList.ALL_LIST.getTitleAndCount(); + for (int i = 0; i < title.length(); i++) { + assertFalse("pseudo lists shall not have a number shown in their title", Character.isDigit(title.charAt(i))); + } + } + + public static void testIsConcrete() throws Exception { + assertFalse("pseudo lists are not concrete lists", PseudoList.ALL_LIST.isConcrete()); + } + +} diff --git a/tests/src/cgeo/geocaching/list/StoredListTest.java b/tests/src/cgeo/geocaching/list/StoredListTest.java new file mode 100644 index 0000000..bc4ebe4 --- /dev/null +++ b/tests/src/cgeo/geocaching/list/StoredListTest.java @@ -0,0 +1,31 @@ +package cgeo.geocaching.list; + +import cgeo.geocaching.DataStore; + +import junit.framework.TestCase; + +public class StoredListTest extends TestCase { + + public static void testStandardListExists() { + final StoredList list = getStandardList(); + assertNotNull(list); + } + + private static StoredList getStandardList() { + return DataStore.getList(StoredList.STANDARD_LIST_ID); + } + + public static void testEquals() { + final StoredList list1 = getStandardList(); + final StoredList list2 = getStandardList(); + assertEquals(list1, list2); + } + + public static void testConcrete() { + assertTrue(getStandardList().isConcrete()); + } + + public static void testTitleAndCountContainsTitle() { + assertTrue(getStandardList().getTitleAndCount().startsWith(getStandardList().getTitle())); + } +} diff --git a/tests/src/cgeo/geocaching/speech/TextFactoryTest.java b/tests/src/cgeo/geocaching/speech/TextFactoryTest.java index 864757b..ec8e1b0 100644 --- a/tests/src/cgeo/geocaching/speech/TextFactoryTest.java +++ b/tests/src/cgeo/geocaching/speech/TextFactoryTest.java @@ -1,6 +1,6 @@ package cgeo.geocaching.speech; -import cgeo.geocaching.cgeoapplication; +import cgeo.geocaching.CgeoApplication; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.settings.Settings; import cgeo.geocaching.settings.TestSettings; @@ -29,7 +29,7 @@ public class TextFactoryTest extends AndroidTestCase { @Override protected void setUp() throws Exception { super.setUp(); - final Resources resources = cgeoapplication.getInstance().getResources(); + final Resources resources = CgeoApplication.getInstance().getResources(); final Configuration config = resources.getConfiguration(); defaultLocale1 = config.locale; defaultLocale2 = Locale.getDefault(); @@ -149,7 +149,7 @@ public class TextFactoryTest extends AndroidTestCase { private static void setLocale(Locale locale1, Locale locale2, boolean metric) { final Configuration config = new Configuration(); config.locale = locale1; - final Resources resources = cgeoapplication.getInstance().getResources(); + final Resources resources = CgeoApplication.getInstance().getResources(); resources.updateConfiguration(config, resources.getDisplayMetrics()); Locale.setDefault(locale2); diff --git a/tests/src/cgeo/geocaching/test/AbstractResourceInstrumentationTestCase.java b/tests/src/cgeo/geocaching/test/AbstractResourceInstrumentationTestCase.java index cb8238f..12e83cc 100644 --- a/tests/src/cgeo/geocaching/test/AbstractResourceInstrumentationTestCase.java +++ b/tests/src/cgeo/geocaching/test/AbstractResourceInstrumentationTestCase.java @@ -1,14 +1,14 @@ package cgeo.geocaching.test; +import cgeo.geocaching.DataStore; import cgeo.geocaching.Geocache; import cgeo.geocaching.SearchResult; -import cgeo.geocaching.StoredList; -import cgeo.geocaching.cgData; import cgeo.geocaching.enumerations.CacheType; import cgeo.geocaching.enumerations.LoadFlags; import cgeo.geocaching.enumerations.LoadFlags.RemoveFlag; import cgeo.geocaching.files.GPX10Parser; import cgeo.geocaching.files.ParserException; +import cgeo.geocaching.list.StoredList; import android.content.res.Resources; import android.test.InstrumentationTestCase; @@ -27,7 +27,7 @@ public abstract class AbstractResourceInstrumentationTestCase extends Instrument protected static void removeCacheCompletely(final String geocode) { final EnumSet<RemoveFlag> flags = EnumSet.copyOf(LoadFlags.REMOVE_ALL); flags.add(RemoveFlag.REMOVE_OWN_WAYPOINTS_ONLY_FOR_TESTING); - cgData.removeCache(geocode, flags); + DataStore.removeCache(geocode, flags); } protected InputStream getResourceStream(int resourceId) { @@ -65,17 +65,17 @@ public abstract class AbstractResourceInstrumentationTestCase extends Instrument @Override protected void setUp() throws Exception { super.setUp(); - temporaryListId = cgData.createList("Temporary unit testing"); + temporaryListId = DataStore.createList("Temporary unit testing"); assertTrue(temporaryListId != StoredList.TEMPORARY_LIST_ID); assertTrue(temporaryListId != StoredList.STANDARD_LIST_ID); } @Override protected void tearDown() throws Exception { - final SearchResult search = cgData.getBatchOfStoredCaches(null, CacheType.ALL, temporaryListId); + final SearchResult search = DataStore.getBatchOfStoredCaches(null, CacheType.ALL, temporaryListId); assertNotNull(search); - cgData.removeCaches(search.getGeocodes(), LoadFlags.REMOVE_ALL); - cgData.removeList(temporaryListId); + DataStore.removeCaches(search.getGeocodes(), LoadFlags.REMOVE_ALL); + DataStore.removeList(temporaryListId); super.tearDown(); } diff --git a/tests/src/cgeo/geocaching/test/BottomAwareScrollView.java b/tests/src/cgeo/geocaching/test/BottomAwareScrollView.java new file mode 100644 index 0000000..5735241 --- /dev/null +++ b/tests/src/cgeo/geocaching/test/BottomAwareScrollView.java @@ -0,0 +1,36 @@ +package cgeo.geocaching.test; + +import android.content.Context; +import android.util.AttributeSet; +import android.view.View; +import android.widget.ScrollView; + +public class BottomAwareScrollView extends ScrollView { + + private boolean isAtBottom = true; + + public BottomAwareScrollView(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + } + + public BottomAwareScrollView(Context context, AttributeSet attrs) { + super(context, attrs); + } + + public BottomAwareScrollView(Context context) { + super(context); + } + + @Override + protected void onScrollChanged(int l, int t, int oldl, int oldt) { + View lastChildView = getChildAt(getChildCount() - 1); + int diff = (lastChildView.getBottom() - (getHeight() + getScrollY())); + isAtBottom = diff <= 0; + super.onScrollChanged(l, t, oldl, oldt); + } + + public boolean isAtBottom() { + return isAtBottom; + } + +} diff --git a/tests/src/cgeo/geocaching/test/CgeoTestsActivity.java b/tests/src/cgeo/geocaching/test/CgeoTestsActivity.java new file mode 100644 index 0000000..0f41cef --- /dev/null +++ b/tests/src/cgeo/geocaching/test/CgeoTestsActivity.java @@ -0,0 +1,147 @@ +package cgeo.geocaching.test; + +import android.app.Activity; +import android.content.ComponentName; +import android.content.pm.InstrumentationInfo; +import android.os.AsyncTask; +import android.os.Bundle; +import android.text.Html; +import android.text.TextUtils; +import android.util.Log; +import android.view.View; +import android.widget.Button; +import android.widget.TextView; +import android.widget.Toast; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.util.List; + +public class CgeoTestsActivity extends Activity { + private static final String TAG = CgeoTestsActivity.class.getName(); + + private static final int TIMEOUT = 600 * 1000; + + private TextView logView; + private LogcatAsyncTask logCatTask; + + private BottomAwareScrollView scrollView; + + private class LogcatAsyncTask extends AsyncTask<Integer, String, Void> { + // TestRunner and silence others + private static final String CMD = "logcat -v brief TestRunner:I cgeo:I *:S"; + private BufferedReader mReader; + private Process mProc; + + public LogcatAsyncTask() { + try { + mProc = Runtime.getRuntime().exec(CMD); + mReader = new BufferedReader(new InputStreamReader( + mProc.getInputStream())); + } catch (Exception e) { + Log.e(TAG, "Creating proc", e); + } + } + + @Override + protected void onProgressUpdate(String... values) { + final String line = values[0]; + final boolean isAtBottom = scrollView.isAtBottom(); + if (!TextUtils.isEmpty(line)) { + logView.append(Html.fromHtml("<font color=\"" + color(line) + "\">" + line + "</font><br/>")); + if (isAtBottom) { + scrollView.scrollTo(0, logView.getBottom()); + } + } + } + + private String color(String line) { + switch (line.charAt(0)) { + case 'E': + return "red"; + case 'W': + return "#FFA500"; + case 'D': + return "blue"; + default: + return "white"; + } + } + + @Override + protected Void doInBackground(Integer... params) { + final long timeout = System.currentTimeMillis() + params[0]; + try { + do { + Thread.sleep(50); + publishProgress(mReader.readLine()); + } while (System.currentTimeMillis() < timeout); + } catch (Exception e) { + publishProgress("ERROR: " + e); + } finally { + publishProgress("END"); + mProc.destroy(); + } + return null; + } + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.cgeo_tests_activity); + logView = (TextView) findViewById(R.id.logOutput); + scrollView = (BottomAwareScrollView) findViewById(R.id.scrollView); + } + + @Override + protected void onDestroy() { + if (logCatTask != null) { + logCatTask.cancel(true); + } + super.onDestroy(); + } + + private InstrumentationInfo getInstrumentationInfo(final String packageName) { + final List<InstrumentationInfo> list = + getPackageManager() + .queryInstrumentation(packageName, 0); + return (!list.isEmpty()) ? list.get(0) : null; + } + + /** + * @param v + * referenced from XML layout + */ + public void runTests(final View v) { + final Button button = (Button) findViewById(R.id.buttonRun); + button.setEnabled(false); + try { + runTestsInternally(); + } finally { + // button.setEnabled(true); + } + } + + private void runTestsInternally() { + final String pn = getPackageName().replaceFirst(".test$", ""); + final InstrumentationInfo info = getInstrumentationInfo(pn); + if (info == null) { + Toast.makeText(this, + "Cannot find instrumentation for " + pn, Toast.LENGTH_SHORT) + .show(); + return; + } + final ComponentName cn = new ComponentName(info.packageName, + info.name); + if (startInstrumentation(cn, null, null)) { + logCatTask = new LogcatAsyncTask(); + logCatTask.execute(TIMEOUT); + } + else { + Toast.makeText(this, + "Cannot run instrumentation for " + pn, Toast.LENGTH_SHORT) + .show(); + } + } +} diff --git a/tests/src/cgeo/geocaching/ui/FormatterTest.java b/tests/src/cgeo/geocaching/ui/FormatterTest.java index e65f425..53aba0f 100644 --- a/tests/src/cgeo/geocaching/ui/FormatterTest.java +++ b/tests/src/cgeo/geocaching/ui/FormatterTest.java @@ -2,7 +2,7 @@ package cgeo.geocaching.ui; import cgeo.geocaching.R; import cgeo.geocaching.Waypoint; -import cgeo.geocaching.cgeoapplication; +import cgeo.geocaching.CgeoApplication; import cgeo.geocaching.enumerations.WaypointType; import android.test.AndroidTestCase; @@ -20,7 +20,7 @@ public class FormatterTest extends AndroidTestCase { public static void testOwnWaypoint() { final Waypoint own = new Waypoint("my own", WaypointType.OWN, true); own.setPrefix(Waypoint.PREFIX_OWN); - assertFormatting(own, cgeoapplication.getInstance().getString(R.string.waypoint_custom)); + assertFormatting(own, CgeoApplication.getInstance().getString(R.string.waypoint_custom)); } private static void assertFormatting(Waypoint waypoint, String expected) { diff --git a/tests/src/cgeo/geocaching/utils/CryptUtilsTest.java b/tests/src/cgeo/geocaching/utils/CryptUtilsTest.java index e727747..9264d29 100644 --- a/tests/src/cgeo/geocaching/utils/CryptUtilsTest.java +++ b/tests/src/cgeo/geocaching/utils/CryptUtilsTest.java @@ -23,4 +23,16 @@ public class CryptUtilsTest extends TestCase { public static void testIssue1902() { assertEquals("ƖƖlƖƖƖƖ", CryptUtils.rot13("ƖƖyƖƖƖƖ")); } + + public static void testSha1() { + assertEquals("da39a3ee5e6b4b0d3255bfef95601890afd80709", CryptUtils.sha1("")); + // expected value taken from debugger. should assure every developer uses UTF-8 + assertEquals("cf2f343f59cea81afc0a5a566cb138ba349c548f", CryptUtils.sha1("äöü")); + } + + public static void testMd5() { + assertEquals("d41d8cd98f00b204e9800998ecf8427e", CryptUtils.md5("")); + // expected value taken from debugger. should assure every developer uses UTF-8 + assertEquals("a7f4e3ec08f09be2ef7ecb4eea5f8981", CryptUtils.md5("äöü")); + } } diff --git a/tests/src/cgeo/geocaching/utils/UncertainPropertyTest.java b/tests/src/cgeo/geocaching/utils/UncertainPropertyTest.java new file mode 100644 index 0000000..74aa680 --- /dev/null +++ b/tests/src/cgeo/geocaching/utils/UncertainPropertyTest.java @@ -0,0 +1,19 @@ +package cgeo.geocaching.utils; + +import junit.framework.TestCase; + +public class UncertainPropertyTest extends TestCase { + + public static void testHigherCertaintyWins() throws Exception { + final UncertainProperty<String> prop1 = new UncertainProperty<String>("prop1", 10); + final UncertainProperty<String> prop2 = new UncertainProperty<String>("prop2", 20); + assertEquals(prop2, UncertainProperty.getMergedProperty(prop1, prop2)); + } + + public static void testAvoidNull() throws Exception { + final UncertainProperty<String> prop1 = new UncertainProperty<String>("prop1", 10); + final UncertainProperty<String> prop2 = new UncertainProperty<String>(null, 20); + assertEquals(prop1, UncertainProperty.getMergedProperty(prop1, prop2)); + assertEquals(prop1, UncertainProperty.getMergedProperty(prop2, prop1)); + } +} diff --git a/tests/src/cgeo/geocaching/utils/XmlUtilsTest.java b/tests/src/cgeo/geocaching/utils/XmlUtilsTest.java new file mode 100644 index 0000000..a089ee0 --- /dev/null +++ b/tests/src/cgeo/geocaching/utils/XmlUtilsTest.java @@ -0,0 +1,48 @@ +package cgeo.geocaching.utils; + +import cgeo.org.kxml2.io.KXmlSerializer; + +import org.apache.commons.lang3.CharEncoding; +import org.xmlpull.v1.XmlSerializer; + +import java.io.IOException; +import java.io.StringWriter; + +import junit.framework.TestCase; + +public class XmlUtilsTest extends TestCase { + + private XmlSerializer xml; + private StringWriter stringWriter; + + @Override + protected void setUp() throws Exception { + super.setUp(); + stringWriter = new StringWriter(); + xml = new KXmlSerializer(); + xml.setOutput(stringWriter); + xml.startDocument(CharEncoding.UTF_8, null); + } + + public void testSimpleText() throws Exception { + XmlUtils.simpleText(xml, "", "tag", "text"); + assertXmlEquals("<tag>text</tag>"); + } + + public void testSimpleTextWithPrefix() throws Exception { + XmlUtils.simpleText(xml, "prefix", "tag", "text"); + assertXmlEquals("<n0:tag xmlns:n0=\"prefix\">text</n0:tag>"); + } + + private void assertXmlEquals(final String expected) throws IOException { + xml.endDocument(); + xml.flush(); + assertEquals("<?xml version='1.0' encoding='UTF-8' ?>" + expected, stringWriter.toString()); + } + + public void testMultipleTexts() throws Exception { + XmlUtils.multipleTexts(xml, "", "tag1", "text1", "tag2", "text2"); + assertXmlEquals("<tag1>text1</tag1><tag2>text2</tag2>"); + } + +} |
