From 4a6d2753b5d27a3c06daa1b3e669cacf3ddd59d4 Mon Sep 17 00:00:00 2001 From: Bananeweizen Date: Mon, 16 Dec 2013 17:38:58 +0100 Subject: cleanup: fix all findbugs on test and calendar --- .../.settings/edu.umd.cs.findbugs.core.prefs | 133 +++++++ cgeo-calendar/src/cgeo/calendar/CalendarEntry.java | 2 +- main/.settings/edu.umd.cs.findbugs.core.prefs | 2 +- main/project/findbugs/exclusions.xml | 12 +- tests/.settings/edu.umd.cs.findbugs.core.prefs | 133 +++++++ tests/src/cgeo/geocaching/CgeoApplicationTest.java | 427 +++++++++++++++++++++ tests/src/cgeo/geocaching/HtmlPerformanceTest.java | 3 + tests/src/cgeo/geocaching/PersonalNoteTest.java | 4 +- tests/src/cgeo/geocaching/cgeoApplicationTest.java | 426 -------------------- tests/src/cgeo/geocaching/export/ExportTest.java | 3 +- .../src/cgeo/geocaching/files/GPXImporterTest.java | 23 +- tests/src/cgeo/geocaching/files/GPXParserTest.java | 4 +- .../cgeo/geocaching/test/CgeoTestsActivity.java | 13 +- tests/src/cgeo/geocaching/test/mock/GC3XX5J.java | 6 - 14 files changed, 730 insertions(+), 461 deletions(-) create mode 100644 cgeo-calendar/.settings/edu.umd.cs.findbugs.core.prefs create mode 100644 tests/.settings/edu.umd.cs.findbugs.core.prefs create mode 100644 tests/src/cgeo/geocaching/CgeoApplicationTest.java delete mode 100644 tests/src/cgeo/geocaching/cgeoApplicationTest.java diff --git a/cgeo-calendar/.settings/edu.umd.cs.findbugs.core.prefs b/cgeo-calendar/.settings/edu.umd.cs.findbugs.core.prefs new file mode 100644 index 0000000..a16868e --- /dev/null +++ b/cgeo-calendar/.settings/edu.umd.cs.findbugs.core.prefs @@ -0,0 +1,133 @@ +#FindBugs User Preferences +#Sun Dec 08 19:08:28 CET 2013 +cloud_id=edu.umd.cs.findbugs.cloud.doNothingCloud +detectorAppendingToAnObjectOutputStream=AppendingToAnObjectOutputStream|true +detectorAtomicityProblem=AtomicityProblem|true +detectorBadAppletConstructor=BadAppletConstructor|false +detectorBadResultSetAccess=BadResultSetAccess|true +detectorBadSyntaxForRegularExpression=BadSyntaxForRegularExpression|true +detectorBadUseOfReturnValue=BadUseOfReturnValue|true +detectorBadlyOverriddenAdapter=BadlyOverriddenAdapter|true +detectorBooleanReturnNull=BooleanReturnNull|true +detectorCallToUnsupportedMethod=CallToUnsupportedMethod|false +detectorCheckExpectedWarnings=CheckExpectedWarnings|false +detectorCheckImmutableAnnotation=CheckImmutableAnnotation|true +detectorCheckTypeQualifiers=CheckTypeQualifiers|true +detectorCloneIdiom=CloneIdiom|true +detectorComparatorIdiom=ComparatorIdiom|true +detectorConfusedInheritance=ConfusedInheritance|true +detectorConfusionBetweenInheritedAndOuterMethod=ConfusionBetweenInheritedAndOuterMethod|true +detectorCrossSiteScripting=CrossSiteScripting|true +detectorDefaultEncodingDetector=DefaultEncodingDetector|true +detectorDoInsideDoPrivileged=DoInsideDoPrivileged|true +detectorDontCatchIllegalMonitorStateException=DontCatchIllegalMonitorStateException|true +detectorDontIgnoreResultOfPutIfAbsent=DontIgnoreResultOfPutIfAbsent|true +detectorDontUseEnum=DontUseEnum|true +detectorDroppedException=DroppedException|true +detectorDumbMethodInvocations=DumbMethodInvocations|true +detectorDumbMethods=DumbMethods|true +detectorDuplicateBranches=DuplicateBranches|true +detectorEmptyZipFileEntry=EmptyZipFileEntry|true +detectorEqualsOperandShouldHaveClassCompatibleWithThis=EqualsOperandShouldHaveClassCompatibleWithThis|true +detectorExplicitSerialization=ExplicitSerialization|true +detectorFinalizerNullsFields=FinalizerNullsFields|true +detectorFindBadCast2=FindBadCast2|true +detectorFindBadForLoop=FindBadForLoop|true +detectorFindCircularDependencies=FindCircularDependencies|false +detectorFindDeadLocalStores=FindDeadLocalStores|true +detectorFindDoubleCheck=FindDoubleCheck|true +detectorFindEmptySynchronizedBlock=FindEmptySynchronizedBlock|true +detectorFindFieldSelfAssignment=FindFieldSelfAssignment|true +detectorFindFinalizeInvocations=FindFinalizeInvocations|true +detectorFindFloatEquality=FindFloatEquality|true +detectorFindHEmismatch=FindHEmismatch|true +detectorFindInconsistentSync2=FindInconsistentSync2|true +detectorFindJSR166LockMonitorenter=FindJSR166LockMonitorenter|true +detectorFindLocalSelfAssignment2=FindLocalSelfAssignment2|true +detectorFindMaskedFields=FindMaskedFields|true +detectorFindMismatchedWaitOrNotify=FindMismatchedWaitOrNotify|true +detectorFindNakedNotify=FindNakedNotify|true +detectorFindNonShortCircuit=FindNonShortCircuit|true +detectorFindNullDeref=FindNullDeref|true +detectorFindNullDerefsInvolvingNonShortCircuitEvaluation=FindNullDerefsInvolvingNonShortCircuitEvaluation|true +detectorFindOpenStream=FindOpenStream|true +detectorFindPuzzlers=FindPuzzlers|true +detectorFindRefComparison=FindRefComparison|true +detectorFindReturnRef=FindReturnRef|true +detectorFindRunInvocations=FindRunInvocations|true +detectorFindSelfComparison=FindSelfComparison|true +detectorFindSelfComparison2=FindSelfComparison2|true +detectorFindSleepWithLockHeld=FindSleepWithLockHeld|true +detectorFindSpinLoop=FindSpinLoop|true +detectorFindSqlInjection=FindSqlInjection|true +detectorFindTwoLockWait=FindTwoLockWait|true +detectorFindUncalledPrivateMethods=FindUncalledPrivateMethods|true +detectorFindUnconditionalWait=FindUnconditionalWait|true +detectorFindUninitializedGet=FindUninitializedGet|true +detectorFindUnrelatedTypesInGenericContainer=FindUnrelatedTypesInGenericContainer|true +detectorFindUnreleasedLock=FindUnreleasedLock|true +detectorFindUnsatisfiedObligation=FindUnsatisfiedObligation|true +detectorFindUnsyncGet=FindUnsyncGet|true +detectorFindUseOfNonSerializableValue=FindUseOfNonSerializableValue|true +detectorFindUselessControlFlow=FindUselessControlFlow|true +detectorFormatStringChecker=FormatStringChecker|true +detectorHugeSharedStringConstants=HugeSharedStringConstants|true +detectorIDivResultCastToDouble=IDivResultCastToDouble|true +detectorIncompatMask=IncompatMask|true +detectorInconsistentAnnotations=InconsistentAnnotations|true +detectorInefficientMemberAccess=InefficientMemberAccess|false +detectorInefficientToArray=InefficientToArray|true +detectorInfiniteLoop=InfiniteLoop|true +detectorInfiniteRecursiveLoop=InfiniteRecursiveLoop|true +detectorInheritanceUnsafeGetResource=InheritanceUnsafeGetResource|true +detectorInitializationChain=InitializationChain|true +detectorInitializeNonnullFieldsInConstructor=InitializeNonnullFieldsInConstructor|true +detectorInstantiateStaticClass=InstantiateStaticClass|true +detectorIntCast2LongAsInstant=IntCast2LongAsInstant|true +detectorInvalidJUnitTest=InvalidJUnitTest|true +detectorIteratorIdioms=IteratorIdioms|true +detectorLazyInit=LazyInit|true +detectorLoadOfKnownNullValue=LoadOfKnownNullValue|true +detectorLostLoggerDueToWeakReference=LostLoggerDueToWeakReference|true +detectorMethodReturnCheck=MethodReturnCheck|true +detectorMultithreadedInstanceAccess=MultithreadedInstanceAccess|true +detectorMutableLock=MutableLock|true +detectorMutableStaticFields=MutableStaticFields|true +detectorNaming=Naming|true +detectorNoteUnconditionalParamDerefs=NoteUnconditionalParamDerefs|true +detectorNumberConstructor=NumberConstructor|true +detectorOverridingEqualsNotSymmetrical=OverridingEqualsNotSymmetrical|true +detectorPreferZeroLengthArrays=PreferZeroLengthArrays|true +detectorPublicSemaphores=PublicSemaphores|false +detectorQuestionableBooleanAssignment=QuestionableBooleanAssignment|true +detectorReadOfInstanceFieldInMethodInvokedByConstructorInSuperclass=ReadOfInstanceFieldInMethodInvokedByConstructorInSuperclass|true +detectorReadReturnShouldBeChecked=ReadReturnShouldBeChecked|true +detectorRedundantInterfaces=RedundantInterfaces|true +detectorRepeatedConditionals=RepeatedConditionals|true +detectorRuntimeExceptionCapture=RuntimeExceptionCapture|true +detectorSerializableIdiom=SerializableIdiom|true +detectorStartInConstructor=StartInConstructor|true +detectorStaticCalendarDetector=StaticCalendarDetector|true +detectorStringConcatenation=StringConcatenation|true +detectorSuperfluousInstanceOf=SuperfluousInstanceOf|true +detectorSuspiciousThreadInterrupted=SuspiciousThreadInterrupted|true +detectorSwitchFallthrough=SwitchFallthrough|true +detectorSynchronizeAndNullCheckField=SynchronizeAndNullCheckField|true +detectorSynchronizeOnClassLiteralNotGetClass=SynchronizeOnClassLiteralNotGetClass|true +detectorSynchronizingOnContentsOfFieldToProtectField=SynchronizingOnContentsOfFieldToProtectField|true +detectorURLProblems=URLProblems|true +detectorUncallableMethodOfAnonymousClass=UncallableMethodOfAnonymousClass|true +detectorUnnecessaryMath=UnnecessaryMath|true +detectorUnreadFields=UnreadFields|true +detectorUselessSubclassMethod=UselessSubclassMethod|true +detectorVarArgsProblems=VarArgsProblems|true +detectorVolatileUsage=VolatileUsage|true +detectorWaitInLoop=WaitInLoop|true +detectorWrongMapIterator=WrongMapIterator|true +detectorXMLFactoryBypass=XMLFactoryBypass|true +detector_threshold=3 +effort=max +excludefilter0=../main/project/findbugs/exclusions.xml|true +filter_settings=Low|BAD_PRACTICE,CORRECTNESS,EXPERIMENTAL,MALICIOUS_CODE,MT_CORRECTNESS,PERFORMANCE,SECURITY,STYLE|false|20 +filter_settings_neg=NOISE,I18N| +run_at_full_build=true diff --git a/cgeo-calendar/src/cgeo/calendar/CalendarEntry.java b/cgeo-calendar/src/cgeo/calendar/CalendarEntry.java index 6c7624d..ff36aa4 100644 --- a/cgeo-calendar/src/cgeo/calendar/CalendarEntry.java +++ b/cgeo-calendar/src/cgeo/calendar/CalendarEntry.java @@ -35,7 +35,7 @@ class CalendarEntry { final String startTime = getParameter(ICalendar.PARAM_START_TIME_MINUTES); if (startTime.length() > 0) { try { - this.startTimeMinutes = Integer.valueOf(startTime); + this.startTimeMinutes = Integer.parseInt(startTime); } catch (NumberFormatException e) { Log.e("CalendarEntry creation", e); } diff --git a/main/.settings/edu.umd.cs.findbugs.core.prefs b/main/.settings/edu.umd.cs.findbugs.core.prefs index c371a1d..36ab342 100644 --- a/main/.settings/edu.umd.cs.findbugs.core.prefs +++ b/main/.settings/edu.umd.cs.findbugs.core.prefs @@ -130,4 +130,4 @@ effort=max excludefilter0=project/findbugs/exclusions.xml|true filter_settings=Low|BAD_PRACTICE,CORRECTNESS,EXPERIMENTAL,MALICIOUS_CODE,MT_CORRECTNESS,PERFORMANCE,SECURITY,STYLE|false|20 filter_settings_neg=NOISE,I18N| -run_at_full_build=false +run_at_full_build=true diff --git a/main/project/findbugs/exclusions.xml b/main/project/findbugs/exclusions.xml index c3e6299..798ecb4 100644 --- a/main/project/findbugs/exclusions.xml +++ b/main/project/findbugs/exclusions.xml @@ -25,6 +25,8 @@ + + @@ -32,9 +34,17 @@ + + - + + + + + + + \ No newline at end of file diff --git a/tests/.settings/edu.umd.cs.findbugs.core.prefs b/tests/.settings/edu.umd.cs.findbugs.core.prefs new file mode 100644 index 0000000..a16868e --- /dev/null +++ b/tests/.settings/edu.umd.cs.findbugs.core.prefs @@ -0,0 +1,133 @@ +#FindBugs User Preferences +#Sun Dec 08 19:08:28 CET 2013 +cloud_id=edu.umd.cs.findbugs.cloud.doNothingCloud +detectorAppendingToAnObjectOutputStream=AppendingToAnObjectOutputStream|true +detectorAtomicityProblem=AtomicityProblem|true +detectorBadAppletConstructor=BadAppletConstructor|false +detectorBadResultSetAccess=BadResultSetAccess|true +detectorBadSyntaxForRegularExpression=BadSyntaxForRegularExpression|true +detectorBadUseOfReturnValue=BadUseOfReturnValue|true +detectorBadlyOverriddenAdapter=BadlyOverriddenAdapter|true +detectorBooleanReturnNull=BooleanReturnNull|true +detectorCallToUnsupportedMethod=CallToUnsupportedMethod|false +detectorCheckExpectedWarnings=CheckExpectedWarnings|false +detectorCheckImmutableAnnotation=CheckImmutableAnnotation|true +detectorCheckTypeQualifiers=CheckTypeQualifiers|true +detectorCloneIdiom=CloneIdiom|true +detectorComparatorIdiom=ComparatorIdiom|true +detectorConfusedInheritance=ConfusedInheritance|true +detectorConfusionBetweenInheritedAndOuterMethod=ConfusionBetweenInheritedAndOuterMethod|true +detectorCrossSiteScripting=CrossSiteScripting|true +detectorDefaultEncodingDetector=DefaultEncodingDetector|true +detectorDoInsideDoPrivileged=DoInsideDoPrivileged|true +detectorDontCatchIllegalMonitorStateException=DontCatchIllegalMonitorStateException|true +detectorDontIgnoreResultOfPutIfAbsent=DontIgnoreResultOfPutIfAbsent|true +detectorDontUseEnum=DontUseEnum|true +detectorDroppedException=DroppedException|true +detectorDumbMethodInvocations=DumbMethodInvocations|true +detectorDumbMethods=DumbMethods|true +detectorDuplicateBranches=DuplicateBranches|true +detectorEmptyZipFileEntry=EmptyZipFileEntry|true +detectorEqualsOperandShouldHaveClassCompatibleWithThis=EqualsOperandShouldHaveClassCompatibleWithThis|true +detectorExplicitSerialization=ExplicitSerialization|true +detectorFinalizerNullsFields=FinalizerNullsFields|true +detectorFindBadCast2=FindBadCast2|true +detectorFindBadForLoop=FindBadForLoop|true +detectorFindCircularDependencies=FindCircularDependencies|false +detectorFindDeadLocalStores=FindDeadLocalStores|true +detectorFindDoubleCheck=FindDoubleCheck|true +detectorFindEmptySynchronizedBlock=FindEmptySynchronizedBlock|true +detectorFindFieldSelfAssignment=FindFieldSelfAssignment|true +detectorFindFinalizeInvocations=FindFinalizeInvocations|true +detectorFindFloatEquality=FindFloatEquality|true +detectorFindHEmismatch=FindHEmismatch|true +detectorFindInconsistentSync2=FindInconsistentSync2|true +detectorFindJSR166LockMonitorenter=FindJSR166LockMonitorenter|true +detectorFindLocalSelfAssignment2=FindLocalSelfAssignment2|true +detectorFindMaskedFields=FindMaskedFields|true +detectorFindMismatchedWaitOrNotify=FindMismatchedWaitOrNotify|true +detectorFindNakedNotify=FindNakedNotify|true +detectorFindNonShortCircuit=FindNonShortCircuit|true +detectorFindNullDeref=FindNullDeref|true +detectorFindNullDerefsInvolvingNonShortCircuitEvaluation=FindNullDerefsInvolvingNonShortCircuitEvaluation|true +detectorFindOpenStream=FindOpenStream|true +detectorFindPuzzlers=FindPuzzlers|true +detectorFindRefComparison=FindRefComparison|true +detectorFindReturnRef=FindReturnRef|true +detectorFindRunInvocations=FindRunInvocations|true +detectorFindSelfComparison=FindSelfComparison|true +detectorFindSelfComparison2=FindSelfComparison2|true +detectorFindSleepWithLockHeld=FindSleepWithLockHeld|true +detectorFindSpinLoop=FindSpinLoop|true +detectorFindSqlInjection=FindSqlInjection|true +detectorFindTwoLockWait=FindTwoLockWait|true +detectorFindUncalledPrivateMethods=FindUncalledPrivateMethods|true +detectorFindUnconditionalWait=FindUnconditionalWait|true +detectorFindUninitializedGet=FindUninitializedGet|true +detectorFindUnrelatedTypesInGenericContainer=FindUnrelatedTypesInGenericContainer|true +detectorFindUnreleasedLock=FindUnreleasedLock|true +detectorFindUnsatisfiedObligation=FindUnsatisfiedObligation|true +detectorFindUnsyncGet=FindUnsyncGet|true +detectorFindUseOfNonSerializableValue=FindUseOfNonSerializableValue|true +detectorFindUselessControlFlow=FindUselessControlFlow|true +detectorFormatStringChecker=FormatStringChecker|true +detectorHugeSharedStringConstants=HugeSharedStringConstants|true +detectorIDivResultCastToDouble=IDivResultCastToDouble|true +detectorIncompatMask=IncompatMask|true +detectorInconsistentAnnotations=InconsistentAnnotations|true +detectorInefficientMemberAccess=InefficientMemberAccess|false +detectorInefficientToArray=InefficientToArray|true +detectorInfiniteLoop=InfiniteLoop|true +detectorInfiniteRecursiveLoop=InfiniteRecursiveLoop|true +detectorInheritanceUnsafeGetResource=InheritanceUnsafeGetResource|true +detectorInitializationChain=InitializationChain|true +detectorInitializeNonnullFieldsInConstructor=InitializeNonnullFieldsInConstructor|true +detectorInstantiateStaticClass=InstantiateStaticClass|true +detectorIntCast2LongAsInstant=IntCast2LongAsInstant|true +detectorInvalidJUnitTest=InvalidJUnitTest|true +detectorIteratorIdioms=IteratorIdioms|true +detectorLazyInit=LazyInit|true +detectorLoadOfKnownNullValue=LoadOfKnownNullValue|true +detectorLostLoggerDueToWeakReference=LostLoggerDueToWeakReference|true +detectorMethodReturnCheck=MethodReturnCheck|true +detectorMultithreadedInstanceAccess=MultithreadedInstanceAccess|true +detectorMutableLock=MutableLock|true +detectorMutableStaticFields=MutableStaticFields|true +detectorNaming=Naming|true +detectorNoteUnconditionalParamDerefs=NoteUnconditionalParamDerefs|true +detectorNumberConstructor=NumberConstructor|true +detectorOverridingEqualsNotSymmetrical=OverridingEqualsNotSymmetrical|true +detectorPreferZeroLengthArrays=PreferZeroLengthArrays|true +detectorPublicSemaphores=PublicSemaphores|false +detectorQuestionableBooleanAssignment=QuestionableBooleanAssignment|true +detectorReadOfInstanceFieldInMethodInvokedByConstructorInSuperclass=ReadOfInstanceFieldInMethodInvokedByConstructorInSuperclass|true +detectorReadReturnShouldBeChecked=ReadReturnShouldBeChecked|true +detectorRedundantInterfaces=RedundantInterfaces|true +detectorRepeatedConditionals=RepeatedConditionals|true +detectorRuntimeExceptionCapture=RuntimeExceptionCapture|true +detectorSerializableIdiom=SerializableIdiom|true +detectorStartInConstructor=StartInConstructor|true +detectorStaticCalendarDetector=StaticCalendarDetector|true +detectorStringConcatenation=StringConcatenation|true +detectorSuperfluousInstanceOf=SuperfluousInstanceOf|true +detectorSuspiciousThreadInterrupted=SuspiciousThreadInterrupted|true +detectorSwitchFallthrough=SwitchFallthrough|true +detectorSynchronizeAndNullCheckField=SynchronizeAndNullCheckField|true +detectorSynchronizeOnClassLiteralNotGetClass=SynchronizeOnClassLiteralNotGetClass|true +detectorSynchronizingOnContentsOfFieldToProtectField=SynchronizingOnContentsOfFieldToProtectField|true +detectorURLProblems=URLProblems|true +detectorUncallableMethodOfAnonymousClass=UncallableMethodOfAnonymousClass|true +detectorUnnecessaryMath=UnnecessaryMath|true +detectorUnreadFields=UnreadFields|true +detectorUselessSubclassMethod=UselessSubclassMethod|true +detectorVarArgsProblems=VarArgsProblems|true +detectorVolatileUsage=VolatileUsage|true +detectorWaitInLoop=WaitInLoop|true +detectorWrongMapIterator=WrongMapIterator|true +detectorXMLFactoryBypass=XMLFactoryBypass|true +detector_threshold=3 +effort=max +excludefilter0=../main/project/findbugs/exclusions.xml|true +filter_settings=Low|BAD_PRACTICE,CORRECTNESS,EXPERIMENTAL,MALICIOUS_CODE,MT_CORRECTNESS,PERFORMANCE,SECURITY,STYLE|false|20 +filter_settings_neg=NOISE,I18N| +run_at_full_build=true diff --git a/tests/src/cgeo/geocaching/CgeoApplicationTest.java b/tests/src/cgeo/geocaching/CgeoApplicationTest.java new file mode 100644 index 0000000..72cfcdb --- /dev/null +++ b/tests/src/cgeo/geocaching/CgeoApplicationTest.java @@ -0,0 +1,427 @@ +package cgeo.geocaching; + +import cgeo.CGeoTestCase; +import cgeo.geocaching.connector.ConnectorFactory; +import cgeo.geocaching.connector.gc.GCLogin; +import cgeo.geocaching.connector.gc.GCParser; +import cgeo.geocaching.connector.gc.Tile; +import cgeo.geocaching.enumerations.CacheType; +import cgeo.geocaching.enumerations.LiveMapStrategy.Strategy; +import cgeo.geocaching.enumerations.LoadFlags; +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; +import cgeo.geocaching.test.RegExPerformanceTest; +import cgeo.geocaching.test.mock.GC1ZXX2; +import cgeo.geocaching.test.mock.GC2CJPF; +import cgeo.geocaching.test.mock.GC2JVEH; +import cgeo.geocaching.test.mock.MockedCache; +import cgeo.geocaching.utils.CancellableHandler; +import cgeo.geocaching.utils.Log; +import cgeo.test.Compare; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.tuple.ImmutablePair; + +import android.test.suitebuilder.annotation.MediumTest; +import android.test.suitebuilder.annotation.SmallTest; + +import java.util.GregorianCalendar; + +import junit.framework.Assert; + +/** + * The c:geo application test. It can be used for tests that require an + * application and/or context. + */ + +public class CgeoApplicationTest extends CGeoTestCase { + + private static final String[] INVALID_TOKEN = null; + + /** + * The name 'test preconditions' is a convention to signal that if this test + * doesn't pass, the test case was not set up properly and it might explain + * any and all failures in other tests. This is not guaranteed to run before + * other tests, as junit uses reflection to find the tests. + */ + @SuppressWarnings("static-method") + @SmallTest + public void testPreconditions() { + assertEquals(StatusCode.NO_ERROR, GCLogin.getInstance().login()); + } + + /** + * Test {@link GCParser#searchTrackable(String, String, String)} + */ + @MediumTest + public static void testSearchTrackableNotExisting() { + final Trackable tb = GCParser.searchTrackable("123456", null, null); + assertNull(tb); + } + + /** + * Test {@link GCParser#searchTrackable(String, String, String)} + */ + @MediumTest + public static void testSearchTrackable() { + final Trackable tb = GCParser.searchTrackable("TB2J1VZ", null, null); + assertNotNull(tb); + // fix data + assertEquals("aefffb86-099f-444f-b132-605436163aa8", tb.getGuid()); + assertEquals("TB2J1VZ", tb.getGeocode()); + assertEquals("http://www.geocaching.com/images/wpttypes/21.gif", tb.getIconUrl()); + assertEquals("blafoo's Children Music CD", tb.getName()); + assertEquals("Travel Bug Dog Tag", tb.getType()); + assertEquals(new GregorianCalendar(2009, 8 - 1, 24).getTime(), tb.getReleased()); + assertEquals("Niedersachsen, Germany", tb.getOrigin()); + assertEquals("blafoo", tb.getOwner()); + assertEquals("0564a940-8311-40ee-8e76-7e91b2cf6284", tb.getOwnerGuid()); + assertEquals("Kinder erfreuen.

Make children happy.", tb.getGoal()); + assertTrue(tb.getDetails().startsWith("Auf der CD sind")); + assertEquals("http://imgcdn.geocaching.com/track/display/38382780-87a7-4393-8393-78841678ee8c.jpg", tb.getImage()); + // Following data can change over time + assertTrue(tb.getDistance() >= 10617.8f); + assertTrue(tb.getLogs().size() >= 10); + assertTrue(Trackable.SPOTTED_CACHE == tb.getSpottedType() || Trackable.SPOTTED_USER == tb.getSpottedType()); + // no assumption possible: assertEquals("faa2d47d-19ea-422f-bec8-318fc82c8063", tb.getSpottedGuid()); + // no assumption possible: assertEquals("Nice place for a break cache", tb.getSpottedName()); + + // we can't check specifics in the log entries since they change, but we can verify data was parsed + for (LogEntry log : tb.getLogs()) { + assertTrue(log.date > 0); + assertTrue(StringUtils.isNotEmpty(log.author)); + if (log.type == LogType.PLACED_IT || log.type == LogType.RETRIEVED_IT) { + assertTrue(StringUtils.isNotEmpty(log.cacheName)); + assertTrue(StringUtils.isNotEmpty(log.cacheGuid)); + } else { + assertTrue(log.type != LogType.UNKNOWN); + } + } + } + + /** + * Test {@link GCParser#searchByGeocode(String, String, int, boolean, CancellableHandler)} + */ + @MediumTest + public static Geocache testSearchByGeocode(final String geocode) { + final SearchResult search = Geocache.searchByGeocode(geocode, null, 0, true, null); + assertNotNull(search); + if (Settings.isPremiumMember() || search.getError() == null) { + assertEquals(1, search.getGeocodes().size()); + assertTrue(search.getGeocodes().contains(geocode)); + return DataStore.loadCache(geocode, LoadFlags.LOAD_CACHE_OR_DB); + } + assertEquals(0, search.getGeocodes().size()); + return null; + } + + /** + * Test {@link Geocache#searchByGeocode(String, String, int, boolean, CancellableHandler)} + */ + @MediumTest + public static void testSearchByGeocodeNotExisting() { + final SearchResult search = Geocache.searchByGeocode("GC123456", null, 0, true, null); + assertNotNull(search); + assertEquals(StatusCode.COMMUNICATION_ERROR, search.getError()); + } + + /** + * Set the login data to the cgeo login, run the given Runnable, and restore the login. + * + * @param runnable + */ + private static void withMockedLoginDo(final Runnable runnable) { + final ImmutablePair login = Settings.getGcLogin(); + final String memberStatus = Settings.getMemberStatus(); + + try { + runnable.run(); + } finally { + // restore user and password + TestSettings.setLogin(login.left, login.right); + Settings.setMemberStatus(memberStatus); + GCLogin.getInstance().login(); + } + } + + /** + * Test {@link Geocache#searchByGeocode(String, String, int, boolean, CancellableHandler)} + */ + @MediumTest + public static void testSearchByGeocodeNotLoggedIn() { + withMockedLoginDo(new Runnable() { + + public void run() { + // 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()); + } + }); + } + + /** + * 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()); + } + }); + } + + /** + * mock the "exclude disabled caches" and "exclude my caches" options for the execution of the runnable + * + * @param runnable + */ + private static void withMockedFilters(Runnable runnable) { + // backup user settings + final boolean excludeMine = Settings.isExcludeMyCaches(); + final boolean excludeDisabled = Settings.isExcludeDisabledCaches(); + try { + // set up settings required for test + TestSettings.setExcludeMine(false); + TestSettings.setExcludeDisabledCaches(false); + + runnable.run(); + + } finally { + // restore user settings + TestSettings.setExcludeMine(excludeMine); + TestSettings.setExcludeDisabledCaches(excludeDisabled); + } + } + + /** + * Test {@link GCParser#searchByCoords(Geopoint, CacheType, boolean, RecaptchaReceiver)} + */ + @MediumTest + public static void testSearchByCoords() { + withMockedFilters(new Runnable() { + + @Override + public void run() { + final SearchResult search = GCParser.searchByCoords(new Geopoint("N 52° 24.972 E 009° 35.647"), CacheType.MYSTERY, false, null); + assertNotNull(search); + assertTrue(20 <= search.getGeocodes().size()); + assertTrue(search.getGeocodes().contains("GC1RMM2")); + } + }); + } + + /** + * Test {@link GCParser#searchByOwner(String, CacheType, boolean, RecaptchaReceiver)} + */ + @MediumTest + public static void testSearchByOwner() { + withMockedFilters(new Runnable() { + + @Override + public void run() { + final SearchResult search = GCParser.searchByOwner("blafoo", CacheType.MYSTERY, false, null); + assertNotNull(search); + assertEquals(3, search.getGeocodes().size()); + assertTrue(search.getGeocodes().contains("GC36RT6")); + } + }); + } + + /** + * Test {@link GCParser#searchByUsername(String, CacheType, boolean, RecaptchaReceiver)} + */ + @MediumTest + public static void testSearchByUsername() { + withMockedFilters(new Runnable() { + + @Override + public void run() { + final SearchResult search = GCParser.searchByUsername("blafoo", CacheType.WEBCAM, false, null); + assertNotNull(search); + assertEquals(4, search.getTotal()); + assertTrue(search.getGeocodes().contains("GCP0A9")); + } + }); + } + + /** + * Test {@link ConnectorFactory#searchByViewport(Viewport, String)} + */ + @MediumTest + public static void testSearchByViewport() { + withMockedFilters(new Runnable() { + + @Override + public void run() { + // backup user settings + final Strategy strategy = Settings.getLiveMapStrategy(); + final CacheType cacheType = Settings.getCacheType(); + + try { + // set up settings required for test + TestSettings.setExcludeMine(false); + Settings.setCacheType(CacheType.ALL); + + final GC2CJPF mockedCache = new GC2CJPF(); + deleteCacheFromDB(mockedCache.getGeocode()); + + final String[] tokens = GCLogin.getMapTokens(); + final Viewport viewport = new Viewport(mockedCache, 0.003, 0.003); + + // check coords for DETAILED + Settings.setLiveMapStrategy(Strategy.DETAILED); + SearchResult search = ConnectorFactory.searchByViewport(viewport, tokens); + assertNotNull(search); + assertTrue(search.getGeocodes().contains(mockedCache.getGeocode())); + Geocache parsedCache = DataStore.loadCache(mockedCache.getGeocode(), LoadFlags.LOAD_CACHE_OR_DB); + + assertEquals(Settings.isPremiumMember(), mockedCache.getCoords().equals(parsedCache.getCoords())); + assertEquals(Settings.isPremiumMember(), parsedCache.isReliableLatLon()); + + // check update after switch strategy to FAST + Settings.setLiveMapStrategy(Strategy.FAST); + Tile.Cache.removeFromTileCache(mockedCache); + + search = ConnectorFactory.searchByViewport(viewport, tokens); + assertNotNull(search); + assertTrue(search.getGeocodes().contains(mockedCache.getGeocode())); + parsedCache = DataStore.loadCache(mockedCache.getGeocode(), LoadFlags.LOAD_CACHE_OR_DB); + + assertEquals(Settings.isPremiumMember(), mockedCache.getCoords().equals(parsedCache.getCoords())); + assertEquals(Settings.isPremiumMember(), parsedCache.isReliableLatLon()); + + } finally { + // restore user settings + Settings.setLiveMapStrategy(strategy); + Settings.setCacheType(cacheType); + } + } + }); + } + + /** + * Test {@link ConnectorFactory#searchByViewport(Viewport, String)} + */ + @MediumTest + public static void testSearchByViewportNotLoggedIn() { + withMockedLoginDo(new Runnable() { + + 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(); + + try { + + // non premium cache + MockedCache cache = new GC2CJPF(); + deleteCacheFromDBAndLogout(cache.getGeocode()); + Tile.Cache.removeFromTileCache(cache); + Settings.setCacheType(CacheType.ALL); + + Viewport viewport = new Viewport(cache, 0.003, 0.003); + SearchResult search = ConnectorFactory.searchByViewport(viewport, INVALID_TOKEN); + + 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, INVALID_TOKEN); + + 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 { + Settings.setLiveMapStrategy(strategy); + Settings.setCacheType(cacheType); + } + } + }); + } + + /** + * Test cache parsing. Esp. useful after a GC.com update + */ + public static void testSearchByGeocodeBasis() { + for (MockedCache mockedCache : RegExPerformanceTest.MOCKED_CACHES) { + String oldUser = mockedCache.getMockedDataUser(); + try { + mockedCache.setMockedDataUser(Settings.getUsername()); + Geocache parsedCache = CgeoApplicationTest.testSearchByGeocode(mockedCache.getGeocode()); + if (null != parsedCache) { + Compare.assertCompareCaches(mockedCache, parsedCache, true); + } + } finally { + mockedCache.setMockedDataUser(oldUser); + } + } + } + + /** + * Caches that are good test cases + */ + public static void testSearchByGeocodeSpecialties() { + final Geocache GCV2R9 = CgeoApplicationTest.testSearchByGeocode("GCV2R9"); + Assert.assertEquals("California, United States", GCV2R9.getLocation()); + + final Geocache GC1ZXEZ = CgeoApplicationTest.testSearchByGeocode("GC1ZXEZ"); + Assert.assertEquals("Ms.Marple/Mr.Stringer", GC1ZXEZ.getOwnerUserId()); + } + + /** Remove cache from DB and cache to ensure that the cache is not loaded from the database */ + private static void deleteCacheFromDBAndLogout(String geocode) { + deleteCacheFromDB(geocode); + + GCLogin.getInstance().logout(); + // Modify login data to avoid an automatic login again + TestSettings.setLogin("c:geo", "c:geo"); + Settings.setMemberStatus("Basic member"); + } + +} diff --git a/tests/src/cgeo/geocaching/HtmlPerformanceTest.java b/tests/src/cgeo/geocaching/HtmlPerformanceTest.java index b08b06e..695cd4a 100644 --- a/tests/src/cgeo/geocaching/HtmlPerformanceTest.java +++ b/tests/src/cgeo/geocaching/HtmlPerformanceTest.java @@ -2,6 +2,8 @@ package cgeo.geocaching; import cgeo.geocaching.utils.Log; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; + import org.apache.commons.lang3.StringEscapeUtils; import android.os.SystemClock; @@ -51,6 +53,7 @@ public class HtmlPerformanceTest extends AndroidTestCase { }); } + @SuppressFBWarnings("DM_GC") private static long measure(String label, Runnable runnable) { System.gc(); final long start = SystemClock.elapsedRealtime(); diff --git a/tests/src/cgeo/geocaching/PersonalNoteTest.java b/tests/src/cgeo/geocaching/PersonalNoteTest.java index 38085d5..74e1bab 100644 --- a/tests/src/cgeo/geocaching/PersonalNoteTest.java +++ b/tests/src/cgeo/geocaching/PersonalNoteTest.java @@ -36,10 +36,10 @@ public class PersonalNoteTest extends TestCase { Geocache exceedingCache = new Geocache(); exceedingCache.setListId(StoredList.STANDARD_LIST_ID); // stored - exceedingCache.setPersonalNote(testString.toString()); + exceedingCache.setPersonalNote(testString); PersonalNote otherNote = new PersonalNote(exceedingCache); PersonalNote result = parsedNote.mergeWith(otherNote); - assertPersonalNote(result, null, testString.toString()); + assertPersonalNote(result, null, testString); } public static void testParseCgeoOnly() { diff --git a/tests/src/cgeo/geocaching/cgeoApplicationTest.java b/tests/src/cgeo/geocaching/cgeoApplicationTest.java deleted file mode 100644 index c4737db..0000000 --- a/tests/src/cgeo/geocaching/cgeoApplicationTest.java +++ /dev/null @@ -1,426 +0,0 @@ -package cgeo.geocaching; - -import cgeo.CGeoTestCase; -import cgeo.geocaching.connector.ConnectorFactory; -import cgeo.geocaching.connector.gc.GCLogin; -import cgeo.geocaching.connector.gc.GCParser; -import cgeo.geocaching.connector.gc.Tile; -import cgeo.geocaching.enumerations.CacheType; -import cgeo.geocaching.enumerations.LiveMapStrategy.Strategy; -import cgeo.geocaching.enumerations.LoadFlags; -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; -import cgeo.geocaching.test.RegExPerformanceTest; -import cgeo.geocaching.test.mock.GC1ZXX2; -import cgeo.geocaching.test.mock.GC2CJPF; -import cgeo.geocaching.test.mock.GC2JVEH; -import cgeo.geocaching.test.mock.MockedCache; -import cgeo.geocaching.utils.CancellableHandler; -import cgeo.geocaching.utils.Log; -import cgeo.test.Compare; - -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.tuple.ImmutablePair; - -import android.test.suitebuilder.annotation.MediumTest; -import android.test.suitebuilder.annotation.SmallTest; - -import java.util.GregorianCalendar; - -import junit.framework.Assert; - -/** - * The c:geo application test. It can be used for tests that require an - * application and/or context. - */ - -public class cgeoApplicationTest extends CGeoTestCase { - - /** - * The name 'test preconditions' is a convention to signal that if this test - * doesn't pass, the test case was not set up properly and it might explain - * any and all failures in other tests. This is not guaranteed to run before - * other tests, as junit uses reflection to find the tests. - */ - @SuppressWarnings("static-method") - @SmallTest - public void testPreconditions() { - assertEquals(StatusCode.NO_ERROR, GCLogin.getInstance().login()); - } - - /** - * Test {@link GCParser#searchTrackable(String, String, String)} - */ - @MediumTest - public static void testSearchTrackableNotExisting() { - final Trackable tb = GCParser.searchTrackable("123456", null, null); - assertNull(tb); - } - - /** - * Test {@link GCParser#searchTrackable(String, String, String)} - */ - @MediumTest - public static void testSearchTrackable() { - final Trackable tb = GCParser.searchTrackable("TB2J1VZ", null, null); - // fix data - assertEquals("aefffb86-099f-444f-b132-605436163aa8", tb.getGuid()); - assertEquals("TB2J1VZ", tb.getGeocode()); - assertEquals("http://www.geocaching.com/images/wpttypes/21.gif", tb.getIconUrl()); - assertEquals("blafoo's Children Music CD", tb.getName()); - assertEquals("Travel Bug Dog Tag", tb.getType()); - assertEquals(new GregorianCalendar(2009, 8 - 1, 24).getTime(), tb.getReleased()); - assertEquals("Niedersachsen, Germany", tb.getOrigin()); - assertEquals("blafoo", tb.getOwner()); - assertEquals("0564a940-8311-40ee-8e76-7e91b2cf6284", tb.getOwnerGuid()); - assertEquals("Kinder erfreuen.

Make children happy.", tb.getGoal()); - assertTrue(tb.getDetails().startsWith("Auf der CD sind")); - assertEquals("http://imgcdn.geocaching.com/track/display/38382780-87a7-4393-8393-78841678ee8c.jpg", tb.getImage()); - // Following data can change over time - assertTrue(tb.getDistance() >= 10617.8f); - assertTrue(tb.getLogs().size() >= 10); - assertTrue(Trackable.SPOTTED_CACHE == tb.getSpottedType() || Trackable.SPOTTED_USER == tb.getSpottedType()); - // no assumption possible: assertEquals("faa2d47d-19ea-422f-bec8-318fc82c8063", tb.getSpottedGuid()); - // no assumption possible: assertEquals("Nice place for a break cache", tb.getSpottedName()); - - // we can't check specifics in the log entries since they change, but we can verify data was parsed - for (LogEntry log : tb.getLogs()) { - assertTrue(log.date > 0); - assertTrue(StringUtils.isNotEmpty(log.author)); - if (log.type == LogType.PLACED_IT || log.type == LogType.RETRIEVED_IT) { - assertTrue(StringUtils.isNotEmpty(log.cacheName)); - assertTrue(StringUtils.isNotEmpty(log.cacheGuid)); - } else { - assertTrue(log.type != LogType.UNKNOWN); - } - } - } - - /** - * Test {@link GCParser#searchByGeocode(String, String, int, boolean, CancellableHandler)} - */ - @MediumTest - public static Geocache testSearchByGeocode(final String geocode) { - final SearchResult search = Geocache.searchByGeocode(geocode, null, 0, true, null); - assertNotNull(search); - if (Settings.isPremiumMember() || search.getError() == null) { - assertEquals(1, search.getGeocodes().size()); - assertTrue(search.getGeocodes().contains(geocode)); - return DataStore.loadCache(geocode, LoadFlags.LOAD_CACHE_OR_DB); - } - assertEquals(0, search.getGeocodes().size()); - return null; - } - - /** - * Test {@link Geocache#searchByGeocode(String, String, int, boolean, CancellableHandler)} - */ - @MediumTest - public static void testSearchByGeocodeNotExisting() { - final SearchResult search = Geocache.searchByGeocode("GC123456", null, 0, true, null); - assertNotNull(search); - assertEquals(StatusCode.COMMUNICATION_ERROR, search.getError()); - } - - /** - * Set the login data to the cgeo login, run the given Runnable, and restore the login. - * - * @param runnable - */ - private static void withMockedLoginDo(final Runnable runnable) { - final ImmutablePair login = Settings.getGcLogin(); - final String memberStatus = Settings.getMemberStatus(); - - try { - runnable.run(); - } finally { - // restore user and password - TestSettings.setLogin(login.left, login.right); - Settings.setMemberStatus(memberStatus); - GCLogin.getInstance().login(); - } - } - - /** - * Test {@link Geocache#searchByGeocode(String, String, int, boolean, CancellableHandler)} - */ - @MediumTest - public static void testSearchByGeocodeNotLoggedIn() { - withMockedLoginDo(new Runnable() { - - public void run() { - // 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()); - } - }); - } - - /** - * 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()); - } - }); - } - - /** - * mock the "exclude disabled caches" and "exclude my caches" options for the execution of the runnable - * - * @param runnable - */ - private static void withMockedFilters(Runnable runnable) { - // backup user settings - final boolean excludeMine = Settings.isExcludeMyCaches(); - final boolean excludeDisabled = Settings.isExcludeDisabledCaches(); - try { - // set up settings required for test - TestSettings.setExcludeMine(false); - TestSettings.setExcludeDisabledCaches(false); - - runnable.run(); - - } finally { - // restore user settings - TestSettings.setExcludeMine(excludeMine); - TestSettings.setExcludeDisabledCaches(excludeDisabled); - } - } - - /** - * Test {@link GCParser#searchByCoords(Geopoint, CacheType, boolean, RecaptchaReceiver)} - */ - @MediumTest - public static void testSearchByCoords() { - withMockedFilters(new Runnable() { - - @Override - public void run() { - final SearchResult search = GCParser.searchByCoords(new Geopoint("N 52° 24.972 E 009° 35.647"), CacheType.MYSTERY, false, null); - assertNotNull(search); - assertTrue(20 <= search.getGeocodes().size()); - assertTrue(search.getGeocodes().contains("GC1RMM2")); - } - }); - } - - /** - * Test {@link GCParser#searchByOwner(String, CacheType, boolean, RecaptchaReceiver)} - */ - @MediumTest - public static void testSearchByOwner() { - withMockedFilters(new Runnable() { - - @Override - public void run() { - final SearchResult search = GCParser.searchByOwner("blafoo", CacheType.MYSTERY, false, null); - assertNotNull(search); - assertEquals(3, search.getGeocodes().size()); - assertTrue(search.getGeocodes().contains("GC36RT6")); - } - }); - } - - /** - * Test {@link GCParser#searchByUsername(String, CacheType, boolean, RecaptchaReceiver)} - */ - @MediumTest - public static void testSearchByUsername() { - withMockedFilters(new Runnable() { - - @Override - public void run() { - final SearchResult search = GCParser.searchByUsername("blafoo", CacheType.WEBCAM, false, null); - assertNotNull(search); - assertEquals(4, search.getTotal()); - assertTrue(search.getGeocodes().contains("GCP0A9")); - } - }); - } - - /** - * Test {@link ConnectorFactory#searchByViewport(Viewport, String)} - */ - @MediumTest - public static void testSearchByViewport() { - withMockedFilters(new Runnable() { - - @Override - public void run() { - // backup user settings - final Strategy strategy = Settings.getLiveMapStrategy(); - final CacheType cacheType = Settings.getCacheType(); - - try { - // set up settings required for test - TestSettings.setExcludeMine(false); - Settings.setCacheType(CacheType.ALL); - - final GC2CJPF mockedCache = new GC2CJPF(); - deleteCacheFromDB(mockedCache.getGeocode()); - - final String[] tokens = GCLogin.getMapTokens(); - final Viewport viewport = new Viewport(mockedCache, 0.003, 0.003); - - // check coords for DETAILED - Settings.setLiveMapStrategy(Strategy.DETAILED); - SearchResult search = ConnectorFactory.searchByViewport(viewport, tokens); - assertNotNull(search); - assertTrue(search.getGeocodes().contains(mockedCache.getGeocode())); - Geocache parsedCache = DataStore.loadCache(mockedCache.getGeocode(), LoadFlags.LOAD_CACHE_OR_DB); - - assertEquals(Settings.isPremiumMember(), mockedCache.getCoords().equals(parsedCache.getCoords())); - assertEquals(Settings.isPremiumMember(), parsedCache.isReliableLatLon()); - - // check update after switch strategy to FAST - Settings.setLiveMapStrategy(Strategy.FAST); - Tile.Cache.removeFromTileCache(mockedCache); - - search = ConnectorFactory.searchByViewport(viewport, tokens); - assertNotNull(search); - assertTrue(search.getGeocodes().contains(mockedCache.getGeocode())); - parsedCache = DataStore.loadCache(mockedCache.getGeocode(), LoadFlags.LOAD_CACHE_OR_DB); - - assertEquals(Settings.isPremiumMember(), mockedCache.getCoords().equals(parsedCache.getCoords())); - assertEquals(Settings.isPremiumMember(), parsedCache.isReliableLatLon()); - - } finally { - // restore user settings - Settings.setLiveMapStrategy(strategy); - Settings.setCacheType(cacheType); - } - } - }); - } - - /** - * Test {@link ConnectorFactory#searchByViewport(Viewport, String)} - */ - @MediumTest - public static void testSearchByViewportNotLoggedIn() { - withMockedLoginDo(new Runnable() { - - 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(); - - try { - - final String[] tokens = null; // without a valid token we are "logged off" - - // non premium cache - MockedCache cache = new GC2CJPF(); - deleteCacheFromDBAndLogout(cache.getGeocode()); - Tile.Cache.removeFromTileCache(cache); - Settings.setCacheType(CacheType.ALL); - - Viewport viewport = new Viewport(cache, 0.003, 0.003); - SearchResult 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())); - - } finally { - Settings.setLiveMapStrategy(strategy); - Settings.setCacheType(cacheType); - } - } - }); - } - - /** - * Test cache parsing. Esp. useful after a GC.com update - */ - public static void testSearchByGeocodeBasis() { - for (MockedCache mockedCache : RegExPerformanceTest.MOCKED_CACHES) { - String oldUser = mockedCache.getMockedDataUser(); - try { - mockedCache.setMockedDataUser(Settings.getUsername()); - Geocache parsedCache = cgeoApplicationTest.testSearchByGeocode(mockedCache.getGeocode()); - if (null != parsedCache) { - Compare.assertCompareCaches(mockedCache, parsedCache, true); - } - } finally { - mockedCache.setMockedDataUser(oldUser); - } - } - } - - /** - * Caches that are good test cases - */ - public static void testSearchByGeocodeSpecialties() { - final Geocache GCV2R9 = cgeoApplicationTest.testSearchByGeocode("GCV2R9"); - Assert.assertEquals("California, United States", GCV2R9.getLocation()); - - final Geocache GC1ZXEZ = cgeoApplicationTest.testSearchByGeocode("GC1ZXEZ"); - Assert.assertEquals("Ms.Marple/Mr.Stringer", GC1ZXEZ.getOwnerUserId()); - } - - /** Remove cache from DB and cache to ensure that the cache is not loaded from the database */ - private static void deleteCacheFromDBAndLogout(String geocode) { - deleteCacheFromDB(geocode); - - GCLogin.getInstance().logout(); - // Modify login data to avoid an automatic login again - TestSettings.setLogin("c:geo", "c:geo"); - Settings.setMemberStatus("Basic member"); - } - -} diff --git a/tests/src/cgeo/geocaching/export/ExportTest.java b/tests/src/cgeo/geocaching/export/ExportTest.java index 6d39f8d..b8f1ffd 100644 --- a/tests/src/cgeo/geocaching/export/ExportTest.java +++ b/tests/src/cgeo/geocaching/export/ExportTest.java @@ -7,6 +7,7 @@ import cgeo.geocaching.LogEntry; import cgeo.geocaching.enumerations.LoadFlags; import cgeo.geocaching.enumerations.LogType; import cgeo.geocaching.geopoint.Geopoint; +import cgeo.geocaching.utils.FileUtils; import java.io.File; import java.util.ArrayList; @@ -43,7 +44,7 @@ public class ExportTest extends CGeoTestCase { assertNotNull(result); - result.delete(); + FileUtils.deleteIgnoringFailure(result); } private static class GpxExportTester extends GpxExport { diff --git a/tests/src/cgeo/geocaching/files/GPXImporterTest.java b/tests/src/cgeo/geocaching/files/GPXImporterTest.java index ee42d23..6d7456c 100644 --- a/tests/src/cgeo/geocaching/files/GPXImporterTest.java +++ b/tests/src/cgeo/geocaching/files/GPXImporterTest.java @@ -12,6 +12,7 @@ import cgeo.geocaching.test.R; import cgeo.geocaching.utils.CancellableHandler; import cgeo.geocaching.utils.Log; +import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import android.net.Uri; @@ -50,8 +51,8 @@ public class GPXImporterTest extends AbstractResourceInstrumentationTestCase { // the "real" method check assertEquals(wptsFileName, GPXImporter.getWaypointsFileNameForGpxFile(gpx)); // they also need to be deleted, because of case sensitive tests that will not work correct on case insensitive file systems - gpx.delete(); - wpts.delete(); + FileUtils.deleteQuietly(gpx); + FileUtils.deleteQuietly(wpts); } final File gpx1 = new File(tempDir, "abc.gpx"); assertNull(GPXImporter.getWaypointsFileNameForGpxFile(gpx1)); @@ -260,7 +261,7 @@ public class GPXImporterTest extends AbstractResourceInstrumentationTestCase { msg1.copyFrom(msg); messages.add(msg1); lastMessage = System.currentTimeMillis(); - notify(); + notifyAll(); } public synchronized void waitForCompletion(final long milliseconds, final int maxMessages) { @@ -287,7 +288,7 @@ public class GPXImporterTest extends AbstractResourceInstrumentationTestCase { assertTrue("java.io.tmpdir is not defined", StringUtils.isNotBlank(globalTempDir)); tempDir = new File(globalTempDir, "cgeogpxesTest"); - tempDir.mkdir(); + cgeo.geocaching.utils.FileUtils.mkdirs(tempDir); assertTrue("Could not create directory " + tempDir.getPath(), tempDir.exists()); // workaround to get storage initialized DataStore.getAllHistoryCachesCount(); @@ -306,21 +307,9 @@ public class GPXImporterTest extends AbstractResourceInstrumentationTestCase { cachesInList.addAll(search.getCachesFromSearchResult(LoadFlags.LOAD_CACHE_OR_DB)); DataStore.markDropped(cachesInList); DataStore.removeList(listId); - deleteDirectory(tempDir); + FileUtils.deleteDirectory(tempDir); TestSettings.setStoreOfflineMaps(importCacheStaticMaps); TestSettings.setStoreOfflineWpMaps(importWpStaticMaps); super.tearDown(); } - - private static void deleteDirectory(File dir) { - for (File f : dir.listFiles()) { - if (f.isFile()) { - f.delete(); - } else if (f.isDirectory()) { - deleteDirectory(f); - } - } - dir.delete(); - } - } diff --git a/tests/src/cgeo/geocaching/files/GPXParserTest.java b/tests/src/cgeo/geocaching/files/GPXParserTest.java index 9604519..dcaad22 100644 --- a/tests/src/cgeo/geocaching/files/GPXParserTest.java +++ b/tests/src/cgeo/geocaching/files/GPXParserTest.java @@ -12,13 +12,13 @@ import cgeo.geocaching.enumerations.WaypointType; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.test.AbstractResourceInstrumentationTestCase; import cgeo.geocaching.test.R; +import cgeo.geocaching.utils.SynchronizedDateFormat; import org.apache.commons.lang3.StringUtils; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; -import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.EnumSet; @@ -28,7 +28,7 @@ import java.util.Locale; import java.util.Set; public class GPXParserTest extends AbstractResourceInstrumentationTestCase { - private static final SimpleDateFormat LOG_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US); // 2010-04-20T07:00:00Z + private static final SynchronizedDateFormat LOG_DATE_FORMAT = new SynchronizedDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US); // 2010-04-20T07:00:00Z public void testGPXVersion100() throws Exception { testGPXVersion(R.raw.gc1bkp3_gpx100); diff --git a/tests/src/cgeo/geocaching/test/CgeoTestsActivity.java b/tests/src/cgeo/geocaching/test/CgeoTestsActivity.java index 0f41cef..c1f6fdd 100644 --- a/tests/src/cgeo/geocaching/test/CgeoTestsActivity.java +++ b/tests/src/cgeo/geocaching/test/CgeoTestsActivity.java @@ -1,5 +1,7 @@ package cgeo.geocaching.test; +import butterknife.ButterKnife; + import android.app.Activity; import android.content.ComponentName; import android.content.pm.InstrumentationInfo; @@ -14,6 +16,7 @@ import android.widget.TextView; import android.widget.Toast; import java.io.BufferedReader; +import java.io.IOException; import java.io.InputStreamReader; import java.util.List; @@ -76,7 +79,9 @@ public class CgeoTestsActivity extends Activity { Thread.sleep(50); publishProgress(mReader.readLine()); } while (System.currentTimeMillis() < timeout); - } catch (Exception e) { + } catch (InterruptedException e) { + publishProgress("ERROR: " + e); + } catch (IOException e) { publishProgress("ERROR: " + e); } finally { publishProgress("END"); @@ -90,8 +95,8 @@ public class CgeoTestsActivity extends Activity { 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); + logView = ButterKnife.findById(this, R.id.logOutput); + scrollView = ButterKnife.findById(this, R.id.scrollView); } @Override @@ -114,7 +119,7 @@ public class CgeoTestsActivity extends Activity { * referenced from XML layout */ public void runTests(final View v) { - final Button button = (Button) findViewById(R.id.buttonRun); + final Button button = ButterKnife.findById(this, R.id.buttonRun); button.setEnabled(false); try { runTestsInternally(); diff --git a/tests/src/cgeo/geocaching/test/mock/GC3XX5J.java b/tests/src/cgeo/geocaching/test/mock/GC3XX5J.java index e9db12d..ea8079b 100644 --- a/tests/src/cgeo/geocaching/test/mock/GC3XX5J.java +++ b/tests/src/cgeo/geocaching/test/mock/GC3XX5J.java @@ -133,10 +133,4 @@ public class GC3XX5J extends MockedCache { public String getShortDescription() { return "Kadar zbolimo nam pomaga...

When we get sick, they are helpful..."; } - - @Override - public String getPersonalNote() { - return super.getPersonalNote(); - } - } -- cgit v1.1